Skip to content

Return downloads for the top 5 most downloaded versions #9696

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

Closed
wants to merge 2 commits into from
Closed
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/downloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use axum::Json;
use diesel::prelude::*;
use diesel_async::RunQueryDsl;
use serde_json::Value;
use std::cmp;

/// Handles the `GET /crates/:crate_id/downloads` route.
pub async fn downloads(state: AppState, Path(crate_name): Path<String>) -> AppResult<Json<Value>> {
Expand All @@ -30,15 +29,24 @@ pub async fn downloads(state: AppState, Path(crate_name): Path<String>) -> AppRe
.optional()?
.ok_or_else(|| crate_not_found(&crate_name))?;

let mut versions: Vec<Version> = versions::table
let versions: Vec<Version> = versions::table
.filter(versions::crate_id.eq(crate_id))
.load(&mut conn)
.await?;

versions.sort_by_cached_key(|version| cmp::Reverse(semver::Version::parse(&version.num).ok()));
let (latest_five, rest) = versions.split_at(cmp::min(5, versions.len()));
let top_downloaded_versions: Vec<i32> = VersionDownload::belonging_to(&versions)
.filter(version_downloads::date.gt(date(now - 90.days())))
.group_by(version_downloads::version_id)
.select(version_downloads::version_id)
.order(sum(version_downloads::downloads).desc())
.limit(5)
.load(&mut conn)
.await?;
let (top_five, rest): (Vec<_>, Vec<_>) = versions
.iter()
.partition(|v| top_downloaded_versions.contains(&v.id));

let downloads = VersionDownload::belonging_to(latest_five)
let downloads = VersionDownload::belonging_to(&top_five)
.filter(version_downloads::date.gt(date(now - 90.days())))
.order((
version_downloads::date.asc(),
Expand All @@ -51,7 +59,7 @@ pub async fn downloads(state: AppState, Path(crate_name): Path<String>) -> AppRe
.collect::<Vec<EncodableVersionDownload>>();

let sum_downloads = sql::<BigInt>("SUM(version_downloads.downloads)");
let extra: Vec<ExtraDownload> = VersionDownload::belonging_to(rest)
let extra: Vec<ExtraDownload> = VersionDownload::belonging_to(&rest)
.select((
to_char(version_downloads::date, "YYYY-MM-DD"),
sum_downloads,
Expand Down