Files
dtf-system/tests/upload_retry_test.mjs
Cauê Faleiros 3b4f851fc2
All checks were successful
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Successful in 9m2s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m15s
fix: the page waits while the antivirus restarts instead of showing its English reason (DTF-WEB-2F)
At 19:22 a customer read "Malware scanner unavailable; file remains blocked":
the scan answered "error" (the antivirus not answering, likely restarting
with the deploy), and the page treated it as final, while the worker scans
an "error" file again a minute later (app/scanning.py). The page now keeps
waiting through "error", within the same budget as a pending scan; only
"rejected" stops at once, with its reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 16:40:38 -03:00

240 lines
7.9 KiB
JavaScript

// 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;
let scanStates = [];
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: scanStates.length ? scanStates.shift() : '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');
}
// A file the phone can no longer read (Android NotReadableError, DTF-WEB-2A):
// the customer is told in Portuguese to pick it again, and nothing is sent.
{
const RealBlob = globalThis.Blob;
globalThis.Blob = class extends RealBlob {
arrayBuffer() { return Promise.reject(new DOMException('The requested file could not be read', 'NotReadableError')); }
};
try {
const {result, error, calls} = await run([{}]);
assert.equal(result, undefined);
assert.equal(error?.unreadable, true);
assert.match(error.message, /salve no aparelho e escolha de novo/);
// Sentry learns the kind of file, never its name (DTF-WEB-2D).
assert.deepEqual(error.detalhe, {erro: 'NotReadableError', tipo: '', extensao: 'png', mb: 0});
assert.ok(!JSON.stringify(error.detalhe).includes('a.png'));
assert.equal(calls.length, 0, 'nothing reaches the server');
} finally {
globalThis.Blob = RealBlob;
}
}
// The antivirus takes one file at a time for every customer: a file waiting
// behind others is still waited for, past the old two and a half minutes
// (Sentry DTF-WEB-2E), polling every 5 s after the first 150.
{
scanStates = Array(250).fill('pending');
const {result, error} = await run([{}]);
assert.equal(error, undefined);
assert.equal(result, 'u1');
const waits = delays.filter(d => d === 1000 || d === 5000);
assert.ok(waits.filter(d => d === 1000).length === 150 && waits.includes(5000));
}
// The antivirus not answering (a deploy restarting it) is scanned again by the
// worker a minute later: the page waits through it (Sentry DTF-WEB-2F).
{
scanStates = Array(70).fill('error');
const {result, error} = await run([{}]);
assert.equal(error, undefined);
assert.equal(result, 'u1');
scanStates = [];
}
// A refused file stops at once, with the server's reason.
{
scanStates = ['pending', 'rejected'];
const {error} = await run([{}]);
assert.match(error?.message || '', /bloqueado pela verificação/);
scanStates = [];
}
// A scan the server never finishes ends with the message, after its 15 minutes.
{
scanStates = Array(5000).fill('pending');
const {error} = await run([{}]);
assert.match(error?.message || '', /Verificação de segurança pendente/);
const waited = delays.filter(d => d === 1000 || d === 5000).reduce((t, d) => t + d, 0);
assert.ok(waited >= 900000 && waited < 910000, 'waited ' + waited);
scanStates = [];
}
console.log('upload retry checks passed');