← back to Dw Image Shrink
finalize-cleanup.js
35 lines
// Clean up the 409-race stragglers correctly.
// Two classes among the reset-to-pending rows:
// (A) delete_409 dups: new_image_id IS NOT NULL → new copy already live, original leftover.
// Verify new is live, delete the leftover ORIGINAL, mark done. (Do NOT re-encode.)
// (B) upload_409: new_image_id IS NULL → original intact, no new copy.
// Leave pending; the worker re-run handles these.
import fs from 'fs';
import pg from 'pg';
const SHOP='designer-laboratory-sandbox.myshopify.com';
const ATOK=fs.readFileSync('/Users/macstudio3/Projects/secrets-manager/.env','utf8').split('\n').find(l=>l.startsWith('SHOPIFY_ADMIN_TOKEN=')).split('=').slice(1).join('=').replace(/["' ]/g,'');
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
async function api(m,p){const r=await fetch(`https://${SHOP}/admin/api/2024-10/${p}`,{method:m,headers:{'X-Shopify-Access-Token':ATOK}});await sleep(300);return {status:r.status,json:await r.json().catch(()=>({}))};}
const db=new pg.Client({host:'/tmp',database:'dw_unified'}); await db.connect();
const {rows}=await db.query("SELECT id,product_id,orig_image_id,new_image_id FROM img_shrink_ledger WHERE state='pending' AND new_image_id IS NOT NULL");
console.log(`delete_409 dup rows to resolve: ${rows.length}`);
let cleaned=0, retry=0, kept=0;
for(const r of rows){
const pr=await api('GET',`products/${r.product_id}.json?fields=images`);
const ids=(pr.json.product?.images||[]).map(x=>String(x.id));
const newLive=ids.includes(String(r.new_image_id));
const origLive=ids.includes(String(r.orig_image_id));
if(newLive && origLive){
const d=await api('DELETE',`products/${r.product_id}/images/${r.orig_image_id}.json`);
if(d.status===200){ await db.query("UPDATE img_shrink_ledger SET state='done',fail_reason=NULL WHERE id=$1",[r.id]); cleaned++; console.log(` ✓ ${r.product_id} deleted leftover original → done`); }
else { console.log(` ⚠ ${r.product_id} delete HTTP ${d.status} — leaving pending`); }
} else if(newLive && !origLive){
await db.query("UPDATE img_shrink_ledger SET state='done',fail_reason=NULL WHERE id=$1",[r.id]); kept++; console.log(` ✓ ${r.product_id} already clean (only new live) → done`);
} else { // new not live → true retry
await db.query("UPDATE img_shrink_ledger SET new_image_id=NULL WHERE id=$1",[r.id]); retry++; console.log(` ↻ ${r.product_id} new not live → reset for re-encode`);
}
}
const {rows:[c]}=await db.query("SELECT count(*) FILTER(WHERE state='pending') pending, count(*) FILTER(WHERE state='done') done FROM img_shrink_ledger");
console.log(`\ndup cleaned=${cleaned} already-clean=${kept} reset-for-retry=${retry} | ledger now: ${c.pending} pending, ${c.done} done`);
await db.end();