All checks were successful
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Successful in 8m14s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m22s
The same Android 10 phone failed three times on 2026-12-02 reading a file seven seconds after picking it: not a permission lost over time, but a file the phone does not have yet (Google Drive or WhatsApp). "Escolha o arquivo de novo" sent the customer back to the same file. The message now says "Se ele está no Google Drive ou no WhatsApp, salve no aparelho e escolha de novo". The Sentry notice carries the browser's error name, the file's type, extension and size in MB, never its name, so the next one says which case it is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
155 lines
8.0 KiB
JavaScript
155 lines
8.0 KiB
JavaScript
/* Shared direct multipart transport for customer originals/corrections and operator finals. */
|
|
// 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))]);
|
|
// A phone can lose the right to read a file it picked (Android: a file from
|
|
// Drive or Photos, after switching apps). The browser's message is English
|
|
// and a retry reads the same dead reference: picking the file again is the
|
|
// way out (Sentry DTF-WEB-2A).
|
|
let sampled;
|
|
try{ sampled=await samples.arrayBuffer(); }
|
|
catch(error){
|
|
if(error?.name!=='NotReadableError' && error?.name!=='NotFoundError') throw error;
|
|
// A file in Google Drive or WhatsApp that is not on the phone yet fails the
|
|
// same way, at once (DTF-WEB-2D): the message says how to get out of it.
|
|
const unreadable=new Error('não conseguimos ler este arquivo no aparelho. Se ele está no Google Drive ou no WhatsApp, salve no aparelho e escolha de novo');
|
|
unreadable.unreadable=true;
|
|
// For Sentry: what kind of file the phone refused, never its name.
|
|
const ext=/\.([a-z0-9]{1,5})$/i.exec(file.name||'')?.[1]?.toLowerCase()||'';
|
|
unreadable.detalhe={erro:error.name,tipo:file.type||'',extensao:ext,mb:Math.round((file.size||0)/1048576*10)/10};
|
|
throw unreadable;
|
|
}
|
|
const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',sampled)),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. 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(attempt<RETRIES?{expected:[429]}:{});}
|
|
catch(error){
|
|
const wait=retryWait(error);
|
|
if(wait===null||attempt>=RETRIES)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,undefined,{expected:[403,404,410]});}
|
|
catch(error){
|
|
// 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);
|
|
}
|
|
}
|
|
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
|
|
// least two and a half minutes.
|
|
const attempts=Math.max(150,Math.ceil(file.size/2e6));
|
|
for(let attempt=0;attempt<attempts;attempt++){
|
|
const checked=await api(prefix+'/'+id);
|
|
if(checked.scan_state==='clean')return id;
|
|
if(['rejected','error'].includes(checked.scan_state))throw new Error(checked.scan_reason||'Arquivo bloqueado pela verificação de segurança.');
|
|
progress('Verificando segurança de '+file.name+'…');
|
|
await new Promise(resolve=>setTimeout(resolve,1000));
|
|
}
|
|
throw new Error('Verificação de segurança pendente. Tente novamente para consultar o resultado.');
|
|
}
|
|
if(state.complete)return waitForScan();
|
|
const done=new Set(state.parts||[]),size=state.part_bytes;
|
|
const length=part=>Math.min(size,file.size-(part-1)*size);
|
|
let sent=[...done].reduce((t,part)=>t+length(part),0);
|
|
onBytes(sent);
|
|
// Each part through XMLHttpRequest, which reports the bytes as they go: the
|
|
// bar moves while a part is on its way, not once per part (Dropstar, 2026-10-29).
|
|
const put=(url,body)=>new Promise((resolve,reject)=>{
|
|
if(signal?.aborted)return reject(cancelled());
|
|
const xhr=new XMLHttpRequest();xhr.open('PUT',url);
|
|
xhr.upload.onprogress=e=>onBytes(Math.min(file.size,sent+e.loaded));
|
|
const lost=()=>reject(new Error('Upload interrompido. Tente novamente para retomar.'));
|
|
xhr.onload=()=>xhr.status>=200&&xhr.status<300?resolve():lost();
|
|
xhr.onerror=lost;xhr.ontimeout=lost;xhr.onabort=()=>reject(cancelled());
|
|
signal?.addEventListener('abort',()=>xhr.abort(),{once:true});
|
|
xhr.send(body);
|
|
});
|
|
// A file taken off the page while it went gives its place back at once: a
|
|
// reservation it left would hold the pending cap for 20 minutes, and a
|
|
// customer switching products filled it (Sentry DTF-WEB-14, 29/11).
|
|
const giveBack=()=>{
|
|
fetch('/api'+prefix+'/'+id,{method:'DELETE',credentials:'same-origin'}).catch(()=>{});
|
|
if(resume)localStorage.removeItem(key);
|
|
};
|
|
if(signal?.aborted){giveBack();throw cancelled();}
|
|
for(let offset=0,part=1;offset<file.size;offset+=size,part++){
|
|
if(done.has(part))continue;
|
|
if(signal?.aborted){giveBack();throw cancelled();}
|
|
progress('Enviando '+file.name+' · parte '+part+'/'+Math.ceil(file.size/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'){giveBack();throw error;}
|
|
if(attempt>=2)throw error;
|
|
await new Promise(resolve=>setTimeout(resolve,(attempt+1)*3000));
|
|
}
|
|
}
|
|
done.add(part);sent+=length(part);
|
|
onBytes(sent);
|
|
}
|
|
// Closing the upload reads the parts back from storage, which can fail for
|
|
// a few seconds (an R2 500, Sentry DTF-API-D, 01/12). Asked again after 3 s
|
|
// and 6 s, quietly: closing twice is safe, the server answers an upload that
|
|
// is already closed. A refusal (4xx) is shown at once; only the last
|
|
// failure reaches the customer and Sentry. No status is a reply that was
|
|
// not JSON (the gateway's 500 page) or no reply at all.
|
|
const SERVER_ERRORS=[500,502,503,504];
|
|
for(let attempt=0;;attempt++){
|
|
const last=attempt>=2;
|
|
try{await api(prefix+'/'+id+'/complete',{},last?{}:{expected:SERVER_ERRORS});break;}
|
|
catch(error){
|
|
if(last||error?.name==='AbortError'||(error?.status!==undefined&&!SERVER_ERRORS.includes(error.status)))throw error;
|
|
await new Promise(resolve=>setTimeout(resolve,(attempt+1)*3000));
|
|
if(signal?.aborted){giveBack();throw cancelled();}
|
|
}
|
|
}
|
|
return waitForScan();
|
|
}
|
|
window.dtfUpload = async (file, options) => {
|
|
if(options?.signal?.aborted)throw new DOMException('Envio cancelado.','AbortError');
|
|
await uploadSlot();
|
|
try{
|
|
// Taken off the page while it waited for a place: no reservation at all.
|
|
if(options?.signal?.aborted)throw new DOMException('Envio cancelado.','AbortError');
|
|
return await sendUpload(file, options);
|
|
}
|
|
finally{releaseUploadSlot();}
|
|
};
|