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)
All checks were successful
Build and deploy / Validate source (push) Successful in 1m7s
Build and deploy / Integration suite on a real stack (push) Successful in 8m2s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m35s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-24 17:17:31 -03:00
parent 242a56aae8
commit a1fad7698a
4 changed files with 31 additions and 9 deletions

View File

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

View File

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

View File

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

View File

@@ -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<RETRIES?{expected:[429]}:{});}
catch(error){
const wait=retryWait(error);
if(wait===null||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);
}