← back to Dw Domain Fleet

scripts/apply-retry.js

38 lines

#!/usr/bin/env node
// Runs ON PROD. For each failed domain, walks its candidate urls, downloading
// until one is a valid JPEG/PNG >= 60KB, then installs it (backup already
// exists from the first pass). Ensures global uniqueness across the retry batch.
const fs = require('fs');
const { execSync } = require('child_process');
const [candPath, allocPath] = process.argv.slice(2);
const cand = JSON.parse(fs.readFileSync(candPath, 'utf8'));
const alloc = JSON.parse(fs.readFileSync(allocPath, 'utf8'));
const used = new Set();
let ok = 0, fail = 0;
for (const [dom, urls] of Object.entries(cand)) {
  const p = alloc[dom] && alloc[dom].path;
  if (!p || !fs.existsSync(p)) { console.log(`SKIP ${dom} (no path)`); continue; }
  const tmp = p + '.tmp-retry';
  let done = false;
  for (const url of urls) {
    if (used.has(url)) continue;
    try {
      execSync(`curl -sL --max-time 40 -o ${JSON.stringify(tmp)} ${JSON.stringify(url)}`, { stdio: 'ignore' });
      const sz = fs.existsSync(tmp) ? fs.statSync(tmp).size : 0;
      const head = sz ? fs.readFileSync(tmp).subarray(0, 4) : Buffer.alloc(0);
      const jpeg = head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff;
      const png = head.toString('hex') === '89504e47';
      if (sz >= 60000 && (jpeg || png)) {
        if (!fs.existsSync(p + '.pre-uniquehero')) fs.copyFileSync(p, p + '.pre-uniquehero');
        fs.renameSync(tmp, p);
        used.add(url);
        console.log(`OK   ${dom}  ${sz}b`);
        ok++; done = true; break;
      }
      fs.rmSync(tmp, { force: true });
    } catch { fs.rmSync(tmp, { force: true }); }
  }
  if (!done) { console.log(`FAIL ${dom} (no candidate >=60KB)`); fail++; }
}
console.log(`\n[retry] ok=${ok} fail=${fail}`);