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
4 changed files with 217 additions and 26 deletions

View file

@ -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
View 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
View 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()];
}

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)`,
);