Skip to content

Expose the default_version on the API #9741

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

Merged
merged 7 commits into from
Oct 25, 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
20 changes: 14 additions & 6 deletions src/controllers/krate/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,19 @@ pub async fn show(app: AppState, Path(name): Path<String>, req: Parts) -> AppRes
.transpose()?
.unwrap_or_default();

let (krate, downloads): (Crate, i64) = Crate::by_name(&name)
.inner_join(crate_downloads::table)
.select((Crate::as_select(), crate_downloads::downloads))
.first(conn)
.optional()?
.ok_or_else(|| crate_not_found(&name))?;
let (krate, downloads, default_version): (Crate, i64, Option<String>) =
Crate::by_name(&name)
.inner_join(crate_downloads::table)
.left_join(default_versions::table)
.left_join(versions::table.on(default_versions::version_id.eq(versions::id)))
.select((
Crate::as_select(),
crate_downloads::downloads,
versions::num.nullable(),
))
.first(conn)
.optional()?
.ok_or_else(|| crate_not_found(&name))?;

let versions_publishers_and_audit_actions = if include.versions {
let mut versions_and_publishers: Vec<(Version, Option<User>)> = krate
Expand Down Expand Up @@ -120,6 +127,7 @@ pub async fn show(app: AppState, Path(name): Path<String>, req: Parts) -> AppRes

let encodable_crate = EncodableCrate::from(
krate.clone(),
default_version.as_deref(),
top_versions.as_ref(),
ids,
kws.as_deref(),
Expand Down
13 changes: 12 additions & 1 deletion src/controllers/krate/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,7 @@ pub async fn publish(app: AppState, req: BytesRequest) -> AppResult<Json<GoodCra
.first(conn)
.optional()?;

let mut default_version = None;
// Upsert the `default_value` determined by the existing `default_value` and the
// published version. Note that this could potentially write an outdated version
// (although this should not happen regularly), as we might be comparing to an
Expand All @@ -412,6 +413,8 @@ pub async fn publish(app: AppState, req: BytesRequest) -> AppResult<Json<GoodCra
.filter(default_versions::crate_id.eq(krate.id))
.set(default_versions::version_id.eq(version.id))
.execute(conn)?;
} else {
default_version = Some(existing_default_version.num.to_string());
}

// Update the default version asynchronously in a background job
Expand Down Expand Up @@ -505,7 +508,15 @@ pub async fn publish(app: AppState, req: BytesRequest) -> AppResult<Json<GoodCra
};

Ok(Json(GoodCrate {
krate: EncodableCrate::from_minimal(krate, Some(&top_versions), None, false, downloads, None),
krate: EncodableCrate::from_minimal(
krate,
default_version.or(Some(version_string)).as_deref(),
Some(&top_versions),
None,
false,
downloads,
None,
),
warnings,
}))
})
Expand Down
42 changes: 29 additions & 13 deletions src/controllers/krate/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,16 @@ pub async fn search(app: AppState, req: Parts) -> AppResult<Json<Value>> {
crate_downloads::downloads,
recent_crate_downloads::downloads.nullable(),
0_f32.into_sql::<Float>(),
versions::num.nullable(),
);

let mut seek: Option<Seek> = None;
let mut query = filter_params
.make_query(&req, conn)?
.inner_join(crate_downloads::table)
.left_join(recent_crate_downloads::table)
.left_join(default_versions::table)
.left_join(versions::table.on(default_versions::version_id.eq(versions::id)))
.select(selection);

if let Some(q_string) = &filter_params.q_string {
Expand All @@ -113,6 +116,7 @@ pub async fn search(app: AppState, req: Parts) -> AppResult<Json<Value>> {
crate_downloads::downloads,
recent_crate_downloads::downloads.nullable(),
rank.clone(),
versions::num.nullable(),
));
seek = Some(Seek::Relevance);
query = query.then_order_by(rank.desc())
Expand All @@ -123,6 +127,7 @@ pub async fn search(app: AppState, req: Parts) -> AppResult<Json<Value>> {
crate_downloads::downloads,
recent_crate_downloads::downloads.nullable(),
0_f32.into_sql::<Float>(),
versions::num.nullable(),
));
seek = Some(Seek::Query);
}
Expand Down Expand Up @@ -225,16 +230,19 @@ pub async fn search(app: AppState, req: Parts) -> AppResult<Json<Value>> {

let crates = versions
.zip(data)
.map(|(max_version, (krate, perfect_match, total, recent, _))| {
EncodableCrate::from_minimal(
krate,
Some(&max_version),
Some(vec![]),
perfect_match,
total,
Some(recent.unwrap_or(0)),
)
})
.map(
|(max_version, (krate, perfect_match, total, recent, _, default_version))| {
EncodableCrate::from_minimal(
krate,
default_version.as_deref(),
Some(&max_version),
Some(vec![]),
perfect_match,
total,
Some(recent.unwrap_or(0)),
)
},
)
.collect::<Vec<_>>();

Ok(Json(json!({
Expand Down Expand Up @@ -614,6 +622,7 @@ mod seek {
downloads,
recent_downloads,
rank,
_,
) = *record;

match *self {
Expand All @@ -636,11 +645,18 @@ mod seek {
}
}

type Record = (Crate, bool, i64, Option<i64>, f32);
type Record = (Crate, bool, i64, Option<i64>, f32, Option<String>);

type QuerySource = LeftJoinQuerySource<
InnerJoinQuerySource<crates::table, crate_downloads::table>,
recent_crate_downloads::table,
LeftJoinQuerySource<
LeftJoinQuerySource<
InnerJoinQuerySource<crates::table, crate_downloads::table>,
recent_crate_downloads::table,
>,
default_versions::table,
>,
versions::table,
diesel::dsl::Eq<default_versions::version_id, versions::id>,
>;

type BoxedCondition<'a> = Box<
Expand Down
18 changes: 15 additions & 3 deletions src/controllers/summary.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::app::AppState;
use crate::models::{Category, Crate, CrateVersions, Keyword, TopVersions, Version};
use crate::schema::{crate_downloads, crates, keywords, metadata, recent_crate_downloads};
use crate::schema::{
crate_downloads, crates, default_versions, keywords, metadata, recent_crate_downloads, versions,
};
use crate::tasks::spawn_blocking;
use crate::util::diesel::Conn;
use crate::util::errors::AppResult;
Expand All @@ -25,7 +27,7 @@ pub async fn summary(state: AppState) -> AppResult<Json<Value>> {

fn encode_crates(
conn: &mut impl Conn,
data: Vec<(Crate, i64, Option<i64>)>,
data: Vec<(Crate, i64, Option<i64>, Option<String>)>,
) -> AppResult<Vec<EncodableCrate>> {
let krates = data.iter().map(|(c, ..)| c).collect::<Vec<_>>();
let versions: Vec<Version> = krates.versions().load(conn)?;
Expand All @@ -34,9 +36,10 @@ pub async fn summary(state: AppState) -> AppResult<Json<Value>> {
.into_iter()
.map(TopVersions::from_versions)
.zip(data)
.map(|(top_versions, (krate, total, recent))| {
.map(|(top_versions, (krate, total, recent, default_version))| {
Ok(EncodableCrate::from_minimal(
krate,
default_version.as_deref(),
Some(&top_versions),
None,
false,
Expand All @@ -51,18 +54,23 @@ pub async fn summary(state: AppState) -> AppResult<Json<Value>> {
Crate::as_select(),
crate_downloads::downloads,
recent_crate_downloads::downloads.nullable(),
versions::num.nullable(),
);

let new_crates = crates::table
.inner_join(crate_downloads::table)
.left_join(recent_crate_downloads::table)
.left_join(default_versions::table)
.left_join(versions::table.on(default_versions::version_id.eq(versions::id)))
.order(crates::created_at.desc())
.select(selection)
.limit(10)
.load(conn)?;
let just_updated = crates::table
.inner_join(crate_downloads::table)
.left_join(recent_crate_downloads::table)
.left_join(default_versions::table)
.left_join(versions::table.on(default_versions::version_id.eq(versions::id)))
.filter(crates::updated_at.ne(crates::created_at))
.order(crates::updated_at.desc())
.select(selection)
Expand All @@ -72,6 +80,8 @@ pub async fn summary(state: AppState) -> AppResult<Json<Value>> {
let mut most_downloaded_query = crates::table
.inner_join(crate_downloads::table)
.left_join(recent_crate_downloads::table)
.left_join(default_versions::table)
.left_join(versions::table.on(default_versions::version_id.eq(versions::id)))
.into_boxed();
if !config.excluded_crate_names.is_empty() {
most_downloaded_query =
Expand All @@ -86,6 +96,8 @@ pub async fn summary(state: AppState) -> AppResult<Json<Value>> {
let mut most_recently_downloaded_query = crates::table
.inner_join(crate_downloads::table)
.inner_join(recent_crate_downloads::table)
.left_join(default_versions::table)
.left_join(versions::table.on(default_versions::version_id.eq(versions::id)))
.into_boxed();
if !config.excluded_crate_names.is_empty() {
most_recently_downloaded_query = most_recently_downloaded_query
Expand Down
31 changes: 31 additions & 0 deletions src/tests/krate/publish/basics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,37 @@ async fn new_krate_twice() {
"###);
}

// This is similar to the `new_krate_twice` case, but the versions are published in reverse order.
// The primary purpose is to verify that the `default_version` we provide is as expected.
#[tokio::test(flavor = "multi_thread")]
async fn new_krate_twice_alt() {
let (app, _, _, token) = TestApp::full().with_token();

let crate_to_publish =
PublishBuilder::new("foo_twice", "2.0.0").description("2.0.0 description");
token.publish_crate(crate_to_publish).await.good();

let crate_to_publish = PublishBuilder::new("foo_twice", "0.99.0");
let response = token.publish_crate(crate_to_publish).await;
assert_eq!(response.status(), StatusCode::OK);
assert_json_snapshot!(response.json(), {
".crate.created_at" => "[datetime]",
".crate.updated_at" => "[datetime]",
});

let crates = app.crates_from_index_head("foo_twice");
assert_json_snapshot!(crates);

assert_snapshot!(app.stored_files().await.join("\n"), @r###"
crates/foo_twice/foo_twice-0.99.0.crate
crates/foo_twice/foo_twice-2.0.0.crate
index/fo/o_/foo_twice
rss/crates.xml
rss/crates/foo_twice.xml
rss/updates.xml
"###);
}

#[tokio::test(flavor = "multi_thread")]
async fn new_krate_duplicate_version() {
let (app, _, user, token) = TestApp::full().with_token();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ expression: response.json()
"badges": null,
"categories": null,
"created_at": "[datetime]",
"default_version": "1.0.0",
"description": "description",
"documentation": null,
"downloads": 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ expression: response.json()
"badges": null,
"categories": null,
"created_at": "[datetime]",
"default_version": "2.0.0",
"description": "2.0.0 description",
"documentation": null,
"downloads": 0,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
source: src/tests/krate/publish/basics.rs
expression: crates
---
[
{
"name": "foo_twice",
"vers": "2.0.0",
"deps": [],
"cksum": "d6e88a7d30b9e5c3d268ede9a9937b62815e45a06fd2c572d602e0705ab6513d",
"features": {},
"yanked": false
},
{
"name": "foo_twice",
"vers": "0.99.0",
"deps": [],
"cksum": "45b0b19cd0280034e07820789d9bb6e4016526eba85c75fc697d49ec99fd2550",
"features": {},
"yanked": false
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
source: src/tests/krate/publish/basics.rs
expression: response.json()
---
{
"crate": {
"badges": null,
"categories": null,
"created_at": "[datetime]",
"default_version": "2.0.0",
"description": "description",
"documentation": null,
"downloads": 0,
"exact_match": false,
"homepage": null,
"id": "foo_twice",
"keywords": null,
"links": {
"owner_team": "/api/v1/crates/foo_twice/owner_team",
"owner_user": "/api/v1/crates/foo_twice/owner_user",
"owners": "/api/v1/crates/foo_twice/owners",
"reverse_dependencies": "/api/v1/crates/foo_twice/reverse_dependencies",
"version_downloads": "/api/v1/crates/foo_twice/downloads",
"versions": "/api/v1/crates/foo_twice/versions"
},
"max_stable_version": "2.0.0",
"max_version": "2.0.0",
"name": "foo_twice",
"newest_version": "0.99.0",
"recent_downloads": null,
"repository": null,
"updated_at": "[datetime]",
"versions": null
},
"warnings": {
"invalid_badges": [],
"invalid_categories": [],
"other": []
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ expression: response.json()
"badges": null,
"categories": null,
"created_at": "[datetime]",
"default_version": "0.0.0-pre",
"description": "description",
"documentation": null,
"downloads": 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ expression: response.json()
"badges": null,
"categories": null,
"created_at": "[datetime]",
"default_version": "1.0.0",
"description": "description",
"documentation": null,
"downloads": 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ expression: response.json()
"badges": null,
"categories": null,
"created_at": "[datetime]",
"default_version": "1.0.0+foo",
"description": "description",
"documentation": null,
"downloads": 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ expression: response.json()
"badges": null,
"categories": null,
"created_at": "[datetime]",
"default_version": "1.0.0-beta.1",
"description": "description",
"documentation": null,
"downloads": 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ expression: response.json()
"badges": null,
"categories": null,
"created_at": "[datetime]",
"default_version": "1.0.0+foo",
"description": "description",
"documentation": null,
"downloads": 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ expression: response.json()
"badges": null,
"categories": null,
"created_at": "[datetime]",
"default_version": "1.0.0",
"description": "description",
"documentation": null,
"downloads": 0,
Expand Down
Loading