Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parse request version in extractor, refactor match_version #2383

Merged
merged 3 commits into from
Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 85 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,10 @@ uuid = { version = "1.1.2", features = ["v4"]}
# Data serialization and deserialization
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_with = "3.4.0"

# axum dependencies
axum = "0.7.3"
axum = { version = "0.7.3", features = ["macros"] }
axum-extra = { version = "0.9.1", features = ["typed-header"] }
hyper = { version = "1.1.0", default-features = false }
tower = "0.4.11"
Expand Down
3 changes: 3 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[[disallowed-types]]
path = "axum::extract::Path"
reason = "use our own custom web::extractors::Path for a nicer error response"
17 changes: 8 additions & 9 deletions src/web/build_details.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@ use crate::{
impl_axum_webpage,
web::{
error::{AxumNope, AxumResult},
extractors::DbConnection,
extractors::{DbConnection, Path},
file::File,
MetaData,
},
AsyncStorage, Config,
};
use anyhow::Context as _;
use axum::{
extract::{Extension, Path},
response::IntoResponse,
};
use axum::{extract::Extension, response::IntoResponse};
use chrono::{DateTime, Utc};
use semver::Version;
use serde::Serialize;
use std::sync::Arc;

Expand All @@ -39,7 +37,7 @@ impl_axum_webpage! {
}

pub(crate) async fn build_details_handler(
Path((name, version, id)): Path<(String, String, String)>,
Path((name, version, id)): Path<(String, Version, String)>,
mut conn: DbConnection,
Extension(config): Extension<Arc<Config>>,
Extension(storage): Extension<Arc<AsyncStorage>>,
Expand All @@ -60,7 +58,7 @@ pub(crate) async fn build_details_handler(
WHERE builds.id = $1 AND crates.name = $2 AND releases.version = $3",
id,
name,
version,
version.to_string(),
)
.fetch_optional(&mut *conn)
.await?
Expand All @@ -75,7 +73,7 @@ pub(crate) async fn build_details_handler(
};

Ok(BuildDetailsPage {
metadata: MetaData::from_crate(&mut conn, &name, &version, &version).await?,
metadata: MetaData::from_crate(&mut conn, &name, &version, None).await?,
build_details: BuildDetails {
id,
rustc_version: row.rustc_version,
Expand Down Expand Up @@ -147,7 +145,8 @@ mod tests {
let attrs = node.attributes.borrow();
let url = attrs.get("href").unwrap();

let page = kuchikiki::parse_html().one(env.frontend().get(url).send()?.text()?);
let page = kuchikiki::parse_html()
.one(env.frontend().get(url).send()?.error_for_status()?.text()?);

let log = page.select("pre").unwrap().next().unwrap().text_contents();

Expand Down
64 changes: 29 additions & 35 deletions src/web/builds.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
use super::{cache::CachePolicy, headers::CanonicalUrl, MatchSemver};
use super::{cache::CachePolicy, error::AxumNope, headers::CanonicalUrl};
use crate::{
docbuilder::Limits,
impl_axum_webpage,
web::{error::AxumResult, extractors::DbConnection, match_version, MetaData},
web::{
error::AxumResult,
extractors::{DbConnection, Path},
match_version, MetaData, ReqVersion,
},
Config,
};
use anyhow::Result;
use axum::{
extract::{Extension, Path},
http::header::ACCESS_CONTROL_ALLOW_ORIGIN,
response::IntoResponse,
Json,
extract::Extension, http::header::ACCESS_CONTROL_ALLOW_ORIGIN, response::IntoResponse, Json,
};
use chrono::{DateTime, Utc};
use semver::Version;
use serde::Serialize;
use std::sync::Arc;

Expand All @@ -39,28 +41,23 @@ impl_axum_webpage! {
}

pub(crate) async fn build_list_handler(
Path((name, req_version)): Path<(String, String)>,
Path((name, req_version)): Path<(String, ReqVersion)>,
mut conn: DbConnection,
Extension(config): Extension<Arc<Config>>,
) -> AxumResult<impl IntoResponse> {
let (version, version_or_latest) = match match_version(&mut conn, &name, Some(&req_version))
let version = match_version(&mut conn, &name, &req_version)
.await?
.exact_name_only()?
{
MatchSemver::Exact((version, _)) => (version.clone(), version),
MatchSemver::Latest((version, _)) => (version, "latest".to_string()),

MatchSemver::Semver((version, _)) => {
return Ok(super::axum_cached_redirect(
&format!("/crate/{name}/{version}/builds"),
.assume_exact_name()?
.into_canonical_req_version_or_else(|version| {
AxumNope::Redirect(
format!("/crate/{name}/{version}/builds"),
CachePolicy::ForeverInCdn,
)?
.into_response());
}
};
)
})?
.into_version();

Ok(BuildsPage {
metadata: MetaData::from_crate(&mut conn, &name, &version, &version_or_latest).await?,
metadata: MetaData::from_crate(&mut conn, &name, &version, Some(req_version)).await?,
builds: get_builds(&mut conn, &name, &version).await?,
limits: Limits::for_crate(&config, &mut conn, &name).await?,
canonical_url: CanonicalUrl::from_path(format!("/crate/{name}/latest/builds")),
Expand All @@ -70,22 +67,19 @@ pub(crate) async fn build_list_handler(
}

pub(crate) async fn build_list_json_handler(
Path((name, req_version)): Path<(String, String)>,
Path((name, req_version)): Path<(String, ReqVersion)>,
mut conn: DbConnection,
) -> AxumResult<impl IntoResponse> {
let version = match match_version(&mut conn, &name, Some(&req_version))
let version = match_version(&mut conn, &name, &req_version)
.await?
.exact_name_only()?
{
MatchSemver::Exact((version, _)) | MatchSemver::Latest((version, _)) => version,
MatchSemver::Semver((version, _)) => {
return Ok(super::axum_cached_redirect(
&format!("/crate/{name}/{version}/builds.json"),
.assume_exact_name()?
.into_canonical_req_version_or_else(|version| {
AxumNope::Redirect(
format!("/crate/{name}/{version}/builds.json"),
CachePolicy::ForeverInCdn,
)?
.into_response());
}
};
)
})?
.into_version();

Ok((
Extension(CachePolicy::NoStoreMustRevalidate),
Expand All @@ -98,7 +92,7 @@ pub(crate) async fn build_list_json_handler(
async fn get_builds(
conn: &mut sqlx::PgConnection,
name: &str,
version: &str,
version: &Version,
) -> Result<Vec<Build>> {
Ok(sqlx::query_as!(
Build,
Expand All @@ -114,7 +108,7 @@ async fn get_builds(
WHERE crates.name = $1 AND releases.version = $2
ORDER BY id DESC",
name,
version,
version.to_string(),
)
.fetch_all(&mut *conn)
.await?)
Expand Down
Loading
Loading