devxy/build-cran-binaries
Watch
1
0
Fork
You've already forked build-cran-binaries
0

feat(stats): publish per-package download statistics

Write one JSON file per package to stats/packages/<name>.json with its
daily series and its versions, distributions, R versions and
architectures for 7 days, 30 days and all time, for the package view
of the rpkgs.com dashboard.

- Add distinct package and byte counts to each window in downloads.json.
- Add breakdowns for every window as breakdownsByWindow, keeping
  breakdowns as the 30-day set for existing readers.
- Upload package files before the main file and purge them with one
  wildcard purge.
This commit is contained in:
Patrick Schratz 2026-11-14 13:29:58 +01:00
commit 06afded1fe

View file

@ -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 {
@ -76,14 +91,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 +151,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 +162,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 +196,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`
@ -280,14 +311,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 +325,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 +341,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)`,
);