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
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:
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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).
|
||||
|
||||
50
tests/observability_web_test.mjs
Normal file
50
tests/observability_web_test.mjs
Normal 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');
|
||||
@@ -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__':
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -8,6 +8,11 @@
|
||||
(function () {
|
||||
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;
|
||||
// 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_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.
|
||||
}
|
||||
|
||||
@@ -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(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 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();}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user