Skip to content
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
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ dry run first, then sent to BigQuery as `maximumBytesBilled`, so BigQuery refuse
would bill more; such a refusal bills nothing and ends the run with status `refused_cap`) and
768 GiB per calendar month (a ledger in `data/pypi-country-budget.json`).
The month-to-date figure is never lower than the bytes the database's fetch records show billed
that month, so a checkout without the ledger file still counts the month's earlier queries.
that month, so a checkout without the ledger file still counts the days landed earlier that month.
Without the ledger file it does not count a billed query that failed, since only the ledger
records that charge.

To see what the next run would scan before paying for it:

Expand All @@ -116,10 +118,14 @@ This issues only BigQuery dry runs, which are not billed, prints each day's scan
both caps, and writes nothing. It exits 0 only when the next run would clear both caps. When
every day in the window is already fetched, the next run bills nothing; the dry run then
measures yesterday as a sample and reports whether a new day of that size would clear both caps.
`npm run collect:pypi-countries --dry-run` (without the `--`) is also a dry run. Any other
argument after the `--` is refused with a usage message and exit code 2. A flag given without
the `--` goes to npm, not to the collector's arguments, so a mistyped
`npm run collect:pypi-countries --dryrun` is not refused: the run collects as normal.
`npm run collect:pypi-countries --dry-run` (without the `--`) is also a dry run, and
`npm run collect:pypi-countries -- --help` prints the usage and exits 0. Any other argument after
the `--` is refused with a usage message and exit code 2. A flag given without the `--` goes to
npm, which passes it on as an `npm_config_` variable rather than as an argument; one that looks
like a mistyped `--dry-run`, such as `npm run collect:pypi-countries --dryrun`, is refused the
same way before anything runs. Any other flag given without the `--` is left to npm, and the
run collects as normal. npm 11 warns that the next major version of npm will stop accepting unknown
flags, which would change how these arrive.

## Automated daily collection

Expand Down
37 changes: 37 additions & 0 deletions lib/cron.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* What the cron route (pages/api/cron/collect.js) runs, and the environment it
* hands each collector, kept apart from the handler so both can be tested.
*/

const CRON_COLLECTORS = [
{ name: 'github', script: 'collect-stats.js', needsToken: true },
{ name: 'npm', script: 'collect-npm-stats.js', needsToken: false },
{ name: 'pypi', script: 'collect-pypi-stats.js', needsToken: false },
{ name: 'docker', script: 'collect-docker-stats.js', needsToken: false },
{ name: 'huggingface', script: 'collect-huggingface-stats.js', needsToken: false },
{ name: 'telemetry', script: 'collect-telemetry-stats.js', needsToken: false },
];

// Pass only the variables the collectors actually need to the child processes,
// rather than spreading the entire environment (which would leak unrelated
// secrets into every subprocess). Add new collector config keys here. No
// Google Cloud credentials: only the BigQuery country collector reads them,
// and the route does not run it.
const COLLECTOR_ENV_KEYS = [
'PATH', 'NODE_ENV', 'HOME',
'GITHUB_TOKEN', 'GITHUB_ORG', 'REPOS_TO_TRACK',
'NPM_AUTHOR', 'NPM_PACKAGES',
'PYPI_PACKAGES',
'DOCKER_IMAGES',
'HF_AUTHOR', 'HF_MODELS', 'HF_TOKEN',
'REGISTRY_URL',
];

/** The allowlisted subset of `env` that a collector child process receives. */
function collectorEnv(env = process.env) {
return Object.fromEntries(
COLLECTOR_ENV_KEYS.filter(k => env[k] !== undefined).map(k => [k, env[k]])
);
}

module.exports = { CRON_COLLECTORS, COLLECTOR_ENV_KEYS, collectorEnv };
29 changes: 3 additions & 26 deletions pages/api/cron/collect.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { execSync } = require('child_process');
const path = require('path');
const { CRON_COLLECTORS, collectorEnv } = require('../../../lib/cron');

export default async function handler(req, res) {
const authHeader = req.headers.authorization;
Expand All @@ -10,33 +11,9 @@ export default async function handler(req, res) {
const results = { timestamp: new Date().toISOString(), collectors: {} };
const scriptsDir = path.join(process.cwd(), 'scripts');

// Pass only the variables the collectors actually need to the child processes,
// rather than spreading the entire environment (which would leak unrelated
// secrets into every subprocess). Add new collector config keys here.
const ALLOWED_ENV = [
'PATH', 'NODE_ENV', 'HOME',
'GITHUB_TOKEN', 'GITHUB_ORG', 'REPOS_TO_TRACK',
'NPM_AUTHOR', 'NPM_PACKAGES',
'PYPI_PACKAGES',
'DOCKER_IMAGES',
'HF_AUTHOR', 'HF_MODELS', 'HF_TOKEN',
'GOOGLE_APPLICATION_CREDENTIALS', 'GOOGLE_APPLICATION_CREDENTIALS_JSON',
'REGISTRY_URL',
];
const childEnv = Object.fromEntries(
ALLOWED_ENV.filter(k => process.env[k] !== undefined).map(k => [k, process.env[k]])
);
const childEnv = collectorEnv();

const collectors = [
{ name: 'github', script: 'collect-stats.js', needsToken: true },
{ name: 'npm', script: 'collect-npm-stats.js', needsToken: false },
{ name: 'pypi', script: 'collect-pypi-stats.js', needsToken: false },
{ name: 'docker', script: 'collect-docker-stats.js', needsToken: false },
{ name: 'huggingface', script: 'collect-huggingface-stats.js', needsToken: false },
{ name: 'telemetry', script: 'collect-telemetry-stats.js', needsToken: false },
];

for (const collector of collectors) {
for (const collector of CRON_COLLECTORS) {
if (collector.needsToken && !process.env.GITHUB_TOKEN) {
results.collectors[collector.name] = { status: 'skipped', reason: 'no GITHUB_TOKEN' };
continue;
Expand Down
96 changes: 79 additions & 17 deletions scripts/collect-pypi-country-stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
* and a job it refuses there ends the run as refused_cap)
* - 768 GiB per month (a persisted ledger of billed bytes, data/pypi-country-budget.json,
* floored by the bytes the store's fetch records show billed this month,
* so a checkout that lacks the ledger file still counts the month's spend)
* so a checkout that lacks the ledger file still counts the days landed
* this month, though not a billed call that failed)
*
* Per run it fetches at most three missing closed days (newest first, from the
* 30 most recent closed days; no backfill beyond that window), lands the rows
* in pypi_country_daily keyed by the closed day itself, then rewrites the
* 30-day rollup in pypi_country_downloads as a local SUM — no query. A run
* that stops early (a cap, a refusal, an error) still rewrites the rollup
* when it landed at least one day.
* that stops early (a cap, a refusal, an error) still rewrites the rollup,
* whether or not it landed a day.
*
* Every run ends by persisting data/pypi-country-run.json with a status from
* {ok, empty, skipped_no_credentials, refused_cap, capped_month, error}. A
Expand All @@ -29,8 +30,10 @@
* caps; when every candidate day is already fetched, it measures D-1 as a
* sample and exits 0 only when a new day of that size would clear them.
* npm_config_dry_run=true, which npm sets for
* `npm run collect:pypi-countries --dry-run`, selects it as well; any other
* argument exits 2 with a usage message before anything runs.
* `npm run collect:pypi-countries --dry-run`, selects it as well. `--help`
* prints the usage and exits 0; any other argument, and an npm option that
* looks like a mistyped --dry-run (npm_config_dryrun from `--dryrun`), exits 2
* with a usage message before anything runs.
*
* The client port this module consumes: one async `query(options)` that
* resolves to { rows, totalBytesProcessed } for both dry and billed runs. A
Expand Down Expand Up @@ -253,7 +256,9 @@ function storeMonthBytes(db, month) {
* because either one can be stale. The ledger file is not committed, so a
* checkout may lack it or carry one older than the store's fetch records;
* the store never sees the reservation the ledger keeps for a billed call
* that failed. Taking the larger can over-count, never under-count.
* that failed. Taking the larger never reads below either source, but it can
* still under-count: once the ledger file is gone, so is the reservation for
* a billed call that failed, since the store records only days that landed.
*/
function monthToDate(db, dataDir, month) {
return Math.max(readBudget(dataDir, month), storeMonthBytes(db, month));
Expand Down Expand Up @@ -439,10 +444,11 @@ async function collect({
});

let rowsLanded = 0;
// A run that stops early still rolls up the days it already landed, so
// the 30-day total never lags the daily rows.
// A run that stops early still rewrites the rollup, whether or not it
// landed a day: the daily rows may hold days an earlier run stored and
// never rolled up, and the asOf it reports must have its 30-day total.
const stop = (status) => finish(status, {
asOf: daysFetched > 0 ? rollupCountryDownloads(db, now) : newestStoredDay(db),
asOf: rollupCountryDownloads(db, now),
daysFetched, bytesBilled: runBytes, exitCode: 1,
});
for (const day of missingDays) {
Expand Down Expand Up @@ -513,9 +519,10 @@ async function collect({
console.error('PyPI country collection failed: %s', error.message);
let asOf = null;
if (db) {
// Days that landed before the failure still reach the rollup.
// Stored days, including any this run landed before the failure, still
// reach the rollup.
try {
asOf = daysFetched > 0 ? rollupCountryDownloads(db, now) : newestStoredDay(db);
asOf = rollupCountryDownloads(db, now);
} catch {
try { asOf = newestStoredDay(db); } catch { /* keep null */ }
}
Expand Down Expand Up @@ -643,25 +650,79 @@ async function estimate({
}
}

const USAGE = 'Usage: npm run collect:pypi-countries -- [--dry-run]';
const USAGE = 'Usage: npm run collect:pypi-countries -- [--dry-run | --help]';

const HELP = `${USAGE}

Without an argument it collects up to ${MAX_DAYS_PER_RUN} missing closed days from BigQuery,
within a ${PER_QUERY_CAP_BYTES / 1073741824} GiB per-query cap and a ${MONTH_CAP_BYTES / 1073741824} GiB monthly cap.

--dry-run measure what the next run would scan against both caps;
bills nothing and writes nothing
--help print this message`;

/** Levenshtein distance between two short strings. */
function editDistance(a, b) {
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
const row = [i];
for (let j = 1; j <= b.length; j++) {
row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
}
prev = row;
}
return prev[b.length];
}

/**
* npm options in `env` that look like a mistyped --dry-run. A flag given
* without the `--` separator goes to npm, not to the collector's arguments,
* and npm passes even one it does not know on as npm_config_<name>, lowercased:
* `npm run collect:pypi-countries --dryrun` arrives only as
* npm_config_dryrun=true. Read as no argument, it would start the billed run
* the flag was meant to measure. npm_config_dry_run is the dry run itself.
*/
function mistypedDryRunOptions(env) {
return Object.keys(env).filter(key => {
if (!key.toLowerCase().startsWith('npm_config_')) return false;
const name = key.slice('npm_config_'.length).toLowerCase();
if (name === 'dry_run') return false;
const bare = name.replace(/[-_]/g, '');
return bare.startsWith('dry') || editDistance(bare, 'dryrun') <= 2;
});
}

/**
* Read the command line. `--dry-run` is the only argument; anything else is
* refused, never read as a request for a billed collection. Without the `--`
* separator, `npm run collect:pypi-countries --dry-run` keeps the flag for
* npm, which passes it on as npm_config_dry_run=true, so that is a dry run
* too. Returns { dryRun } or { error }.
* Read the command line. `--dry-run` is the only argument besides `--help`
* (or `-h`); anything else is refused, never read as a request for a billed
* collection. Without the `--` separator, `npm run collect:pypi-countries
* --dry-run` keeps the flag for npm, which passes it on as
* npm_config_dry_run=true, so that is a dry run too, and an npm option that
* looks like a mistyped --dry-run is refused. Returns { help }, { dryRun } or
* { error }.
*/
function parseArgs(argv, env = process.env) {
if (argv.includes('--help') || argv.includes('-h')) return { help: true };
const unknown = argv.filter(arg => arg !== '--dry-run');
if (unknown.length > 0) {
return { error: `Unrecognised argument(s): ${unknown.join(' ')}` };
}
const mistyped = mistypedDryRunOptions(env);
if (mistyped.length > 0) {
return {
error: `Unrecognised npm option(s): ${mistyped.join(' ')}. A flag given without the -- separator `
+ 'goes to npm, which passed it on under that name; the dry-run flag is --dry-run.',
};
}
return { dryRun: argv.includes('--dry-run') || env.npm_config_dry_run === 'true' };
}

async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help) {
console.log(HELP);
return;
}
if (args.error) {
console.error(args.error);
console.error(USAGE);
Expand Down Expand Up @@ -696,4 +757,5 @@ module.exports = {
BUDGET_FILE,
RUN_FILE,
readByteFigure,
parseArgs,
};
33 changes: 33 additions & 0 deletions test/cron.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const { test } = require('node:test');
const assert = require('node:assert');
const { readFileSync } = require('node:fs');
const { join } = require('node:path');

const { CRON_COLLECTORS, COLLECTOR_ENV_KEYS, collectorEnv } = require('../lib/cron');

const SCRIPTS = join(__dirname, '..', 'scripts');
const PROCESS_KEYS = ['PATH', 'NODE_ENV', 'HOME'];

test('the cron route hands its collectors no Google Cloud credential variable', () => {
const env = collectorEnv({
PATH: '/usr/bin',
NPM_PACKAGES: 'hackmyagent',
GOOGLE_APPLICATION_CREDENTIALS: '/keys/service-account.json',
GOOGLE_APPLICATION_CREDENTIALS_JSON: '{"type":"service_account"}',
GOOGLE_CLOUD_PROJECT: 'example-project',
CRON_SECRET: 'not-for-collectors',
});
assert.deepEqual(env, { PATH: '/usr/bin', NPM_PACKAGES: 'hackmyagent' });
});

test('every config variable the cron route passes on is read by a collector it runs', () => {
const sources = CRON_COLLECTORS.map(c => readFileSync(join(SCRIPTS, c.script), 'utf8'));
const unread = COLLECTOR_ENV_KEYS
.filter(key => !PROCESS_KEYS.includes(key))
.filter(key => !sources.some(source => source.includes(key)));
assert.deepEqual(unread, [], 'a variable no collector reads is a secret handed out for nothing');
});

test('the cron route does not run the BigQuery country collector', () => {
assert.ok(!CRON_COLLECTORS.some(c => c.script === 'collect-pypi-country-stats.js'));
});
34 changes: 34 additions & 0 deletions test/pypi-country-collector.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,40 @@ for (const [label, status, second, ledger] of [
});
}

for (const [label, status, second, ledger] of [
['its dry run is over the per-query cap', 'refused_cap', { dryBytes: PER_QUERY_CAP_BYTES + 1 }],
['BigQuery refuses its billed job at the ceiling', 'refused_cap', { billedError: ceilingRefusal() }],
['its estimate would pass the monthly cap', 'capped_month', { dryBytes: 1000 }, MONTH_CAP_BYTES - 500],
['its dry run is unreadable', 'error', { dryBytes: 'abc' }],
['its billed call fails', 'error', { billedError: new Error('backend error') }],
]) {
test(`a run that lands nothing and stops because ${label} still rolls up the days already stored`, async () => {
const dir = tmp();
try {
// D-1 is stored and fetched but its rollup is empty; only D-2 is missing.
const dbPath = makeStore(dir, {
fetchedDays: ALL_CANDIDATES.filter(d => d !== dayBefore(2)),
daily: [{ pkg: 5, date: dayBefore(1), cc: 'DE', dl: 7 }],
});
if (ledger !== undefined) {
writeFileSync(join(dir, BUDGET_FILE), JSON.stringify({ month: '2026-09', bytesBilled: ledger }));
}
const res = await runCollect(dbPath, secondDayStops(second));
assert.equal(res.status, status);
assert.equal(res.exitCode, 1);
assert.equal(res.daysFetched, 0);
assert.equal(res.asOf, dayBefore(1));
const db = new Database(dbPath, { readonly: true });
const rows = db.prepare('SELECT package_id, date, country_code, downloads FROM pypi_country_downloads').all();
db.close();
assert.deepEqual(rows, [{ package_id: 5, date: dayBefore(1), country_code: 'DE', downloads: 7 }],
'the reported as-of day has its 30-day total');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
}

// ---------------------------------------------------------------------------
// AC7 — scheduled run without credentials exits 1; population needs no env
// ---------------------------------------------------------------------------
Expand Down
Loading
Loading