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
52 changes: 47 additions & 5 deletions pipeline/run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,51 @@ export function validateRows(rows, step, previousRows) {
return failures;
}

/** Statuses that mean "ask again", not "here is your answer". */
const RETRYABLE = new Set([408, 425, 429, 500, 502, 503, 504]);

/**
* Fetch one publisher file, trying again after a transient failure. EIA-930
* republishes a workbook per balancing authority every day and the largest are
* over 100 MB, so a single dropped connection used to fail a whole monthly
* refresh. `read` consumes the body, inside the attempt, so a failure part-way
* through the download is retried too, from the start. Any other status is the
* publisher's own answer rather than a blip, and is handed back unread for the
* caller to report as it does today.
* @param {string} url
* @param {(res: Response) => Promise<any>} [read] consumes the body; omitted, the response is returned unread
* @param {{attempts?: number, delayMs?: number, fetch?: typeof fetch, sleep?: (ms: number) => Promise<void>}} [o]
* @returns {Promise<{res: Response, value: any}>}
*/
export async function fetchRaw(url, read, o = {}) {
const f = o.fetch ?? fetch;
const attempts = o.attempts ?? 3;
const delayMs = o.delayMs ?? 2000;
const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
let res = null;
let err = null;
for (let attempt = 1; attempt <= attempts; attempt++) {
res = null;
err = null;
try {
res = await f(url);
if (res.ok) return { res, value: read ? await read(res) : res };
if (!RETRYABLE.has(res.status)) return { res, value: null };
} catch (e) {
err = e;
}
// Wait longer each time, so a publisher that is briefly overloaded is not hammered.
if (attempt < attempts) await sleep(delayMs * attempt);
}
if (err) throw err;
return { res, value: null };
}

/**
* The lines of a raw file, from its bytes or streamed from its path or URL. A
* streamed file's SHA-256 and size are recorded once it has been read to the end.
* Only opening the stream is retried: once bytes are flowing, the hash is part-built
* and the read cannot restart, so a mid-stream drop still fails the run.
*/
async function* linesOf(r) {
const decoder = new TextDecoder();
Expand All @@ -139,7 +181,7 @@ async function* linesOf(r) {
const hash = createHash('sha256');
let size = 0;
let rest = '';
const source = r.path ? createReadStream(r.path) : Readable.fromWeb((await fetch(r.url)).body);
const source = r.path ? createReadStream(r.path) : Readable.fromWeb((await fetchRaw(r.url)).res.body);
// A gzipped file (GHCN-Daily's per-station CSVs) is hashed as downloaded and read as text after inflating.
const gunzip = r.gzip ? createGunzip() : null;
const text = gunzip ? source.on('data', (c) => { hash.update(c); size += c.length; }).pipe(gunzip) : source;
Expand All @@ -164,9 +206,9 @@ async function xlsxOf(r, sheet) {
let bytes;
if (r.path) bytes = new Uint8Array(readFileSync(r.path));
else {
const res = await fetch(r.url);
const { res, value } = await fetchRaw(r.url, (x) => x.arrayBuffer());
if (!res.ok) throw new Error(`fetch ${r.url}: HTTP ${res.status}`);
bytes = new Uint8Array(await res.arrayBuffer());
bytes = new Uint8Array(value);
r.lastModified = res.headers.get('last-modified');
}
r.sha256 = sha256(bytes);
Expand Down Expand Up @@ -202,9 +244,9 @@ export async function runRecipe({ dataset, year, input, retrieved, outDir = join
}
let bytes = name ? input?.[name] : input;
if (!bytes) {
const res = await fetch(file.url);
const { res, value } = await fetchRaw(file.url, (x) => x.arrayBuffer());
if (!res.ok) return { ok: false, failures: [`fetch ${file.url}: HTTP ${res.status}`] };
bytes = new Uint8Array(await res.arrayBuffer());
bytes = new Uint8Array(value);
}
const sum = sha256(bytes);
if (verifyPin && file.sha256 && file.sha256 !== sum) return { ok: false, failures: [`raw file${name ? ` ${name}` : ''} SHA-256 ${sum} differs from the registry's ${file.sha256}`] };
Expand Down
83 changes: 83 additions & 0 deletions verify/tests/pipeline/raw-fetch.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Fetching a publisher's raw file, when the network drops part-way
// (issue #2: the EIA-930 refresh failed because the PJM workbook was never
// read to the end, so its SHA-256 was unknown).

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fetchRaw } from '../../../pipeline/run.mjs';

/** A publisher that fails in a given way the first `failures` times, then answers. */
function flaky(failures, fail) {
let calls = 0;
const f = async (url) => {
calls += 1;
if (calls <= failures) return fail(url);
return new Response('the workbook', { status: 200 });
};
return { fetch: f, calls: () => calls };
}

const nap = { delayMs: 0, sleep: async () => {} };
const dropped = () => { throw new TypeError('fetch failed'); };

test('a dropped connection is retried, and the file still arrives', async () => {
const site = flaky(2, dropped);
const { res, value } = await fetchRaw('https://eia.gov/PJM.xlsx', (x) => x.text(), { ...nap, fetch: site.fetch });
assert.equal(res.status, 200);
assert.equal(value, 'the workbook');
assert.equal(site.calls(), 3, 'two failures, then the attempt that worked');
});

test('a connection that never comes back throws the publisher\'s own error, after every attempt', async () => {
const site = flaky(Infinity, dropped);
await assert.rejects(
() => fetchRaw('https://eia.gov/PJM.xlsx', (x) => x.text(), { ...nap, fetch: site.fetch }),
(e) => e.message === 'fetch failed',
);
assert.equal(site.calls(), 3);
});

test('a failure part-way through the body is retried from the start of the download', async () => {
let calls = 0;
const f = async () => {
calls += 1;
if (calls === 1) return new Response(new ReadableStream({ start: (c) => c.error(new TypeError('terminated')) }), { status: 200 });
return new Response('the workbook', { status: 200 });
};
const { value } = await fetchRaw('https://eia.gov/PJM.xlsx', (x) => x.text(), { ...nap, fetch: f });
assert.equal(value, 'the workbook', 'a half-read 100 MB workbook is downloaded again, not left without a SHA-256');
assert.equal(calls, 2);
});

test('a 503 is retried; the last response is returned when it never clears', async () => {
const slow = flaky(1, () => new Response('busy', { status: 503 }));
assert.equal((await fetchRaw('https://eia.gov/PJM.xlsx', (x) => x.text(), { ...nap, fetch: slow.fetch })).res.status, 200);
assert.equal(slow.calls(), 2);

const down = flaky(Infinity, () => new Response('busy', { status: 503 }));
const { res } = await fetchRaw('https://eia.gov/PJM.xlsx', (x) => x.text(), { ...nap, fetch: down.fetch });
assert.equal(res.status, 503, 'the caller still reports "HTTP 503", as it did before the retry');
assert.equal(down.calls(), 3);
});

test('a 404 is the publisher\'s answer, not a blip: it is returned at once, unread', async () => {
const gone = flaky(Infinity, () => new Response('no such file', { status: 404 }));
const { res, value } = await fetchRaw('https://eia.gov/WAUE.xlsx', (x) => x.text(), { ...nap, fetch: gone.fetch });
assert.equal(res.status, 404);
assert.equal(value, null);
assert.equal(gone.calls(), 1, 'a missing file is not asked for three times');
});

test('without a reader the response is handed back unread, for a file that is streamed', async () => {
const site = flaky(1, dropped);
const { res, value } = await fetchRaw('https://eia.gov/eaglei.csv', undefined, { ...nap, fetch: site.fetch });
assert.equal(value, res);
assert.equal(await res.text(), 'the workbook', 'the body is still unread, so it can be streamed');
});

test('the wait grows with each attempt, so a busy publisher is not hammered', async () => {
const waits = [];
const site = flaky(2, dropped);
await fetchRaw('https://eia.gov/PJM.xlsx', (x) => x.text(), { fetch: site.fetch, delayMs: 100, sleep: async (ms) => { waits.push(ms); } });
assert.deepEqual(waits, [100, 200]);
});