← back to Dw Image Shrink
reaper.js
18 lines
// Crash-recovery reaper: reset rows stuck in 'claimed' longer than STALE minutes
// back to 'pending' so another worker re-processes them. Safe to run on a loop
// alongside the workers. node reaper.js [--stale 15] [--loop]
import pg from 'pg';
const arg=(k,d)=>{const a=process.argv.find(x=>x.startsWith('--'+k+'='));return a?a.split('=').slice(1).join('='):d;};
const STALE=+arg('stale','15');
const LOOP=process.argv.includes('--loop');
const db=new pg.Client({host:'/tmp',database:'dw_unified'});
await db.connect();
async function reap(){
const r=await db.query(`UPDATE img_shrink_ledger SET state='pending', worker_id=null, updated_at=now()
WHERE state='claimed' AND claimed_at < now() - ($1 || ' minutes')::interval RETURNING id`,[STALE]);
if(r.rowCount) console.log(new Date().toISOString(),'reaped',r.rowCount,'stale claimed rows');
return r.rowCount;
}
if(LOOP){ while(true){ await reap(); await new Promise(r=>setTimeout(r,60000)); } }
else { await reap(); await db.end(); }