diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index f83664e..01ff561 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -32,6 +32,7 @@ jobs: tests.test_observability \ tests.test_secrets -v node tests/observability_web_test.mjs + node tests/upload_retry_test.mjs sh -n infra/lock_dependencies.sh integration: @@ -101,7 +102,7 @@ jobs: # the generator's geometry. The provider suites use a fake transport: they # prove the documented contract, not the integration. - name: Print-file geometry and provider adapters - run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_proof_parts tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health tests.test_saved_size -v + run: $COMPOSE exec -T api python -m unittest tests.test_storage_steady tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_sheet_trim tests.test_one_machine tests.test_profiles tests.test_sheet_gap tests.test_reprint tests.test_proof_parts tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain tests.test_db_outage tests.test_health tests.test_saved_size -v - name: Runtime and retention regressions run: | diff --git a/app/adapters.py b/app/adapters.py index d366732..d66e043 100644 --- a/app/adapters.py +++ b/app/adapters.py @@ -254,15 +254,16 @@ def server_error(exc): return (exc.response.get('ResponseMetadata', {}).get('HTTPStatusCode') or 0) >= 500 -def steady(call, sleep=time.sleep): - """`call()`, again after each wait in STEADY_WAITS while storage answers 5xx.""" +def steady(call, sleep=None): + """`call()`, again after each wait in STEADY_WAITS while storage answers 5xx. + `sleep` is time.sleep, looked up when it waits (tests patch it).""" for wait in STEADY_WAITS + (None,): try: return call() except ClientError as exc: if wait is None or not server_error(exc): raise - sleep(wait) + (sleep or time.sleep)(wait) class LocalS3Storage: diff --git a/tests/test_storage_steady.py b/tests/test_storage_steady.py new file mode 100644 index 0000000..ec65762 --- /dev/null +++ b/tests/test_storage_steady.py @@ -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() diff --git a/tests/upload_retry_test.mjs b/tests/upload_retry_test.mjs new file mode 100644 index 0000000..c0d6d4d --- /dev/null +++ b/tests/upload_retry_test.mjs @@ -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');