// Closing the upload: a short R2 failure is retried after 3 s and 6 s // (contract output/revisao/contrato-r2-retry.md, Browser B1-B6). // Dependency-free: Node loads web/upload.js with stub browser globals. import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; import vm from 'node:vm'; globalThis.window = globalThis; globalThis.localStorage = { store: new Map(), getItem(key) { return this.store.has(key) ? this.store.get(key) : null; }, setItem(key, value) { this.store.set(key, String(value)); }, removeItem(key) { this.store.delete(key); }, }; let calls; let delays; let fetches; let onTimeout; globalThis.setTimeout = (fn, delay) => { delays.push(delay); onTimeout?.(fn, delay); fn(); return 0; }; globalThis.XMLHttpRequest = class { constructor() { this.status = 200; this.upload = {}; } open() {} send() { this.onload?.(); } abort() { this.onabort?.(); } }; globalThis.fetch = async (url, options) => { fetches.push({url, options}); return {ok: true}; }; vm.runInThisContext(readFileSync('web/upload.js', 'utf8')); const completeCalls = () => calls.filter(call => call.path === '/uploads/u1/complete'); const withStatus = (message, status) => { const error = new Error(message); error.status = status; return error; }; const makeApi = completeSteps => { let completed = 0; return async (path, body, options) => { calls.push({path, body, options}); if (path === '/uploads') return {id: 'u1', part_bytes: 1000, parts: [], complete: false}; if (path === '/uploads/u1/parts/1') return {url: 'https://r2.test/part1'}; if (path === '/uploads/u1/complete') { const step = completeSteps[Math.min(completed, completeSteps.length - 1)]; completed++; if (step instanceof Error) throw step; return step ?? {}; } if (path === '/uploads/u1') return {scan_state: 'clean'}; throw new Error('caminho inesperado: ' + path); }; }; // One independent run: fresh records, a fresh File and a fresh api. const run = async (completeSteps, {abortAfter} = {}) => { calls = []; delays = []; fetches = []; const controller = new AbortController(); onTimeout = abortAfter === undefined ? undefined : (fn, delay) => { if (delay === abortAfter) controller.abort(); }; const api = makeApi(completeSteps); const file = new File([new Uint8Array(1000)], 'a.png', {lastModified: 1}); let result; let error; try { result = await window.dtfUpload(file, { api, prefix: '/uploads', progress() {}, onBytes() {}, scope: 'guest', resume: false, signal: controller.signal, }); } catch (caught) { error = caught; } onTimeout = undefined; return {result, error, calls, delays, fetches}; }; // B1. complete answers: no retry, upload continues to the scan wait. { const {result, error, delays} = await run([{}]); assert.equal(error, undefined); assert.equal(result, 'u1'); assert.equal(completeCalls().length, 1); assert.deepEqual(delays, []); } // B2. No status (non-JSON reply or network) then success. { const noStatus = new Error('O serviço está indisponível. Tente novamente em instantes.'); const {result, error, delays} = await run([noStatus, {}]); assert.equal(error, undefined); assert.equal(result, 'u1'); assert.equal(completeCalls().length, 2); assert.deepEqual(delays, [3000]); } // B2. A 503 then success, same wait. { const unavailable = withStatus('O serviço está indisponível. Tente novamente em instantes.', 503); const {result, error, delays} = await run([unavailable, {}]); assert.equal(error, undefined); assert.equal(result, 'u1'); assert.equal(completeCalls().length, 2); assert.deepEqual(delays, [3000]); } // B3. Three failures: the third error is thrown, after 3 s and 6 s. { const failures = [ new Error('falha 1'), new Error('falha 2'), new Error('falha 3'), ]; const {result, error, delays} = await run(failures); assert.equal(result, undefined); assert.equal(error, failures[2]); assert.equal(completeCalls().length, 3); assert.deepEqual(delays, [3000, 6000]); } // B4. Only the last attempt may be reported: attempts 1 and 2 expect the // server errors, attempt 3 passes no options. { const failures = [ new Error('falha 1'), new Error('falha 2'), new Error('falha 3'), ]; await run(failures); const options = completeCalls().map(call => call.options); assert.deepEqual(options, [ {expected: [500, 502, 503, 504]}, {expected: [500, 502, 503, 504]}, {}, ]); } // B5. A 409 is thrown at once, one call and no wait. { const conflict = withStatus('O envio do arquivo não chegou inteiro.', 409); const {result, error, delays} = await run([conflict]); assert.equal(result, undefined); assert.equal(error, conflict); assert.equal(completeCalls().length, 1); assert.deepEqual(delays, []); } // B6. Aborted during the wait: the upload is given back (DELETE) and an // AbortError is thrown; complete is not asked again. { const noStatus = new Error('O serviço está indisponível. Tente novamente em instantes.'); const {result, error, delays, fetches: requested} = await run([noStatus], {abortAfter: 3000}); assert.equal(result, undefined); assert.equal(error?.name, 'AbortError'); assert.equal(completeCalls().length, 1); assert.deepEqual(delays, [3000]); assert.equal(requested.length, 1); assert.equal(requested[0].url, '/api/uploads/u1'); assert.equal(requested[0].options.method, 'DELETE'); } console.log('upload retry checks passed');