fix: the Kanban writes each file in _tmp and moves it in whole, so the FlexiPRINT never sees a temporary file (order #30)
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 6m28s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m3s

Chrome writes a .crswap working copy beside the file it writes. In the
hot folder the FlexiPRINT took each one as it appeared, the write failed
and every 30 s try left another; when the rename failed, the copy fallback
created the final name empty first and never removed it (0 KB files in
Arte conferida and maquina5\C2, Marcus 2026-11-17).

- Every file is written in _tmp, at the root of the chosen folder, under
  its own name, then moved under its final name into its folder.
- An empty file, or one shorter than the download's length, is deleted
  and reported in red (so in Sentry); the pass goes on and the next one
  tries it again.
- In the hot folders and Recibos a failed move is tried again; nothing
  is ever copied there. Elsewhere the copy stays, removes the final file
  if it fails, and reports to Sentry that it was used.
- Each page load clears the old .baixando and .crswap leftovers from the
  flow's folders; each pass clears tries over an hour old from _tmp.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-17 09:38:47 -03:00
parent bd25cb9c1c
commit b6837023bf
2 changed files with 90 additions and 28 deletions

View File

@@ -289,7 +289,9 @@ const FOLDER={mode:'showDirectoryPicker' in window?'folder':/Firefox\//.test(nav
// Passes in a row each file was held open by another program (DTF-WEB-M).
locked:new Map(),
// Since when the main folder does not answer (DTF-WEB-P), and whether that was reported.
awaySince:0,awayReported:false};
awaySince:0,awayReported:false,
// Whether this page load cleared the old version's leftovers (order #30).
swept:false};
const LOCKED_REPORT_PASSES=10;
const FOLDER_AWAY_REPORT_MS=5*60000;
// When the folders were chosen: every order paid since then ends up in them,
@@ -379,6 +381,7 @@ function folderCard(){
['Último',FOLDER.last?FOLDER.last.toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'}):'—'],
node('p','Dentro de “'+h.name+'”: o arquivo do pedido chega em '+STAGE_FOLDERS.rec+', passa para '+STAGE_FOLDERS.tra+' quando o card vai para lá '+
'e fica lá enquanto imprime, vai para '+STAGE_FOLDERS.rev+' com o card e para '+STAGE_FOLDERS.fin+' quando o pedido é finalizado, onde fica '+KEEP_FINISHED_DAYS+' dias.'),
node('p','A pasta '+WORK_FOLDER+' é a de trabalho do Kanban: cada arquivo é gravado nela e só entra na pasta da etapa ou na hot folder completo, com o nome final. Não coloque nada nela.'),
node('p','Pedido de retirada que chega em Finalizado: o recibo para a bobina de 80 mm vai para '+RECEIPTS_FOLDER+', uma vez só, por um dos computadores com a pasta ligada. As fotos da revisão vão para '+REVIEWS_FOLDER+' e não saem de lá.'),
node('p','Pedido cancelado, excluído ou devolvido para correção: o arquivo sai das pastas. Arquivo trocado: a versão antiga sai. '+
'Pedidos que já estavam imprimindo quando a pasta foi escolhida não são baixados. Se este computador ficar desligado, '+
@@ -402,7 +405,7 @@ async function chooseFolder(){
let handle;
try{handle=await window.showDirectoryPicker({id:'dtf-fila',mode:'readwrite'});}
catch(e){if(e.name==='AbortError')return;throw e;}
FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null;FOLDER.error='';FOLDER.last=null;
FOLDER.handle=handle;FOLDER.granted=true;FOLDER.lastSig=null;FOLDER.error='';FOLDER.last=null;FOLDER.swept=false;
FOLDER.saved=await loadSaved();
await kv.set('folder',handle).catch(()=>{});
await folderSince(true);
@@ -431,36 +434,83 @@ async function setDownloads(on){
paintFolder();say(on?'Download automático ligado.':'Download automático desligado.');
if(on)syncFolder();
}
// A whole file in a folder: written under another name and renamed at the
// end, so the FlexiPRINT never sees half of it. `source` is a download's body
// or a file.
async function writeWhole(dir,name,source){
const temp=await dir.getFileHandle(name+'.baixando',{create:true});
const out=await temp.createWritable();
try{if(source instanceof Blob){await out.write(source);await out.close();}else await source.pipeTo(out);}
catch(e){await out.abort().catch(()=>{});await dir.removeEntry(temp.name).catch(()=>{});throw e;}
await dir.removeEntry(name).catch(()=>{});
// A browser that cannot rename a file outside its own storage copies it.
try{await temp.move(name);}
catch{
try{const whole=await (await dir.getFileHandle(name,{create:true})).createWritable();
await whole.write(await temp.getFile());await whole.close();}
catch(e){await dir.removeEntry(temp.name).catch(()=>{});throw e;}
await dir.removeEntry(temp.name);}
// Where a file is written before it goes to its folder (Marcus, 2026-11-17,
// order #30). Chrome writes a working copy (.crswap) beside the file it
// writes; in a hot folder the FlexiPRINT took each one as it appeared, the
// write failed and every try left one behind. Nothing watches this folder;
// the whole file then moves to its own folder under its final name, a
// rename on the same share. What stays here an hour is a try that never finished.
const WORK_FOLDER='_tmp';
const WORK_KEEP_MS=3600000;
// A file that arrived empty or short: deleted, reported, tried again.
class IncompleteFile extends Error{constructor(message){super(message);this.name='IncompleteFile';}}
const fileSize=bytes=>bytes<1048576?Math.round(bytes/1024)+' KB':(bytes/1048576).toLocaleString('pt-BR',{maximumFractionDigits:1})+' MB';
// A whole file in a folder: written in WORK_FOLDER, its size checked, then
// moved in, so no program ever sees half of it. `source` is a download's
// response or a file. In a folder a program watches (`watched`: the hot
// folders, and Recibos for the counter's printer) nothing else is ever written: a move that fails is tried again on
// the next pass. Elsewhere a browser that cannot move the file copies it.
async function writeWhole(dir,name,source,watched=false){
const blob=source instanceof Blob;
// A compressed response's length is not the file's: then only "not empty".
const expected=blob?source.size:source.headers.get('content-encoding')?0:Number(source.headers.get('content-length'))||0;
// Its own name, so two computers writing the same file never meet.
const work=await stageDir(WORK_FOLDER);
const temp=await work.getFileHandle(Math.random().toString(36).slice(2,10)+'-'+name,{create:true});
try{
const out=await temp.createWritable();
try{if(blob){await out.write(source);await out.close();}else await source.body.pipeTo(out);}
catch(e){await out.abort().catch(()=>{});throw e;}
const size=(await temp.getFile()).size;
if(!size||expected&&size!==expected)
throw new IncompleteFile('O arquivo '+name+' chegou incompleto ('+fileSize(size)+(expected?' de '+fileSize(expected):'')+') e foi descartado.');
await dir.removeEntry(name).catch(e=>{if(e.name!=='NotFoundError')throw e;});
try{await temp.move(dir,name);}
catch(e){
if(watched)throw e;
window.dtfObservability?.uiError?.('Pastas automáticas: o navegador não moveu '+name+' ('+e.name+') e copiou o arquivo.','kanban');
let out;
try{out=await (await dir.getFileHandle(name,{create:true})).createWritable();await out.write(await temp.getFile());await out.close();}
catch(error){await out?.abort().catch(()=>{});await dir.removeEntry(name).catch(()=>{});throw error;}
}
}finally{await work.removeEntry(temp.name).catch(()=>{});}
}
// The tries that never finished in WORK_FOLDER, and what the Kanban of
// before 2026-11-17 left in the flow's folders: its .baixando files and
// Chrome's .crswap copies (order #30). The leftovers once per page load, the
// work folder on every pass. A file still held open waits for the next time.
const LEFTOVER=/\.(baixando|crswap)$/;
async function clearWork(){
const work=await stageDir(WORK_FOLDER);
for await(const [name,entry] of work.entries()){
if(entry.kind!=='file')continue;
const old=await entry.getFile().then(f=>Date.now()-f.lastModified>WORK_KEEP_MS,()=>true);
if(old)await work.removeEntry(name).catch(()=>{});
}
}
async function sweepLeftovers(dir,depth){
for await(const [name,entry] of dir.entries()){
if(entry.kind==='directory'){if(depth>0)await sweepLeftovers(entry,depth-1);}
else if(LEFTOVER.test(name))await dir.removeEntry(name).catch(()=>{});
}
}
// A file another program holds open (FlexiPRINT reading it, an editor): the
// browser refuses to write, move or delete it. One that program changed while
// the browser wrote or copied it (the hot folder's watcher, Sentry DTF-WEB-S)
// is the same case. The pass goes on without it and the next one, 30 s later,
// tries again.
// A file that arrived incomplete waits for the next pass too, reported.
const LOCKED=new Set(['NoModificationAllowedError','InvalidModificationError','NotReadableError','InvalidStateError']);
function fileStep(locked){
function fileStep(locked,incomplete){
return async(name,fn)=>{try{await fn();return true;}
catch(e){if(!LOCKED.has(e.name))throw e;locked.push(name);return false;}};
catch(e){
if(e.name==='IncompleteFile'){incomplete.push(e.message);return false;}
if(!LOCKED.has(e.name))throw e;locked.push(name);return false;}};
}
const stageDir=name=>FOLDER.handle.getDirectoryHandle(name,{create:true});
// The flow's folders exist from the moment the main one is chosen, empty or not.
const makeStageFolders=()=>Promise.all([...new Set([...Object.values(STAGE_FOLDERS),PRINTING_FOLDER,RECEIPTS_FOLDER,REVIEWS_FOLDER])].map(stageDir));
const FLOW_FOLDERS=[...new Set([...Object.values(STAGE_FOLDERS),PRINTING_FOLDER,RECEIPTS_FOLDER,REVIEWS_FOLDER])];
const makeStageFolders=()=>Promise.all(FLOW_FOLDERS.map(stageDir));
// Whether the main folder answers at all. A folder on the network can be away
// for a while: the server's share not up yet when the computer starts, the
// network down (Sentry DTF-WEB-P).
@@ -482,10 +532,10 @@ async function moveSaved(rec,to){
return true;
}
// One file from storage, whole, into a folder.
async function fetchInto(dir,file){
async function fetchInto(dir,file,watched=false){
const r=await fetch(file.url,{referrerPolicy:'no-referrer'});
if(!r.ok||!r.body)throw new Error('não foi possível baixar '+file.name+' (erro '+r.status+').');
await writeWhole(dir,file.name,r.body);
await writeWhole(dir,file.name,r,watched);
}
// The machines' hot folders (item 10): 3. Imprimindo/<máquina>/<C1|C2|C3|PREMIUM>/.
@@ -512,7 +562,7 @@ async function syncHot(step){
for(const p of hot.write){
FOLDER.status='Gravando na hot folder '+p.folder+': '+p.name;paintFolder();
const ok=await step(p.name,async()=>{
try{await fetchInto(await dirOf(p.folder),p);}
try{await fetchInto(await dirOf(p.folder),p,true);}
catch(e){await api('/queue/hot/'+p.id,{state:'released'}).catch(()=>{});throw e;}
});
if(ok){await api('/queue/hot/'+p.id,{state:'written'});written++;}
@@ -548,7 +598,11 @@ async function syncFolder(force=false){
const wanted=new Map(files.map(f=>[f.upload_id,f]));
const where=stages?'“'+FOLDER.handle.name+'”':'a pasta de downloads';
let removed=0, moved=0, saved=0;
const locked=[], step=fileStep(locked);
const locked=[], incomplete=[], step=fileStep(locked,incomplete);
if(stages){
await clearWork();
if(!FOLDER.swept){for(const name of FLOW_FOLDERS)await sweepLeftovers(await stageDir(name),2);FOLDER.swept=true;}
}
const record=async(uid,file,folder)=>{
FOLDER.saved.set(uid,{order:file.order,item:file.item,name:file.name,folder,
...(folder===STAGE_FOLDERS.fin?{at:file.at||Date.now()}:{})});
@@ -600,7 +654,7 @@ async function syncFolder(force=false){
await step(r.name,async()=>{try{
const res=await fetch('/api/operator/orders/'+r.order+'/receipt');
if(!res.ok||!res.body)throw new Error('não foi possível gerar '+r.name+' (erro '+res.status+').');
await writeWhole(await stageDir(RECEIPTS_FOLDER),r.name,res.body);printed++;
await writeWhole(await stageDir(RECEIPTS_FOLDER),r.name,res,true);printed++;
}catch(e){await api('/orders/'+r.order+'/receipt/release',{}).catch(()=>{});throw e;}});
}
// The review photos and videos, once each, into Revisões/. They are never
@@ -614,7 +668,7 @@ async function syncFolder(force=false){
const view=await api('/orders/'+review.order+'/reviews/'+review.id+'/view');
const res=await fetch(view.url,{referrerPolicy:'no-referrer'});
if(!res.ok||!res.body)throw new Error('não foi possível baixar '+review.name+' (erro '+res.status+').');
await writeWhole(await stageDir(REVIEWS_FOLDER),review.name,res.body);
await writeWhole(await stageDir(REVIEWS_FOLDER),review.name,res);
}))continue;
FOLDER.saved.set(key,{order:review.order,name:review.name,review:true});
FOLDER.last=new Date();await keepSaved();reviewSaved++;
@@ -642,6 +696,12 @@ async function syncFolder(force=false){
Math.round(LOCKED_REPORT_PASSES*30/60)+' minutos. Feche-o no programa que o usa.',true);
else if(locked.some(name=>FOLDER.locked.get(name)===1))say('Pastas automáticas: '+FOLDER.error);
}
// Empty or short: an error every time, since a file must arrive whole.
if(incomplete.length){
FOLDER.lastSig=null;
FOLDER.error=incomplete.join(' ')+' O Kanban tenta de novo em 30 s.';
say('Pastas automáticas: '+FOLDER.error,true);
}
}catch(e){
// The session ended (8 h) or the server is restarting: load() already shows
// the sign-in, and the folders resume after it (Sentry DTF-WEB-N).