diff --git a/.env.example b/.env.example index 605610e..1becb88 100644 --- a/.env.example +++ b/.env.example @@ -58,6 +58,6 @@ MAX_UPLOAD_BYTES=4294967296 UPLOAD_PART_BYTES=8388608 STORAGE_QUOTA_BYTES=53687091200 OWNER_UPLOAD_QUOTA_BYTES=10737418240 -MAX_PENDING_UPLOADS=10 +MAX_PENDING_UPLOADS=30 # Files above 128 MiB remain blocked (ClamAV config must agree with this limit). SCAN_MAX_BYTES=134217728 diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 18b8566..90b40f7 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -31,6 +31,7 @@ jobs: tests.test_label \ tests.test_observability \ tests.test_secrets -v + node tests/observability_web_test.mjs sh -n infra/lock_dependencies.sh integration: diff --git a/app/api/uploads.py b/app/api/uploads.py index 95a9652..46124a8 100644 --- a/app/api/uploads.py +++ b/app/api/uploads.py @@ -47,10 +47,16 @@ def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(u count(*) FILTER(WHERE owner=%s AND NOT complete) AS pending FROM dtf_local.uploads WHERE purged_at IS NULL''', (session_id,session_id)).fetchone() - if (usage['total']+body.size > int(os.environ.get('STORAGE_QUOTA_BYTES','53687091200')) or - usage['owned']+body.size > int(os.environ.get('OWNER_UPLOAD_QUOTA_BYTES','10737418240')) or - usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','10'))): + storage_full = (usage['total']+body.size > int(os.environ.get('STORAGE_QUOTA_BYTES','53687091200')) or + usage['owned']+body.size > int(os.environ.get('OWNER_UPLOAD_QUOTA_BYTES','10737418240'))) + pending_full = usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','30')) + if storage_full or pending_full: audit('upload_quota_rejected') + if pending_full and not storage_full: + # A big cart goes 4 at a time now (web/upload.js); a burst may + # still meet the pending cap: ask the Site to wait and retry. + raise HTTPException(429, 'Muitos envios ao mesmo tempo. O site tenta de novo sozinho.', + headers={'Retry-After': '15'}) raise HTTPException(429, 'Limite de armazenamento ou de envios pendentes atingido. Tente de novo mais tarde.') multipart = storage.begin(key) c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,original_name,size,object_key,multipart_id,expires_at) diff --git a/app/grade_check.py b/app/grade_check.py index cd9686d..09888fa 100644 --- a/app/grade_check.py +++ b/app/grade_check.py @@ -217,10 +217,12 @@ def resolution_issue(files, items, rows): dpis.append(dpi) if not dpis: continue - lowest = min(dpis) - if lowest < DPI_REFUSE: - return f'Item {index}: resolução de {js_round(lowest)} DPI abaixo do mínimo de {DPI_REFUSE} DPI.' - if lowest < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']): + # The Site shows and compares the rounded DPI (web/site-quality.js, + # site-pdf.js): decide on the same whole number, not the raw fraction. + shown = js_round(min(dpis)) + if shown < DPI_REFUSE: + return f'Item {index}: resolução de {shown} DPI abaixo do mínimo de {DPI_REFUSE} DPI.' + if shown < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']): return f'Item {index}: confirme a ressalva de resolução entre {DPI_REFUSE} e {DPI_IDEAL - 1} DPI.' return None diff --git a/compose.local.yaml b/compose.local.yaml index 76932e0..f6222c0 100644 --- a/compose.local.yaml +++ b/compose.local.yaml @@ -102,7 +102,7 @@ x-app: &app UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608} STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200} OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240} - MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-10} + MAX_PENDING_UPLOADS: ${MAX_PENDING_UPLOADS:-30} SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-2097152000} networks: [local] init: true diff --git a/docker-compose.yml b/docker-compose.yml index ddaa617..c991fab 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -156,7 +156,7 @@ x-app-environment: &app-environment # Sheets of several GB are the normal order, so room for many of them. STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}" OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}" - MAX_PENDING_UPLOADS: "10" + MAX_PENDING_UPLOADS: "30" # ClamAV scans up to its own limit, 2000 MiB (infra/clamd.conf); a larger # file, up to the 4 GB above, is released after the file-format check # (app/scanning.py, check_large). diff --git a/tests/observability_web_test.mjs b/tests/observability_web_test.mjs new file mode 100644 index 0000000..48619a5 --- /dev/null +++ b/tests/observability_web_test.mjs @@ -0,0 +1,50 @@ +// The browser's API error grouping (note Sentry): one issue per kind of error. +// Dependency-free: Node loads web/observability.js with a stub Sentry. +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import vm from 'node:vm'; + +let captured; +globalThis.window = globalThis; +globalThis.location = {pathname: '/carrinho'}; +globalThis.Sentry = { + init() {}, + setTag() {}, + captureMessage(message, options) { captured = {message, options}; }, +}; +vm.runInThisContext(readFileSync('web/observability.js', 'utf8')); +window.dtfObservability.start('https://key@o1.ingest.sentry.io/1', 'site'); + +const apiError = (path, status, message) => { + captured = null; + window.dtfObservability.apiError(path, status, message); + assert.ok(captured, 'apiError sends one event'); + return captured; +}; + +const expired = 'Este arquivo expirou. Escolha o arquivo de novo.'; +const first = apiError('/uploads/ba39b432-b0d1-4b1b-8971-09123e067067', 410, expired); +const second = apiError('/uploads/5f2be7e0-1111-2222-3333-444455556666', 410, expired); +assert.deepEqual(first.options.fingerprint, second.options.fingerprint); +assert.equal(first.message, 'API 410 /uploads/:id: ' + expired); +assert.deepEqual(first.options.fingerprint, ['api-error', '410', '/uploads/:id', expired]); + +const otherMessage = apiError('/uploads/ba39b432-b0d1-4b1b-8971-09123e067067', 410, + 'Arquivo não encontrado. Escolha o arquivo de novo.'); +assert.notDeepEqual(first.options.fingerprint, otherMessage.options.fingerprint); + +// The numbers and the file names in the server message change per occurrence; +// the kind does not. +const png = apiError('/quotes', 422, 'Item 1: layout.png abaixo do mínimo de 96 DPI.'); +const jpg = apiError('/quotes', 422, 'Item 2: final.jpg abaixo do mínimo de 300 DPI.'); +assert.deepEqual(png.options.fingerprint, jpg.options.fingerprint); +assert.equal(png.message, 'API 422 /quotes: Item :id: :arquivo abaixo do mínimo de :id DPI.'); + +// The status and the path are part of the kind. +assert.notDeepEqual(png.options.fingerprint, + apiError('/quotes', 500, 'Item 1: layout.png abaixo do mínimo de 96 DPI.').options.fingerprint); +assert.notDeepEqual( + apiError('/quotes/ba39b432-b0d1-4b1b-8971-09123e067067', 422, expired).options.fingerprint, + apiError('/orders/ba39b432-b0d1-4b1b-8971-09123e067067', 422, expired).options.fingerprint); + +console.log('observability web checks passed'); diff --git a/tests/test_grade_check.py b/tests/test_grade_check.py index f35b2fc..b751cf3 100644 --- a/tests/test_grade_check.py +++ b/tests/test_grade_check.py @@ -142,6 +142,20 @@ class GradeCheckTests(unittest.TestCase): for dpi in (200, 287, 293): self.assertIsNone(issue(dpi), dpi) self.assertEqual(grade_check.grade_of(dpi), 100) + # The Site shows the rounded DPI: 95.6 is 96 and passes; 95.4 is 95 + # and is refused. The warning band starts at the shown 199. + width_px = lambda dpi: round(dpi * 57 / 2.54) + for dpi in (95.6, 95.4, 199.6, 199.4): + files.blobs[f'{dpi}.png'] = encoded('PNG', (width_px(dpi), 20)) + rows[f'{dpi}.png'] = {'name': f'{dpi}.png', 'size': 1} + # 95.6 is shown as 96: the warning band, not the refusal; acknowledged, + # it goes through. 95.4 is shown as 95 and refused. + self.assertNotIn('abaixo do mínimo', issue(95.6)) + self.assertIn('confirme a ressalva', issue(95.6)) + self.assertIsNone(issue(95.6, 'warning', True)) + self.assertIn('95 DPI', issue(95.4)) + self.assertIsNone(issue(199.6)) + self.assertIn('confirme a ressalva', issue(199.4)) if __name__ == '__main__': diff --git a/tests/upload_limits_test.py b/tests/upload_limits_test.py index 4acb857..1ff162b 100644 --- a/tests/upload_limits_test.py +++ b/tests/upload_limits_test.py @@ -4,8 +4,12 @@ takes up to 200 files per item (Sentry DTF-WEB-1). Run against the local stack: python -m tests.upload_limits_test """ +import json +import os import secrets from pathlib import Path +from urllib.error import HTTPError +from urllib.request import Request from uuid import UUID, uuid4 from fastapi import HTTPException @@ -13,7 +17,7 @@ from fastapi import HTTPException from app.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT from app.core import db from app.core.auth import rate_limit -from tests.smoke_test import Client, upload_bytes +from tests.smoke_test import BASE, Client, upload_bytes, with_host PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes() TOO_MANY = 'Este item tem mais de 200 arquivos. Divida em dois itens.' @@ -59,6 +63,25 @@ def run(): else: raise AssertionError('the per-source upload bucket accepted above its limit') + # DTF-WEB-3: a burst above MAX_PENDING_UPLOADS (now 30). The 31st start + # answers 429 with Retry-After 15, so the Site waits and retries alone. + assert int(os.environ.get('MAX_PENDING_UPLOADS', '30')) == 30 + pending = [] + for index in range(30): + pending.append(client.call('/uploads', {'name': f'PENDING-{index}.png', 'size': 1})['id']) + burst = Request(BASE + '/api/uploads', + data=json.dumps({'name': 'PENDING-31.png', 'size': 1}).encode(), + headers=with_host({'Content-Type': 'application/json'}), method='POST') + try: + with client.opener.open(burst, timeout=30) as response: + raise AssertionError('the pending-upload cap accepted the 31st upload') + except HTTPError as error: + assert error.code == 429, error + assert error.headers.get('Retry-After') == '15', error.headers + assert json.load(error)['detail'] == 'Muitos envios ao mesmo tempo. O site tenta de novo sozinho.' + for uid in pending: + client.call(f'/uploads/{uid}', expected=200, method='DELETE') + # Sentry DTF-WEB-1: 66 sheets in one ready-sheet item is quoted and # approved; the old cap of 20 refused it with a generic 422. uploads = [upload_bytes(client, PNG, name=f'SHEET66-{index}.png') for index in range(66)] diff --git a/web/checkout.js b/web/checkout.js index 61b274b..97fd19f 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -37,7 +37,7 @@ localStorage.removeItem(key); } function clearDraft() { forgetDraft(); actions.replaceChildren(); } - const api = async (path, body) => { + const api = async (path, body, options = {}) => { const response = await fetch('/api'+path, { credentials: 'same-origin', headers: {'Content-Type':'application/json'}, ...(body === undefined ? {} : {method:'POST', body:JSON.stringify(body)}) @@ -55,7 +55,10 @@ const error=new Error(text);error.status=response.status; const retry=response.headers.get('Retry-After'); if(retry!=null)error.retryAfter=retry; - window.dtfObservability?.apiError?.(path,response.status,error.message,data.detail); + // A status the caller expects (a resumed upload that expired) is handled + // there, not reported. + if(!(options.expected||[]).includes(response.status)) + window.dtfObservability?.apiError?.(path,response.status,error.message,data.detail); throw error; } return data; diff --git a/web/observability.js b/web/observability.js index 47fdc0a..c893fa5 100644 --- a/web/observability.js +++ b/web/observability.js @@ -8,6 +8,11 @@ (function () { const EMAIL = /[^\s@]+@[^\s@]+\.[A-Za-z]{2,}/g; const DOCUMENT = /(?:,;()[\]{}]+\.(?:png|jpe?g|pdf|tiff?|psd|psb|ai|cdr|webp|zip)\b/gi; + const NUMBER = /\d+/g; const SENSITIVE_PARAM = /token|signature|x-amz/i; const SENSITIVE_HEADER = /^(cookie|authorization|x-.*token.*)$/i; const REDACTED = '[removido]'; @@ -104,13 +109,24 @@ } } + const normalizedPath = value => clean(String(value == null ? '' : value) + .replace(UUID, ':id').replace(NUMBER, ':id')); + const normalizedMessage = value => clean(String(value == null ? '' : value) + .replace(UUID, ':id').replace(FILE_NAME, ':arquivo').replace(NUMBER, ':id')); + function apiError(path, status, message, detail) { if (!started || status === 401 || typeof Sentry === 'undefined') return; try { + // One issue per kind of API error: without this Sentry groups them all + // by apiError and DTF-WEB-1 mixes a 422 for 66 files with a 422 for + // 96 DPI. The title names the same kind as the fingerprint. + const kindPath = normalizedPath(path); + const kindMessage = normalizedMessage(message); const extra = {path, status, page: location.pathname}; if (status === 422 && detail) extra.detail = detail; - Sentry.captureMessage(clean('API ' + status + ' ' + path + ': ' + (message || '')), - {level: 'error', tags: {app}, extra}); + Sentry.captureMessage('API ' + status + ' ' + kindPath + ': ' + kindMessage, + {level: 'error', tags: {app}, extra, + fingerprint: ['api-error', String(status), kindPath, kindMessage]}); } catch (error) { // Reporting an error must never break the page. } diff --git a/web/upload.js b/web/upload.js index 87a1fb3..53eb65e 100644 --- a/web/upload.js +++ b/web/upload.js @@ -1,5 +1,18 @@ /* Shared direct multipart transport for customer originals/corrections and operator finals. */ -window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progress=()=>{}, onBytes=()=>{}, scope='guest', resume=true, signal=null}) => { +// A big cart would otherwise open dozens of server reservations at once and +// meet the pending-upload cap. Four at a time, the rest queued here. +const DTF_UPLOAD_SLOTS=4; +let uploadSlotsUsed=0; +const uploadSlotsWaiting=[]; +function uploadSlot(){ + if(uploadSlotsUseduploadSlotsWaiting.push(resolve)); +} +function releaseUploadSlot(){ + const next=uploadSlotsWaiting.shift(); + if(next)next();else uploadSlotsUsed--; +} +async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progress=()=>{}, onBytes=()=>{}, scope='guest', resume=true, signal=null}) { const cancelled=()=>new DOMException('Envio cancelado.','AbortError'); const samples=new Blob([file.slice(0,65536),file.slice(Math.max(0,file.size-65536))]); const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',await samples.arrayBuffer())),b=>b.toString(16).padStart(2,'0')).join(''); @@ -23,11 +36,12 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr }; let id=resume?localStorage.getItem(key):null,state; if(id){ - try{state=await api(prefix+'/'+id);} + try{state=await api(prefix+'/'+id,undefined,{expected:[403,404,410]});} catch(error){ - // The id was started under another session (a sign-in changes the scope): - // the new session does not own it, so this file starts again as a new - // upload. A 403/404/410 must never keep the retry on the old id. + // The id is only a hint from the last visit. When the upload expired or + // was started under another session (a sign-in changes the scope), this + // file starts again as a new upload, silently, and its id is replaced. + // These refusals are expected here and never reach Sentry. if(![403,404,410].includes(error.status))throw error; id=null; if(resume)localStorage.removeItem(key); @@ -76,4 +90,10 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr } await api(prefix+'/'+id+'/complete',{}); return waitForScan(); +} +window.dtfUpload = async (file, options) => { + if(options?.signal?.aborted)throw new DOMException('Envio cancelado.','AbortError'); + await uploadSlot(); + try{return await sendUpload(file, options);} + finally{releaseUploadSlot();} };