fix: large carts upload all their files (Marcus's bugs of 11/11, B1 to B4)
B1: an upload start was limited to 60 per 15 minutes per session, so a 66-file cart failed with 'Muitas tentativas'; now 1000 per session and 3000 per source, and the Site waits Retry-After and retries quietly. B2: a failed file shows its error and 'Tentar de novo' on its own card, and payment stays blocked with 'Falta enviar N arquivos'. B3: after signing in again, an upload id the new session does not own (403) is dropped and the file starts again. B4: the quote is never created before every file is sent, and an untranslatable 422 is logged for Sentry. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -86,7 +86,7 @@ jobs:
|
||||
# one a developer exercises on localhost.
|
||||
- name: API and workflow regressions
|
||||
run: |
|
||||
for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
|
||||
for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do
|
||||
echo "--- $suite"
|
||||
$COMPOSE exec -T \
|
||||
-e SITE_BASE_URL=http://site \
|
||||
|
||||
@@ -12,7 +12,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from ..core import db
|
||||
from ..core.auth import audit, owner, rate_limit
|
||||
from ..core.auth import audit, client_ip, owner, rate_limit
|
||||
from ..core.limits import upload_limit_bytes
|
||||
from ..core.models import UploadStart
|
||||
from ..payments import UNPAID_HOLD
|
||||
@@ -20,13 +20,25 @@ from ..runtime import PART_BYTES, storage, upload_row
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# A cart of many files: 66 in Marcus's case (2026-11-11), and adding more or
|
||||
# retrying must fit. The per-source bucket bounds abuse, not a real order.
|
||||
UPLOAD_START_LIMIT = 1000
|
||||
UPLOAD_START_IP_LIMIT = 3000
|
||||
|
||||
|
||||
def upload_ip_limit(request: Request):
|
||||
"""The public upload route's per-source bucket. The operator upload routes
|
||||
reuse begin_upload directly and stay bound by their own session bucket."""
|
||||
rate_limit('upload-start-ip', client_ip(request), UPLOAD_START_IP_LIMIT, 900)
|
||||
|
||||
|
||||
@router.post('/api/uploads')
|
||||
def begin_upload(body: UploadStart, session_id=Depends(owner)):
|
||||
def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(upload_ip_limit)):
|
||||
if body.size > upload_limit_bytes():
|
||||
raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.')
|
||||
uid = uuid4()
|
||||
key = f'originals/{uid}'
|
||||
rate_limit('upload-start', str(session_id), 60, 900)
|
||||
rate_limit('upload-start', str(session_id), UPLOAD_START_LIMIT, 900)
|
||||
with db.connect() as c:
|
||||
# Serialize reservations across API processes, including changing guest IDs.
|
||||
c.execute('SELECT pg_advisory_xact_lock(804208)')
|
||||
|
||||
40
tests/upload_limits_test.py
Normal file
40
tests/upload_limits_test.py
Normal file
@@ -0,0 +1,40 @@
|
||||
"""The upload start limit: a large cart fits, and the per-source bucket
|
||||
still refuses above its own limit (Marcus's bugs of 2026-11-11, B1).
|
||||
|
||||
Run against the local stack: python -m tests.upload_limits_test
|
||||
"""
|
||||
import secrets
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT
|
||||
from app.core.auth import rate_limit
|
||||
from tests.smoke_test import Client
|
||||
|
||||
|
||||
def run():
|
||||
assert (UPLOAD_START_LIMIT, UPLOAD_START_IP_LIMIT) == (1000, 3000)
|
||||
client = Client()
|
||||
client.call('/session')
|
||||
# A 66-file cart, with retries, fits in one session. Each reservation is
|
||||
# cancelled so the pending-upload quota (unchanged) does not stop the test.
|
||||
for index in range(70):
|
||||
uid = client.call('/uploads', {'name': f'LIMIT-{index}.png', 'size': 1})['id']
|
||||
client.call(f'/uploads/{uid}', expected=200, method='DELETE')
|
||||
# The per-source bucket, exercised directly with a small limit: 3000 real
|
||||
# starts would only slow CI. A unique key keeps other suites out of it.
|
||||
key = 'upload-start-ip-test-' + secrets.token_hex(8)
|
||||
for _ in range(3):
|
||||
rate_limit('upload-start-ip', key, 3, 900)
|
||||
try:
|
||||
rate_limit('upload-start-ip', key, 3, 900)
|
||||
except HTTPException as error:
|
||||
assert error.status_code == 429, error
|
||||
assert error.headers.get('Retry-After') == '900', error.headers
|
||||
else:
|
||||
raise AssertionError('the per-source upload bucket accepted above its limit')
|
||||
print('PASS: 70 upload starts in one session; the per-source bucket refuses above its limit')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run()
|
||||
@@ -46,7 +46,17 @@
|
||||
let data;
|
||||
try { data = text ? JSON.parse(text) : {}; }
|
||||
catch (_) { throw new Error(response.ok ? 'Resposta inválida do serviço.' : 'O serviço está indisponível. Tente novamente em instantes.'); }
|
||||
if (!response.ok) { const error=new Error(problem(data.detail));error.status=response.status;throw error; }
|
||||
if (!response.ok) {
|
||||
const text=problem(data.detail);
|
||||
// A validation the customer cannot read still needs to reach us (Sentry
|
||||
// picks up console.error later); the customer keeps the generic sentence.
|
||||
if (response.status===422 && text==='Não foi possível concluir. Confira os dados e tente de novo.')
|
||||
console.error('Detalhe da validação recusada:',data.detail);
|
||||
const error=new Error(text);error.status=response.status;
|
||||
const retry=response.headers.get('Retry-After');
|
||||
if(retry!=null)error.retryAfter=retry;
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
// A refusal as one sentence: the server's own, or the first field a form
|
||||
@@ -262,10 +272,35 @@
|
||||
pintaEnvio();
|
||||
}
|
||||
const arquivosDoCarrinho=()=>[...pedido.filter(it=>it.marcado!==false),...(busy&&itemAtual?[itemAtual]:[])].flatMap(it=>it.localFiles||[]);
|
||||
// Every file of the paying cart must be sent (and none failed) before the
|
||||
// quote and before the payment button (bugs B2 and B4, Marcus 2026-11-11).
|
||||
function faltaEnvio(){
|
||||
const files=arquivosDoCarrinho();
|
||||
let pending=0,failed=0;
|
||||
for(const f of files){
|
||||
const k=chaveArquivo(f);
|
||||
if(falhas.has(k)){failed++;continue;}
|
||||
const e=envios.get(k);
|
||||
if(!e||!e.done)pending++;
|
||||
}
|
||||
return {total:files.length,pending,failed,falta:pending+failed};
|
||||
}
|
||||
window.dtfFaltaEnvio=faltaEnvio;
|
||||
function faltaEnvioMensagem(){
|
||||
const missing=[];
|
||||
for(const f of arquivosDoCarrinho()){
|
||||
const k=chaveArquivo(f),e=envios.get(k);
|
||||
if(falhas.has(k)||!e||!e.done)missing.push(f);
|
||||
}
|
||||
if(!missing.length) return '';
|
||||
return 'Falta enviar '+missing[0].name+
|
||||
(missing.length>1?' (e mais '+(missing.length-1)+')':'');
|
||||
}
|
||||
const gb=n=>(n/1073741824).toLocaleString('pt-BR',{maximumFractionDigits:1})+' GB';
|
||||
const mb=n=>n>=1073741824 ? gb(n) : Math.round(n/1048576)+' MB';
|
||||
// Where the uploads stand, and roughly how long is left from the recent speed.
|
||||
const amostras=[];
|
||||
let ultimaFalta=null;
|
||||
function estadoEnvio() {
|
||||
const files=arquivosDoCarrinho(); if(!files.length) return null;
|
||||
let total=0, sent=0, pendentes=0;
|
||||
@@ -292,6 +327,13 @@
|
||||
return 'Enviando seus arquivos · '+restante(e);
|
||||
}
|
||||
function pintaEnvio() {
|
||||
// The cart button carries the uploads too (B2): repaint it only when the
|
||||
// number of missing files changes, not on every progress tick.
|
||||
const falta=faltaEnvio().falta;
|
||||
if(falta!==ultimaFalta){
|
||||
ultimaFalta=falta;
|
||||
if(typeof pintaPedido==='function')pintaPedido();
|
||||
}
|
||||
window.dispatchEvent(new Event('dtf-envio'));
|
||||
const e=estadoEnvio(), texto=textoEnvio(e);
|
||||
const el=document.getElementById('envioArq');
|
||||
@@ -391,6 +433,8 @@
|
||||
if (!clienteOk() || !entrega.cotado) return;
|
||||
if (!enderecoOk()) return message('Preencha o endereço de entrega.','error');
|
||||
if (!cartPodeEnviar()) return message('Revise a qualidade e confirme a ressalva de cada item antes de enviar o pedido.','error');
|
||||
const semArquivo=faltaEnvioMensagem();
|
||||
if (semArquivo) return message(semArquivo+'.','error');
|
||||
const cart = itensAPagar();
|
||||
if (!cart.length) return message('Adicione um item ao pedido.','error');
|
||||
const initialCart=cartSnapshot();
|
||||
|
||||
@@ -114,13 +114,18 @@ function pintaPedido(){
|
||||
'<div class="l"><span>Revisão e reencaixe</span>'+
|
||||
'<b><span style="color:var(--verde-ml)">Grátis</span></b></div>';
|
||||
$('carrTot').textContent=rs(soma);
|
||||
$('bPagarTx').textContent = n>1
|
||||
? 'Pagar os '+n+' itens de uma vez'
|
||||
: 'Ir para o pagamento';
|
||||
// A file still on its way (or failed) keeps the payment closed (B2).
|
||||
const faltaEnvio=window.dtfFaltaEnvio?window.dtfFaltaEnvio():null;
|
||||
const falta=faltaEnvio?.falta||0;
|
||||
$('bPagarTx').textContent = falta
|
||||
? 'Falta enviar '+falta+(falta===1?' arquivo':' arquivos')
|
||||
: n>1
|
||||
? 'Pagar os '+n+' itens de uma vez'
|
||||
: 'Ir para o pagamento';
|
||||
// The proof is only for orders above 10 m (Dropstar, 2026-10-28): below it the box is gone.
|
||||
const prova=$('fProva');
|
||||
if(prova){ const longo=aPagar.reduce((t,it)=>t+(it.cob||0),0)>10; prova.closest('.cxE').hidden=!longo; if(!longo) prova.checked=false; }
|
||||
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk();
|
||||
$('bPagar').disabled = !cartPodeEnviar() || !entrega.cotado || !clienteOk() || !enderecoOk() || falta>0;
|
||||
if(pedido.length || itemAtual) $('carr').classList.add('on');
|
||||
if($('cartN')){ $('cartN').textContent=noCarrinho>99?'99+':noCarrinho; $('cartN').hidden=!noCarrinho;
|
||||
$('cartLink').setAttribute('aria-label','Carrinho, '+noCarrinho+(noCarrinho===1?' item':' itens')); }
|
||||
|
||||
@@ -66,9 +66,44 @@ const enviadoEm=new WeakMap();
|
||||
// A few repaints a second, page in view or not: progress comes in far more often.
|
||||
let envioQuadro=0;
|
||||
function agendaEnvios(){ if(!envioQuadro) envioQuadro=setTimeout(()=>{ envioQuadro=0; pintaEnvios(); },120); }
|
||||
// A failed upload must show on the file's own card too (B2, Marcus 11/11):
|
||||
// the same red block and "Tentar de novo" as the row under the uploader, on
|
||||
// the sheet/art card itself, so the list does not look complete.
|
||||
function pintaErrosDosArquivos(){
|
||||
const lista=$('lista'); if(!lista || !window.dtfEnvio) return;
|
||||
const decorate=(selector,items,kind)=>{
|
||||
items.forEach((item,index)=>{
|
||||
const card=lista.querySelector(selector.replace('{i}',index));
|
||||
if(!card) return;
|
||||
const estado=dtfEnvio.estado(item.f);
|
||||
const atual=card.querySelector('[data-envio-falha]');
|
||||
if(!estado || estado.fase!=='falhou'){ if(atual) atual.remove(); return; }
|
||||
if(atual){
|
||||
// Keep the block while the file is failed: a repaint for another
|
||||
// file's progress must not take the button from under the pointer.
|
||||
const texto=atual.querySelector('span');
|
||||
if(texto) texto.textContent='Não foi possível enviar '+item.f.name+': '+
|
||||
(estado.erro||'erro no envio').replace(/\.$/,'')+'.';
|
||||
return;
|
||||
}
|
||||
const box=document.createElement('div');
|
||||
box.className='envio erro';box.dataset.envioFalha='1';
|
||||
const texto=document.createElement('span');
|
||||
texto.textContent='Não foi possível enviar '+item.f.name+': '+
|
||||
(estado.erro||'erro no envio').replace(/\.$/,'')+'.';
|
||||
const button=document.createElement('button');
|
||||
button.type='button';button.textContent='Tentar de novo';
|
||||
button.dataset.envioCard=kind;button.dataset.envioIndex=String(index);
|
||||
box.append(texto,button);card.append(box);
|
||||
});
|
||||
};
|
||||
decorate('[data-folha="{i}"]',folhas,'folha');
|
||||
decorate('[data-arte="{i}"]',artes,'arte');
|
||||
}
|
||||
function pintaEnvios(){
|
||||
const el=$('envios'); if(!el || !window.dtfEnvio) return;
|
||||
dtfEnvio.manter([...artes,...folhas].map(x=>x.f));
|
||||
pintaErrosDosArquivos();
|
||||
// Off the product page there is no uploader to paint under.
|
||||
if(!MODOS[modo]){ el.innerHTML=''; return; }
|
||||
const agora=Date.now();
|
||||
@@ -92,6 +127,11 @@ $('envios').addEventListener('click',e=>{
|
||||
const b=e.target.closest('[data-envio]'); if(!b || !MODOS[modo]) return;
|
||||
const x=(ehFolha()?folhas:artes)[+b.dataset.envio]; if(x) dtfEnvio.deNovo(x.f);
|
||||
});
|
||||
$('lista').addEventListener('click',e=>{
|
||||
const b=e.target.closest('[data-envio-card]'); if(!b || !window.dtfEnvio) return;
|
||||
const x=(b.dataset.envioCard==='folha'?folhas:artes)[+b.dataset.envioIndex];
|
||||
if(x) dtfEnvio.deNovo(x.f);
|
||||
});
|
||||
// A sheet with residue gets its preview circled where the dots are.
|
||||
async function marcaResiduos(x){
|
||||
if(!(x.an && x.an.residuos && !x.an.fundoChapado && x.previewSrc && x.an.pontos?.length)) return;
|
||||
|
||||
@@ -4,9 +4,36 @@ window.dtfUpload = async (file, {api, prefix='/uploads', startPath=prefix, progr
|
||||
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 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.
|
||||
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();}
|
||||
catch(error){
|
||||
const wait=retryWait(error);
|
||||
if(wait===null||attempt>=3)throw error;
|
||||
await new Promise(resolve=>setTimeout(resolve,wait*1000));
|
||||
}
|
||||
}
|
||||
};
|
||||
let id=resume?localStorage.getItem(key):null,state;
|
||||
if(id){try{state=await api(prefix+'/'+id);}catch(error){if(![404,410].includes(error.status))throw error;id=null;}}
|
||||
if(!id){state=await api(startPath,{name:file.name,size:file.size});id=state.id;if(resume)localStorage.setItem(key,id);}
|
||||
if(id){
|
||||
try{state=await api(prefix+'/'+id);}
|
||||
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.
|
||||
if(![403,404,410].includes(error.status))throw error;
|
||||
id=null;
|
||||
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);}
|
||||
async function waitForScan(){
|
||||
onBytes(file.size);
|
||||
// The antivirus streams the whole file: about a second per 2 MB, and at
|
||||
@@ -42,7 +69,7 @@ window.dtfUpload = async (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 api(prefix+'/'+id+'/parts/'+part,{});
|
||||
const signed=await withRetry(()=>api(prefix+'/'+id+'/parts/'+part,{}));
|
||||
await put(signed.url,file.slice(offset,offset+size));
|
||||
done.add(part);sent+=length(part);
|
||||
onBytes(sent);
|
||||
|
||||
Reference in New Issue
Block a user