import type { Decision } from "@/lib/decisions"; import { askEditor, editorUrl } from "@/lib/articles/generation"; import { xJarDecision } from "./xJar.mjs"; // --------------------------------------------------------------------------- // X's jar, for the Inbox (lib/inbox/xJar.mjs says when it is a call): the // editor's services route asked through umtool's editor client (askEditor, // its WORKER_TOKEN), answered from a minute's memo, and never waited on for // more than WAIT_MS (0.4 s) -- the Inbox and the rail's count read it, and an editor // that is slow or down must not slow them. Any failure is no row. SERVER ONLY. // --------------------------------------------------------------------------- /** UMTOOL_XJAR_MEMO_MS (the e2e suite's 0: each read asks the stub), else a minute. */ const memoMs = () => { const v = Number(process.env.UMTOOL_XJAR_MEMO_MS); return Number.isFinite(v) && v >= 0 ? v : 60_000; }; /** The editor's services answer from a stat: a late answer still lands in the memo for the next read. */ const WAIT_MS = 400; /** What the editor said of X's jar: its row when X work waits on a stale jar; `known` false when it did not answer. */ type JarRead = { row: Decision | null; known: boolean }; type Memo = { at: number; value: Promise } | null; const g = globalThis as typeof globalThis & { __umtoolXJarMemo?: Memo }; /** Forget the memo (a spec that changed the stub's services; a Recheck). */ export function clearXJarMemo(): void { g.__umtoolXJarMemo = null; } async function ask(): Promise { const payload = await askEditor("/api/ops/services", { fresh: true }); return { row: xJarDecision(payload, { href: `${editorUrl()}/settings` }) as Decision | null, known: !!payload && typeof payload === "object" }; } /** * What the editor says of X's jar, never waited on past WAIT_MS: `known` false when it did not answer (down, slow, * an error) -- the readiness bar says "—" then, never ✓ (umtool redesign L7b). Never throws. */ export async function xJarStatus({ fresh = false }: { fresh?: boolean } = {}): Promise { const m = g.__umtoolXJarMemo; let value: Promise; if (m && !fresh && Date.now() - m.at < memoMs()) value = m.value; else { value = ask().catch(() => ({ row: null, known: false })); g.__umtoolXJarMemo = { at: Date.now(), value }; } const timeout = new Promise((resolve) => setTimeout(() => resolve({ row: null, known: false }), WAIT_MS).unref?.()); return Promise.race([value, timeout]).catch(() => ({ row: null, known: false })); } /** The X jar's row when X work waits on it, else none. Never throws. */ export async function xJarDecisions({ fresh = false }: { fresh?: boolean } = {}): Promise { const { row } = await xJarStatus({ fresh }); return row ? [row] : []; }