Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341// In-process backfill worker: paginates Discord channel history backwards and// runs each message through the same match → extract → dispatch pipeline used// by live MessageCreate. One worker, one job at a time, ~1s/page so we stay// well under Discord's per-channel rate limit.
import { client } from './bot.js';import { nextPendingBackfillJob, markBackfillRunning, updateBackfillProgress, finishBackfillJob, getBackfillJobById, getRuleForDispatch, requeueOrphanedBackfillJobs, recordBackfillErrors, bumpCounter, isWithinGrace,} from './db.js';import { extractItems } from './extract.js';import { messageMatches } from './match.js';import { dispatch } from './destinations/index.js';
const DISCORD_EPOCH = 1420070400000;const PAGE_LIMIT = 100;const PAGE_DELAY_MS = 1000;const IDLE_POLL_MS = 5000;
// Proactive pace: keep total PDS writes per rolling 60s below this. The// observed eurosky.social policy is 5000 writes per rolling hour (= 83/min),// shared with live dispatch and any other tooling that writes to the user's// repo. 60/min leaves headroom for live writes and other apps on the same// account. Tunable per-PDS without a redeploy.const TARGET_WRITES_PER_MIN = Math.max( 1, Number(process.env.BACKFILL_WRITES_PER_MIN ?? 60));// Reactive: when a dispatch comes back with a 429 in its errors, sleep for// Retry-After / ratelimit-reset and re-dispatch the same message. Deterministic// rkeys make the retry safe — already-written records are idempotent puts.const RETRY_AFTER_DEFAULT_S = 60;const MAX_RETRY_SLEEP_S = 60 * 60; // cap any single backoff at 1hconst MAX_DISPATCH_RETRIES = 8;// Non-429 transient errors (5xx, socket resets, thrown dispatches) don't carry a// ratelimit-reset to wait out, so they back off exponentially instead.const TRANSIENT_BACKOFF_BASE_S = 2;const MAX_TRANSIENT_SLEEP_S = 60;
// An error is worth retrying unless it's a definitively-permanent client error.// 429 (rate limit), 5xx (server), and status-less network/socket failures are all// transient; only a non-429 4xx (e.g. 400 malformed record) is permanent, since// re-sending the identical record can't change the outcome. Erring toward retry// here is deliberate: a dropped record violates the "never lose a record" invariant,// while a needless retry just costs a little time.function isRetryableDispatchError(e) { const s = e?.status; if (s === 429) return true; if (typeof s === 'number' && s >= 400 && s < 500) return false; return true;}
// Mirror of db.js's dispatchGateClause logic, evaluated against a rule row// loaded by getRuleForDispatch. Kept in sync by both reading from the same// env at module load.const _isLoopback = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i.test(process.env.PUBLIC_URL ?? '');const _billingDisabled = _isLoopback || process.env.BILLING_DISABLED === '1';
// Belt-and-suspenders: even if a job somehow got inserted (stale DB, manual// SQL), the worker refuses to process it unless the rule's owner matches the// allowlist. Web.js enforces the same check at the API layer.const BACKFILL_ALLOWED_DISCORD_ID = process.env.BACKFILL_ALLOWED_DISCORD_ID ?? null;
function canDispatchRule(rule) { if (!rule) return false; if (!rule.enabled) return false; if (!rule.owner_active) return false; if (_billingDisabled) return true; if (rule.owner_stripe_customer_id) return true; if (isWithinGrace()) return true; return false;}
function ruleMatchesMessage(rule, msg) { if (rule.guild_id && rule.guild_id !== msg.guildId) return false; if (rule.channel_id && rule.channel_id !== msg.channelId) return false; if (rule.author_id === 'self') { return msg.author.id === rule.owner_discord_id; } if (rule.author_id) { return msg.author.id === rule.author_id; } return true;}
// Synthetic snowflake whose embedded timestamp == epochSeconds, used as the// `before` cursor for the first page of a job. Discord excludes the cursor// itself, so a synthetic id one second past until_ts captures everything// up to and including until_ts.function snowflakeAt(epochSeconds) { const ms = epochSeconds * 1000; return (BigInt(ms - DISCORD_EPOCH) << 22n).toString();}
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
// Rolling 60s budget of successful PDS write timestamps. Global to the// worker process — there's only ever one backfill job in flight at a time.const writeHistory = [];function trimWriteHistory(now) { const cutoff = now - 60_000; while (writeHistory.length > 0 && writeHistory[0] < cutoff) writeHistory.shift();}function pacingDelayMs() { const now = Date.now(); trimWriteHistory(now); if (writeHistory.length < TARGET_WRITES_PER_MIN) return 0; return Math.max(0, writeHistory[0] + 60_000 - now);}function recordWrites(n) { const now = Date.now(); for (let i = 0; i < n; i++) writeHistory.push(now);}
let _running = false;
async function processOneJob(job) { let rule = getRuleForDispatch.get(job.rule_id); if (!rule) { finishBackfillJob(job.id, 'error', 'rule deleted'); return; } if (!BACKFILL_ALLOWED_DISCORD_ID || rule.owner_discord_id !== BACKFILL_ALLOWED_DISCORD_ID) { finishBackfillJob(job.id, 'error', 'backfill is restricted to an allowlisted account'); return; } if (!canDispatchRule(rule)) { finishBackfillJob(job.id, 'error', 'rule disabled or owner not eligible to dispatch'); return; }
let channel; try { channel = await client.channels.fetch(job.channel_id); } catch (err) { finishBackfillJob(job.id, 'error', `channel fetch failed: ${err.message}`); return; } if (!channel?.isTextBased?.()) { finishBackfillJob(job.id, 'error', 'channel not text-based or not accessible to bot'); return; }
markBackfillRunning(job.id); console.log(`backfill[job=${job.id} rule=${job.rule_id}] started channel=${job.channel_id} window ${job.since_ts}..${job.until_ts}`);
let cursor = job.cursor_message_id ?? snowflakeAt(job.until_ts + 1);
while (true) { // Re-load rule + job each page so a user-initiated cancel, or a /disable // / /delete during a long job, stops it before the next API hit. const liveJob = getBackfillJobById.get(job.id); if (!liveJob || liveJob.status !== 'running') { console.log(`backfill[job=${job.id}] exiting: status=${liveJob?.status ?? 'missing'}`); return; } rule = getRuleForDispatch.get(job.rule_id); if (!canDispatchRule(rule)) { finishBackfillJob(job.id, 'cancelled', 'rule disabled or deleted mid-job'); return; }
let page; try { page = await channel.messages.fetch({ limit: PAGE_LIMIT, before: cursor }); } catch (err) { finishBackfillJob(job.id, 'error', `messages.fetch failed: ${err.message}`); return; } const messages = page ? Array.from(page.values()) : []; if (messages.length === 0) { finishBackfillJob(job.id, 'done'); console.log(`backfill[job=${job.id}] done — channel beginning reached`); return; }
let oldestId = cursor; let oldestTs = null; let hitCutoff = false; // We update progress per-message rather than per-page so the UI / diag // poller can see what's happening during a long 429 backoff sleep.
for (const msg of messages) { const ts = Math.floor(msg.createdTimestamp / 1000); if (ts < job.since_ts) { hitCutoff = true; break; } oldestId = msg.id; oldestTs = ts; let scannedDelta = 1; let dispatchedDelta = 0; let writtenDelta = 0;
const finishMessage = () => updateBackfillProgress({ id: job.id, cursor_message_id: oldestId, cursor_ts: oldestTs ?? job.since_ts, scanned_delta: scannedDelta, dispatched_delta: dispatchedDelta, records_written_delta: writtenDelta, });
if (msg.author?.bot) { finishMessage(); continue; } if (!ruleMatchesMessage(rule, msg)) { finishMessage(); continue; } if (!messageMatches(msg.content, rule.match_kind, rule.match_value)) { finishMessage(); continue; } const items = extractItems(msg.content, rule.mode); if (items.length === 0) { finishMessage(); continue; }
const ctx = { guildId: msg.guildId, channelId: msg.channelId, messageId: msg.id, authorId: msg.author.id, createdAt: new Date(msg.createdTimestamp).toISOString(), }; try { let result; let attempt = 0; while (true) { const pace = pacingDelayMs(); if (pace > 0) { console.log(`backfill[job=${job.id}] pacing — sleeping ${(pace / 1000).toFixed(1)}s to stay under ${TARGET_WRITES_PER_MIN}/min`); await sleep(pace); } try { result = await dispatch(rule, items, ctx); } catch (err) { // A thrown dispatch (whole-call failure, usually a socket-level // throw) is itself transient — fold it into the retry path with a // synthetic error rather than dropping the message on the floor. result = { written: 0, errors: [{ where: 'dispatch', status: null, message_id: msg.id, message: err?.message ?? String(err) }] }; } recordWrites(result.written);
// Retry while any error is non-permanent. Re-dispatching is safe: // deterministic rkeys make already-written records idempotent puts, so // a retry only meaningfully re-attempts what actually failed. const retryable = result.errors.filter(isRetryableDispatchError); if (retryable.length === 0) break; // everything wrote, or only permanent errors remain if (attempt >= MAX_DISPATCH_RETRIES) { console.error(`backfill[job=${job.id}] retries exhausted on msg=${msg.id}; ${retryable.length} unrecovered error(s) left for the repair re-run`); break; }
// 429s carry a ratelimit-reset to wait out; other transients (5xx, // socket resets) get exponential backoff. const rl = retryable.find(e => e.status === 429); let sleepSec; let kind; if (rl) { kind = '429'; // Sleep priority: explicit Retry-After header > ratelimit-reset epoch // > default. eurosky sends ratelimit-* (5000;w=3600) without // Retry-After, so reset is usually the source of truth. sleepSec = rl.retry_after_s; if (sleepSec == null) { const resetEpoch = Number(rl.ratelimit_headers?.['ratelimit-reset']); if (Number.isFinite(resetEpoch)) sleepSec = resetEpoch - Math.floor(Date.now() / 1000); } if (sleepSec == null || !Number.isFinite(sleepSec)) sleepSec = RETRY_AFTER_DEFAULT_S; } else { kind = 'transient'; sleepSec = Math.min(TRANSIENT_BACKOFF_BASE_S * 2 ** attempt, MAX_TRANSIENT_SLEEP_S); } sleepSec = Math.max(1, Math.min(MAX_RETRY_SLEEP_S, sleepSec)); console.warn(`backfill[job=${job.id}] ${kind} on msg=${msg.id} (attempt ${attempt + 1}/${MAX_DISPATCH_RETRIES}); sleeping ${sleepSec}s before retry`); await sleep(sleepSec * 1000); attempt++; } bumpCounter(rule.job_id, items.length); dispatchedDelta += items.length; writtenDelta += result.written; // Whatever errors remain on the final attempt are either permanent (a // 4xx we won't retry) or transient survivors that exhausted retries. // Both are real and need the repair re-run, so persist them. A fully // successful retry leaves result.errors empty. if (result.errors.length > 0) recordBackfillErrors(job.id, result.errors); } catch (err) { // Backstop only — dispatch throws are folded into the retry loop above, // so this fires solely on an unexpected error in the retry machinery. console.error(`backfill[job=${job.id}] unexpected retry-loop error for msg=${msg.id}`, err?.message ?? err); recordBackfillErrors(job.id, [{ where: 'dispatch', message_id: msg.id, message: err?.message ?? String(err), }]); } finishMessage(); }
if (hitCutoff) { finishBackfillJob(job.id, 'done'); console.log(`backfill[job=${job.id}] done — reached since_ts`); return; } if (messages.length < PAGE_LIMIT) { finishBackfillJob(job.id, 'done'); console.log(`backfill[job=${job.id}] done — short page (channel beginning)`); return; }
cursor = oldestId; await sleep(PAGE_DELAY_MS); }}
export async function startBackfillWorker() { if (_running) return; _running = true; const requeued = requeueOrphanedBackfillJobs(); if (requeued > 0) { console.log(`backfill: requeued ${requeued} orphaned running job(s) from previous container`); } console.log('backfill worker started'); while (_running) { if (!client.isReady?.()) { await sleep(IDLE_POLL_MS); continue; } const job = nextPendingBackfillJob.get(); if (!job) { await sleep(IDLE_POLL_MS); continue; } try { await processOneJob(job); } catch (err) { console.error(`backfill worker: unexpected error on job=${job.id}`, err.message); try { finishBackfillJob(job.id, 'error', err.message); } catch {} } }}
export function stopBackfillWorker() { _running = false; }