Files
linkspin/health.js
T
2026-10-20 05:50:00 -05:00

249 lines
19 KiB
JavaScript

// Destination health checks (LinkSpin, 2026-10-10): every 30 minutes each ACTIVE destination of every rotation
// (and the fallback) is fetched with a browser-like UA, HEAD first then GET when the server refuses HEAD or when
// the page is HTML (the body is what tells a parked page from a live one). States: ok, slow (over 6 s), dead
// (network error, timeout, 404/410/5xx), parked (parking-page signatures). Three failing checks in a row pause
// the destination (d.active = false, d.autoPaused = when); a paused one is re-checked every 6 hours and comes back
// on its own after two clean passes, but only when LinkSpin paused it, never when the owner did. The last live
// destination of a rotation with no fallback is never paused: a redirect to something beats a dead end.
// frameBlocked is informational: LinkSpin links run inside traffic-exchange frames, so the owner wants to know.
// At most 4 requests in flight at once. A small event log (Central-time day keys) sits at DATA_DIR/health-log.json.
const fs = require('fs');
const path = require('path');
// Banner Spin (phase 3, 2026-10-20): the same pass also checks every live banner. Its IMAGE must load as an image
// (PNG / GIF / JPEG / WebP by magic bytes, an uploaded file read from disk, a pasted one fetched) at the Banner Spin's size,
// and its TARGET must pass check() above (a spin-link target only has to exist: its destinations are checked as spin
// links). Same counters: three failing checks pause the banner (b.active = false, b.autoPaused), two clean passes resume
// it, auto-paused ones are re-checked every 6 hours, and the last live banner of a Banner Spin is NEVER auto-paused.
let rotator = null, DATA_DIR = null, notify = null, bannerspin = null;
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36 LinkSpinHealth/1.0';
const TIMEOUT = 10000, SLOW = 6000, MAX_REDIRECTS = 5, PARALLEL = 4, FAILS_TO_PAUSE = 3, PASSES_TO_RESUME = 2;
const RECHECK_PAUSED = 6 * 3600 * 1000, MANUAL_GAP = 60 * 1000;
const PARKED = /domain is for sale|this domain (?:is|may be) for sale|parked free|sedoparking|sedo\.com\/search|buy this domain|godaddy\.com\/parked|hugedomains|afternic|\bdan\.com\b|parkingcrew|bodis\.com|domain parking|this domain has expired|<title>\s*(?:default web page|welcome to nginx!?|apache2 .* default page|index of \/|website coming soon|domain default page)\s*<\/title>/i;
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const L = { file: () => path.join(DATA_DIR, 'health-log.json'), db: null,
load() { try { this.db = JSON.parse(fs.readFileSync(this.file(), 'utf8')); } catch (e) { this.db = { events: [] }; } },
add(ev) { if (!this.db) this.load(); this.db.events.push(Object.assign({ ts: Date.now(), day: ctDay(Date.now()) }, ev)); if (this.db.events.length > 500) this.db.events = this.db.events.slice(-400); try { fs.writeFileSync(this.file(), JSON.stringify(this.db)); } catch (e) {} } };
function init(opts) { rotator = opts.rotator; DATA_DIR = opts.dataDir; notify = opts.notify || null; bannerspin = opts.bannerspin || null; L.load(); }
// one request with a hard timeout; returns the Response or throws
async function req(url, method, signalMs) {
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), signalMs || TIMEOUT);
try { return await fetch(url, { method, redirect: 'manual', signal: ac.signal, headers: { 'User-Agent': UA, Accept: 'text/html,application/xhtml+xml,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.8' } }); }
finally { clearTimeout(t); }
}
// follow up to MAX_REDIRECTS by hand (so the chain is bounded and the final URL is known)
async function follow(url, method) {
let u = url, hops = 0, res;
for (;;) {
res = await req(u, method);
if (res.status >= 300 && res.status < 400 && res.headers.get('location') && hops < MAX_REDIRECTS) {
try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {}
u = new URL(res.headers.get('location'), u).toString(); hops++; continue;
}
return { res, finalUrl: u, hops };
}
}
// read at most 64 KB of a body
async function head64k(res) {
if (!res.body) return '';
const reader = res.body.getReader(); const chunks = []; let n = 0;
try { while (n < 65536) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); n += value.length; } } catch (e) {}
try { reader.cancel().catch(() => {}); } catch (e) {}
return Buffer.concat(chunks.map(c => Buffer.from(c))).toString('utf8');
}
const frameBlocked = h => {
const xfo = String(h.get('x-frame-options') || '').toLowerCase(); if (/deny|sameorigin/.test(xfo)) return true;
const csp = String(h.get('content-security-policy') || '').toLowerCase(); const m = /frame-ancestors([^;]*)/.exec(csp);
if (m) { const v = m[1].trim(); return !(v === '*' || /(^|\s)https?:(\s|$)|\*/.test(v)); }
return false;
};
// classify one URL -> { state, code, ms, note, frameBlocked, finalUrl }
async function check(url) {
const t0 = Date.now();
let out = { state: 'dead', code: 0, ms: 0, note: '', frameBlocked: false, finalUrl: url };
try {
let { res, finalUrl } = await follow(url, 'HEAD');
let ms = Date.now() - t0; out.finalUrl = finalUrl;
const ctype = () => String(res.headers.get('content-type') || '').toLowerCase();
let body = '';
if (res.status === 405 || res.status === 501 || res.status === 403 || (res.status >= 200 && res.status < 300 && /html/.test(ctype()))) {
// the server refuses HEAD, or the page is HTML (we need the body to spot a parking page)
try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {}
const t1 = Date.now(); const g = await follow(url, 'GET'); res = g.res; out.finalUrl = g.finalUrl; ms = Date.now() - t1;
if (/html/.test(ctype())) body = await head64k(res); else { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} }
} else { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} }
out.code = res.status; out.ms = ms; out.frameBlocked = frameBlocked(res.headers);
if (res.status === 404 || res.status === 410 || res.status >= 500) { out.state = 'dead'; out.note = 'HTTP ' + res.status; }
else if (body && PARKED.test(body)) { out.state = 'parked'; out.note = 'Parked page'; }
else if (res.status >= 200 && res.status < 400) { out.state = ms > SLOW ? 'slow' : 'ok'; out.note = ms > SLOW ? 'Slow, ' + (ms / 1000).toFixed(1) + ' s' : ''; }
else { out.state = 'ok'; out.note = 'HTTP ' + res.status + ' to our checker (a bot wall, most likely); visitors may still get through'; }
} catch (e) {
out.ms = Date.now() - t0; out.state = 'dead';
out.note = (e && e.name === 'AbortError') ? 'No answer in 10 s' : ('Could not connect' + (e && e.cause && e.cause.code ? ' (' + e.cause.code + ')' : ''));
}
return out;
}
const failing = s => s === 'dead' || s === 'parked';
const when = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric' });
// apply a fresh result to a destination record: counters, auto-pause, auto-resume. Returns a change note or null.
function apply(r, d, c) {
const prev = d.health || {}; const now = Date.now();
const fails = failing(c.state) ? (prev.fails || 0) + 1 : 0;
const passes = failing(c.state) ? 0 : (prev.passes || 0) + 1;
d.health = { state: c.state, code: c.code, ms: c.ms, checkedAt: now, fails, passes, note: c.note, frameBlocked: !!c.frameBlocked };
if (d.active && fails >= FAILS_TO_PAUSE) {
const others = r.destinations.filter(x => x !== d && x.active);
if (!others.length && !r.fallback) { d.health.note = (c.note || c.state) + '. Kept live: it is the only destination and there is no fallback.'; return null; }
d.active = false; d.autoPaused = now; d.health.passes = 0;
L.add({ ev: 'pause', r: r.id, d: d.id, url: d.url, state: c.state, note: c.note });
return { kind: 'paused', text: (c.state === 'parked' ? 'Parked page' : 'Dead page') + ', auto-paused ' + when(now) };
}
if (!d.active && d.autoPaused && passes >= PASSES_TO_RESUME) {
d.active = true; delete d.autoPaused; d.health.fails = 0;
L.add({ ev: 'resume', r: r.id, d: d.id, url: d.url, state: c.state });
return { kind: 'resumed', text: 'Back up, resumed ' + when(now) };
}
return null;
}
async function tell(r, d, change) {
if (!notify || !change || change.kind !== 'paused' || /^demo:/.test(r.owner)) return;
const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const html = '<p>LinkSpin paused one destination in your link <b>' + esc(r.name) + '</b> (/r/' + esc(r.code) + ') because it failed three checks in a row.</p>'
+ '<p><span style="font-family:monospace">' + esc(d.url) + '</span><br>' + esc(d.health.note || d.health.state) + '</p>'
+ '<p>Visitors keep flowing to your other destinations' + (r.fallback ? ' and the fallback' : '') + '. If the page comes back, LinkSpin resumes it on its own after two clean checks. You can also fix the address or resume it yourself under Links.</p>';
try { await notify(r.owner, 'A destination in ' + r.name + ' was paused', html); } catch (e) {}
}
// run a list of jobs, at most PARALLEL at once
async function runAll(jobs) {
let i = 0; const workers = new Array(Math.min(PARALLEL, jobs.length)).fill(0).map(async () => { while (i < jobs.length) { const j = jobs[i++]; try { await j(); } catch (e) {} } });
if (workers.length) await Promise.all(workers);
}
// ── Banner Spin banners ──
const MAGIC = buf => buf.length >= 12 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 ? 'image/png' : buf.length >= 6 && buf.slice(0, 4).toString('latin1') === 'GIF8' ? 'image/gif'
: buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff ? 'image/jpeg' : buf.length >= 12 && buf.slice(0, 4).toString('latin1') === 'RIFF' && buf.slice(8, 12).toString('latin1') === 'WEBP' ? 'image/webp' : '';
async function headBytes(res, max) {
if (!res.body) return Buffer.alloc(0);
const reader = res.body.getReader(); const chunks = []; let n = 0;
try { while (n < max) { const { done, value } = await reader.read(); if (done) break; chunks.push(Buffer.from(value)); n += value.length; } } catch (e) {}
try { reader.cancel().catch(() => {}); } catch (e) {}
return Buffer.concat(chunks);
}
// one banner image -> { state: ok | broken | size, note, w, h, ms }
async function checkImage(src, size) {
const t0 = Date.now(); const [W, H] = size || [0, 0];
const where = bannerspin && bannerspin.imageSource ? bannerspin.imageSource(src) : null;
if (!where) return { state: 'broken', note: 'No image address', w: 0, h: 0, ms: 0 };
let buf, type = '';
if (where.file) {
try { buf = fs.readFileSync(where.file); } catch (e) { return { state: 'broken', note: 'The uploaded image file is missing', w: 0, h: 0, ms: Date.now() - t0 }; }
} else {
try {
const { res } = await follow(where.url, 'GET');
if (res.status >= 400 || res.status < 200) { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} return { state: 'broken', note: 'The image address answers HTTP ' + res.status, w: 0, h: 0, ms: Date.now() - t0 }; }
type = String(res.headers.get('content-type') || '').toLowerCase();
buf = await headBytes(res, 65536);
} catch (e) { return { state: 'broken', note: (e && e.name === 'AbortError') ? 'The image did not load in 10 s' : 'The image address could not be reached', w: 0, h: 0, ms: Date.now() - t0 }; }
}
const mime = MAGIC(buf); const ms = Date.now() - t0;
if (!mime) return { state: 'broken', note: /^text\/html/.test(type) ? 'The image address returns a web page, not an image' : 'The file is not a readable image', w: 0, h: 0, ms };
const d = mime === 'image/webp' ? { w: 0, h: 0 } : bannerspin.dims(buf, mime);
// a size mismatch is a warning, not a failure (2026-10-20): the builder allows it with a warning, so live banners must not be auto-paused for it
if (d.w && d.h && W && (d.w !== W || d.h !== H)) return { state: 'ok', warn: 'size', note: 'The image is ' + d.w + 'x' + d.h + '; this Banner Spin is ' + W + 'x' + H, w: d.w, h: d.h, ms };
return { state: 'ok', note: d.w ? '' : 'Loads as an image (size not readable)', w: d.w, h: d.h, ms };
}
// one banner target -> the spin-link check shape. A spin link only has to still exist.
async function checkTarget(s, b) {
if (b.link) { const r = rotator && rotator.rawRotations ? rotator.rawRotations().find(x => x.id === b.link && x.owner === s.owner) : null; return r ? { state: 'ok', code: 0, ms: 0, note: 'Spin link /r/' + r.code + ' (its pages are checked as spin links)' } : { state: 'dead', code: 0, ms: 0, note: 'The spin link this banner points at was deleted' }; }
if (!b.target) return { state: 'dead', code: 0, ms: 0, note: 'No target set' };
return check(String(b.target).replace(/\{[a-z0-9_]{1,24}\}/gi, 'x')); // macros filled with a placeholder, like a real click would
}
// apply both results to the banner: counters, auto-pause (never the last live banner), auto-resume
function applyBanner(s, b, img, tgt) {
const prev = b.health || {}; const now = Date.now();
const bad = img.state !== 'ok' || failing(tgt.state);
const fails = bad ? (prev.fails || 0) + 1 : 0, passes = bad ? 0 : (prev.passes || 0) + 1;
const note = img.state !== 'ok' ? img.note : failing(tgt.state) ? (tgt.state === 'parked' ? 'Target is a parked page' : 'Target page is down') + (tgt.note ? ' (' + tgt.note + ')' : '') : tgt.state === 'slow' ? 'Target is slow' + (tgt.note ? ' (' + tgt.note + ')' : '') : '';
b.health = { state: img.state !== 'ok' ? 'image' : tgt.state, note, checkedAt: now, fails, passes,
image: { state: img.state, note: img.note || '', w: img.w || 0, h: img.h || 0 }, target: { state: tgt.state, code: tgt.code || 0, ms: tgt.ms || 0, note: tgt.note || '' } };
if (b.active && !b.adminOff && fails >= FAILS_TO_PAUSE) {
const others = s.banners.filter(x => x !== b && x.active && !x.adminOff);
if (!others.length) { b.health.note = note + '. Kept live: it is the last live banner in this Banner Spin.'; return null; }
b.active = false; b.autoPaused = now; b.health.passes = 0;
L.add({ ev: 'pause', bs: s.id, b: b.id, url: b.image, state: b.health.state, note });
return { kind: 'paused', text: note + ', auto-paused ' + when(now) };
}
if (!b.active && b.autoPaused && passes >= PASSES_TO_RESUME) {
b.active = true; delete b.autoPaused; b.health.fails = 0;
L.add({ ev: 'resume', bs: s.id, b: b.id, url: b.image, state: b.health.state });
return { kind: 'resumed', text: 'Back up, resumed ' + when(now) };
}
return null;
}
async function tellBanner(s, b, change) {
if (!notify || !change || change.kind !== 'paused') return;
const esc = x => String(x).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const html = '<p>LinkSpin paused one banner in your Banner Spin <b>' + esc(s.name) + '</b> because it failed three checks in a row.</p>'
+ '<p>' + esc(b.label || 'Banner ' + b.id) + '<br>' + esc((b.health && b.health.note) || '') + '</p>'
+ '<p>Your other banners keep rotating. If it comes back, LinkSpin resumes it on its own after two clean checks. You can also fix the image or the target, or resume it yourself, under Links, Banner Spins.</p>';
try { await notify(s.owner, 'A banner in ' + s.name + ' was paused', html); } catch (e) {}
}
// the banner jobs for one pass. force = check auto-paused ones now too (admin "run checks"); onlyId = one Banner Spin
function bannerJobs(force, onlyId, onChange) {
if (!bannerspin || !bannerspin.rawSpins || (bannerspin.live && !bannerspin.live())) return [];
const now = Date.now(); const jobs = [];
for (const s of bannerspin.rawSpins()) {
if (s.adminOff || (onlyId && s.id !== Number(onlyId))) continue;
const size = bannerspin.SIZES[s.size];
for (const b of s.banners) {
if (b.adminOff) continue;
const due = (b.active) || (b.autoPaused && (force || !b.health || now - (b.health.checkedAt || 0) >= RECHECK_PAUSED));
if (!due) continue;
jobs.push(async () => { const [img, tgt] = await Promise.all([checkImage(b.image, size), checkTarget(s, b)]); const ch = applyBanner(s, b, img, tgt); onChange(); if (ch) await tellBanner(s, b, ch); });
}
}
return jobs;
}
// admin "run the checks now" for Banner Spins (no once-a-minute limit; auto-paused banners are re-checked at once)
let bannerRunning = false;
async function checkBannerSpins(opts) {
opts = opts || {}; if (bannerRunning) return { error: 'A check is already running.' }; bannerRunning = true;
let n = 0; try { const jobs = bannerJobs(true, opts.id, () => { n++; }); await runAll(jobs); } finally { bannerRunning = false; if (n && bannerspin) bannerspin.save(); }
return { ok: true, checked: n };
}
let running = false;
// the scheduled pass: active destinations + fallbacks every time; auto-paused destinations when 6 h have gone by
async function tick() {
if (running || !rotator) return { skipped: true }; running = true;
const now = Date.now(); const jobs = []; let changed = false, n = 0, bn = 0;
try {
jobs.push(...bannerJobs(false, 0, () => { bn++; })); // Banner Spin banners, same pass, same 4-at-once limit
for (const r of rotator.rawRotations()) {
for (const d of r.destinations) {
const due = d.active || (d.autoPaused && (!d.health || now - (d.health.checkedAt || 0) >= RECHECK_PAUSED));
if (!due) continue;
jobs.push(async () => { const c = await check(d.url); const ch = apply(r, d, c); changed = true; n++; if (ch) await tell(r, d, ch); });
}
if (r.fallback) jobs.push(async () => { const c = await check(r.fallback); r.fallbackHealth = { state: c.state, code: c.code, ms: c.ms, checkedAt: Date.now(), note: c.note, frameBlocked: !!c.frameBlocked }; changed = true; });
}
await runAll(jobs);
} finally { running = false; if (changed) rotator.save(); if (bn && bannerspin) bannerspin.save(); }
return { checked: n, banners: bn };
}
// "Check now" for one rotation (owner-scoped, once a minute): every destination, paused ones too, plus the fallback
const lastManual = new Map();
async function checkRotation(owner, id) {
const r = rotator.findMine(owner, id); if (!r) return { error: 'No such rotation.' };
const last = lastManual.get(r.id) || 0; if (Date.now() - last < MANUAL_GAP) return { error: 'Checked less than a minute ago. Give it a moment.' };
lastManual.set(r.id, Date.now());
const jobs = r.destinations.map(d => async () => { const c = await check(d.url); const ch = apply(r, d, c); if (ch) await tell(r, d, ch); });
if (r.fallback) jobs.push(async () => { const c = await check(r.fallback); r.fallbackHealth = { state: c.state, code: c.code, ms: c.ms, checkedAt: Date.now(), note: c.note, frameBlocked: !!c.frameBlocked }; });
await runAll(jobs); rotator.save();
return { ok: true, rotation: rotator.pub(r) };
}
function recent() { if (!L.db) L.load(); return L.db.events.slice(-50).reverse(); }
module.exports = { init, tick, check, checkRotation, recent, checkImage, checkBannerSpins };