diff --git a/README.md b/README.md index 32391410..a20d9687 100644 --- a/README.md +++ b/README.md @@ -118,14 +118,16 @@ 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, 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. +`npm run collect:pypi-countries --dry-run` (without the `--`) is also a dry run, as is +`npm_config_dry_run=true` set in the environment in any letter case. +`npm run collect:pypi-countries -- --help` (or `-h`) prints the usage and exits 0, even when other +arguments are given with it. Without the `--`, `--help` goes to npm, which prints its own usage +and runs nothing. Any other argument after the `--` is refused with a usage message and exit +code 2. A flag given without the `--` goes to npm. npm 8 through 11 pass an unknown one 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, +and any other is left to npm, so the run collects as normal. npm 12 refuses an unknown flag +itself and exits 1 before the script starts. ## Automated daily collection diff --git a/lib/cron.js b/lib/cron.js index 50e6051d..5752df49 100644 --- a/lib/cron.js +++ b/lib/cron.js @@ -1,8 +1,12 @@ /** - * 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. + * What the cron route (pages/api/cron/collect.js) runs, who may run it, and + * the environment it hands each child process, kept apart from the handler so + * all of it can be tested. */ +const { execSync } = require('child_process'); +const path = require('path'); + const CRON_COLLECTORS = [ { name: 'github', script: 'collect-stats.js', needsToken: true }, { name: 'npm', script: 'collect-npm-stats.js', needsToken: false }, @@ -27,11 +31,81 @@ const COLLECTOR_ENV_KEYS = [ 'REGISTRY_URL', ]; +// What scripts/generate-summary.js reads, on top of the collector set. +const SUMMARY_ENV_KEYS = ['SUMMARY_DB', 'SUMMARY_OUT', 'COLLECTOR_OUTCOMES']; + +function pick(env, keys) { + return Object.fromEntries(keys.filter(k => env[k] !== undefined).map(k => [k, env[k]])); +} + /** 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]]) - ); + return pick(env, COLLECTOR_ENV_KEYS); +} + +/** The allowlisted subset of `env` that the summary step receives. */ +function summaryEnv(env = process.env) { + return { ...collectorEnv(env), ...pick(env, SUMMARY_ENV_KEYS) }; +} + +/** + * True when the Authorization header carries CRON_SECRET as a bearer token. + * Fails closed: with CRON_SECRET unset or empty nothing is authorized, since + * `Bearer undefined` and `Bearer ` are headers anyone can send. + */ +function isAuthorized(authorization, env = process.env) { + const secret = env.CRON_SECRET; + if (!secret) return false; + return authorization === `Bearer ${secret}`; +} + +/** + * Run every cron collector, then regenerate the summary, each as a child + * process that receives only its allowlisted environment. `exec` defaults to + * execSync; tests inject a recorder. Returns the per-collector results. + */ +function runCron({ env = process.env, exec = execSync, cwd = process.cwd(), now = new Date() } = {}) { + const results = { timestamp: now.toISOString(), collectors: {} }; + const scriptsDir = path.join(cwd, 'scripts'); + + const childEnv = collectorEnv(env); + + for (const collector of CRON_COLLECTORS) { + if (collector.needsToken && !env.GITHUB_TOKEN) { + results.collectors[collector.name] = { status: 'skipped', reason: 'no GITHUB_TOKEN' }; + continue; + } + try { + exec(`node ${path.join(scriptsDir, collector.script)}`, { + encoding: 'utf-8', + timeout: 120000, + env: childEnv, + cwd, + }); + results.collectors[collector.name] = { status: 'success' }; + } catch (err) { + results.collectors[collector.name] = { status: 'error', message: err.message.slice(0, 200) }; + } + } + + try { + exec(`node ${path.join(scriptsDir, 'generate-summary.js')}`, { + encoding: 'utf-8', timeout: 30000, env: summaryEnv(env), cwd, + }); + results.summary = 'regenerated'; + } catch (err) { + results.summary = 'failed'; + } + + return results; } -module.exports = { CRON_COLLECTORS, COLLECTOR_ENV_KEYS, collectorEnv }; +module.exports = { + CRON_COLLECTORS, + COLLECTOR_ENV_KEYS, + SUMMARY_ENV_KEYS, + collectorEnv, + summaryEnv, + isAuthorized, + runCron, +}; diff --git a/pages/api/cron/collect.js b/pages/api/cron/collect.js index 3561bd72..75792a28 100644 --- a/pages/api/cron/collect.js +++ b/pages/api/cron/collect.js @@ -1,44 +1,8 @@ -const { execSync } = require('child_process'); -const path = require('path'); -const { CRON_COLLECTORS, collectorEnv } = require('../../../lib/cron'); +import { isAuthorized, runCron } from '../../../lib/cron.js'; export default async function handler(req, res) { - const authHeader = req.headers.authorization; - if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) { + if (!isAuthorized(req.headers.authorization)) { return res.status(401).json({ error: 'Unauthorized' }); } - - const results = { timestamp: new Date().toISOString(), collectors: {} }; - const scriptsDir = path.join(process.cwd(), 'scripts'); - - const childEnv = collectorEnv(); - - for (const collector of CRON_COLLECTORS) { - if (collector.needsToken && !process.env.GITHUB_TOKEN) { - results.collectors[collector.name] = { status: 'skipped', reason: 'no GITHUB_TOKEN' }; - continue; - } - try { - execSync(`node ${path.join(scriptsDir, collector.script)}`, { - encoding: 'utf-8', - timeout: 120000, - env: childEnv, - cwd: process.cwd(), - }); - results.collectors[collector.name] = { status: 'success' }; - } catch (err) { - results.collectors[collector.name] = { status: 'error', message: err.message.slice(0, 200) }; - } - } - - try { - execSync(`node ${path.join(scriptsDir, 'generate-summary.js')}`, { - encoding: 'utf-8', timeout: 30000, cwd: process.cwd(), - }); - results.summary = 'regenerated'; - } catch (err) { - results.summary = 'failed'; - } - - return res.status(200).json(results); + return res.status(200).json(runCron()); } diff --git a/scripts/collect-pypi-country-stats.js b/scripts/collect-pypi-country-stats.js index d437dcb2..a2d0b9ea 100644 --- a/scripts/collect-pypi-country-stats.js +++ b/scripts/collect-pypi-country-stats.js @@ -29,11 +29,12 @@ * ledger, no run status). It exits 0 only when the next run would clear both * 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_config_dry_run=true (in any letter case), which npm sets for * `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. + * or `-h` prints the usage and exits 0, whatever else is given; 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 @@ -285,18 +286,20 @@ function newestStoredDay(db) { /** * Rewrite pypi_country_downloads for the as-of date (the newest stored closed * day) as the per-(package_id, country_code) SUM of pypi_country_daily over - * the stored days inside the 30 most recent closed days. Purely local: no + * the stored days among the 30 days ending at the as-of day. Purely local: no * client call; fewer than 30 stored days simply sum over what is stored. + * The window is anchored on the as-of day, not on the run date, so the total + * always covers the 30 days its date names, even when the newest stored day + * is weeks old. * The whole table is replaced, not just the as-of rows: a stale snapshot at * any other date would otherwise shadow the rollup through the consumers' * MAX(date) reads. */ -function rollupCountryDownloads(db, now) { +function rollupCountryDownloads(db) { const asOf = newestStoredDay(db); if (!asOf) return null; - const today = utcMidnight(now); - const windowStart = isoDay(addDays(today, -WINDOW_DAYS)); - const windowEnd = isoDay(addDays(today, -1)); + const windowEnd = asOf; + const windowStart = isoDay(addDays(new Date(`${asOf}T00:00:00Z`), -(WINDOW_DAYS - 1))); // One transaction: an insert that aborts must not leave the table empty. db.transaction(() => { db.prepare('DELETE FROM pypi_country_downloads').run(); @@ -311,6 +314,21 @@ function rollupCountryDownloads(db, now) { return asOf; } +/** + * The rollup for a run that is ending anyway. A failed rewrite leaves the + * previous rollup in place (one transaction) and must not replace the run's + * own status, so it is logged and the as-of falls back to the newest stored + * day, or null when even that cannot be read. + */ +function rollupOrNewestStoredDay(db) { + try { + return rollupCountryDownloads(db); + } catch (error) { + console.error('PyPI country rollup failed: %s', error.message); + try { return newestStoredDay(db); } catch { return null; } + } +} + /** * Thin adapter producing the client port over @google-cloud/bigquery. Options * pass through to createQueryJob unchanged, so the billed call's @@ -446,9 +464,11 @@ async function collect({ let rowsLanded = 0; // 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. + // never rolled up. The rewrite gives the as-of day it reports the 30-day + // total ending there; if the rewrite fails, the previous rollup stays and + // the run keeps the status it stopped with. const stop = (status) => finish(status, { - asOf: rollupCountryDownloads(db, now), + asOf: rollupOrNewestStoredDay(db), daysFetched, bytesBilled: runBytes, exitCode: 1, }); for (const day of missingDays) { @@ -511,22 +531,15 @@ async function collect({ log(' %s: %d rows, %d bytes billed', dayIso, rows.length, charge); } - const asOf = rollupCountryDownloads(db, now); + const asOf = rollupCountryDownloads(db); const status = daysFetched > 0 && rowsLanded === 0 ? 'empty' : 'ok'; log('Country stats collection complete (%s, as of %s).', status, asOf || 'never'); return finish(status, { asOf, daysFetched, bytesBilled: runBytes, exitCode: 0 }); } catch (error) { console.error('PyPI country collection failed: %s', error.message); - let asOf = null; - if (db) { - // Stored days, including any this run landed before the failure, still - // reach the rollup. - try { - asOf = rollupCountryDownloads(db, now); - } catch { - try { asOf = newestStoredDay(db); } catch { /* keep null */ } - } - } + // Stored days, including any this run landed before the failure, still + // reach the rollup. + const asOf = db ? rollupOrNewestStoredDay(db) : null; return finish('error', { asOf, daysFetched, bytesBilled: runBytes, exitCode: 1 }); } finally { if (db) db.close(); @@ -650,16 +663,16 @@ async function estimate({ } } -const USAGE = 'Usage: npm run collect:pypi-countries -- [--dry-run | --help]'; +const USAGE = 'Usage: npm run collect:pypi-countries -- [--dry-run | -h | --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`; + --dry-run measure what the next run would scan against both caps; + bills nothing and writes nothing + -h, --help print this message and exit, whatever else is given`; /** Levenshtein distance between two short strings. */ function editDistance(a, b) { @@ -676,11 +689,12 @@ function editDistance(a, b) { /** * 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_, lowercased: - * `npm run collect:pypi-countries --dryrun` arrives only as + * without the `--` separator goes to npm, not to the collector's arguments. + * npm 8 to 11 pass even one they do not know on as npm_config_, + * 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. + * the flag was meant to measure. npm 12 exits 1 on an unknown flag before the + * script starts. npm_config_dry_run, in any letter case, is the dry run itself. */ function mistypedDryRunOptions(env) { return Object.keys(env).filter(key => { @@ -692,14 +706,23 @@ function mistypedDryRunOptions(env) { }); } +/** + * True when npm_config_dry_run is 'true'. npm reads its npm_config_ variables + * without regard to letter case, so NPM_CONFIG_DRY_RUN=true asks for a dry run + * as well; read as no argument, it would start a billed run. + */ +function npmDryRun(env) { + return Object.keys(env).some(key => key.toLowerCase() === 'npm_config_dry_run' && env[key] === 'true'); +} + /** * 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 }. + * (or `-h`), which wins over anything else given; 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, + * even alongside --dry-run. Returns { help }, { dryRun } or { error }. */ function parseArgs(argv, env = process.env) { if (argv.includes('--help') || argv.includes('-h')) return { help: true }; @@ -714,7 +737,7 @@ function parseArgs(argv, env = process.env) { + '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' }; + return { dryRun: argv.includes('--dry-run') || npmDryRun(env) }; } async function main() { diff --git a/test/cron.test.js b/test/cron.test.js index 83c8b91a..35c54107 100644 --- a/test/cron.test.js +++ b/test/cron.test.js @@ -1,11 +1,16 @@ const { test } = require('node:test'); const assert = require('node:assert'); -const { readFileSync } = require('node:fs'); +const { readFileSync, mkdtempSync, rmSync } = require('node:fs'); const { join } = require('node:path'); +const { tmpdir } = require('node:os'); +const { pathToFileURL } = require('node:url'); -const { CRON_COLLECTORS, COLLECTOR_ENV_KEYS, collectorEnv } = require('../lib/cron'); +const { + CRON_COLLECTORS, COLLECTOR_ENV_KEYS, SUMMARY_ENV_KEYS, collectorEnv, isAuthorized, runCron, +} = require('../lib/cron'); const SCRIPTS = join(__dirname, '..', 'scripts'); +const ROUTE = join(__dirname, '..', 'pages', 'api', 'cron', 'collect.js'); const PROCESS_KEYS = ['PATH', 'NODE_ENV', 'HOME']; test('the cron route hands its collectors no Google Cloud credential variable', () => { @@ -31,3 +36,76 @@ test('every config variable the cron route passes on is read by a collector it r test('the cron route does not run the BigQuery country collector', () => { assert.ok(!CRON_COLLECTORS.some(c => c.script === 'collect-pypi-country-stats.js')); }); + + +for (const [label, env, header] of [ + ['unset', {}, 'Bearer undefined'], + ['empty', { CRON_SECRET: '' }, 'Bearer '], +]) { + test(`with CRON_SECRET ${label} the cron route answers 401 and runs nothing`, async () => { + assert.equal(isAuthorized(header, env), false); + const { default: handler } = await import(pathToFileURL(ROUTE).href); + const prevSecret = process.env.CRON_SECRET; + const prevCwd = process.cwd(); + // An empty directory holds no collector, so a route that let the request + // through would fail to start one rather than collect for real. + const dir = mkdtempSync(join(tmpdir(), 'cron-route-')); + process.chdir(dir); + if (env.CRON_SECRET === undefined) delete process.env.CRON_SECRET; else process.env.CRON_SECRET = env.CRON_SECRET; + try { + const res = { statusCode: null, body: null }; + res.status = (code) => { res.statusCode = code; return res; }; + res.json = (obj) => { res.body = obj; return res; }; + await handler({ headers: { authorization: header } }, res); + assert.equal(res.statusCode, 401); + assert.deepEqual(res.body, { error: 'Unauthorized' }); + } finally { + process.chdir(prevCwd); + if (prevSecret === undefined) delete process.env.CRON_SECRET; else process.env.CRON_SECRET = prevSecret; + rmSync(dir, { recursive: true, force: true }); + } + }); +} + +test('the cron route accepts only the bearer token in CRON_SECRET', () => { + const env = { CRON_SECRET: 's3cret' }; + assert.equal(isAuthorized('Bearer s3cret', env), true); + assert.equal(isAuthorized('Bearer other', env), false); + assert.equal(isAuthorized('s3cret', env), false); + assert.equal(isAuthorized(undefined, env), false); +}); + +test('each cron child process receives only its allowlisted environment', () => { + const env = { + PATH: '/usr/bin', HOME: '/home/cron', GITHUB_TOKEN: 'gh-token', NPM_PACKAGES: 'hackmyagent', + SUMMARY_OUT: '/tmp/summary.json', COLLECTOR_OUTCOMES: '{}', + CRON_SECRET: 'not-for-children', GOOGLE_APPLICATION_CREDENTIALS: '/keys/service-account.json', + UNRELATED_SECRET: 'not-for-children', + }; + const calls = []; + const results = runCron({ + env, cwd: '/app', now: new Date('2026-09-02T00:00:00Z'), + exec: (command, options) => calls.push({ command, options }), + }); + const collectorEnvExpected = { PATH: '/usr/bin', HOME: '/home/cron', GITHUB_TOKEN: 'gh-token', NPM_PACKAGES: 'hackmyagent' }; + const collectorCalls = calls.filter(c => !c.command.endsWith('generate-summary.js')); + assert.deepEqual(collectorCalls.map(c => c.command), + CRON_COLLECTORS.map(c => `node ${join('/app', 'scripts', c.script)}`)); + for (const { options } of collectorCalls) { + assert.deepEqual(options.env, collectorEnvExpected); + assert.equal(options.cwd, '/app'); + } + const summary = calls.filter(c => c.command.endsWith('generate-summary.js')); + assert.equal(summary.length, 1); + assert.deepEqual(summary[0].options.env, + { ...collectorEnvExpected, SUMMARY_OUT: '/tmp/summary.json', COLLECTOR_OUTCOMES: '{}' }); + assert.equal(results.summary, 'regenerated'); + assert.deepEqual(Object.values(results.collectors).map(r => r.status), CRON_COLLECTORS.map(() => 'success')); +}); + +test('every variable the summary step adds is read by the summary generator', () => { + const sources = ['scripts/generate-summary.js', 'lib/summary.js'] + .map(file => readFileSync(join(__dirname, '..', file), 'utf8')); + const unread = SUMMARY_ENV_KEYS.filter(key => !sources.some(source => source.includes(key))); + assert.deepEqual(unread, []); +}); diff --git a/test/pypi-country-collector.test.js b/test/pypi-country-collector.test.js index ce6a78d5..8c06fbb3 100644 --- a/test/pypi-country-collector.test.js +++ b/test/pypi-country-collector.test.js @@ -37,7 +37,7 @@ const ALL_CANDIDATES = Array.from({ length: 30 }, (_, i) => dayBefore(i + 1)); const tmp = () => mkdtempSync(join(tmpdir(), 'pypi-country-')); -function makeStore(dir, { packages = SEVEN, fetchedDays = [], daily = [] } = {}) { +function makeStore(dir, { packages = SEVEN, fetchedDays = [], daily = [], rollup = [] } = {}) { const p = join(dir, 'analytics.db'); const db = new Database(p); db.exec(` @@ -60,6 +60,8 @@ function makeStore(dir, { packages = SEVEN, fetchedDays = [], daily = [] } = {}) for (const d of fetchedDays) insFetch.run(d, NOW.toISOString()); const insDaily = db.prepare('INSERT INTO pypi_country_daily (package_id, date, country_code, downloads) VALUES (?, ?, ?, ?)'); for (const r of daily) insDaily.run(r.pkg, r.date, r.cc, r.dl); + const insRollup = db.prepare('INSERT INTO pypi_country_downloads (package_id, date, country_code, downloads) VALUES (?, ?, ?, ?)'); + for (const r of rollup) insRollup.run(r.pkg, r.date, r.cc, r.dl); db.close(); return p; } @@ -599,6 +601,63 @@ for (const [label, status, second, ledger] of [ }); } +/** 35 consecutive stored days of 10 downloads ending `newest` days before NOW, rolled up as 300. */ +function staleStore(dir, newest, extra = {}) { + return makeStore(dir, { + ...extra, + daily: Array.from({ length: 35 }, (_, i) => ({ pkg: 1, date: dayBefore(newest + i), cc: 'US', dl: 10 })), + rollup: [{ pkg: 1, date: dayBefore(newest), cc: 'US', dl: 300 }], + }); +} + +for (const newest of [11, 32]) { + for (const [label, client, extra, status] of [ + ['stops at the per-query cap', () => fakeClient({ dryBytes: PER_QUERY_CAP_BYTES + 1 }), {}, 'refused_cap'], + ['has no day to fetch', () => fakeClient(), { fetchedDays: ALL_CANDIDATES }, 'ok'], + ]) { + test(`a run that ${label} with the newest stored day D-${newest} keeps that day's 30-day total`, async () => { + const dir = tmp(); + try { + const dbPath = staleStore(dir, newest, extra); + const res = await runCollect(dbPath, client()); + assert.equal(res.status, status); + assert.equal(res.asOf, dayBefore(newest)); + 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: 1, date: dayBefore(newest), country_code: 'US', downloads: 300 }], + 'the rollup sums the 30 days ending at its own date, not the days since the run date'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + } +} + +test('a stopped run whose rollup write fails keeps its own status and the previous rollup', async () => { + const dir = tmp(); + try { + const dbPath = makeStore(dir, { + daily: [{ pkg: 1, date: dayBefore(1), cc: 'US', dl: 10 }], + rollup: [{ pkg: 1, date: dayBefore(2), cc: 'US', dl: 99 }], + }); + const db = new Database(dbPath); + db.exec("CREATE TRIGGER abort_ins BEFORE INSERT ON pypi_country_downloads BEGIN SELECT RAISE(ABORT, 'injected'); END"); + db.close(); + const res = await runCollect(dbPath, fakeClient({ dryBytes: PER_QUERY_CAP_BYTES + 1 })); + assert.equal(res.status, 'refused_cap', 'a failed rollup does not turn the refusal into an error'); + assert.equal(res.exitCode, 1); + assert.equal(res.asOf, dayBefore(1), 'the as-of falls back to the newest stored day'); + assert.equal(readStatus(dir).status, 'refused_cap'); + const after = new Database(dbPath, { readonly: true }); + const rows = after.prepare('SELECT date, downloads FROM pypi_country_downloads').all(); + after.close(); + assert.deepEqual(rows, [{ date: dayBefore(2), downloads: 99 }], 'the previous rollup is left in place'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + // --------------------------------------------------------------------------- // AC7 — scheduled run without credentials exits 1; population needs no env // --------------------------------------------------------------------------- @@ -614,7 +673,7 @@ function runScript(extraEnv, dbPath) { delete env.GOOGLE_APPLICATION_CREDENTIALS; delete env.GOOGLE_CLOUD_PROJECT; delete env.PYPI_PACKAGES; - delete env.npm_config_dry_run; + for (const key of Object.keys(env)) if (key.toLowerCase() === 'npm_config_dry_run') delete env[key]; if (!extraEnv.GITHUB_ACTIONS) delete env.GITHUB_ACTIONS; const child = spawn(process.execPath, [SCRIPT], { env, cwd: dirname(dbPath) }); let stdout = ''; diff --git a/test/pypi-country-estimate.test.js b/test/pypi-country-estimate.test.js index 21078ca4..59e76054 100644 --- a/test/pypi-country-estimate.test.js +++ b/test/pypi-country-estimate.test.js @@ -260,7 +260,7 @@ function runScript(args, dbPath, extraEnv = {}) { delete env.GOOGLE_CLOUD_PROJECT; delete env.PYPI_PACKAGES; delete env.GITHUB_ACTIONS; - delete env.npm_config_dry_run; + for (const key of Object.keys(env)) if (key.toLowerCase() === 'npm_config_dry_run') delete env[key]; Object.assign(env, extraEnv); const child = spawn(process.execPath, [SCRIPT, ...args], { env, cwd: dirname(dbPath) }); let stdout = ''; @@ -320,7 +320,7 @@ for (const args of [['--dryrun'], ['--dry-run', 'extra'], ['--dry-run=true']]) { }); } -for (const args of [['--help'], ['-h'], ['--help', '--dry-run']]) { +for (const args of [['--help'], ['-h'], ['--help', '--dry-run'], ['--dryrun', '-h']]) { test(`\`${args.join(' ')}\` prints the usage and exits 0 without starting a run`, async () => { const dir = tmp(); try { @@ -330,6 +330,7 @@ for (const args of [['--help'], ['-h'], ['--help', '--dry-run']]) { assert.equal(res.status, 0, `expected exit 0; stdout:\n${res.stdout}\nstderr:\n${res.stderr}`); assert.match(res.stdout, /usage:/i); assert.match(res.stdout, /--dry-run/); + assert.match(res.stdout, /-h, --help/); assert.equal(res.stderr, ''); assert.doesNotMatch(res.stdout, /credentials not configured/i, 'no collection was started'); assert.deepEqual(snapshot(dir), before, 'no run status is written'); @@ -360,7 +361,7 @@ for (const key of ['npm_config_dryrun', 'npm_config_dry_rn', 'npm_config_dyrrun' }); } -test('the npm options npm 11 sets for every `npm run` are not read as a mistyped dry-run flag', () => { +test('the npm options npm 11 sets for every `npm run`, and the loglevel a flag such as --silent adds, are not read as a mistyped dry-run flag', () => { const npmEnv = Object.fromEntries([ 'allow_scripts', 'cache', 'global_prefix', 'globalconfig', 'init_module', 'local_prefix', 'loglevel', 'node_gyp', 'noproxy', 'npm_version', 'prefix', 'user_agent', 'userconfig', @@ -369,6 +370,42 @@ test('the npm options npm 11 sets for every `npm run` are not read as a mistyped assert.deepEqual(parseArgs([], { ...npmEnv, npm_config_dry_run: 'true' }), { dryRun: true }); }); +// Each is caught by one clause of the check alone: dry_running only by the +// `dry` prefix (it is 3 edits from dryrun), NPM_CONFIG_DRYRUN only by reading +// the npm_config_ prefix in any letter case, and npm_config_dryrun beside +// --dry-run only because the check also runs when --dry-run is given. +for (const [argv, key] of [ + [[], 'npm_config_dry_running'], + [[], 'NPM_CONFIG_DRYRUN'], + [['--dry-run'], 'npm_config_dryrun'], +]) { + test(`${key}=true${argv.length ? ` with ${argv.join(' ')}` : ''} is refused as a mistyped dry-run flag`, () => { + const res = parseArgs(argv, { [key]: 'true' }); + assert.ok(res.error && res.error.includes(key), `expected a refusal naming ${key}; got ${JSON.stringify(res)}`); + }); +} + +test('npm_config_dru=true, 3 edits from dryrun and without its prefix, is left to npm', () => { + assert.deepEqual(parseArgs([], { npm_config_dru: 'true' }), { dryRun: false }); +}); + +test('NPM_CONFIG_DRY_RUN=true, which npm reads as its dry-run option, is a dry run and starts nothing billed', async () => { + assert.deepEqual(parseArgs([], { NPM_CONFIG_DRY_RUN: 'true' }), { dryRun: true }); + assert.deepEqual(parseArgs([], { Npm_Config_Dry_Run: 'true', npm_config_dry_run: 'false' }), { dryRun: true }); + 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('npm_config_dry_run=true, which `npm run collect:pypi-countries --dry-run` sets, is a dry run', async () => { const dir = tmp(); try {