// Per-provider latency/success stats (in memory) -> adaptive scrape budget + ordering score. const RING = 32; const ALPHA = 0.3; const MIN_BUDGET = 3000; const stats = new Map(); // name -> { ok, empty, fail, timeouts, ewma, ring[], i } let maxBudget = 20000; function init(cfg) { maxBudget = cfg.timeoutMs || maxBudget; } function entry(name) { let s = stats.get(name); if (!s) { s = { ok: 0, empty: 0, fail: 0, timeouts: 0, ewma: null, ring: [], i: 0 }; stats.set(name, s); } return s; } // status: ok | empty | error | timeout function record(name, status, ms) { const s = entry(name); if (status === 'ok') s.ok++; else if (status === 'empty') s.empty++; else if (status === 'timeout') s.timeouts++; else s.fail++; // timeouts count at the budget they hit, so p90 grows towards the cap for slow providers if (status !== 'error' || ms > 0) { s.ewma = s.ewma == null ? ms : s.ewma * (1 - ALPHA) + ms * ALPHA; if (s.ring.length < RING) s.ring.push(ms); else s.ring[s.i] = ms; s.i = (s.i + 1) % RING; } } function p90(s) { if (!s.ring.length) return null; const sorted = s.ring.slice().sort((a, b) => a - b); return sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * 0.9) - 1)]; } // ms the provider gets before its fetches are aborted function budget(name) { const s = stats.get(name); const p = s && s.ok + s.empty >= 2 ? p90(s) : null; // need a couple of samples first if (p == null) return maxBudget; return Math.round(Math.min(maxBudget, Math.max(MIN_BUDGET, p * 1.5))); } // higher is better: success rate weighted by speed function score(name) { const s = stats.get(name); if (!s) return 0.5; const total = s.ok + s.empty + s.fail + s.timeouts; const rate = (s.ok + 1) / (total + 2); return rate * (2000 / ((s.ewma ?? 4000) + 2000)); } function get(name) { const s = stats.get(name); if (!s) return { ok: 0, empty: 0, fail: 0, timeouts: 0, avgMs: null, p90Ms: null, budgetMs: budget(name) }; return { ok: s.ok, empty: s.empty, fail: s.fail, timeouts: s.timeouts, avgMs: s.ewma == null ? null : Math.round(s.ewma), p90Ms: p90(s), budgetMs: budget(name), }; } module.exports = { init, record, budget, score, get };