From a1fad7698a325858f33cd57ec46c7ce0cf904aaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Tue, 24 Nov 2026 17:17:31 -0300 Subject: [PATCH] fix: an interrupted upload stops holding the pending cap after 20 idle minutes; a dropped part goes again, quiet 429s, one Sentry report (DTF-WEB-13/14/15) Co-Authored-By: Claude Opus 5.5 (1M context) --- app/api/uploads.py | 9 +++++++-- tests/upload_limits_test.py | 6 ++++++ web/checkout.js | 3 ++- web/upload.js | 22 ++++++++++++++++------ 4 files changed, 31 insertions(+), 9 deletions(-) diff --git a/app/api/uploads.py b/app/api/uploads.py index 46124a8..dad91ff 100644 --- a/app/api/uploads.py +++ b/app/api/uploads.py @@ -24,6 +24,10 @@ router = APIRouter() # retrying must fit. The per-source bucket bounds abuse, not a real order. UPLOAD_START_LIMIT = 1000 UPLOAD_START_IP_LIMIT = 3000 +# A reservation counts toward the pending cap while its upload is alive: begun +# or given a part in the last 20 minutes (a part is 8 MB). One left behind by an +# interrupted upload stops holding a place long before its hour (DTF-WEB-14). +PENDING_IDLE_MINUTES = 20 def upload_ip_limit(request: Request): @@ -44,9 +48,10 @@ def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(u c.execute('SELECT pg_advisory_xact_lock(804208)') usage = c.execute('''SELECT COALESCE(sum(size),0) AS total, COALESCE(sum(size) FILTER(WHERE owner=%s),0) AS owned, - count(*) FILTER(WHERE owner=%s AND NOT complete) AS pending + count(*) FILTER(WHERE owner=%s AND NOT complete + AND expires_at > now() + interval '1 hour' - make_interval(mins => %s)) AS pending FROM dtf_local.uploads WHERE purged_at IS NULL''', - (session_id,session_id)).fetchone() + (session_id,session_id,PENDING_IDLE_MINUTES)).fetchone() 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')) diff --git a/tests/upload_limits_test.py b/tests/upload_limits_test.py index 1ff162b..d3778db 100644 --- a/tests/upload_limits_test.py +++ b/tests/upload_limits_test.py @@ -79,6 +79,12 @@ def run(): 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.' + # DTF-WEB-14: reservations left by interrupted uploads, idle for 20 + # minutes, no longer hold the cap; the next start goes through. + with db.connect() as c: + c.execute("UPDATE dtf_local.uploads SET expires_at=now()+interval '30 minutes' WHERE id=ANY(%s)", + ([UUID(uid) for uid in pending],)) + pending.append(client.call('/uploads', {'name': 'PENDING-AFTER-IDLE.png', 'size': 1})['id']) for uid in pending: client.call(f'/uploads/{uid}', expected=200, method='DELETE') diff --git a/web/checkout.js b/web/checkout.js index efea981..d100a3f 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -266,7 +266,8 @@ })(); e.promise.then(()=>{e.done=true;if(window.dtfTimings)T.uploadEnd=performance.now();falhas.delete(k);pintaEnvio();}, error=>{envios.delete(k);if(error?.name!=='AbortError'){falhas.set(k,{file,error}); - window.dtfObservability?.uiError?.('Envio de arquivo falhou: '+(error?.message||'erro no envio'),'site');}pintaEnvio();}); + // A refusal with a status already went to Sentry as an API error (DTF-WEB-15). + if(!error?.status)window.dtfObservability?.uiError?.('Envio de arquivo falhou: '+(error?.message||'erro no envio'),'site');}pintaEnvio();}); envios.set(k,e); } return e.promise; diff --git a/web/upload.js b/web/upload.js index 53eb65e..913ab0b 100644 --- a/web/upload.js +++ b/web/upload.js @@ -19,17 +19,19 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr const key='dtf-upload:'+JSON.stringify([scope,file.name,file.size,file.lastModified,hash]); // A busy server asks for a wait: retry this file alone, quietly, before the // customer sees the failure (Marcus, 2026-11-11). Only a 429 that carries - // Retry-After; the quota refusal has none and is shown at once. + // Retry-After; the quota refusal has none and is shown at once. About two + // minutes of patience, and only the last refusal reaches Sentry (DTF-WEB-14). + const RETRIES=8; const retryWait=error=>{ const seconds=Number(error?.retryAfter); return error?.status===429&&Number.isFinite(seconds)?Math.min(60,Math.max(1,Math.ceil(seconds))):null; }; const withRetry=async call=>{ for(let attempt=0;;attempt++){ - try{return await call();} + try{return await call(attempt=3)throw error; + if(wait===null||attempt>=RETRIES)throw error; await new Promise(resolve=>setTimeout(resolve,wait*1000)); } } @@ -47,7 +49,7 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr if(resume)localStorage.removeItem(key); } } - if(!id){state=await withRetry(()=>api(startPath,{name:file.name,size:file.size}));id=state.id;if(resume)localStorage.setItem(key,id);} + if(!id){state=await withRetry(options=>api(startPath,{name:file.name,size:file.size},options));id=state.id;if(resume)localStorage.setItem(key,id);} async function waitForScan(){ onBytes(file.size); // The antivirus streams the whole file: about a second per 2 MB, and at @@ -83,8 +85,16 @@ async function sendUpload(file, {api, prefix='/uploads', startPath=prefix, progr if(done.has(part))continue; if(signal?.aborted)throw cancelled(); progress('Enviando '+file.name+' ยท parte '+part+'/'+Math.ceil(file.size/size)); - const signed=await withRetry(()=>api(prefix+'/'+id+'/parts/'+part,{})); - await put(signed.url,file.slice(offset,offset+size)); + // A part the network dropped goes again twice, on a fresh link, before + // the customer is asked to resume (DTF-WEB-13). + for(let attempt=0;;attempt++){ + const signed=await withRetry(options=>api(prefix+'/'+id+'/parts/'+part,{},options)); + try{await put(signed.url,file.slice(offset,offset+size));break;} + catch(error){ + if(error?.name==='AbortError'||attempt>=2)throw error; + await new Promise(resolve=>setTimeout(resolve,(attempt+1)*3000)); + } + } done.add(part);sent+=length(part); onBytes(sent); }