Merge Sentry bugs of 12/11: 96 DPI, pending uploads, error grouping
All checks were successful
Build and deploy / Validate source (push) Successful in 1m53s
Build and deploy / Integration suite on a real stack (push) Successful in 8m3s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m49s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-12 10:23:40 -03:00
12 changed files with 155 additions and 20 deletions

View File

@@ -58,6 +58,6 @@ MAX_UPLOAD_BYTES=4294967296
UPLOAD_PART_BYTES=8388608 UPLOAD_PART_BYTES=8388608
STORAGE_QUOTA_BYTES=53687091200 STORAGE_QUOTA_BYTES=53687091200
OWNER_UPLOAD_QUOTA_BYTES=10737418240 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). # Files above 128 MiB remain blocked (ClamAV config must agree with this limit).
SCAN_MAX_BYTES=134217728 SCAN_MAX_BYTES=134217728

View File

@@ -31,6 +31,7 @@ jobs:
tests.test_label \ tests.test_label \
tests.test_observability \ tests.test_observability \
tests.test_secrets -v tests.test_secrets -v
node tests/observability_web_test.mjs
sh -n infra/lock_dependencies.sh sh -n infra/lock_dependencies.sh
integration: integration:

View File

@@ -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 count(*) FILTER(WHERE owner=%s AND NOT complete) AS pending
FROM dtf_local.uploads WHERE purged_at IS NULL''', FROM dtf_local.uploads WHERE purged_at IS NULL''',
(session_id,session_id)).fetchone() (session_id,session_id)).fetchone()
if (usage['total']+body.size > int(os.environ.get('STORAGE_QUOTA_BYTES','53687091200')) or 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')) or usage['owned']+body.size > int(os.environ.get('OWNER_UPLOAD_QUOTA_BYTES','10737418240')))
usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','10'))): pending_full = usage['pending'] >= int(os.environ.get('MAX_PENDING_UPLOADS','30'))
if storage_full or pending_full:
audit('upload_quota_rejected') 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.') raise HTTPException(429, 'Limite de armazenamento ou de envios pendentes atingido. Tente de novo mais tarde.')
multipart = storage.begin(key) multipart = storage.begin(key)
c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,original_name,size,object_key,multipart_id,expires_at) c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,original_name,size,object_key,multipart_id,expires_at)

View File

@@ -217,10 +217,12 @@ def resolution_issue(files, items, rows):
dpis.append(dpi) dpis.append(dpi)
if not dpis: if not dpis:
continue continue
lowest = min(dpis) # The Site shows and compares the rounded DPI (web/site-quality.js,
if lowest < DPI_REFUSE: # site-pdf.js): decide on the same whole number, not the raw fraction.
return f'Item {index}: resolução de {js_round(lowest)} DPI abaixo do mínimo de {DPI_REFUSE} DPI.' shown = js_round(min(dpis))
if lowest < DPI_IDEAL and (item['quality_status'] != 'warning' or not item['quality_acknowledged']): 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 f'Item {index}: confirme a ressalva de resolução entre {DPI_REFUSE} e {DPI_IDEAL - 1} DPI.'
return None return None

View File

@@ -102,7 +102,7 @@ x-app: &app
UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608} UPLOAD_PART_BYTES: ${UPLOAD_PART_BYTES:-8388608}
STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200} STORAGE_QUOTA_BYTES: ${STORAGE_QUOTA_BYTES:-53687091200}
OWNER_UPLOAD_QUOTA_BYTES: ${OWNER_UPLOAD_QUOTA_BYTES:-10737418240} 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} SCAN_MAX_BYTES: ${SCAN_MAX_BYTES:-2097152000}
networks: [local] networks: [local]
init: true init: true

View File

@@ -156,7 +156,7 @@ x-app-environment: &app-environment
# Sheets of several GB are the normal order, so room for many of them. # Sheets of several GB are the normal order, so room for many of them.
STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}" STORAGE_QUOTA_BYTES: "${STORAGE_QUOTA_BYTES:-536870912000}"
OWNER_UPLOAD_QUOTA_BYTES: "${OWNER_UPLOAD_QUOTA_BYTES:-53687091200}" 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 # 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 # file, up to the 4 GB above, is released after the file-format check
# (app/scanning.py, check_large). # (app/scanning.py, check_large).

View File

@@ -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');

View File

@@ -142,6 +142,20 @@ class GradeCheckTests(unittest.TestCase):
for dpi in (200, 287, 293): for dpi in (200, 287, 293):
self.assertIsNone(issue(dpi), dpi) self.assertIsNone(issue(dpi), dpi)
self.assertEqual(grade_check.grade_of(dpi), 100) 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__': if __name__ == '__main__':

View File

@@ -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 Run against the local stack: python -m tests.upload_limits_test
""" """
import json
import os
import secrets import secrets
from pathlib import Path from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request
from uuid import UUID, uuid4 from uuid import UUID, uuid4
from fastapi import HTTPException 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.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT
from app.core import db from app.core import db
from app.core.auth import rate_limit 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() PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes()
TOO_MANY = 'Este item tem mais de 200 arquivos. Divida em dois itens.' TOO_MANY = 'Este item tem mais de 200 arquivos. Divida em dois itens.'
@@ -59,6 +63,25 @@ def run():
else: else:
raise AssertionError('the per-source upload bucket accepted above its limit') 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 # 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. # 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)] uploads = [upload_bytes(client, PNG, name=f'SHEET66-{index}.png') for index in range(66)]

View File

@@ -37,7 +37,7 @@
localStorage.removeItem(key); localStorage.removeItem(key);
} }
function clearDraft() { forgetDraft(); actions.replaceChildren(); } function clearDraft() { forgetDraft(); actions.replaceChildren(); }
const api = async (path, body) => { const api = async (path, body, options = {}) => {
const response = await fetch('/api'+path, { const response = await fetch('/api'+path, {
credentials: 'same-origin', headers: {'Content-Type':'application/json'}, credentials: 'same-origin', headers: {'Content-Type':'application/json'},
...(body === undefined ? {} : {method:'POST', body:JSON.stringify(body)}) ...(body === undefined ? {} : {method:'POST', body:JSON.stringify(body)})
@@ -55,6 +55,9 @@
const error=new Error(text);error.status=response.status; const error=new Error(text);error.status=response.status;
const retry=response.headers.get('Retry-After'); const retry=response.headers.get('Retry-After');
if(retry!=null)error.retryAfter=retry; if(retry!=null)error.retryAfter=retry;
// 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); window.dtfObservability?.apiError?.(path,response.status,error.message,data.detail);
throw error; throw error;
} }

View File

@@ -8,6 +8,11 @@
(function () { (function () {
const EMAIL = /[^\s@]+@[^\s@]+\.[A-Za-z]{2,}/g; const EMAIL = /[^\s@]+@[^\s@]+\.[A-Za-z]{2,}/g;
const DOCUMENT = /(?<!\d)(?:\d{2}\.?\d{3}\.?\d{3}\/?\d{4}-?\d{2}|\d{3}\.?\d{3}\.?\d{3}-?\d{2})(?!\d)/g; const DOCUMENT = /(?<!\d)(?:\d{2}\.?\d{3}\.?\d{3}\/?\d{4}-?\d{2}|\d{3}\.?\d{3}\.?\d{3}-?\d{2})(?!\d)/g;
// What changes from one API error to the next of the same kind: the ids of
// the files, quotes and orders, the numbers and the file names.
const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
const FILE_NAME = /[^\s"'<>:,;()[\]{}]+\.(?: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_PARAM = /token|signature|x-amz/i;
const SENSITIVE_HEADER = /^(cookie|authorization|x-.*token.*)$/i; const SENSITIVE_HEADER = /^(cookie|authorization|x-.*token.*)$/i;
const REDACTED = '[removido]'; 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) { function apiError(path, status, message, detail) {
if (!started || status === 401 || typeof Sentry === 'undefined') return; if (!started || status === 401 || typeof Sentry === 'undefined') return;
try { 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}; const extra = {path, status, page: location.pathname};
if (status === 422 && detail) extra.detail = detail; if (status === 422 && detail) extra.detail = detail;
Sentry.captureMessage(clean('API ' + status + ' ' + path + ': ' + (message || '')), Sentry.captureMessage('API ' + status + ' ' + kindPath + ': ' + kindMessage,
{level: 'error', tags: {app}, extra}); {level: 'error', tags: {app}, extra,
fingerprint: ['api-error', String(status), kindPath, kindMessage]});
} catch (error) { } catch (error) {
// Reporting an error must never break the page. // Reporting an error must never break the page.
} }

View File

@@ -1,5 +1,18 @@
/* Shared direct multipart transport for customer originals/corrections and operator finals. */ /* 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(uploadSlotsUsed<DTF_UPLOAD_SLOTS){uploadSlotsUsed++;return Promise.resolve();}
return new Promise(resolve=>uploadSlotsWaiting.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 cancelled=()=>new DOMException('Envio cancelado.','AbortError');
const samples=new Blob([file.slice(0,65536),file.slice(Math.max(0,file.size-65536))]); 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(''); 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; let id=resume?localStorage.getItem(key):null,state;
if(id){ if(id){
try{state=await api(prefix+'/'+id);} try{state=await api(prefix+'/'+id,undefined,{expected:[403,404,410]});}
catch(error){ catch(error){
// The id was started under another session (a sign-in changes the scope): // The id is only a hint from the last visit. When the upload expired or
// the new session does not own it, so this file starts again as a new // was started under another session (a sign-in changes the scope), this
// upload. A 403/404/410 must never keep the retry on the old id. // 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; if(![403,404,410].includes(error.status))throw error;
id=null; id=null;
if(resume)localStorage.removeItem(key); if(resume)localStorage.removeItem(key);
@@ -76,4 +90,10 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr
} }
await api(prefix+'/'+id+'/complete',{}); await api(prefix+'/'+id+'/complete',{});
return waitForScan(); 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();}
}; };