// X'S JOB COUNT, ON DISK (lane x-followups, R2; review 2 M1 and ruling R-c): // every counted X job's start on this machine, ONE list, in // `/.x-session/job-starts.json`: // { "version": 2, "starts": [, …] } // The rule and its numbers are lib/xJobRule.ts. Here: // - the file is read and written under its lock (one check-and-record at a // time) and survives a restart; // - ONE BUCKET: the count is the machine's, whatever login source, cookie // spec or channel a job uses. A file of the first shape (version 1, one // list per login key) is read as the SUM of its lists and rewritten as one; // - it FAILS CLOSED: a file that is there and cannot be read or parsed // refuses every X job until it is repaired; // - A FILE THAT IS NOT THERE IS NOT AN EMPTY COUNT (ruling R-c): the last // 24 hours of counted starts are rebuilt from the job records (each job's // `.meta.json` carries the starts it was counted for, `xStarts`) and // written. When X jobs ran (X's queue gap names an end in the last day) // but their records cannot be read — the directory refuses, a record of // the day is unreadable, or none is left — every X job is refused. A // corpus where no X job ever ran starts at zero. // // SERVER-ONLY (node:fs). In jobs/ (not lib/) because it reads the job records. import path from "node:path"; import { readdir, readFile } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; import { X_JOB_CAP, X_QUEUE_KEY, xJobCapSentence, xJobCapUnreadableSentence, xJobCapUnrebuildableSentence, xJobCapVerdict, xJobCounts, type XJobCapVerdict, } from "../lib/xJobRule"; import { kindIsNetwork } from "./jobKinds"; import { QUEUE_GAPS_FILE } from "./queueGap"; import { jobIdTime } from "./ulid"; type CapPaths = Pick; export function xJobStartsFile(paths: Pick): string { return path.join(paths.transcriptsDir, ".x-session", "job-starts.json"); } type StartsFile = { version: 2; starts: number[] }; const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); // The file as it is: absent, unreadable (fail closed), or its starts (a // version-1 file's lists summed into one — `migrated`). async function readStartsFile(paths: CapPaths): Promise<{ state: "absent" } | { state: "bad" } | { state: "ok"; starts: number[]; migrated: boolean }> { const read = await readJsonFile(xJobStartsFile(paths)); if (!read.ok) return read.reason === "absent" ? { state: "absent" } : { state: "bad" }; const v = read.value as { version?: unknown; starts?: unknown; logins?: unknown } | null; if (!v || typeof v !== "object") return { state: "bad" }; if (v.version === 2) { if (!Array.isArray(v.starts) || !v.starts.every(finite)) return { state: "bad" }; return { state: "ok", starts: [...v.starts], migrated: false }; } if (v.version === 1) { // THE FIRST SHAPE, ONE LIST PER LOGIN KEY: every login's starts are the // machine's, so they are summed. if (!v.logins || typeof v.logins !== "object" || Array.isArray(v.logins)) return { state: "bad" }; const starts: number[] = []; for (const list of Object.values(v.logins as Record)) { if (!Array.isArray(list) || !list.every(finite)) return { state: "bad" }; starts.push(...list); } return { state: "ok", starts: starts.sort((a, b) => a - b), migrated: true }; } return { state: "bad" }; } // The counted starts on disk, for X's sitting rebuild (jobs/xSitting.ts): // null when the file is absent or cannot be read. A look: nothing written. export async function readXJobStarts(paths: CapPaths): Promise { const file = await readStartsFile(paths); return file.state === "ok" ? file.starts : null; } // ── the records are kept (review 3 M3) ───────────────────────────────────── // RETENTION NEVER DELETES THE RECORD OF AN X JOB THAT MAY STILL COUNT // (jobs/listJobs.ts pruneJobLogs asks xRecordMayCount), and says since when it // has kept them: `/x-records-kept.json`, {version: 1, since: }, // written once, by the first prune (or rebuild) of code that keeps them. A // rebuild trusts the records of the last day only when that is over a day // old. The marker is the ONLY proof (review 4 A): an old finished record on // disk shows nothing (a job cancelled while queued has no log and is never // pruned; retention goes by id and queue time, not start time). A "since" // after now is no proof either: it is said again, at now. export const X_RECORDS_KEPT_FILE = "x-records-kept.json"; export async function readXRecordsKeptSince(paths: Pick): Promise { const read = await readJsonFile(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE)); const since = read.ok ? (read.value as { since?: unknown } | null)?.since : undefined; return finite(since) ? since : undefined; } // Said once: a "since" already on disk is never moved later. One after `now` // (a clock that jumped) proves nothing and is said again at `now`, so the // refusal it causes ends within a day (review 4 A). export async function noteXRecordsKept(paths: Pick, now: number): Promise { const had = await readXRecordsKeptSince(paths); if (had !== undefined && had <= now) return had; await writeJsonAtomic(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE), { version: 1, since: now }, { mkdir: true }); return now; } // MAY THIS RECORD STILL COUNT AGAINST X'S CAP? An X-queue record (or one that // says it was counted) with a start, a counted start or its queueing inside // the last day — or after `now`; and a record that cannot be read whose id // is of the last day (or of no known day). Kept by retention while it may. export function xRecordMayCount(id: string, meta: Record | null, now: number): boolean { const since = now - X_JOB_CAP.dayMs; const born = jobIdTime(id); if (!meta) return born === 0 || born > since; const xStarts = Array.isArray(meta.xStarts) ? meta.xStarts.filter(finite) : []; if (meta.queueKey !== X_QUEUE_KEY && xStarts.length === 0) return false; return [...xStarts, meta.startedAt, born].some((t) => finite(t) && t > since); } // ── the rebuild (ruling R-c) ─────────────────────────────────────────────── export type XJobStartsRebuild = | { ok: true; starts: number[]; records: number } | { ok: false; why: string; until?: number }; // The last day's counted X starts, from the job records. A record written by // this code says its starts (`xStarts`, [] for an X job that counted none); a // record of X's queue from before it is counted once at its start when its // kind and plan count (lib/xJobRule.ts xJobCounts) — more rather than fewer. export async function rebuildXJobStarts(paths: Pick, now: number): Promise { const since = now - X_JOB_CAP.dayMs; // The evidence that X jobs ran in the last day: X's queue gap's last end. let lastXEnd: number | undefined; const gaps = await readJsonFile(path.join(paths.jobsDir, QUEUE_GAPS_FILE)); if (gaps.ok) { const end = (gaps.value as { ends?: Record } | null)?.ends?.[X_QUEUE_KEY]; if (finite(end) && end > since) lastXEnd = end; } const until = lastXEnd !== undefined ? lastXEnd + X_JOB_CAP.dayMs : undefined; let names: string[]; try { names = await readdir(paths.jobsDir); } catch (err) { const code = (err as NodeJS.ErrnoException)?.code; if (code === "ENOENT" || code === "ENOTDIR") return { ok: true, starts: [], records: 0 }; return { ok: false, why: `the job records cannot be listed (${code ?? (err as Error).message})`, ...(until ? { until } : {}) }; } const starts: number[] = []; let records = 0; for (const name of names) { if (!name.endsWith(".meta.json")) continue; const id = name.slice(0, -".meta.json".length); const born = jobIdTime(id); let m: Record | null = null; try { const parsed = JSON.parse(await readFile(path.join(paths.jobsDir, name), "utf8")) as unknown; m = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record) : null; } catch { m = null; } if (!m) { // A record of the last day (or of no known day) that cannot be read may // be an X job's: nothing is counted on a guess. if (born === 0 || born > since) return { ok: false, why: `the job record ${name} cannot be read`, ...(until ? { until } : {}) }; continue; } if (m.queueKey !== X_QUEUE_KEY) continue; if (Array.isArray(m.xStarts)) { records++; for (const t of m.xStarts) if (finite(t) && t > since) starts.push(t); continue; } // A record from before `xStarts`: once, at its start, when it would count. const kind = typeof m.kind === "string" ? m.kind : ""; const at = finite(m.startedAt) ? m.startedAt : undefined; if (!kindIsNetwork(kind) || at === undefined) continue; records++; const spec = m.spec as { params?: Record } | undefined; // The channel is not read: a record of a library's media-only capture is // counted (more rather than fewer). if (at > since && xJobCounts({ kind, ...(spec?.params ? { params: spec.params } : {}) })) starts.push(at); } // X jobs ran, and not one record of them is left. if (lastXEnd !== undefined && records === 0) { return { ok: false, why: "X's queue ended a job within the last 24 hours and no record of an X job is left", ...(until ? { until } : {}) }; } // X JOBS RAN TODAY: THE RECORDS MUST BE SHOWN TO COVER THE DAY (review 3 // M3). A count from records retention may have thinned is a guess, and // nothing is counted on a guess. if (lastXEnd !== undefined || starts.length > 0) { const kept = await noteXRecordsKept(paths, now); if (!(kept <= since)) { const ends = [kept + X_JOB_CAP.dayMs, ...(until !== undefined ? [until] : [])]; return { ok: false, why: "records of the last 24 hours may have been deleted (by the jobs list's retention or Clear logs, before it kept X's): " + "nothing shows they are all there", until: Math.min(...ends), }; } } return { ok: true, starts: starts.sort((a, b) => a - b), records }; } // ── the count ────────────────────────────────────────────────────────────── export type XJobCapStatus = XJobCapVerdict & { perHour: number; perDay: number; // The count could not be read or rebuilt: `ok` is false and nothing starts. unreadable?: true; // The refusal, when `ok` is false. sentence?: string; }; function statusOf(starts: ReadonlyArray, now: number): XJobCapStatus { const v = xJobCapVerdict(starts, now); return { ...v, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, ...(v.ok ? {} : { sentence: xJobCapSentence(v, now) }) }; } function closed(sentence: string): XJobCapStatus { return { ok: false, lastHour: 0, lastDay: 0, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, unreadable: true, sentence }; } // What a day can still count (the longer window), as of `now`: a start in // the future is kept, and never a reason to drop the real ones (review 3 S4). function keptOf(starts: ReadonlyArray, now: number): number[] { return starts.filter((t) => t > now - X_JOB_CAP.dayMs); } async function writeStarts(paths: CapPaths, starts: number[]): Promise { await writeJsonAtomic(xJobStartsFile(paths), { version: 2, starts } satisfies StartsFile, { mkdir: true }); } // The starts, HOLDING THE FILE'S LOCK: a version-1 file rewritten as one // list; an absent one rebuilt from the job records and written; or the // refusal's sentence. async function loadLocked(paths: CapPaths, now: number): Promise<{ ok: true; starts: number[] } | { ok: false; sentence: string }> { const file = await readStartsFile(paths); if (file.state === "bad") return { ok: false, sentence: xJobCapUnreadableSentence(xJobStartsFile(paths)) }; if (file.state === "ok") { if (file.migrated) await writeStarts(paths, keptOf(file.starts, now)); return { ok: true, starts: file.starts }; } const rebuilt = await rebuildXJobStarts(paths, now); if (!rebuilt.ok) return { ok: false, sentence: xJobCapUnrebuildableSentence(xJobStartsFile(paths), rebuilt.why, rebuilt.until) }; await writeStarts(paths, keptOf(rebuilt.starts, now)); return { ok: true, starts: rebuilt.starts }; } // Would an X job start now? Nothing is counted (a file to migrate or rebuild // is written, under the lock). export async function xJobCapStatus(paths: CapPaths, now: number = Date.now()): Promise { const file = await readStartsFile(paths); if (file.state === "ok" && !file.migrated) return statusOf(file.starts, now); if (file.state === "bad") return closed(xJobCapUnreadableSentence(xJobStartsFile(paths))); const loaded = await withJsonFileLock(xJobStartsFile(paths), () => loadLocked(paths, now)); return loaded.ok ? statusOf(loaded.starts, now) : closed(loaded.sentence); } // ONE X JOB STARTS: checked and recorded in one step, under the file's lock. // `ok: false` — the cap is reached, or the count cannot be read — records // nothing, and the job does not start. `at` is the time recorded: the // clock's (a start already on record later than it still counts — S4). export async function recordXJobStart(paths: CapPaths, now: number = Date.now()): Promise { return withJsonFileLock(xJobStartsFile(paths), async () => { const loaded = await loadLocked(paths, now); if (!loaded.ok) return closed(loaded.sentence); const before = statusOf(loaded.starts, now); if (!before.ok) return before; const at = now; const starts = [...keptOf(loaded.starts, now), at]; await writeStarts(paths, starts); // This start was within the cap: said so, with the count it leaves. const after = statusOf(starts, now); return { ok: true, lastHour: after.lastHour, lastDay: after.lastDay, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, at }; }); }