feat(stats): publish per-package download statistics (#253)
Some checks failed
ci/crow/cron/auto-apply-patches Pipeline failed
ci/crow/cron/weekly-audit-missing/2 Pipeline was successful
ci/crow/cron/weekly-audit-missing/1 Pipeline was successful
ci/crow/cron/weekly-audit-missing/4 Pipeline was successful
ci/crow/cron/weekly-audit-missing/5 Pipeline was successful
ci/crow/cron/weekly-audit-missing/6 Pipeline was successful
ci/crow/cron/weekly-audit-missing/7 Pipeline was successful
ci/crow/cron/weekly-audit-missing/8 Pipeline was successful
ci/crow/cron/weekly-audit-missing/9 Pipeline was successful
ci/crow/cron/weekly-audit-missing/10 Pipeline was successful
ci/crow/cron/weekly-audit-missing/3 Pipeline was successful
ci/crow/cron/weekly-audit-missing/11 Pipeline was successful
ci/crow/cron/weekly-audit-missing/12 Pipeline was successful
ci/crow/cron/weekly-audit-missing/13 Pipeline was successful
ci/crow/cron/weekly-audit-missing/14 Pipeline was successful
ci/crow/cron/trial-build-registry/10 Pipeline was successful
ci/crow/cron/trial-build-registry/6 Pipeline was successful
ci/crow/cron/trial-build-registry/8 Pipeline was successful
ci/crow/cron/trial-build-registry/14 Pipeline was successful
ci/crow/cron/trial-build-registry/2 Pipeline was successful
ci/crow/cron/trial-build-registry/12 Pipeline was successful
ci/crow/cron/trial-build-registry/16 Pipeline failed
ci/crow/cron/trial-build-registry/4 Pipeline failed
ci/crow/cron/trial-build-registry/1 Pipeline was successful
ci/crow/cron/trial-build-registry/3 Pipeline was successful
ci/crow/cron/trial-build-registry/5 Pipeline was successful
ci/crow/cron/trial-build-registry/7 Pipeline was successful
ci/crow/cron/trial-build-registry/9 Pipeline was successful
ci/crow/cron/trial-build-registry/11 Pipeline was successful
ci/crow/cron/trial-build-registry/13 Pipeline was successful
ci/crow/cron/trial-build-registry/15 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/17 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/13 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/18 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/3 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/16 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/6 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/2 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/6 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/23 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/24 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/5 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/15 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/4 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/22 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/14 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/8 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/2 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/5 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/19 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/30 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/20 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/1 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/28 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/29 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/10 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/1 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/36 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/21 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/34 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/35 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/7 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/12 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/25 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/26 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/27 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/41 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/9 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/40 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/42 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/14 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/31 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/32 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/33 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/11 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/37 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/38 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/39 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/13 Pipeline was successful
ci/crow/cron/process-updates/2 Pipeline was successful
ci/crow/cron/process-updates/8 Pipeline was successful
ci/crow/cron/process-updates/11 Pipeline was successful
ci/crow/cron/process-updates/12 Pipeline was successful
ci/crow/cron/process-updates/16 Pipeline was successful
ci/crow/cron/process-updates/9 Pipeline was successful
ci/crow/cron/process-updates/13 Pipeline was successful
ci/crow/cron/process-updates/10 Pipeline was successful
ci/crow/cron/process-updates/15 Pipeline was successful
ci/crow/cron/process-updates/14 Pipeline was successful
ci/crow/cron/process-updates/4 Pipeline was successful
ci/crow/cron/process-updates/3 Pipeline was successful
ci/crow/cron/process-updates/5 Pipeline was successful
ci/crow/cron/process-updates/6 Pipeline was successful
ci/crow/cron/download-stats Pipeline was successful
ci/crow/cron/process-updates/7 Pipeline was successful
ci/crow/cron/process-updates/1 Pipeline was successful
Some checks failed
ci/crow/cron/auto-apply-patches Pipeline failed
ci/crow/cron/weekly-audit-missing/2 Pipeline was successful
ci/crow/cron/weekly-audit-missing/1 Pipeline was successful
ci/crow/cron/weekly-audit-missing/4 Pipeline was successful
ci/crow/cron/weekly-audit-missing/5 Pipeline was successful
ci/crow/cron/weekly-audit-missing/6 Pipeline was successful
ci/crow/cron/weekly-audit-missing/7 Pipeline was successful
ci/crow/cron/weekly-audit-missing/8 Pipeline was successful
ci/crow/cron/weekly-audit-missing/9 Pipeline was successful
ci/crow/cron/weekly-audit-missing/10 Pipeline was successful
ci/crow/cron/weekly-audit-missing/3 Pipeline was successful
ci/crow/cron/weekly-audit-missing/11 Pipeline was successful
ci/crow/cron/weekly-audit-missing/12 Pipeline was successful
ci/crow/cron/weekly-audit-missing/13 Pipeline was successful
ci/crow/cron/weekly-audit-missing/14 Pipeline was successful
ci/crow/cron/trial-build-registry/10 Pipeline was successful
ci/crow/cron/trial-build-registry/6 Pipeline was successful
ci/crow/cron/trial-build-registry/8 Pipeline was successful
ci/crow/cron/trial-build-registry/14 Pipeline was successful
ci/crow/cron/trial-build-registry/2 Pipeline was successful
ci/crow/cron/trial-build-registry/12 Pipeline was successful
ci/crow/cron/trial-build-registry/16 Pipeline failed
ci/crow/cron/trial-build-registry/4 Pipeline failed
ci/crow/cron/trial-build-registry/1 Pipeline was successful
ci/crow/cron/trial-build-registry/3 Pipeline was successful
ci/crow/cron/trial-build-registry/5 Pipeline was successful
ci/crow/cron/trial-build-registry/7 Pipeline was successful
ci/crow/cron/trial-build-registry/9 Pipeline was successful
ci/crow/cron/trial-build-registry/11 Pipeline was successful
ci/crow/cron/trial-build-registry/13 Pipeline was successful
ci/crow/cron/trial-build-registry/15 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/17 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/13 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/18 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/3 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/16 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/6 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/2 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/6 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/23 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/24 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/5 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/15 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/4 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/22 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/14 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/8 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/2 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/5 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/19 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/30 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/20 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/1 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/28 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/29 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/10 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/1 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/36 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/21 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/34 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/35 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/7 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/12 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/25 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/26 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/27 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/41 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/9 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/40 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/42 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/14 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/31 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/32 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/33 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/11 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/37 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/38 Pipeline was successful
ci/crow/cron/weekly-rebuild-missing/39 Pipeline was successful
ci/crow/cron/weekly-rebuild-reindex/13 Pipeline was successful
ci/crow/cron/process-updates/2 Pipeline was successful
ci/crow/cron/process-updates/8 Pipeline was successful
ci/crow/cron/process-updates/11 Pipeline was successful
ci/crow/cron/process-updates/12 Pipeline was successful
ci/crow/cron/process-updates/16 Pipeline was successful
ci/crow/cron/process-updates/9 Pipeline was successful
ci/crow/cron/process-updates/13 Pipeline was successful
ci/crow/cron/process-updates/10 Pipeline was successful
ci/crow/cron/process-updates/15 Pipeline was successful
ci/crow/cron/process-updates/14 Pipeline was successful
ci/crow/cron/process-updates/4 Pipeline was successful
ci/crow/cron/process-updates/3 Pipeline was successful
ci/crow/cron/process-updates/5 Pipeline was successful
ci/crow/cron/process-updates/6 Pipeline was successful
ci/crow/cron/download-stats Pipeline was successful
ci/crow/cron/process-updates/7 Pipeline was successful
ci/crow/cron/process-updates/1 Pipeline was successful
Adds the data for the package view of the rpkgs.com download dashboard (rpkgs/website#98). - `stats/packages.ts` writes `stats/packages/<name>.json` per package: daily downloads and clients, latest version, 30-day rank, and versions, distributions, R versions and architectures for 7 days, 30 days and all time. - `downloads.json` gains `packages` and `bytes` per window and `breakdownsByWindow`; `breakdowns` stays as the 30-day set, so the current page keeps working. - Package files are uploaded before the main file and purged with one wildcard purge (`/stats/packages/*`, checked against the Bunny API). Same counting rules as before: own runners excluded, a download is a distinct client, package version and UTC day. ## Verification - `bun test stats`: 16 tests pass, including version ordering. - `publish.ts --out` against the live database wrote the main file and 106 package files; `cli` matches a direct SQL count (5 downloads, 2 clients, 3.6.6). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Reviewed-on: #253
This commit is contained in:
parent
72440f9cf5
commit
fa1e8e8428
4 changed files with 230 additions and 29 deletions
|
|
@ -8,6 +8,7 @@ The `download-stats` pipeline runs it every hour.
|
|||
1. `collect.ts` reads the last 70 hours of access logs from the Bunny Logging API v2 and inserts each request into `download_stats.events` in the build metadata database.
|
||||
2. `classify.ts` derives what each request was (package download, index fetch, redirect, probe, noise) from its path, status and User-Agent.
|
||||
3. `publish.ts` aggregates the events into `stats/downloads.json` in the binaries bucket and purges its CDN copy, so it is served at <https://cran.rpkgs.com/stats/downloads.json>.
|
||||
4. `packages.ts` writes one file per package, `stats/packages/<name>.json`, with its daily series and its versions, distributions, R versions and architectures for each window. The dashboard fetches one only when that package is opened, so the main file does not grow with the number of packages.
|
||||
|
||||
Bunny keeps access logs for three days.
|
||||
Each hourly run re-reads almost all of that window, and events are keyed by Bunny's request id, so re-reading never double counts and up to two days of failed runs lose nothing.
|
||||
|
|
|
|||
8
stats/packages.test.ts
Normal file
8
stats/packages.test.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { compareVersions } from './packages';
|
||||
|
||||
test('versions order numerically, not as text', () => {
|
||||
expect(['1.10.0', '1.9.2', '1.2-3', '1.2-10'].sort(compareVersions)).toEqual(['1.2-3', '1.2-10', '1.9.2', '1.10.0']);
|
||||
expect(compareVersions('3.6.6', '3.6.6')).toBe(0);
|
||||
expect(compareVersions('1.0', '1.0.1')).toBeLessThan(0);
|
||||
});
|
||||
139
stats/packages.ts
Normal file
139
stats/packages.ts
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
/**
|
||||
* Per-package statistics, one file per package at `stats/packages/<name>.json`.
|
||||
*
|
||||
* Kept out of `downloads.json` so the main file stays small however many
|
||||
* packages are served: the dashboard only fetches a package's file when that
|
||||
* package is opened.
|
||||
*
|
||||
* The same rules as the repository numbers apply: our own runners are left out,
|
||||
* and a download is a distinct (client, package, version) on one UTC day.
|
||||
*/
|
||||
import type { SQL } from 'bun';
|
||||
import type { Breakdown } from './publish';
|
||||
|
||||
export interface PackageWindow {
|
||||
downloads: number;
|
||||
clients: number;
|
||||
versions: Breakdown[];
|
||||
os: Breakdown[];
|
||||
rMinor: Breakdown[];
|
||||
arch: Breakdown[];
|
||||
}
|
||||
|
||||
export interface PackageFile {
|
||||
schema: 1;
|
||||
name: string;
|
||||
generatedAt: string;
|
||||
/** Highest version seen downloaded, by `numeric_version` ordering. */
|
||||
latestVersion: string | null;
|
||||
/** Position by downloads in the last 30 days, 1-based; null without downloads in that window. */
|
||||
rank30d: number | null;
|
||||
firstDay: string | null;
|
||||
daily: { date: string; downloads: number; clients: number }[];
|
||||
windows: { last7: PackageWindow; last30: PackageWindow; all: PackageWindow };
|
||||
}
|
||||
|
||||
const WINDOWS = { last7: 7, last30: 30, all: null } as const;
|
||||
|
||||
type Dimension = 'versions' | 'os' | 'rMinor' | 'arch';
|
||||
|
||||
export function compareVersions(a: string, b: string): number {
|
||||
const pa = a.split(/[.-]/).map(Number);
|
||||
const pb = b.split(/[.-]/).map(Number);
|
||||
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
||||
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
|
||||
if (d !== 0) return d;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const emptyWindow = (): PackageWindow => ({ downloads: 0, clients: 0, versions: [], os: [], rMinor: [], arch: [] });
|
||||
|
||||
export async function buildPackageFiles(sql: SQL, generatedAt: string): Promise<PackageFile[]> {
|
||||
const files = new Map<string, PackageFile>();
|
||||
const file = (name: string): PackageFile => {
|
||||
let f = files.get(name);
|
||||
if (!f) {
|
||||
f = {
|
||||
schema: 1,
|
||||
name,
|
||||
generatedAt,
|
||||
latestVersion: null,
|
||||
rank30d: null,
|
||||
firstDay: null,
|
||||
daily: [],
|
||||
windows: { last7: emptyWindow(), last30: emptyWindow(), all: emptyWindow() },
|
||||
};
|
||||
files.set(name, f);
|
||||
}
|
||||
return f;
|
||||
};
|
||||
|
||||
const daily: { package: string; date: string; downloads: number; clients: number }[] = await sql`
|
||||
with dl as (
|
||||
select distinct client, package, version, os, r_minor, arch, (ts at time zone 'UTC')::date as day
|
||||
from download_stats.events
|
||||
where network <> 'own' and outcome = 'served' and kind = 'download' and package is not null
|
||||
)
|
||||
select package, day::text as date, count(distinct (client, version))::int as downloads,
|
||||
count(distinct client)::int as clients
|
||||
from dl group by package, day order by package, day`;
|
||||
for (const row of daily) {
|
||||
const f = file(row.package);
|
||||
f.daily.push({ date: row.date, downloads: row.downloads, clients: row.clients });
|
||||
f.firstDay ??= row.date;
|
||||
}
|
||||
|
||||
for (const [windowId, days] of Object.entries(WINDOWS) as [keyof typeof WINDOWS, number | null][]) {
|
||||
const since = days === null ? new Date(0) : new Date(Date.now() - days * 86400000);
|
||||
const rows: {
|
||||
package: string;
|
||||
dimension: Dimension | null;
|
||||
key: string | null;
|
||||
downloads: number;
|
||||
clients: number;
|
||||
}[] = await sql`
|
||||
with dl as (
|
||||
select distinct client, package, version, os, r_minor, arch, (ts at time zone 'UTC')::date as day
|
||||
from download_stats.events
|
||||
where network <> 'own' and outcome = 'served' and kind = 'download' and package is not null
|
||||
and ts >= ${since}
|
||||
)
|
||||
select package,
|
||||
case
|
||||
when grouping(version) = 0 then 'versions'
|
||||
when grouping(os) = 0 then 'os'
|
||||
when grouping(r_minor) = 0 then 'rMinor'
|
||||
when grouping(arch) = 0 then 'arch'
|
||||
end as dimension,
|
||||
coalesce(version, os, r_minor, arch) as key,
|
||||
count(distinct (client, version, day))::int as downloads,
|
||||
count(distinct client)::int as clients
|
||||
from dl
|
||||
group by package, grouping sets ((), (version), (os), (r_minor), (arch))`;
|
||||
for (const row of rows) {
|
||||
const w = file(row.package).windows[windowId];
|
||||
if (row.dimension === null) {
|
||||
w.downloads = row.downloads;
|
||||
w.clients = row.clients;
|
||||
} else {
|
||||
w[row.dimension].push({ key: row.key ?? 'unknown', clients: row.clients, downloads: row.downloads });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ranked = [...files.values()]
|
||||
.filter((f) => f.windows.last30.downloads > 0)
|
||||
.sort((a, b) => b.windows.last30.downloads - a.windows.last30.downloads || a.name.localeCompare(b.name));
|
||||
ranked.forEach((f, i) => (f.rank30d = i + 1));
|
||||
|
||||
for (const f of files.values()) {
|
||||
const versions = f.windows.all.versions.map((v) => v.key).filter((v) => v !== 'unknown');
|
||||
f.latestVersion = versions.sort(compareVersions).at(-1) ?? null;
|
||||
for (const w of Object.values(f.windows)) {
|
||||
w.versions.sort((a, b) => compareVersions(b.key, a.key));
|
||||
for (const dim of ['os', 'rMinor', 'arch'] as const) w[dim].sort((a, b) => b.clients - a.clients);
|
||||
}
|
||||
}
|
||||
return [...files.values()];
|
||||
}
|
||||
111
stats/publish.ts
111
stats/publish.ts
|
|
@ -15,10 +15,12 @@
|
|||
import { S3Client, type SQL } from 'bun';
|
||||
import { KNOWN_MINORS, RULESET } from './classify';
|
||||
import { connect, migrate } from './db';
|
||||
import { buildPackageFiles, type PackageFile } from './packages';
|
||||
|
||||
const MIN_CLIENTS = 3;
|
||||
const PUBLIC_URL = 'https://cran.rpkgs.com/stats/downloads.json';
|
||||
const OBJECT_KEY = 'stats/downloads.json';
|
||||
const PACKAGES_PREFIX = 'stats/packages/';
|
||||
|
||||
/** Split of a count by network class. */
|
||||
export interface Split {
|
||||
|
|
@ -49,6 +51,19 @@ export interface WindowStats {
|
|||
clients: Split;
|
||||
/** Sum of daily distinct clients: roughly, install sessions. */
|
||||
clientDays: Split;
|
||||
/** Distinct packages with at least one download. */
|
||||
packages: number;
|
||||
/** Bytes served for packages and indexes. */
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface Breakdowns {
|
||||
network: Breakdown[];
|
||||
os: Breakdown[];
|
||||
arch: Breakdown[];
|
||||
rMinor: Breakdown[];
|
||||
tool: Breakdown[];
|
||||
country: Breakdown[];
|
||||
}
|
||||
|
||||
export interface Breakdown {
|
||||
|
|
@ -59,9 +74,12 @@ export interface Breakdown {
|
|||
|
||||
export interface PackageStats {
|
||||
name: string;
|
||||
downloads7d: number;
|
||||
clients7d: number;
|
||||
downloads30d: number;
|
||||
clients30d: number;
|
||||
downloadsAll: number;
|
||||
clientsAll: number;
|
||||
}
|
||||
|
||||
export interface PublicStats {
|
||||
|
|
@ -76,14 +94,9 @@ export interface PublicStats {
|
|||
/** Distribution of distinct packages fetched per client per day (30 days). */
|
||||
packagesPerClientDay: { median: number; p90: number };
|
||||
/** Last 30 days. */
|
||||
breakdowns: {
|
||||
network: Breakdown[];
|
||||
os: Breakdown[];
|
||||
arch: Breakdown[];
|
||||
rMinor: Breakdown[];
|
||||
tool: Breakdown[];
|
||||
country: Breakdown[];
|
||||
};
|
||||
breakdowns: Breakdowns;
|
||||
/** The same breakdowns for every window; `breakdowns` is `last30`, kept for older readers. */
|
||||
breakdownsByWindow: { last7: Breakdowns; last30: Breakdowns; all: Breakdowns };
|
||||
/** Last 30 days: clients we sent elsewhere, and why. */
|
||||
redirects: { reason: string; clients: number; requests: number }[];
|
||||
unsupportedMinors: Breakdown[];
|
||||
|
|
@ -141,6 +154,9 @@ async function windowStats(sql: SQL, days: number | null): Promise<WindowStats>
|
|||
(select count(*) from cd) as client_days_total,
|
||||
(select count(*) from cd where network = 'cloud') as client_days_cloud,
|
||||
(select count(*) from cd where network = 'other') as client_days_other,
|
||||
(select count(distinct package) from dl) as packages,
|
||||
(select coalesce(sum(bytes), 0) from download_stats.events
|
||||
where network <> 'own' and outcome = 'served' and kind in ('download', 'index') and ts >= ${since}) as bytes,
|
||||
(select min(day) from ev) as first_day`;
|
||||
const firstDay = row.first_day ? new Date(row.first_day) : null;
|
||||
const span = firstDay ? Math.max(1, Math.ceil((Date.now() - firstDay.getTime()) / 86400000)) : 0;
|
||||
|
|
@ -149,6 +165,8 @@ async function windowStats(sql: SQL, days: number | null): Promise<WindowStats>
|
|||
downloads: split(row, 'downloads'),
|
||||
clients: split(row, 'clients'),
|
||||
clientDays: split(row, 'client_days'),
|
||||
packages: Number(row.packages),
|
||||
bytes: Number(row.bytes),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -181,8 +199,24 @@ function suppress(rows: Breakdown[]): Breakdown[] {
|
|||
];
|
||||
}
|
||||
|
||||
async function breakdowns(sql: SQL, since: Date): Promise<Breakdowns> {
|
||||
return {
|
||||
network: await breakdown(sql, 'network', since),
|
||||
os: await breakdown(sql, 'os', since),
|
||||
arch: await breakdown(sql, 'arch', since),
|
||||
rMinor: await breakdown(sql, 'r_minor', since),
|
||||
tool: await breakdown(sql, 'tool', since),
|
||||
country: suppress(await breakdown(sql, 'country', since)),
|
||||
};
|
||||
}
|
||||
|
||||
export async function buildStats(sql: SQL): Promise<PublicStats> {
|
||||
const since30 = new Date(Date.now() - 30 * 86400000);
|
||||
const byWindow = {
|
||||
last7: await breakdowns(sql, new Date(Date.now() - 7 * 86400000)),
|
||||
last30: await breakdowns(sql, since30),
|
||||
all: await breakdowns(sql, new Date(0)),
|
||||
};
|
||||
const covered = await coverage(sql);
|
||||
|
||||
const dailyRows: Record<string, unknown>[] = await sql`
|
||||
|
|
@ -250,20 +284,27 @@ export async function buildStats(sql: SQL): Promise<PublicStats> {
|
|||
const packages: PackageStats[] = (
|
||||
await sql`
|
||||
with dl as (
|
||||
select distinct client, package, version, (ts at time zone 'UTC')::date as day, ts >= ${since30} as recent
|
||||
select distinct client, package, version, (ts at time zone 'UTC')::date as day, ts >= ${since30} as recent,
|
||||
ts >= ${new Date(Date.now() - 7 * 86400000)} as week
|
||||
from download_stats.events
|
||||
where network <> 'own' and outcome = 'served' and kind = 'download' and package is not null
|
||||
)
|
||||
select package as name,
|
||||
count(*) filter (where recent)::int as downloads30d,
|
||||
count(distinct (client, version, day)) filter (where week)::int as downloads7d,
|
||||
count(distinct client) filter (where week)::int as clients7d,
|
||||
count(distinct (client, version, day)) filter (where recent)::int as downloads30d,
|
||||
count(distinct client) filter (where recent)::int as clients30d,
|
||||
count(*)::int as downloadsall
|
||||
count(distinct (client, version, day))::int as downloadsall,
|
||||
count(distinct client)::int as clientsall
|
||||
from dl group by package order by downloads30d desc, downloadsall desc, name`
|
||||
).map((row: Record<string, unknown>) => ({
|
||||
name: String(row.name),
|
||||
downloads7d: Number(row.downloads7d),
|
||||
clients7d: Number(row.clients7d),
|
||||
downloads30d: Number(row.downloads30d),
|
||||
clients30d: Number(row.clients30d),
|
||||
downloadsAll: Number(row.downloadsall),
|
||||
clientsAll: Number(row.clientsall),
|
||||
}));
|
||||
|
||||
return {
|
||||
|
|
@ -280,14 +321,8 @@ export async function buildStats(sql: SQL): Promise<PublicStats> {
|
|||
all: await windowStats(sql, null),
|
||||
},
|
||||
packagesPerClientDay: { median: Number(perSession.median), p90: Number(perSession.p90) },
|
||||
breakdowns: {
|
||||
network: await breakdown(sql, 'network', since30),
|
||||
os: await breakdown(sql, 'os', since30),
|
||||
arch: await breakdown(sql, 'arch', since30),
|
||||
rMinor: await breakdown(sql, 'r_minor', since30),
|
||||
tool: await breakdown(sql, 'tool', since30),
|
||||
country: suppress(await breakdown(sql, 'country', since30)),
|
||||
},
|
||||
breakdowns: byWindow.last30,
|
||||
breakdownsByWindow: byWindow,
|
||||
redirects,
|
||||
unsupportedMinors,
|
||||
excluded: {
|
||||
|
|
@ -300,7 +335,15 @@ export async function buildStats(sql: SQL): Promise<PublicStats> {
|
|||
};
|
||||
}
|
||||
|
||||
async function upload(body: string): Promise<void> {
|
||||
async function purge(url: string): Promise<void> {
|
||||
const target = new URL('https://api.bunny.net/purge');
|
||||
target.searchParams.set('url', url);
|
||||
target.searchParams.set('async', 'false');
|
||||
const response = await fetch(target, { method: 'POST', headers: { AccessKey: process.env.BUNNYNET_API_KEY ?? '' } });
|
||||
if (!response.ok) throw new Error(`purging ${url} failed with ${response.status}: ${await response.text()}`);
|
||||
}
|
||||
|
||||
async function upload(body: string, packages: PackageFile[]): Promise<void> {
|
||||
const s3 = new S3Client({
|
||||
accessKeyId: process.env.B2_S3_ACCESS_KEY,
|
||||
secretAccessKey: process.env.B2_S3_SECRET_KEY,
|
||||
|
|
@ -308,30 +351,40 @@ async function upload(body: string): Promise<void> {
|
|||
endpoint: 'https://s3.eu-central-003.backblazeb2.com',
|
||||
region: 'eu-central-003',
|
||||
});
|
||||
// Package files first, so the main file never lists a package whose own
|
||||
// file is not there yet.
|
||||
for (let i = 0; i < packages.length; i += 10) {
|
||||
await Promise.all(
|
||||
packages
|
||||
.slice(i, i + 10)
|
||||
.map((p) => s3.write(`${PACKAGES_PREFIX}${p.name}.json`, JSON.stringify(p), { type: 'application/json' })),
|
||||
);
|
||||
}
|
||||
await s3.write(OBJECT_KEY, body, { type: 'application/json' });
|
||||
|
||||
// The pull zone overrides origin caching with a one-year TTL, so the edge
|
||||
// copy has to be purged for the new file to show up.
|
||||
const purge = new URL('https://api.bunny.net/purge');
|
||||
purge.searchParams.set('url', PUBLIC_URL);
|
||||
purge.searchParams.set('async', 'false');
|
||||
const response = await fetch(purge, { method: 'POST', headers: { AccessKey: process.env.BUNNYNET_API_KEY ?? '' } });
|
||||
if (!response.ok) throw new Error(`purging ${PUBLIC_URL} failed with ${response.status}: ${await response.text()}`);
|
||||
// copies have to be purged for the new files to show up.
|
||||
await purge(`https://cran.rpkgs.com/${PACKAGES_PREFIX}*`);
|
||||
await purge(PUBLIC_URL);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
const sql = connect();
|
||||
await migrate(sql);
|
||||
const stats = await buildStats(sql);
|
||||
const packages = await buildPackageFiles(sql, stats.generatedAt);
|
||||
await sql.close();
|
||||
const body = JSON.stringify(stats);
|
||||
|
||||
const outIndex = process.argv.indexOf('--out');
|
||||
if (outIndex !== -1) {
|
||||
await Bun.write(process.argv[outIndex + 1], JSON.stringify(stats, null, 2));
|
||||
console.log(`wrote ${process.argv[outIndex + 1]} (${body.length} bytes)`);
|
||||
const out = process.argv[outIndex + 1];
|
||||
await Bun.write(out, JSON.stringify(stats, null, 2));
|
||||
const dir = `${out.replace(/[^/]*$/, '')}packages`;
|
||||
for (const p of packages) await Bun.write(`${dir}/${p.name}.json`, JSON.stringify(p, null, 2));
|
||||
console.log(`wrote ${out} (${body.length} bytes) and ${packages.length} files in ${dir}`);
|
||||
} else {
|
||||
await upload(body);
|
||||
await upload(body, packages);
|
||||
console.log(
|
||||
`published ${PUBLIC_URL} (${body.length} bytes, ${stats.daily.length} days, ${stats.packages.length} packages)`,
|
||||
);
|
||||
|
|
|
|||
Loading…
Reference in a new issue