From 31776ca353508fbe3d3fd2e354ce11e74fa06b3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Thu, 12 Nov 2026 09:38:51 -0300 Subject: [PATCH] fix: 96 DPI is accepted as the Site shows it; big carts upload 4 at a time (Sentry 12/11) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The server compared the raw lowest resolution (95,6) with 96 but printed it rounded, refusing '96 DPI abaixo do mínimo de 96'; it now decides on the same rounded value the Site shows. A big cart started every upload at once and hit the limit of 10 pending uploads (429): the limit is 30, that refusal carries Retry-After so the Site retries by itself, and the Site runs at most 4 uploads at a time. Co-Authored-By: Claude Opus 5.5 (1M context) --- .env.example | 2 +- app/api/uploads.py | 12 +++++++++--- app/grade_check.py | 10 ++++++---- compose.local.yaml | 2 +- docker-compose.yml | 2 +- tests/test_grade_check.py | 14 ++++++++++++++ tests/upload_limits_test.py | 25 ++++++++++++++++++++++++- web/upload.js | 21 ++++++++++++++++++++- 8 files changed, 76 insertions(+), 12 deletions(-) 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/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/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/upload.js b/web/upload.js index 87a1fb3..11c436e 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(''); @@ -76,4 +89,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();} };