diff --git a/tests/browser_test.mjs b/tests/browser_test.mjs index e667af4..c261573 100644 --- a/tests/browser_test.mjs +++ b/tests/browser_test.mjs @@ -300,7 +300,9 @@ try{ // Other orders the earlier suites left in the queue may still be coming // down: only once the round ends must no half-written file be left. await waitFor(()=>kanban.eval('!FOLDER.busy'),'folder round finished',60000); - assert.equal((await savedFiles('2. Arte conferida')).some(n=>n.endsWith('.baixando')),false); + assert.equal((await savedFiles('2. Arte conferida')).some(n=>/\.(baixando|crswap)$/.test(n)),false); + // Written in the work folder and moved in whole: nothing stays there (order #30). + assert.deepEqual(await savedFiles('_tmp'),[]); assert.equal((await savedFiles('1. Arte recebida')).some(n=>n.startsWith(prefix)),false); // A file whose order was deleted leaves the folder. await kanban.eval(`(async()=>{const dir=await window.picked.getDirectoryHandle('2. Arte conferida',{create:true}); diff --git a/web/kanban.js b/web/kanban.js index b3ea7cb..a6cc952 100644 --- a/web/kanban.js +++ b/web/kanban.js @@ -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///. @@ -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).