diff --git a/README.md b/README.md index e40bbfd8..23ab5c1c 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,13 @@ npm run collect:pypi-countries -- --dry-run ``` This issues only BigQuery dry runs, which are not billed, prints each day's scan size against -both caps, and writes nothing. It exits 0 only when the next run would clear both caps. +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. ## Automated daily collection @@ -121,8 +127,10 @@ The included workflow (`.github/workflows/collect-stats.yml`) runs daily at `6:0 1. Settings → Secrets and variables → Actions → New secret. 2. Add `GH_STATS_TOKEN` (a Personal Access Token with `repo` or `public_repo` scope). -3. Optionally set `GOOGLE_APPLICATION_CREDENTIALS_JSON` for BigQuery country stats. -4. Optionally set the `REGISTRY_URL` Actions **variable** to enable first-party CLI telemetry collection. Unset, the collector warns and skips. +3. Optionally set the `REGISTRY_URL` Actions **variable** to enable first-party CLI telemetry collection. Unset, the collector warns and skips. + +The workflow does not collect BigQuery country stats, so it needs no Google Cloud credentials; +run `npm run collect:pypi-countries` where your credentials are (see above). ### When telemetry collection stops diff --git a/scripts/collect-pypi-country-stats.js b/scripts/collect-pypi-country-stats.js index 023c60ab..7f397ea8 100644 --- a/scripts/collect-pypi-country-stats.js +++ b/scripts/collect-pypi-country-stats.js @@ -13,7 +13,9 @@ * 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. + * 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. * * 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 @@ -24,7 +26,11 @@ * only the dry runs for the days the next run would fetch, reports each scan * size against both caps, and bills nothing and writes nothing (no rows, no * ledger, no run status). It exits 0 only when the next run would clear both - * caps. + * 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. * * The client port this module consumes: one async `query(options)` that * resolves to { rows, totalBytesProcessed } for both dry and billed runs. A @@ -212,14 +218,24 @@ function readBudget(dataDir, month) { * pypi_country_fetch_days whose fetch ran that month. The store is committed * with the collected days and the ledger file is not, so on a fresh checkout * this is the month-to-date figure that survived. 0 before the table exists. - * Fail closed: a total that is not a non-negative integer throws rather than - * reading as 0. + * Fail closed: a day of the month whose figure is not a non-negative integer + * throws, since a negative or text figure would lower the sum, and so does a + * total that is not one, rather than reading as 0. */ function storeMonthBytes(db, month) { const table = db.prepare( "SELECT name FROM sqlite_master WHERE type='table' AND name='pypi_country_fetch_days'" ).get(); if (!table) return 0; + const { unreadable } = db.prepare(` + SELECT COUNT(*) AS unreadable + FROM pypi_country_fetch_days + WHERE substr(fetched_at, 1, 7) = ? + AND (typeof(bytes_billed) != 'integer' OR bytes_billed < 0) + `).get(month); + if (unreadable > 0) { + throw new Error(`unreadable billed-bytes figure on ${unreadable} day(s) of ${month} in pypi_country_fetch_days`); + } const { total } = db.prepare(` SELECT COALESCE(SUM(bytes_billed), 0) AS total FROM pypi_country_fetch_days @@ -233,10 +249,11 @@ function storeMonthBytes(db, month) { } /** - * Month-to-date billed bytes: the larger of the ledger file and the store. - * The ledger also holds the reservation of a billed call that failed, so it - * is the higher figure whenever it survived; the store is the floor when it - * did not. + * Month-to-date billed bytes: the larger of the ledger file and the store, + * 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. */ function monthToDate(db, dataDir, month) { return Math.max(readBudget(dataDir, month), storeMonthBytes(db, month)); @@ -422,6 +439,12 @@ 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. + const stop = (status) => finish(status, { + asOf: daysFetched > 0 ? rollupCountryDownloads(db, now) : newestStoredDay(db), + daysFetched, bytesBilled: runBytes, exitCode: 1, + }); for (const day of missingDays) { const dayIso = isoDay(day); const options = buildDayQueryOptions(packages, day); @@ -433,22 +456,16 @@ async function collect({ const estimate = readByteFigure(dry.totalBytesProcessed); if (estimate === null) { log('Refusing %s: unreadable dry-run estimate (%s)', dayIso, String(dry.totalBytesProcessed)); - return finish('error', { - asOf: newestStoredDay(db), daysFetched, bytesBilled: runBytes, exitCode: 1, - }); + return stop('error'); } if (estimate > PER_QUERY_CAP_BYTES) { log('Refusing %s: dry run estimates %d bytes, over the per-query cap', dayIso, estimate); - return finish('refused_cap', { - asOf: newestStoredDay(db), daysFetched, bytesBilled: runBytes, exitCode: 1, - }); + return stop('refused_cap'); } if (monthBytes + estimate > MONTH_CAP_BYTES) { log('Refusing %s: month-to-date %d + estimate %d bytes would pass the monthly cap', dayIso, monthBytes, estimate); - return finish('capped_month', { - asOf: newestStoredDay(db), daysFetched, bytesBilled: runBytes, exitCode: 1, - }); + return stop('capped_month'); } // Reservation: charge the estimate to the ledger BEFORE the billed call. @@ -470,9 +487,7 @@ async function collect({ writeBudget(dataDir, month, monthBytes, now); log('Refusing %s: BigQuery refused the job at the %d byte ceiling; nothing was billed', dayIso, PER_QUERY_CAP_BYTES); - return finish('refused_cap', { - asOf: newestStoredDay(db), daysFetched, bytesBilled: runBytes, exitCode: 1, - }); + return stop('refused_cap'); } const billedBytes = readByteFigure(billed.totalBytesProcessed); // An unreadable, negative or non-integer billed figure charges the @@ -497,7 +512,14 @@ async function collect({ } catch (error) { console.error('PyPI country collection failed: %s', error.message); let asOf = null; - try { if (db) asOf = newestStoredDay(db); } catch { /* keep null */ } + if (db) { + // Days that landed before the failure still reach the rollup. + try { + asOf = daysFetched > 0 ? rollupCountryDownloads(db, now) : newestStoredDay(db); + } catch { + try { asOf = newestStoredDay(db); } catch { /* keep null */ } + } + } return finish('error', { asOf, daysFetched, bytesBilled: runBytes, exitCode: 1 }); } finally { if (db) db.close(); @@ -518,7 +540,9 @@ function gib(bytes) { * monthToDateBytes, perQueryCapBytes, monthCapBytes, exitCode } with status * from {estimated, refused_cap, capped_month, skipped_no_credentials, error}; * exitCode is 0 only for estimated. When every candidate day is already - * fetched, D-1 is measured as a sample with fetched: true. + * fetched, the next run bills nothing; D-1 is then measured as a sample with + * fetched: true, and the status and exitCode are the verdict for a new day + * of that size, not for the next run. */ async function estimate({ client = null, @@ -594,11 +618,22 @@ async function estimate({ monthBytes += bytes; } const result = finish(status); - log('Per-query cap %s GiB; month to date %s GiB billed, these queries add %s GiB of the %s GiB monthly cap.', - gib(PER_QUERY_CAP_BYTES), gib(monthToDateBytes), gib(result.estimatedBytes), gib(MONTH_CAP_BYTES)); - log(status === 'estimated' - ? 'The next run would clear both caps.' - : `The next run would be refused (${status}).`); + log('Per-query cap %s GiB; month to date %s GiB billed, %s %s GiB of the %s GiB monthly cap.', + gib(PER_QUERY_CAP_BYTES), gib(monthToDateBytes), + sample ? 'a new day of this size would add' : 'these queries add', + gib(result.estimatedBytes), gib(MONTH_CAP_BYTES)); + if (sample) { + // The next run selects no day, so no cap can refuse it; the verdict is + // a prediction for the next day that closes. + log('The next run would bill nothing: every candidate day is already fetched.'); + log(status === 'estimated' + ? 'A new day of this size would clear both caps.' + : `A new day of this size would be refused (${status}).`); + } else { + log(status === 'estimated' + ? 'The next run would clear both caps.' + : `The next run would be refused (${status}).`); + } return result; } catch (error) { console.error('PyPI country dry run failed: %s', error.message); @@ -608,11 +643,33 @@ async function estimate({ } } +const USAGE = 'Usage: npm run collect:pypi-countries -- [--dry-run]'; + +/** + * 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 }. + */ +function parseArgs(argv, env = process.env) { + const unknown = argv.filter(arg => arg !== '--dry-run'); + if (unknown.length > 0) { + return { error: `Unrecognised argument(s): ${unknown.join(' ')}` }; + } + return { dryRun: argv.includes('--dry-run') || env.npm_config_dry_run === 'true' }; +} + async function main() { + const args = parseArgs(process.argv.slice(2)); + if (args.error) { + console.error(args.error); + console.error(USAGE); + process.exit(2); + } require('dotenv').config(); console.log('PyPI Country Download Stats Collector (BigQuery)'); - const dryRun = process.argv.slice(2).includes('--dry-run'); - const result = dryRun ? await estimate({}) : await collect({}); + const result = args.dryRun ? await estimate({}) : await collect({}); process.exit(result.exitCode); } diff --git a/test/pypi-country-collector.test.js b/test/pypi-country-collector.test.js index 75f89d05..677c4744 100644 --- a/test/pypi-country-collector.test.js +++ b/test/pypi-country-collector.test.js @@ -2,12 +2,13 @@ const { test } = require('node:test'); const assert = require('node:assert'); const { spawn } = require('node:child_process'); const { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } = require('node:fs'); -const { join } = require('node:path'); +const { join, dirname } = require('node:path'); const { tmpdir } = require('node:os'); const Database = require('better-sqlite3'); const { collect, + estimate, PER_QUERY_CAP_BYTES, MONTH_CAP_BYTES, BUDGET_FILE, @@ -317,6 +318,30 @@ test('an unreadable billed total in the store is an error that bills nothing, ne } }); +for (const [label, figures] of [ + ['a negative day', [5000, -1000]], + ['a non-numeric day', [5000, 'abc']], + ['a negative and a non-numeric day', [5000, -1000, 'abc']], +]) { + test(`a month whose fetch records hold ${label} is an error, never a lower month-to-date`, async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir, { fetchedDays: ALL_CANDIDATES.filter(d => d !== dayBefore(1)) }); + figures.forEach((bytes, i) => recordBilled(dbPath, [dayBefore(i + 2)], bytes, '2026-09-01T06:00:00.000Z')); + const client = fakeClient(); + const res = await runCollect(dbPath, client); + assert.equal(res.status, 'error', 'the per-day figures must not sum to a total below the 5000 billed'); + assert.equal(res.exitCode, 1); + assert.equal(client.calls.length, 0, 'nothing is estimated or billed against an unreadable month'); + const dry = await estimate({ client, dbPath, now: NOW, env: {}, log: noop }); + assert.equal(dry.status, 'error'); + assert.equal(client.calls.length, 0); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +} + test('GAT-01.AC3 an unparseable ledger starts the month at 0 rather than failing', async () => { const dir = tmp(); try { @@ -485,18 +510,79 @@ test('GAT-01.AC5 a day 31 days old is excluded from the rollup sum', async () => } }); +/** + * Client for a run over two missing days: D-1 bills and lands one row, then + * D-2 stops the run through `second` (its dry-run figure, or the error its + * billed call rejects with). + */ +function secondDayStops(second) { + return { + async query(options) { + const isSecond = callDay(options) === dayBefore(2); + if (options.dryRun) { + return { rows: [], totalBytesProcessed: isSecond && 'dryBytes' in second ? second.dryBytes : 1000 }; + } + if (isSecond) throw second.billedError; + return { rows: [{ project: 'aim-sdk', country_code: 'DE', downloads: 7 }], totalBytesProcessed: 1000 }; + }, + }; +} + +const ceilingRefusal = () => Object.assign(new Error('Query exceeded limit for bytes billed'), { + code: 400, errors: [{ reason: 'bytesBilledLimitExceeded', message: 'Query exceeded limit for bytes billed' }], +}); + +for (const [label, status, second, ledger] of [ + ['BigQuery refuses its billed job at the ceiling', 'refused_cap', { billedError: ceilingRefusal() }], + ['its dry run is over the per-query cap', 'refused_cap', { dryBytes: PER_QUERY_CAP_BYTES + 1 }], + ['its estimate would pass the monthly cap', 'capped_month', { dryBytes: 1000 }, MONTH_CAP_BYTES - 1500], + ['its dry run is unreadable', 'error', { dryBytes: 'abc' }], + ['its billed call fails', 'error', { billedError: new Error('backend error') }], +]) { + test(`a run that lands D-1 and stops because ${label} still rolls D-1 into the 30-day total`, async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir, { + fetchedDays: ALL_CANDIDATES.filter(d => d !== dayBefore(1) && d !== dayBefore(2)), + }); + 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, 1); + assert.equal(res.asOf, dayBefore(1)); + assert.equal(readStatus(dir).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 landed day is in the rollup, not only in pypi_country_daily'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +} + // --------------------------------------------------------------------------- // AC7 — scheduled run without credentials exits 1; population needs no env // --------------------------------------------------------------------------- +/** + * Run the collector CLI against the store in a temporary directory. The child + * runs in that directory, so the .env it loads is the test's, never the one + * at the repository root, which may hold real BigQuery credentials. + */ function runScript(extraEnv, dbPath) { return new Promise((resolve) => { const env = { ...process.env, ANALYTICS_DB_PATH: dbPath, ...extraEnv }; delete env.GOOGLE_APPLICATION_CREDENTIALS; delete env.GOOGLE_CLOUD_PROJECT; delete env.PYPI_PACKAGES; + delete env.npm_config_dry_run; if (!extraEnv.GITHUB_ACTIONS) delete env.GITHUB_ACTIONS; - const child = spawn(process.execPath, [SCRIPT], { env }); + const child = spawn(process.execPath, [SCRIPT], { env, cwd: dirname(dbPath) }); let stdout = ''; let stderr = ''; child.stdout.on('data', (d) => (stdout += d)); @@ -517,6 +603,22 @@ test('GAT-01.AC7 a scheduled run without credentials persists skipped_no_credent } }); +test('the spawned collector loads .env from the test directory, not the repository root', async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir); + // A key path that does not exist: the collector names it and still + // never reaches BigQuery. + const missingKey = join(dir, 'no-such-key.json'); + writeFileSync(join(dir, '.env'), `GOOGLE_APPLICATION_CREDENTIALS=${missingKey}\n`); + const res = await runScript({}, dbPath); + assert.ok(res.stdout.includes(missingKey), `the test directory's .env was not loaded; stdout:\n${res.stdout}`); + assert.equal(readStatus(dir).status, 'skipped_no_credentials'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + test('GAT-01.AC7 the same credential skip outside Actions exits 0 with the same status', async () => { const dir = tmp(); try { diff --git a/test/pypi-country-estimate.test.js b/test/pypi-country-estimate.test.js index 6faeaebb..482aab8b 100644 --- a/test/pypi-country-estimate.test.js +++ b/test/pypi-country-estimate.test.js @@ -2,8 +2,9 @@ const { test } = require('node:test'); const assert = require('node:assert'); const { spawn } = require('node:child_process'); const { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } = require('node:fs'); -const { join } = require('node:path'); +const { join, dirname } = require('node:path'); const { tmpdir } = require('node:os'); +const { format } = require('node:util'); const Database = require('better-sqlite3'); const { @@ -246,14 +247,21 @@ test('PYPI_PACKAGES filters the estimated population the same way it filters a c } }); -function runScript(args, dbPath) { +/** + * Run the collector CLI against the store in a temporary directory. The child + * runs in that directory, so the .env it loads is the test's, never the one + * at the repository root, which may hold real BigQuery credentials. + */ +function runScript(args, dbPath, extraEnv = {}) { return new Promise((resolve) => { const env = { ...process.env, ANALYTICS_DB_PATH: dbPath }; delete env.GOOGLE_APPLICATION_CREDENTIALS; delete env.GOOGLE_CLOUD_PROJECT; delete env.PYPI_PACKAGES; delete env.GITHUB_ACTIONS; - const child = spawn(process.execPath, [SCRIPT, ...args], { env }); + delete env.npm_config_dry_run; + Object.assign(env, extraEnv); + const child = spawn(process.execPath, [SCRIPT, ...args], { env, cwd: dirname(dbPath) }); let stdout = ''; let stderr = ''; child.stdout.on('data', (d) => (stdout += d)); @@ -276,3 +284,70 @@ test('--dry-run without credentials measures nothing, exits 1 and leaves the las rmSync(dir, { recursive: true, force: true }); } }); + +test('the spawned dry run loads .env from the test directory, not the repository root', async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir); + // A key path that does not exist: the collector names it and still + // never reaches BigQuery. + const missingKey = join(dir, 'no-such-key.json'); + writeFileSync(join(dir, '.env'), `GOOGLE_APPLICATION_CREDENTIALS=${missingKey}\n`); + const res = await runScript(['--dry-run'], dbPath); + assert.ok(res.stdout.includes(missingKey), `the test directory's .env was not loaded; stdout:\n${res.stdout}`); + assert.match(res.stdout, /nothing was measured/i); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +for (const args of [['--dryrun'], ['--dry-run', 'extra'], ['--dry-run=true']]) { + test(`the collector refuses \`${args.join(' ')}\` with a usage message and starts nothing`, async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir); + const before = snapshot(dir); + const res = await runScript(args, dbPath); + assert.equal(res.status, 2, `expected exit 2; stdout:\n${res.stdout}\nstderr:\n${res.stderr}`); + assert.match(res.stderr, /unrecognised argument/i); + assert.match(res.stderr, /usage:/i); + assert.doesNotMatch(res.stdout, /credentials not configured/i, 'no collection was started'); + assert.deepEqual(snapshot(dir), before, 'no run status is written'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +} + +test('npm_config_dry_run=true, which `npm run collect:pypi-countries --dry-run` sets, is a dry run', async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir); + writeFileSync(join(dir, RUN_FILE), JSON.stringify({ status: 'ok' }) + '\n'); + const before = snapshot(dir); + const res = await runScript([], dbPath, { npm_config_dry_run: 'true' }); + assert.equal(res.status, 1, `expected exit 1; stdout:\n${res.stdout}\nstderr:\n${res.stderr}`); + assert.match(res.stdout, /nothing was measured/i); + assert.deepEqual(snapshot(dir), before, 'a dry run writes no run status'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test('with every candidate fetched the verdict is worded for the next new day, not for the next run', async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir, { fetchedDays: ALL_CANDIDATES }); + writeFileSync(join(dir, BUDGET_FILE), JSON.stringify({ month: '2026-09', bytesBilled: MONTH_CAP_BYTES - 1 }) + '\n'); + const lines = []; + const res = await runEstimate(dbPath, fakeClient(2), { log: (...a) => lines.push(format(...a)) }); + assert.equal(res.status, 'capped_month', 'a new day of this size would pass the monthly cap'); + assert.equal(res.exitCode, 1); + const out = lines.join('\n'); + assert.doesNotMatch(out, /next run would be refused/i, 'the next run fetches nothing, so nothing refuses it'); + assert.match(out, /next run would bill nothing/i); + assert.match(out, /a new day of this size would be refused \(capped_month\)/i); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});