test: a short R2 failure while closing an upload: the server's steady retry and the browser's (contract contrato-r2-retry)
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 8m2s
Build and deploy / Secret scan and release gate (push) Successful in 8s
Build and deploy / Publish images (push) Successful in 1m12s

tests/test_storage_steady.py covers steady() and the storage's parts, size
and complete (a 5xx retried after 1, 2, 3 s; a 4xx and other errors at once;
NoSuchUpload on an object that exists is done). tests/upload_retry_test.mjs
covers closing the upload in web/upload.js (again after 3 s and 6 s; only
the last attempt reported; a 409 at once; an abort gives the upload back).
Both fail with the retry turned off. steady now looks time.sleep up when it
waits, so a patch of it reaches the storage methods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-12-01 13:34:23 -03:00
parent 5d70a6f912
commit 52fc90cbcd
4 changed files with 374 additions and 4 deletions

View File

@@ -0,0 +1,188 @@
"""Steady retries of R2/S3 5xx answers (contract contrato-r2-retry).
Run from the repository root: python3 -m unittest tests.test_storage_steady -v.
"""
import unittest
from contextlib import contextmanager
from unittest import mock
from botocore.exceptions import ClientError
from app import adapters
from app.adapters import LocalS3Storage
def stored_error(code='InternalError', status=500, operation='ListParts'):
return ClientError({'Error': {'Code': code, 'Message': 'x'},
'ResponseMetadata': {'HTTPStatusCode': status}}, operation)
@contextmanager
def sleep_spy():
"""The sleep the storage methods wait with (steady looks time.sleep up when it waits)."""
with mock.patch('app.adapters.time.sleep') as sleep:
yield sleep
def storage_with(client):
storage = LocalS3Storage.__new__(LocalS3Storage)
storage.client = client
storage.bucket = 'b'
return storage
class SteadyTest(unittest.TestCase):
def test_success_returns_the_value_without_sleeping(self):
sleep = mock.MagicMock()
call = mock.MagicMock(return_value='done')
self.assertEqual(adapters.steady(call, sleep=sleep), 'done')
self.assertEqual(call.call_count, 1)
sleep.assert_not_called()
def test_a_5xx_then_success_returns_the_value_after_sleeping_one_second(self):
sleep = mock.MagicMock()
call = mock.MagicMock(side_effect=[stored_error(), 'done'])
self.assertEqual(adapters.steady(call, sleep=sleep), 'done')
self.assertEqual(call.call_count, 2)
self.assertEqual(sleep.call_args_list, [mock.call(1)])
def test_four_5xx_raise_the_fourth_error_after_waiting_one_two_three(self):
sleep = mock.MagicMock()
error = stored_error()
call = mock.MagicMock(side_effect=error)
with self.assertRaises(ClientError) as caught:
adapters.steady(call, sleep=sleep)
self.assertIs(caught.exception, error)
self.assertEqual(call.call_count, 4)
self.assertEqual(sleep.call_args_list, [mock.call(1), mock.call(2), mock.call(3)])
def test_a_4xx_is_raised_at_once_without_sleeping(self):
for status in (404, 403, 409):
with self.subTest(status=status):
sleep = mock.MagicMock()
error = stored_error(status=status)
call = mock.MagicMock(side_effect=error)
with self.assertRaises(ClientError) as caught:
adapters.steady(call, sleep=sleep)
self.assertIs(caught.exception, error)
self.assertEqual(call.call_count, 1)
sleep.assert_not_called()
def test_a_non_client_error_is_raised_at_once_without_sleeping(self):
for error in (ValueError('bad'), TimeoutError('slow')):
with self.subTest(error=type(error).__name__):
sleep = mock.MagicMock()
call = mock.MagicMock(side_effect=error)
with self.assertRaises(type(error)) as caught:
adapters.steady(call, sleep=sleep)
self.assertIs(caught.exception, error)
self.assertEqual(call.call_count, 1)
sleep.assert_not_called()
def test_a_client_error_without_a_status_is_not_a_5xx(self):
sleep = mock.MagicMock()
error = ClientError({'Error': {'Code': 'InternalError', 'Message': 'x'}}, 'ListParts')
call = mock.MagicMock(side_effect=error)
with self.assertRaises(ClientError) as caught:
adapters.steady(call, sleep=sleep)
self.assertIs(caught.exception, error)
self.assertEqual(call.call_count, 1)
sleep.assert_not_called()
class PartsTest(unittest.TestCase):
def test_parts_retries_a_5xx_and_returns_every_part_of_every_page(self):
pages = [{'Parts': [{'PartNumber': 1, 'ETag': '"a"'}]},
{'Parts': [{'PartNumber': 2, 'ETag': '"b"'}, {'PartNumber': 3, 'ETag': '"c"'}]}]
paginator = mock.MagicMock()
paginator.paginate.side_effect = [stored_error(operation='ListParts'), pages]
client = mock.MagicMock()
client.get_paginator.return_value = paginator
storage = storage_with(client)
with sleep_spy() as sleep:
parts = storage.parts('key', 'upload')
self.assertEqual(parts, pages[0]['Parts'] + pages[1]['Parts'])
self.assertEqual(paginator.paginate.call_count, 2)
self.assertEqual(sleep.call_args_list, [mock.call(1)])
class SizeTest(unittest.TestCase):
def test_a_404_is_raised_at_once_without_sleeping(self):
error = stored_error('NoSuchKey', 404, 'HeadObject')
client = mock.MagicMock()
client.head_object.side_effect = error
storage = storage_with(client)
with sleep_spy() as sleep:
with self.assertRaises(ClientError) as caught:
storage.size('key')
self.assertIs(caught.exception, error)
self.assertEqual(client.head_object.call_count, 1)
sleep.assert_not_called()
def test_a_5xx_then_200_returns_the_content_length(self):
client = mock.MagicMock()
client.head_object.side_effect = [stored_error(operation='HeadObject'),
{'ContentLength': 1234}]
storage = storage_with(client)
with sleep_spy() as sleep:
self.assertEqual(storage.size('key'), 1234)
self.assertEqual(client.head_object.call_count, 2)
self.assertEqual(sleep.call_args_list, [mock.call(1)])
class CompleteTest(unittest.TestCase):
PARTS = [{'PartNumber': 1, 'ETag': '"a"'}]
def test_a_5xx_then_success_completes(self):
client = mock.MagicMock()
client.complete_multipart_upload.side_effect = [
stored_error(operation='CompleteMultipartUpload'), {}]
storage = storage_with(client)
with sleep_spy() as sleep:
self.assertIsNone(storage.complete('key', 'upload', self.PARTS))
self.assertEqual(client.complete_multipart_upload.call_count, 2)
self.assertEqual(sleep.call_args_list, [mock.call(1)])
def test_no_such_upload_with_the_object_present_returns_none(self):
client = mock.MagicMock()
client.complete_multipart_upload.side_effect = stored_error(
'NoSuchUpload', 404, 'CompleteMultipartUpload')
client.head_object.return_value = {'ContentLength': 10}
storage = storage_with(client)
with sleep_spy() as sleep:
self.assertIsNone(storage.complete('key', 'upload', self.PARTS))
self.assertEqual(client.complete_multipart_upload.call_count, 1)
self.assertEqual(client.head_object.call_count, 1)
sleep.assert_not_called()
def test_no_such_upload_with_a_missing_object_reraises_no_such_upload(self):
missing = stored_error('NoSuchUpload', 404, 'CompleteMultipartUpload')
client = mock.MagicMock()
client.complete_multipart_upload.side_effect = missing
client.head_object.side_effect = stored_error('NoSuchKey', 404, 'HeadObject')
storage = storage_with(client)
with sleep_spy() as sleep:
with self.assertRaises(ClientError) as caught:
storage.complete('key', 'upload', self.PARTS)
self.assertIs(caught.exception, missing)
self.assertEqual(caught.exception.response['Error']['Code'], 'NoSuchUpload')
self.assertEqual(client.complete_multipart_upload.call_count, 1)
self.assertEqual(client.head_object.call_count, 1)
sleep.assert_not_called()
def test_any_other_4xx_is_raised(self):
error = stored_error('AccessDenied', 403, 'CompleteMultipartUpload')
client = mock.MagicMock()
client.complete_multipart_upload.side_effect = error
storage = storage_with(client)
with sleep_spy() as sleep:
with self.assertRaises(ClientError) as caught:
storage.complete('key', 'upload', self.PARTS)
self.assertIs(caught.exception, error)
self.assertEqual(client.complete_multipart_upload.call_count, 1)
client.head_object.assert_not_called()
sleep.assert_not_called()
if __name__ == '__main__':
unittest.main()

180
tests/upload_retry_test.mjs Normal file
View File

@@ -0,0 +1,180 @@
// 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');