// THE COOKIE RECHECK TIMER (plans/cookie-refresh-alerts.md, "Proactive"): // the cookie refresh alerts used to be raised only by a job that FAILED on a // stale cookie — a Rumble sync or a clip fetch met the embed 403 first, and // the banner explained the failure after it. Operator, 2026-10-31: "make // Rumble trigger on a timer so we can be more proactive." // // Every `settings.serviceCookies.recheckIntervalMinutes` (default 180; 0 = // off), stretched by up to `pacing.jitter` and never shortened, ONE tick: // // 1. X's jar, from disk (social/xJarAge.ts — never a request to X): a raised // jar-age banner clears once the jar is fresh; with none up, X jobs // queued on a jar past `social.x.maxCookieAgeMinutes` raise it before // their start refuses them. // 2. Every RAISED alert with something to ask is rechecked once, exactly as // the banner's Recheck (controller/recheckServiceCookies.ts, as a // `recheck-service-cookies` job): a banner clears by itself once the // operator has opened the site in the browser. X's recheck asks X // nothing. // 3. Each of `probeServices` (default Rumble) with no alert up is PROBED: one // metadata request for the last video it answered cleanly. Rumble's embed // 403 is ambiguous (a removed video 403s too), so a 403 there is // confirmed ONCE on the previous, different known-good video, a jittered // minute or more later — two different videos refused raise the banner, // as two in a job do. Never more than two requests per service per tick. // // NEVER STACKING, NEVER PUSHING: a service is skipped when a job is queued or // running on its platform's queues (that job is the probe, and its answer // raises or clears the alert by itself), when the platform is cooling down or // held (jobs/platformBackoff.ts), when it answered cleanly within the // interval, or when a recheck of it is already queued or running; a tick // still in flight when the next is due skips the next. A failed probe is NEVER // retried: the alert goes up and waits for the next tick or a manual Recheck. // // Not armed on an idle boot (ARCHILYZER_IDLE_BOOT, lib/idleBoot.ts) — a tick // is a request to a platform — nor on the e2e test server (instrumentation.ts). // State lives on globalThis: the instrumentation hook and a route may load // this module twice, and two timers would be two probes. import { isIdleBoot } from "../lib/idleBoot"; import { getSettings } from "../lib/settings"; import { jitterMs } from "../lib/jitter"; import type { Paths } from "../lib/paths"; import { buildServiceCookieAlerts, isAlertRaised, serviceFamily, serviceLabel, X_SERVICE, type ServiceCookieState, type ServiceCookieTimerView, type XJarStatusView, } from "../lib/serviceCookies"; import type { ServiceCookiesSettings } from "../lib/serviceCookieSettings"; import type { RecheckOutcome } from "./recheckServiceCookies"; export const RECHECK_JOB_KIND = "recheck-service-cookies"; export const recheckQueueKey = (service: string) => `service-cookies:${service}`; // When the setting is 0, how often the timer looks whether it was turned on. export const OFF_POLL_MS = 15 * 60_000; // The first tick after boot: no sooner than this (boot resumes its own work). export const FIRST_TICK_MAX_MS = 15 * 60_000; // Rumble's second known-good video is asked no sooner than this after the first. export const CONFIRM_GAP_MS = 60_000; export type TickJob = { kind: string; queueKey: string; status: string }; export type TickAction = { service: string; action: "rechecked" | "probed" | "confirmed" | "skipped" | "cleared" | "raised" | "ok"; message: string; }; export type ServiceCookieTickDeps = { now: () => number; settings: () => ServiceCookiesSettings; readState: () => Promise; // The registry's jobs (any status; only queued and running count). jobs: () => TickJob[]; // The platform is cooling down or held. cooling: (platform: string) => Promise; // One recheck, as a job; `target` asks that request instead of the last // clean one. recheck: (service: string, target?: { url: string; channel?: string }) => Promise; xJar: () => Promise; noteXJarStale: (line: string) => Promise; noteXJarFresh: () => Promise; // A wait between Rumble's two known-good videos (jittered up, at least CONFIRM_GAP_MS). confirmWait: () => Promise; log: (line: string) => void; }; const ACTIVE = new Set(["queued", "running"]); export async function runServiceCookieTick(deps: ServiceCookieTickDeps): Promise { const out: TickAction[] = []; const act = (a: TickAction) => { out.push(a); deps.log(`[cookies] ${serviceLabel(a.service)}: ${a.action} — ${a.message}`); }; const settings = deps.settings(); const intervalMs = settings.recheckIntervalMinutes * 60_000; const active = () => deps.jobs().filter((j) => ACTIVE.has(j.status)); const rechecking = (svc: string) => active().some((j) => j.kind === RECHECK_JOB_KIND && j.queueKey === recheckQueueKey(svc)); const busy = (platform: string) => active().some((j) => j.queueKey === `platform:${platform}` || j.queueKey === `clips:${platform}`); // Why a service is not asked now, or null. const holdBack = async (svc: string): Promise => { // Instagram's alert is a person's to clear (Recheck or Dismiss on the // dashboard): the timer never asks it, alert up or not. if (serviceFamily(svc) === "instagram") return "Instagram's alert is cleared by a person's Recheck only"; if (rechecking(svc)) return "a recheck of it is already queued or running"; if (serviceFamily(svc) === "ytdlp") { if (busy(svc)) return `a job is queued or running on its queue (its answer is the probe)`; if (await deps.cooling(svc).catch(() => false)) return "the platform is cooling down or held"; } return null; }; let state = await deps.readState(); // 1. X's jar, from disk. const xEntry = state.services[X_SERVICE]; try { if (isAlertRaised(xEntry) && xEntry!.kind === "jar-age") { const jar = await deps.xJar(); if (jar.fresh) { await deps.noteXJarFresh(); act({ service: X_SERVICE, action: "cleared", message: `the jar is fresh (${jar.summary})` }); } else { act({ service: X_SERVICE, action: "ok", message: `still old: ${jar.summary}` }); } } else if (!isAlertRaised(xEntry)) { const xJobs = active().filter((j) => j.queueKey === "platform:twitter").length; if (xJobs > 0) { const jar = await deps.xJar(); if (!jar.fresh && jar.maxAgeMinutes > 0) { await deps.noteXJarStale( `${xJobs} X job${xJobs === 1 ? " is" : "s are"} queued on an old cookie jar: ${jar.summary}`, ); act({ service: X_SERVICE, action: "raised", message: `${xJobs} queued X job(s), ${jar.summary}` }); } } } } catch (err) { deps.log(`[cookies] X: could not read the jar: ${(err as Error).message}`); } // 2. Every raised (stale) alert with something to ask. const view = buildServiceCookieAlerts(state, { now: deps.now() }); const asked = new Set(); for (const alert of view.alerts) { if (alert.state !== "stale" || !alert.canRecheck) continue; if (alert.service === X_SERVICE && alert.kind === "jar-age") continue; const why = await holdBack(alert.service); if (why) { act({ service: alert.service, action: "skipped", message: why }); continue; } asked.add(alert.service); const res = await deps.recheck(alert.service).catch((err) => ({ service: alert.service, result: "failed" as const, message: (err as Error).message, })); act({ service: alert.service, action: "rechecked", message: `${res.result}: ${res.message}` }); } // 3. The probes, with no alert up. if (settings.probeServices.length) state = await deps.readState(); for (const svc of settings.probeServices) { if (asked.has(svc)) continue; const entry = state.services[svc]; if (isAlertRaised(entry)) continue; const good = state.lastGood[svc]; if (!good) { act({ service: svc, action: "skipped", message: "no clean request is recorded to ask again" }); continue; } const sinceGood = deps.now() - Date.parse(good.at); if (intervalMs > 0 && sinceGood < intervalMs) { act({ service: svc, action: "skipped", message: `answered cleanly ${Math.floor(sinceGood / 60_000)} min ago` }); continue; } const why = await holdBack(svc); if (why) { act({ service: svc, action: "skipped", message: why }); continue; } const res = await deps.recheck(svc).catch((err) => ({ service: svc, result: "failed" as const, message: (err as Error).message, })); act({ service: svc, action: "probed", message: `${res.result}: ${res.message}` }); if (res.result !== "stale") continue; // Rumble's ambiguous 403: one first video, still pending — confirm ONCE // on the previous, different known-good video. const after = (await deps.readState()).services[svc]; const prev = good.prev; if (!after || after.raisedAt || after.kind !== "embed-403" || !prev || prev.url === good.url) continue; await deps.confirmWait(); const why2 = await holdBack(svc); if (why2) { act({ service: svc, action: "skipped", message: `the confirmation: ${why2}` }); continue; } const res2 = await deps.recheck(svc, { url: prev.url, ...(prev.channel ? { channel: prev.channel } : {}) }).catch( (err) => ({ service: svc, result: "failed" as const, message: (err as Error).message }), ); act({ service: svc, action: "confirmed", message: `${res2.result}: ${res2.message}` }); } return out; } // ── the default deps (the live editor) ───────────────────────────────────── export async function defaultTickDeps(paths: Paths, log: (line: string) => void): Promise { const { getRegistry } = await import("../jobs/registry"); const { platformCooldownRemainingMs, platformHold } = await import("../jobs/downloadBackoff"); const { readServiceCookieState, noteXJarStale, noteXJarFresh } = await import("../lib/serviceCookies-server"); const { readXJarAge } = await import("../social/xJarAge"); const { resolvedXMaxCookieAgeMinutes } = await import("../jobs/networkGuard"); return { now: () => Date.now(), settings: () => getSettings().serviceCookies, readState: () => readServiceCookieState(paths), jobs: () => getRegistry().list().map((j) => ({ kind: j.kind, queueKey: j.queueKey, status: j.status })), cooling: async (platform) => (await platformCooldownRemainingMs(platform, paths)) > 0 || (await platformHold(platform, paths)) !== null, recheck: (service, target) => runRecheckServiceJob(paths, service, target), xJar: async () => { const settings = getSettings(); return readXJarAge(paths, settings, { maxAgeMinutes: resolvedXMaxCookieAgeMinutes(settings), fresh: true }); }, noteXJarStale: (line) => noteXJarStale(paths, { line }), noteXJarFresh: () => noteXJarFresh(paths), confirmWait: () => new Promise((r) => setTimeout(r, jitterMs(CONFIRM_GAP_MS)).unref?.()), log, }; } // ONE RECHECK AS A JOB (kind `recheck-service-cookies`, its own queue // `service-cookies:`): what the banner's Recheck and the timer both // run, so it shows on /jobs with its log. export async function runRecheckServiceJob( paths: Paths, service: string, target?: { url: string; channel?: string }, ): Promise { const { runManagedFunction } = await import("../jobs/streamCommand"); const { recheckServiceCookies } = await import("./recheckServiceCookies"); let outcome: RecheckOutcome | null = null; const res = await runManagedFunction({ kind: RECHECK_JOB_KIND, queueKey: recheckQueueKey(service), paths, fn: async (onLog, signal) => { outcome = await recheckServiceCookies({ paths, service, onLog, signal, ...(target ? { target } : {}) }); }, }); if (!res.ok) return { service, result: "failed", message: res.error }; void res.stream.cancel(); const done = await res.done; const o = outcome as RecheckOutcome | null; if (done.status !== "done" || !o) { return { service, result: "failed", message: `The ${serviceLabel(service)} recheck ended ${done.status}.`, jobId: res.jobId }; } return { ...o, jobId: res.jobId }; } // ── the timer ────────────────────────────────────────────────────────────── type TimerState = { handle?: { cancel: () => void }; inFlight: boolean; intervalMinutes: number; lastTickAt?: number; nextTickAt?: number; last?: TickAction[]; }; const KEY = Symbol.for("archilyzer.serviceCookieTimer"); function slot(): { state?: TimerState } { const g = globalThis as unknown as Record; return (g[KEY] ??= {}); } export type TimerScheduler = (fn: () => void, ms: number) => { cancel: () => void }; const realScheduler: TimerScheduler = (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return { cancel: () => clearTimeout(t) }; }; export type StartTimerOpts = { log?: (line: string) => void; env?: Record; // Injected for tests; the live editor's are built from `paths`. deps?: () => Promise; settings?: () => ServiceCookiesSettings; schedule?: TimerScheduler; jitter?: (ms: number) => number; now?: () => number; }; // Arms the timer once per process. Answers false when it is already armed, // or the process booted idle. export function startServiceCookieTimer(opts: StartTimerOpts & { paths?: Paths } = {}): boolean { const s = slot(); if (s.state) return false; if (isIdleBoot(opts.env ?? process.env)) return false; const log = opts.log ?? ((l: string) => console.log(l)); const schedule = opts.schedule ?? realScheduler; const now = opts.now ?? Date.now; const settingsOf = opts.settings ?? (() => getSettings().serviceCookies); const jitter = opts.jitter ?? ((ms: number) => jitterMs(ms)); const depsOf = opts.deps ?? (async () => { const { getPaths } = await import("../lib/paths"); return defaultTickDeps(opts.paths ?? getPaths(), log); }); const state: TimerState = { inFlight: false, intervalMinutes: 0 }; s.state = state; const interval = (): number => { try { return settingsOf().recheckIntervalMinutes; } catch { return 0; } }; const arm = (ms: number) => { state.nextTickAt = now() + ms; state.handle = schedule(tick, ms); }; const tick = () => { const minutes = interval(); state.intervalMinutes = minutes; if (minutes <= 0) { // Off: look again later whether it was turned on. state.nextTickAt = undefined; state.handle = schedule(tick, OFF_POLL_MS); return; } if (state.inFlight) { log("[cookies] the previous tick is still running; this one is skipped"); arm(jitter(minutes * 60_000)); return; } state.inFlight = true; state.lastTickAt = now(); void (async () => { try { state.last = await runServiceCookieTick(await depsOf()); } catch (err) { log(`[cookies] tick failed: ${(err as Error).message}`); } finally { state.inFlight = false; arm(jitter(Math.max(1, interval() || minutes) * 60_000)); } })(); }; const first = interval(); state.intervalMinutes = first; if (first <= 0) state.handle = schedule(tick, OFF_POLL_MS); else arm(jitter(Math.min(first * 60_000, FIRST_TICK_MAX_MS))); return true; } export function stopServiceCookieTimer(): void { const s = slot(); s.state?.handle?.cancel(); s.state = undefined; } // For `pnpm ops get services` / the dashboard payload. export function serviceCookieTimerView(settingsMinutes?: number): ServiceCookieTimerView { const st = slot().state; if (!st) return { intervalMinutes: settingsMinutes ?? 0, armed: false }; return { intervalMinutes: settingsMinutes ?? st.intervalMinutes, armed: true, ...(st.lastTickAt ? { lastTickAt: new Date(st.lastTickAt).toISOString() } : {}), ...(st.nextTickAt ? { nextTickAt: new Date(st.nextTickAt).toISOString() } : {}), ...(st.last ? { last: st.last.map(({ service, action, message }) => ({ service, action, message })) } : {}), }; }