// CLIENT-SIDE RATE BUDGET — a persistent, FAIL-CLOSED spend ledger that sits in front of every // real vendor call a twin pack makes. VENDOR-AGNOSTIC: the mechanism lives here, every vendor // specific (the window, the ceiling, the per-endpoint weights) is DATA a pack declares, exactly // like `TwinPack.browserRouting`. There is no vendor name, and no vendor branch, in this file. // // ── WHY THIS EXISTS ───────────────────────────────────────────────────────────────────────── // This module is a durable ledger of what has been spent in the last rolling window, // consulted BEFORE the request goes out, that THROWS rather than calls when the ceiling is // reached, and that persists across processes so a fresh process does NOT get a fresh allowance. // Failing closed is the whole point — a refused call costs a retry, a lockout costs days. // // Every pack that talks to a live vendor can declare its budget numbers. // // ── WHERE THE NUMBERS COME FROM ───────────────────────────────────────────────────────────── // From the PACK, never from here. A pack calls `declareRateBudget(vendor, { window, ceiling, // weights, reason })` (or ships the same object as `TwinPack.rateBudget`, which `registerPack` // forwards). The kernel only knows how to price a call against declared rules and how to keep // the ledger honest. // // A vendor with NO declaration does NOT become unlimited. It falls back to // `DEFAULT_RATE_BUDGET`, a deliberately austere allowance (see its docstring) — "nobody // configured it" must never mean "no limit". There is deliberately NO opt-out: an escape hatch is // a permanent hole that the next careless caller reaches for, and the cost asymmetry is stark — // a too-tight default costs a refused call plus a one-line declaration, a too-loose one costs days // of lockout. // // ── CONCURRENCY / ATOMICITY — the honest guarantee ────────────────────────────────────────── // Every ledger mutation is a read-modify-write performed while holding an exclusive lock file // created with O_EXCL (`openSync(..., 'wx')`), and the ledger itself is replaced by an atomic // `rename()` of a temp file, so a reader never observes a half-written JSON document. // `checkBudget()` does not merely *look* — it RESERVES, charging the weight to the ledger inside // the same lock hold before returning. That is what makes a burst genuinely refused: two processes // racing cannot both see room, because the first one's spend is already committed before the // second one reads. `recordCall()` then SETTLES that reservation rather than charging twice. // Everything inside `withLock` is SYNCHRONOUS, so N concurrent async callers in one process cannot // interleave between the read and the write either. // // ── WHAT THIS DOES *NOT* GUARANTEE (read this before trusting it) ─────────────────────────── // • It binds only calls made through the guarded client a pack wires it into. A caller who // hand-rolls `fetch` against the vendor host is unaffected. The ban on raw vendor calls // (docs/contributing/architecture.md D8) is enforced separately // by per-pack repo-wide gates, not by this module. // • `path` / `root` / `now` are CALLER-REACHABLE RESETS. A different ledger path, or an injected // clock that fast-forwards, restores the full allowance. They exist because tests must inject // them, and there is no way to offer that seam to a test and deny it to a determined caller in // the same process. `ceiling` / `windowMs` / `maxRetryAfterSeconds` passed at CONSTRUCTION are // clamped so a configuration MISTAKE cannot widen the budget, the DECLARATION itself is // clamped to sane bounds and may never be re-declared more permissively, and the clock is // sanity-checked for the common ACCIDENTS (seconds instead of ms, a monotonic // `performance.now()`-style clock) — but no clamp defeats intent. This guards CARELESSNESS, // NOT MALICE, and that claim is not upgraded anywhere. // • The default ledger is keyed by VENDOR **and** a hash of the TOKEN, and lives in the user's // home dir, because vendors rate-limit per credential. Passing `root` scopes it to one project // instead, which means two project roots sharing one token get two allowances — use it only // when that is what you want. // • O_EXCL locking is reliable on a local filesystem; over NFS or a network share it is not. // • DELETING the ledger restores a full allowance with no cooldown: a missing file is the // legitimate first run and cannot be told apart from a wiped one. A *corrupt* file, by // contrast, costs a full window. The asymmetry is deliberate but worth knowing. // • A call that dies between reserve and settle stays charged for the rest of the window. That // is deliberate: over-charging is the safe direction. // • `checkBudget` uses the synchronous WorldStore lock; it belongs on CLI and connector paths. import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { createHash, randomUUID } from 'node:crypto'; import { volterHome } from './volter-home.ts'; import clockForm from '../world-clock.cjs'; import { dirname, join } from 'node:path'; import { worldPaths } from './storage.ts'; import { FsWorldStore, getActiveWorldStore, type WorldStore } from './world-store.ts'; import type { ErrorSpec } from './derived-core.ts'; // ── bounds the kernel enforces on ANY declaration ─────────────────────────────────────────── /** Shortest window a declaration may claim. A sub-second window is a counter reset, not a budget. */ export const MIN_RATE_BUDGET_WINDOW_MS = 1_000; /** Longest window a declaration may claim — beyond an hour the ledger stops being a rolling window. */ export const MAX_RATE_BUDGET_WINDOW_MS = 60 * 60 * 1_000; /** * The most weighted units any pack may declare per window. Not a vendor fact — a blast radius cap, * so a typo (`ceiling: 100000`) cannot silently disarm the guard for a whole vendor. Every real * declaration is far under it. */ export const MAX_RATE_BUDGET_CEILING = 1_000; /** * The sub-window every declaration's BURST is measured over, regardless of its own window length. * A rolling window bounds total spend but says nothing about how fast it may be spent: a one-hour * window with a 600-unit ceiling admits all 600 in a single millisecond, twenty times what the * austere fallback allows in a minute, and neither `MAX_RATE_BUDGET_CEILING` nor * `MAX_RATE_BUDGET_UNITS_PER_SECOND` (which evaluates to 0.167/s there) reaches it. So a declaration * whose window is longer than this MUST also declare `burstCeiling`, and the kernel refuses against * it independently. */ export const RATE_BUDGET_BURST_WINDOW_MS = 60_000; /** * The most weighted units per SECOND any declaration may imply (`ceiling / (windowMs/1000)`). * The per-dimension caps above do not bound the RATE — `ceiling: 1000, windowMs: 1000` satisfies * both and still buys 1000 units a second, which is not a budget. This is the bound that makes the * "blast radius cap" claim true without depending on a declaration's window length. */ export const MAX_RATE_BUDGET_UNITS_PER_SECOND = 20; /** * The cheapest a single call may be priced. NOTHING IS FREE: a zero-weight call would let an * unbounded loop through, and the ledger's "entries can never outnumber the ceiling" invariant * (which bounds `load()`) depends on every entry costing at least one unit. */ export const MIN_RATE_BUDGET_WEIGHT = 1; /** A cooldown is capped only to keep an absurd/garbage header from producing a nonsense date. */ const MAX_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1000; /** * How long to back off when the vendor says "slow down" without saying for how long. The * conventional answer for a bare 429, and also the cap on the "exhausted, reset unreadable" path — * an unreadable hint must not cost MORE than no hint at all. */ const DEFAULT_BARE_429_BACKOFF_S = 60; /** * A valid ledger cannot hold more entries than the ceiling (every entry costs at least 1 and the * live sum never exceeds the ceiling, which is itself capped at `MAX_RATE_BUDGET_CEILING`), so * anything past this is corruption or a griefing write — and an enormous array is also what would * make `load()` slow enough to matter for the lock. */ const MAX_LEDGER_ENTRIES = MAX_RATE_BUDGET_CEILING; /** Earliest plausible ms-epoch (2001-09-09). Below this the clock is in seconds, or not an epoch. */ const MIN_PLAUSIBLE_EPOCH_MS = 1_000_000_000_000; // ── the per-vendor DATA a pack declares ───────────────────────────────────────────────────── /** * One pricing rule. `match` is a RegExp SOURCE string tested against the *call key* — whatever * string the pack's guarded client uses to name the call it is about to make (a REST path for an * HTTP pack, a dotted SDK method name for an SDK-shaped pack). First matching rule wins, so order * matters; a call matching nothing is priced at `defaultWeight`. * * `whenQueryPresent` / `whenQueryAbsent` let one path split by request shape (e.g. a cheap probe * distinguished from a full fetch only by a query parameter) without needing a vendor-specific * predicate FUNCTION in the declaration — declarations stay pure, inspectable data. */ export type RateBudgetWeightRule = { /** RegExp source, tested against the call key. */ match: string; /** Weighted cost when this rule matches. At least `MIN_RATE_BUDGET_WEIGHT`. */ weight: number; /** Only match when EVERY named query key is present. */ whenQueryPresent?: string[]; /** Only match when EVERY named query key is absent. */ whenQueryAbsent?: string[]; }; /** What a pack declares. Pure data — no vendor code in the kernel; the one function a declaration may hold is a served * bucket's computed weight, which its client budget never reads. */ export type RateBudgetDeclaration = { /** Rolling window, in ms. Spend older than this is pruned. */ windowMs: number; /** Weighted units allowed inside one window. */ ceiling: number; /** * Weighted units allowed inside any 60-SECOND sub-window, enforced independently of `ceiling`. * * REQUIRED when `windowMs` is longer than 60s, and refused as meaningless when it is not (a * window that is already a minute has its ceiling as its burst). This is what stops a long window * from buying an enormous instantaneous burst as a side effect of bounding a long-horizon limit — * the thing github and linear legitimately need, and the thing a careless declaration would get by * accident. Must be ≤ `ceiling`; like every other axis it may only ever be TIGHTENED. */ burstCeiling?: number; /** Cost of a call no rule prices. Never zero — an unknown endpoint must never be free. */ defaultWeight: number; /** * Seconds. A `Retry-After` above this is not something to sleep off — it means the credential is * in real trouble, so it FAILS LOUDLY rather than scheduling a long sleep. */ maxRetryAfterSeconds?: number; /** Ordered pricing rules; first match wins. */ rules?: RateBudgetWeightRule[]; /** * WHY these numbers — the vendor's documented (or observed) limits, and the reasoning that * turned them into this ceiling. Required: a budget nobody can explain is a budget nobody can * review, and the ceiling is the one number that can cost days if it is wrong. */ reason: string; /** The vendor's documented allowance, in calls a minute, and the page that documents it, which the pack cites on a * `// source:` line (checked like every other vendor fact): required of a budget that admits more than the fallback * (`twin-standard invariants`, its RATE row). */ allowance?: { perMinute: number; source: string }; /** The limits as the vendor's own server keeps them: what its simulated twin enforces while a World's scenario switches * them on (`rate-limit`, architecture "Scenarios"; world-core scenario-consume.ts rateLimited), never this client's * ceiling. A request is counted in every bucket it belongs to and refused by the first one it would exhaust. */ buckets?: RateBucket[]; /** The refusal a bucket that declares none answers with. */ refused?: RateRefusal; }; /** What a bucket's key, its weight function and its templates read of one request: its operation id, its path * parameters, its query, headers and body as the vendor reads it, the credential it presents (a hash, never the * credential) and the account it is served in. */ export type RateBucketRequest = { operation: string; params: Record; query: URLSearchParams; headers: Headers; body: unknown; credential: string; account: string; }; /** One limit the vendor keeps: `limit` units a `per` window (`1s`, `1h`), counted per `key` in World time. */ export type RateBucket = { /** The bucket's name: `{bucket}` in a template, and what a scenario's `rate-limit` names to switch it on alone. */ name: string; /** The template a request's count is kept under: `{credential}`, `{account}`, `{operation}` and any path parameter * (`{credential}` alone is one count per credential; `{account}:{channel_id}` one per account and channel). A * request missing a parameter the key names is not counted in this bucket. */ key: string; limit: number; per: string; /** `fixed-window`: windows from the epoch, each starting at zero. `token-bucket`: `limit` tokens refilled evenly over * `per`, a request admitted while its weight in tokens is left. */ counting: 'fixed-window' | 'token-bucket'; /** The operations this bucket counts; absent, every operation. */ operations?: string[]; /** A request's weight, as the client budget's `weights` price a call: by operation id (an operation not listed weighs * 1), or computed from the request by the pack (a query's complexity, a format's quota units). Absent, every request * weighs 1. */ weights?: Record | ((request: RateBucketRequest) => number); /** The most requests of one key in flight at once; one more is refused by this bucket. */ concurrency?: number; /** `{global}` in a template: a limit across all of a credential's routes, as the vendor tells its clients. */ global?: boolean; /** The unit `{reset}` (the instant the bucket next admits, from the epoch) and `{resetAfter}` (the time until then) * are written in, rounded up: seconds, the default, or milliseconds. */ reset?: 'seconds' | 'ms'; /** This bucket's refusal; absent, the declaration's `refused`. */ refused?: RateRefusal; /** Headers on every answer to a request this bucket counted (the vendor's remaining-quota headers), templates over the * values, written only while a scenario switches the bucket on. */ headers?: Record; }; /** A bucket's refusal: the vendor's own status and error (its manifest's envelope, `message` a template over the values), * or `body`, the whole body as a template, and its headers. A template reads `{limit}`, `{remaining}`, `{used}`, * `{reset}`, `{resetAfter}`, `{bucket}` and `{global}`; a body value that is one placeholder alone keeps its type. */ export type RateRefusal = { error: ErrorSpec; body?: unknown; headers?: Record }; /** The values a rate template is filled with. */ export type RateValues = { limit: number; remaining: number; used: number; reset: number; resetAfter: number; bucket: string; global: boolean }; /** A rate template filled with `values`: a string's placeholders replaced, a string that is one placeholder alone given * the value itself, arrays and objects filled throughout. */ export function fillRateTemplate(template: unknown, values: RateValues): unknown { const v = values as unknown as Record; if (typeof template === 'string') { const whole = /^\{(\w+)\}$/.exec(template); if (whole && whole[1]! in v) return v[whole[1]!]; return template.replace(/\{(\w+)\}/g, (all, k: string) => (k in v ? String(v[k]) : all)); } if (Array.isArray(template)) return template.map((t) => fillRateTemplate(t, values)); if (template && typeof template === 'object') return Object.fromEntries(Object.entries(template).map(([k, t]) => [k, fillRateTemplate(t, values)])); return template; } /** A declaration's buckets checked: each named once, with a key, a positive limit, a `per` of `(s|m|h|d)`, a counting * the kernel keeps, and a refusal (its own or the declaration's). */ function checkBuckets(vendor: string, decl: RateBudgetDeclaration): void { const names = new Set(); for (const b of decl.buckets ?? []) { if (!b || typeof b.name !== 'string' || b.name === '') fail(`${vendor}: every bucket needs a \`name\``); if (names.has(b.name)) fail(`${vendor}: bucket ${b.name} is declared twice`); names.add(b.name); if (typeof b.key !== 'string' || b.key === '') fail(`${vendor}: bucket ${b.name} needs a \`key\` template`); if (!finitePositive(b.limit)) fail(`${vendor}: bucket ${b.name}'s limit must be a positive number`); if (typeof b.per !== 'string' || !/^\d+(?:\.\d+)?(s|m|h|d)$/.test(b.per.trim()) || !(Number.parseFloat(b.per) > 0)) fail(`${vendor}: bucket ${b.name}'s per is (s|m|h|d), got ${JSON.stringify(b.per)}`); if (b.counting !== 'fixed-window' && b.counting !== 'token-bucket') fail(`${vendor}: bucket ${b.name}'s counting is fixed-window or token-bucket`); if (b.concurrency !== undefined && !(Number.isInteger(b.concurrency) && b.concurrency > 0)) fail(`${vendor}: bucket ${b.name}'s concurrency is a positive integer`); if (b.weights !== undefined && typeof b.weights !== 'function' && Object.values(b.weights).some((w) => !(typeof w === 'number' && Number.isFinite(w) && w >= 0))) fail(`${vendor}: bucket ${b.name}'s weights are non-negative numbers`); if (!(b.refused ?? decl.refused)) fail(`${vendor}: bucket ${b.name} has no refusal: declare its \`refused\` or the declaration's`); } } /** * A declaration bound to the vendor it governs, with every pattern already compiled. The `RegExp`s * are built ONCE here rather than per call: `priceCall` runs in front of every vendor request, and * recompiling a pattern per call is both wasted work and a needless amplifier for a pathological * pattern. (Declarations are repo source, not user input — this is a performance fix, not a * sanitizer.) */ export type RateBudgetPolicy = Required> & Pick & { vendor: string; rules: RateBudgetWeightRule[]; /** `compiled[i]` is `rules[i].match`, compiled. Same length, same order. */ compiled: RegExp[]; }; /** * The allowance a vendor gets when NOBODY declared one. * * 60 weighted units per 60s at a default weight of 2 — 30 calls a minute, one every two seconds. * That is comfortably above any human- or agent-driven explicit pull (a few dozen calls), and far * below the shape that causes lockouts (a loop emitting hundreds of calls a minute). It is * deliberately NOT generous: an undeclared vendor is one nobody has thought about, and the safe * assumption about an unexamined vendor is that its limits are tight. * * There is no opt-out. A pack that genuinely needs more says so, in its declaration, with a reason. * * ⚠️ HONESTLY: this is tighter than a real declaration in CALL COUNT, but it is NOT uniformly * tighter, because it prices every call the same. A vendor whose pack prices one endpoint high (a * render at 20, a recursive walk at 2) gets that endpoint priced at 2 here — cheaper, not dearer. * That is why `RateBudget` reads the policy LIVE rather than snapshotting it at construction, and * why a pack's binding (its `XBudget` subclass, whose module declares on import) is the only * construction path you should use. */ export const DEFAULT_RATE_BUDGET: RateBudgetDeclaration = { windowMs: 60_000, ceiling: 60, defaultWeight: 2, maxRetryAfterSeconds: 300, rules: [], reason: 'no pack declared a budget for this vendor — this is the conservative fallback (30 calls/min at ' + 'the default weight), not a considered limit. Declare one on the pack with the vendor\'s real limits.', }; // ── declaration registry ──────────────────────────────────────────────────────────────────── const declarations = new Map(); function fail(what: string): never { throw new Error(`rate budget: ${what}`); } function finitePositive(n: unknown): n is number { return typeof n === 'number' && Number.isFinite(n) && n > 0; } /** * Validate + clamp a declaration. Clamping is the ONLY direction that matters: a declaration may * ask for a shorter window or a bigger ceiling than the kernel permits, and it gets the kernel's * bound instead. Anything structurally wrong (a zero-weight rule, an unparseable pattern, a missing * reason) is a THROW, not a clamp — those are mistakes, not preferences. */ function normalize(vendor: string, decl: RateBudgetDeclaration): RateBudgetPolicy { if (typeof vendor !== 'string' || !/^[a-z0-9-]+$/.test(vendor)) fail(`invalid vendor id: ${String(vendor)}`); if (!decl || typeof decl !== 'object') fail(`${vendor}: declaration must be an object`); if (typeof decl.reason !== 'string' || decl.reason.trim() === '') { fail(`${vendor}: a declaration must carry a \`reason\` — the vendor limits that justify this ceiling`); } if (!finitePositive(decl.windowMs)) fail(`${vendor}: windowMs must be a positive number`); if (!finitePositive(decl.ceiling)) fail(`${vendor}: ceiling must be a positive number`); if (!finitePositive(decl.defaultWeight)) fail(`${vendor}: defaultWeight must be a positive number`); if (decl.defaultWeight < MIN_RATE_BUDGET_WEIGHT) { fail(`${vendor}: defaultWeight ${decl.defaultWeight} is below ${MIN_RATE_BUDGET_WEIGHT} — an unclassified call must never be free`); } if (decl.maxRetryAfterSeconds !== undefined && !finitePositive(decl.maxRetryAfterSeconds)) { fail(`${vendor}: maxRetryAfterSeconds must be a positive number`); } // A window LONGER than the kernel's bound is refused, not clamped down: clamping it would hand // the declaration a HIGHER rate than it asked for (a 24h/500 declaration silently becoming // 1h/500), which is the one direction normalization must never move. if (decl.windowMs > MAX_RATE_BUDGET_WINDOW_MS) { fail(`${vendor}: windowMs ${decl.windowMs} is beyond the ${MAX_RATE_BUDGET_WINDOW_MS}ms bound — refusing rather than clamping it down, which would RAISE the rate this declaration asked for`); } // A window longer than the burst sub-window MUST bound its burst explicitly; a window that is // already the sub-window may not, because there its ceiling IS the burst and a second number could // only disagree with the first. const longWindow = decl.windowMs > RATE_BUDGET_BURST_WINDOW_MS; if (longWindow && !finitePositive(decl.burstCeiling)) { fail(`${vendor}: a window longer than ${RATE_BUDGET_BURST_WINDOW_MS / 1000}s must also declare \`burstCeiling\` — otherwise the whole window can be spent in one instant`); } if (!longWindow && decl.burstCeiling !== undefined) { fail(`${vendor}: burstCeiling is meaningless for a window of ${decl.windowMs / 1000}s or less — the ceiling already is the burst`); } if (decl.burstCeiling !== undefined && decl.burstCeiling > decl.ceiling) { fail(`${vendor}: burstCeiling ${decl.burstCeiling} exceeds the ceiling ${decl.ceiling}, which bounds it anyway`); } checkBuckets(vendor, decl); const rules: RateBudgetWeightRule[] = []; const compiled: RegExp[] = []; for (const r of decl.rules ?? []) { if (!r || typeof r !== 'object' || typeof r.match !== 'string') fail(`${vendor}: every rule needs a \`match\` pattern`); if (!finitePositive(r.weight) || r.weight < MIN_RATE_BUDGET_WEIGHT) { fail(`${vendor}: rule ${r.match} has weight ${String(r.weight)} — every priced call must cost at least ${MIN_RATE_BUDGET_WEIGHT}`); } try { compiled.push(new RegExp(r.match)); } catch (e) { fail(`${vendor}: rule ${r.match} is not a valid pattern (${(e as Error).message})`); } rules.push({ match: r.match, weight: r.weight, ...(r.whenQueryPresent ? { whenQueryPresent: [...r.whenQueryPresent] } : {}), ...(r.whenQueryAbsent ? { whenQueryAbsent: [...r.whenQueryAbsent] } : {}), }); } // Clamped into the kernel's bounds — a typo cannot buy a wider budget than the cap. Both legs // move in the TIGHTENING direction only (a shorter window is lengthened, a bigger ceiling is // lowered); the widening leg is the `fail()` above. const windowMs = Math.max(decl.windowMs, MIN_RATE_BUDGET_WINDOW_MS); const ceiling = Math.min(decl.ceiling, MAX_RATE_BUDGET_CEILING); const perSecond = ceiling / (windowMs / 1000); if (perSecond > MAX_RATE_BUDGET_UNITS_PER_SECOND) { fail( `${vendor}: ceiling ${ceiling} per ${windowMs}ms is ${perSecond.toFixed(1)} units/second, past the ` + `${MAX_RATE_BUDGET_UNITS_PER_SECOND}/s cap. No real vendor budget is that fast; this is a typo or a budget that isn't one.`, ); } // The burst bound is clamped to the ceiling too — it can only ever be the tighter of the two. const burstCeiling = windowMs > RATE_BUDGET_BURST_WINDOW_MS ? Math.min(decl.burstCeiling!, ceiling) : ceiling; return { vendor, reason: decl.reason, ...(decl.allowance ? { allowance: { ...decl.allowance } } : {}), windowMs, ceiling, burstCeiling, defaultWeight: decl.defaultWeight, maxRetryAfterSeconds: decl.maxRetryAfterSeconds ?? DEFAULT_RATE_BUDGET.maxRetryAfterSeconds!, rules, compiled, }; } /** Do two rules select exactly the same calls? (Same pattern, same query conditions, same order.) */ function sameSelector(a: RateBudgetWeightRule, b: RateBudgetWeightRule): boolean { const set = (xs?: string[]) => [...(xs ?? [])].sort().join(','); return a.match === b.match && set(a.whenQueryPresent) === set(b.whenQueryPresent) && set(a.whenQueryAbsent) === set(b.whenQueryAbsent); } /** * Is `next` no more permissive than `prev`? (Identical counts as "no more".) * * PRICING IS PART OF THIS, and it is the part that matters most: the ceiling says how many units * fit, the rules say how many units a call COSTS, so dropping an expensive rule multiplies the * number of expensive calls that fit without touching a single number. * * The rule kept here is deliberately BLUNT rather than clever: a re-declaration must present the * SAME selectors in the SAME order, and may only raise their weights. Deciding whether an * arbitrarily reordered/extended rule list prices every possible key at least as high is not * decidable in general, and a "clever" approximation is exactly where a bypass hides. A pack that * genuinely needs a different rule SHAPE changes its source declaration — which is a reviewable * act — rather than re-declaring at runtime. */ function noMorePermissive(prev: RateBudgetPolicy, next: RateBudgetPolicy): boolean { if (next.ceiling > prev.ceiling) return false; if (next.burstCeiling > prev.burstCeiling) return false; if (next.windowMs < prev.windowMs) return false; if (next.defaultWeight < prev.defaultWeight) return false; if (next.maxRetryAfterSeconds > prev.maxRetryAfterSeconds) return false; if (next.rules.length !== prev.rules.length) return false; return prev.rules.every((r, i) => sameSelector(r, next.rules[i]!) && next.rules[i]!.weight >= r.weight); } /** * DECLARE a vendor's budget. Idempotent for an identical declaration; a REPEAT declaration that * would WIDEN the allowance (higher ceiling, shorter window, cheaper default, longer tolerated * back-off) is refused. Without that rule, "declare a bigger budget just before constructing the * client" would be the clean way around every guarantee below. */ export function declareRateBudget(vendor: string, decl: RateBudgetDeclaration): RateBudgetPolicy { const next = normalize(vendor, decl); const prev = declarations.get(vendor); if (prev && !noMorePermissive(prev, next)) { fail( `${vendor}: refusing to re-declare a MORE PERMISSIVE budget (was ceiling ${prev.ceiling}/${prev.windowMs}ms ` + `over ${prev.rules.length} priced rule(s), now ${next.ceiling}/${next.windowMs}ms over ${next.rules.length}). ` + 'A budget may be tightened — lower ceiling, longer window, HIGHER weights — never widened at runtime, and ' + 'the pricing rules count: dropping an expensive rule widens the budget just as surely as raising the ceiling.', ); } declarations.set(vendor, next); return next; } /** The declared policy for a vendor, or the conservative fallback bound to that vendor. */ export function rateBudgetPolicy(vendor: string): RateBudgetPolicy { return declarations.get(vendor) ?? normalize(vendor, DEFAULT_RATE_BUDGET); } /** Has anyone declared a budget for this vendor? (`false` ⇒ it runs on `DEFAULT_RATE_BUDGET`.) */ export function hasRateBudgetDeclaration(vendor: string): boolean { return declarations.has(vendor); } /** Every declared policy, sorted by vendor (deterministic) — for operator/audit listings. */ export function listRateBudgets(): RateBudgetPolicy[] { return [...declarations.values()].sort((a, b) => a.vendor.localeCompare(b.vendor)); } // ── pricing ───────────────────────────────────────────────────────────────────────────────── /** * Price one call against a policy. Keyed off the request the client is ABOUT to make, so an * unclassified key still costs `defaultWeight` — an unknown endpoint must never be free. */ export function priceCall(policy: RateBudgetPolicy, key: string, query?: Record): number { for (const [i, rule] of policy.rules.entries()) { if (!(policy.compiled[i] ?? new RegExp(rule.match)).test(key)) continue; if (rule.whenQueryPresent && !rule.whenQueryPresent.every((k) => query?.[k] !== undefined)) continue; if (rule.whenQueryAbsent && !rule.whenQueryAbsent.every((k) => query?.[k] === undefined)) continue; return rule.weight; } return policy.defaultWeight; } /** Price one call for a vendor, using its declared policy (or the fallback). */ export function rateBudgetWeight(vendor: string, key: string, query?: Record): number { return priceCall(rateBudgetPolicy(vendor), key, query); } // ── the error ─────────────────────────────────────────────────────────────────────────────── export type RateBudgetErrorKind = /** The rolling-window ceiling would be exceeded by this call. */ | 'ceiling' /** A prior response told us to back off and the cooldown has not elapsed. */ | 'cooldown' /** The ledger could not be read/parsed — treated as a full window (see below). */ | 'ledger-unreadable' /** The ledger could not be persisted, so spend cannot be tracked. Refuse rather than fly blind. */ | 'ledger-unwritable' /** The injected clock is not a millisecond epoch — pruning would be nonsense, so refuse. */ | 'clock-invalid' /** The 60-second BURST bound would be exceeded, even though the long window has room. */ | 'burst' /** A `Retry-After` beyond the cap — fail loudly instead of sleeping it off. */ | 'retry-after-too-large'; /** * Thrown INSTEAD OF calling the vendor. Never swallowed, never converted to a retry: the caller is * meant to stop. Carries how long to wait so a caller can schedule rather than spin. */ export class RateBudgetError extends Error { readonly kind: RateBudgetErrorKind; /** The vendor whose budget refused — so a multi-vendor caller can tell which one stopped. */ readonly vendor: string; /** Milliseconds until the budget could plausibly admit this call again. */ readonly retryAfterMs: number; constructor(kind: RateBudgetErrorKind, vendor: string, message: string, retryAfterMs: number) { super(message); this.name = 'RateBudgetError'; this.kind = kind; this.vendor = vendor; this.retryAfterMs = retryAfterMs; } } // ── the ledger ────────────────────────────────────────────────────────────────────────────── type LedgerEntry = { t: number; w: number; id: string }; type Ledger = { v: 1; cooldownUntil: number; entries: LedgerEntry[] }; /** A charge already committed to the ledger by `checkBudget`, settled later by `recordCall`. */ export type RateBudgetReservation = { id: string; weight: number; at: number }; export type RateBudgetSnapshot = { vendor: string; spend: number; /** Weighted spend in the last 60s — the quantity `burstCeiling` bounds. */ burstSpend: number; ceiling: number; burstCeiling: number; windowMs: number; cooldownUntil: number; entries: number; path: string; }; export type RateBudgetOptions = { /** The vendor whose allowance this is. Required — the ledger is keyed by it. */ vendor: string; /** Ledger file path. Injectable so tests never touch the real one. */ path?: string; /** * Scope the ledger to ONE project root instead of the home dir. Note that two roots sharing a * credential then get two allowances — prefer the token-keyed default unless you specifically * want per-world accounting. */ root?: string; /** The credential whose quota this is. Only its HASH is used, to name the default ledger file. */ token?: string; /** Injected clock (ms since epoch). Tests advance it by hand; production passes nothing. */ now?: () => number; /** Window in ms. Can only be made LONGER than the declared one (shorter would widen spend). */ windowMs?: number; /** Weighted ceiling. Can only be made LOWER than the declared one. */ ceiling?: number; /** Seconds; a `Retry-After` above this fails loudly. Can only be made SMALLER. */ maxRetryAfterSeconds?: number; }; /** * Where the ledger lives. Vendors rate-limit PER CREDENTIAL, so the default is keyed by VENDOR and * a hash of the token, and lives in the user's home directory — deliberately NOT under the project * state root, because a cwd-scoped ledger hands the same credential a fresh allowance in every * checkout, worktree and CI matrix leg. Pass `root` to opt into world-scoped accounting anyway. * Only the hash is ever written to disk; the token itself never is. * * Two vendors never collide (the vendor is a path segment) and two credentials for one vendor never * collide (the hash is the filename). */ export function rateBudgetPath(opts: { vendor: string; root?: string; token?: string }): string { if (opts.root !== undefined) return join(worldPaths(opts.vendor, opts.root).dir, 'rate-budget.json'); const key = opts.token ? createHash('sha256').update(opts.token).digest('hex').slice(0, 16) : 'no-token'; return join(volterHome(), opts.vendor, `rate-budget-${key}.json`); } /** * The guard. One instance per ledger path; cheap to construct, so callers may build one per client. * All state lives in the FILE, never in the instance — that is what makes a second instance (or a * second process) see the first one's spend. There is no memoization anywhere, by design. */ /** * Refuse a "budget" whose GUARD HAS BEEN REPLACED, and hand back the same object when it is intact. * * Every pack's guarded factory takes an optional `budget` so several clients can share one ledger. * `instanceof` alone admits a subclass or proxy that replaces a guard with a no-op. * The check is on the METHODS as well as the prototype chain: the three functions a guarded factory * actually calls must be the very functions `RateBudget.prototype` defines. An own-property * override, a subclass override and a `get`-trapping proxy all fail that identity comparison. The * exact-prototype test additionally pins the vendor binding, so another vendor's budget subclass * cannot stand in for this one's. * * HONEST LIMIT, since the point of this function is not over-claiming: a determined caller can still * defeat it (a proxy that returns the real function to the probe and a no-op afterwards, a * `Object.defineProperty` on `RateBudget.prototype` itself, an injected clock, a ledger path in a * temp dir). Nothing reachable from inside this process can stop that, and the module header says so * up front. What this closes is the ACCIDENT and the one-liner — the shapes that actually happen. */ export function assertBudgetGuardIntact( budget: unknown, expected: new (...args: never[]) => T, where: string, ): T { const what = `${where}: \`budget\` must be an unmodified ${expected.name}`; if (!(budget instanceof expected)) { throw new Error(`${what} — refusing to build a client around an unverified rate guard`); } if (Object.getPrototypeOf(budget) !== expected.prototype) { throw new Error(`${what} — a SUBCLASS may override the guard, so it is refused rather than trusted`); } const b = budget as unknown as Record; const proto = RateBudget.prototype as unknown as Record; for (const method of ['checkBudget', 'recordCall', 'weightFor'] as const) { if (b[method] !== proto[method]) { throw new Error(`${what} — its \`${method}\` is not the kernel's, so the ceiling it reports cannot be trusted`); } } // …and it must actually have been CONSTRUCTED. `Object.create(XBudget.prototype)` has the right // prototype and inherits the real methods, so everything above passes — but it has no `vendor` and // no `path`, and the first call dies inside `node:fs` with "the \"path\" property must be of type // string". That already fails CLOSED (zero requests reach the vendor), so this is not a hole; it is // a legibility fix, turning an inscrutable fs error into a refusal that names the real problem. if (typeof b.vendor !== 'string' || b.vendor === '' || typeof b.path !== 'string' || b.path === '') { throw new Error(`${what} — it was never constructed (no vendor/ledger path), so it has no ledger to charge`); } return budget; } export class RateBudget { readonly vendor: string; readonly path: string; private readonly clock: () => number; private readonly askedWindowMs: number | undefined; private readonly askedCeiling: number | undefined; private readonly askedMaxRetryAfterSeconds: number | undefined; constructor(opts: RateBudgetOptions) { if (!opts || typeof opts.vendor !== 'string' || opts.vendor === '') { fail('a budget must name the vendor it guards — the ledger is keyed by it'); } this.vendor = opts.vendor; // Resolving the policy here would VALIDATE the vendor id early; do that explicitly instead, // since the policy itself is read live (see `policy`). rateBudgetPolicy(opts.vendor); this.path = opts.path ?? rateBudgetPath({ vendor: opts.vendor, ...(opts.root !== undefined ? { root: opts.root } : {}), ...(opts.token !== undefined ? { token: opts.token } : {}), }); this.clock = opts.now ?? (() => clockForm.machineNow()); this.askedWindowMs = opts.windowMs; this.askedCeiling = opts.ceiling; this.askedMaxRetryAfterSeconds = opts.maxRetryAfterSeconds; } /** * The effective policy, read LIVE from the declaration registry on every use rather than captured * at construction. * * A budget built for a vendor whose declaration module has not been imported yet falls back to * `DEFAULT_RATE_BUDGET`. The fallback is NOT uniformly tighter than a pack's own numbers — its ceiling is lower, but it * prices every call at `defaultWeight`, which for a vendor with an expensive endpoint (a render, * a recursive walk) is far CHEAPER than the pack's declared weight for it. Capturing that * snapshot would freeze the wrong prices for the instance's whole life. Reading live means the * pack's real weights take effect the moment its declaration lands. * * A caller cannot hand in a policy object — it comes only from the registry, and the registry * refuses a widening re-declaration — so "construct a client around a huge made-up budget" is * still not a move. */ get policy(): RateBudgetPolicy { return rateBudgetPolicy(this.vendor); } /** Window in ms. The caller may only LENGTHEN it; a shorter one would widen spend. */ get windowMs(): number { const declared = this.policy.windowMs; return Math.max(this.askedWindowMs ?? declared, declared); } /** Weighted ceiling. The caller may only LOWER it. */ get ceiling(): number { const declared = this.policy.ceiling; return Math.min(this.askedCeiling ?? declared, declared); } /** * Weighted units allowed in any 60-SECOND sub-window, enforced independently of `ceiling`. For a * pack whose window already IS 60s this equals the ceiling and the second check is a no-op; for a * longer window it is the bound that stops the whole window being spent in an instant. Never * looser than `ceiling` (a lowered ceiling lowers it too). */ get burstCeiling(): number { return Math.min(this.policy.burstCeiling, this.ceiling); } /** Tolerated back-off, in seconds. The caller may only SHRINK it. */ get maxRetryAfterSeconds(): number { const declared = this.policy.maxRetryAfterSeconds; return Math.min(this.askedMaxRetryAfterSeconds ?? declared, declared); } /** Price a call against THIS vendor's declared rules, as they stand right now. */ weightFor(key: string, query?: Record): number { return priceCall(this.policy, key, query); } /** * Read the clock and sanity-check it. Catches the ACCIDENT class that silently disables pruning: * a clock in seconds, a `performance.now()`-style monotonic clock, or NaN. Entry timestamps * written under one epoch prune instantly under another, which would void the whole budget * without anyone noticing. (A deliberate fast-forwarding clock is NOT stopped by this — nothing * can stop that while the seam exists; it is disclosed at the top instead of pretended away.) */ private now(): number { const t = this.clock(); if (!Number.isFinite(t) || t < MIN_PLAUSIBLE_EPOCH_MS) { throw new RateBudgetError( 'clock-invalid', this.vendor, `${this.vendor} budget: injected clock returned ${String(t)}, which is not a millisecond epoch — refusing rather than pruning the ledger against a nonsense clock`, this.windowMs, ); } return t; } // ── locking + durable IO ────────────────────────────────────────────────────────────────── private lockPath(): string { return `${this.path}.lock`; } /** The store the ledger persists through where there is no filesystem of this machine's to hold it: a hosted World's * (its SQL store, one instance serializing its requests). Null on the filesystem, where the ledger is the file below, * locked across processes as it always was. A hosted World's ledger is its own: two hosted Worlds sealed with one * credential each keep an allowance, where a machine's Worlds share one per credential. */ private store(): WorldStore | null { const active = getActiveWorldStore(); return active instanceof FsWorldStore ? null : active; } /** Serialize ledger updates with the kernel's lock, retaining every live owner. */ private withLock(fn: () => T): T { let entered = false; try { return (this.store() ?? new FsWorldStore()).withLock(this.lockPath(), () => { entered = true; return fn(); }, { retainLiveOwner: true, operation: 'rate budget', caller: this.vendor }); } catch (error) { if (entered || error instanceof RateBudgetError) throw error; throw new RateBudgetError('ledger-unwritable', this.vendor, `${this.vendor} budget: ${(error as Error).message}`, this.windowMs); } } /** * Read the ledger. A MISSING file is the legitimate first-run case (no state ⇒ no spend). A file * that exists but cannot be read or parsed is the dangerous case, and it FAILS CLOSED: we cannot * know what was already spent, so the window is treated as fully consumed. A fresh ledger * carrying a one-window cooldown is written in its place, so the guard self-heals after the * window instead of needing a human to delete a file. */ private load(now: number): Ledger { const held = this.store(); if (held ? !held.exists(this.path) : !existsSync(this.path)) return { v: 1, cooldownUntil: 0, entries: [] }; let raw: string; try { raw = held ? (held.read(this.path) ?? '') : readFileSync(this.path, 'utf8'); } catch (e) { throw this.quarantine(now, `unreadable (${(e as Error).message})`); } let parsed: unknown; try { parsed = JSON.parse(raw); } catch (e) { throw this.quarantine(now, `malformed JSON (${(e as Error).message})`); } const l = parsed as Partial; if (!l || typeof l !== 'object' || l.v !== 1 || !Array.isArray(l.entries)) { throw this.quarantine(now, 'unrecognized ledger shape'); } if (l.entries.length > MAX_LEDGER_ENTRIES) { throw this.quarantine(now, `${l.entries.length} entries, far past the ${MAX_LEDGER_ENTRIES} a valid window can hold`); } const entries: LedgerEntry[] = []; for (const e of l.entries as unknown[]) { const row = e as Partial; // A row we cannot price is not skipped — an entry that exists must cost something, or a // partially-corrupt ledger would silently forgive spend. if (!row || typeof row !== 'object') throw this.quarantine(now, 'non-object ledger entry'); const t = Number(row.t); const w = Number(row.w); if (!Number.isFinite(t) || !Number.isFinite(w) || w < 0) throw this.quarantine(now, 'non-numeric ledger entry'); entries.push({ t, w, id: typeof row.id === 'string' ? row.id : randomUUID() }); } // A garbage cooldown must not silently DISARM a back-off a 429 armed — that is the one // corruption that would fail open on the cooldown path, so it quarantines like the rest. const cooldownUntil = Number(l.cooldownUntil); if (!Number.isFinite(cooldownUntil) || cooldownUntil < 0) throw this.quarantine(now, 'non-numeric cooldownUntil'); return { v: 1, cooldownUntil, entries }; } /** Replace a corrupt ledger with a valid one that is already in cooldown, and refuse this call. */ private quarantine(now: number, why: string): RateBudgetError { const until = now + this.windowMs; try { this.save({ v: 1, cooldownUntil: until, entries: [] }); } catch { /* best effort — the throw below is what actually protects the credential */ } return new RateBudgetError( 'ledger-unreadable', this.vendor, `${this.vendor} budget: ledger ${this.path} is ${why} — refusing the call and cooling down for ${Math.round(this.windowMs / 1000)}s ` + 'rather than assuming zero spend', this.windowMs, ); } /** Atomic replace: write a temp file, then rename over the target. No partial ledger is visible. */ private save(ledger: Ledger): void { const held = this.store(); if (held) { try { held.writeAtomic(this.path, `${JSON.stringify(ledger)}\n`); } catch (e) { throw new RateBudgetError('ledger-unwritable', this.vendor, `${this.vendor} budget: cannot persist ${this.path} (${(e as Error).message}) — refusing rather than tracking nothing`, this.windowMs); } return; } const tmp = `${this.path}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`; try { mkdirSync(dirname(this.path), { recursive: true }); writeFileSync(tmp, `${JSON.stringify(ledger)}\n`, 'utf8'); renameSync(tmp, this.path); } catch (e) { try { rmSync(tmp, { force: true }); } catch { /* nothing to clean */ } // If spend cannot be persisted we would be flying blind on the next call. Refuse instead. throw new RateBudgetError( 'ledger-unwritable', this.vendor, `${this.vendor} budget: cannot persist ${this.path} (${(e as Error).message}) — refusing rather than tracking nothing`, this.windowMs, ); } } private prune(ledger: Ledger, now: number): Ledger { return { ...ledger, entries: ledger.entries.filter((e) => now - e.t < this.windowMs) }; } private static spendOf(ledger: Ledger): number { return ledger.entries.reduce((n, e) => n + e.w, 0); } // ── the API ─────────────────────────────────────────────────────────────────────────────── /** * THE GATE. Prunes the window, refuses if we are in cooldown or if `weight` would breach the * ceiling, and otherwise RESERVES the weight (committing it to the ledger) before returning. * When it throws, the caller MUST NOT call the vendor — that is the entire contract. */ checkBudget(weight: number): RateBudgetReservation { const w = Number.isFinite(weight) && weight > 0 ? weight : this.policy.defaultWeight; return this.withLock(() => { const now = this.now(); const ledger = this.prune(this.load(now), now); if (ledger.cooldownUntil > now) { const wait = ledger.cooldownUntil - now; throw new RateBudgetError( 'cooldown', this.vendor, `${this.vendor} budget: in cooldown for another ${Math.ceil(wait / 1000)}s (a previous response asked us to back off) — not calling the vendor`, wait, ); } // THE BURST BOUND, checked first because it is the tighter one whenever it differs. A long // window bounds how much may be spent per hour; it says nothing about how fast, and "all of it // in one millisecond" is exactly the shape a runaway loop has. const burstCeiling = this.burstCeiling; if (burstCeiling < this.ceiling) { const since = now - RATE_BUDGET_BURST_WINDOW_MS; const recent = ledger.entries.filter((e) => e.t > since); const burstSpend = recent.reduce((n, e) => n + e.w, 0); if (burstSpend + w > burstCeiling) { const oldest = recent.reduce((min, e) => Math.min(min, e.t), now); const wait = Math.max(0, RATE_BUDGET_BURST_WINDOW_MS - (now - oldest)); throw new RateBudgetError( 'burst', this.vendor, `${this.vendor} budget: this call costs ${w} and ${burstSpend}/${burstCeiling} weighted units are already spent in the last ` + `${RATE_BUDGET_BURST_WINDOW_MS / 1000}s — refusing the call. The ${Math.round(this.windowMs / 1000)}s window still has room; ` + `this is the BURST bound, which exists so a long window cannot be spent all at once. Retry in ~${Math.ceil(wait / 1000)}s.`, wait, ); } } const spend = RateBudget.spendOf(ledger); if (spend + w > this.ceiling) { // Wait only as long as it takes for enough of the window to age out. const oldest = ledger.entries.reduce((min, e) => Math.min(min, e.t), now); const wait = Math.max(0, this.windowMs - (now - oldest)); throw new RateBudgetError( 'ceiling', this.vendor, `${this.vendor} budget: this call costs ${w} and ${spend}/${this.ceiling} weighted units are already spent in the last ` + `${Math.round(this.windowMs / 1000)}s — refusing the call. Retry in ~${Math.ceil(wait / 1000)}s; ` + 'cached work is preserved, so a re-run resumes where this stopped.', wait, ); } const reservation: RateBudgetReservation = { id: randomUUID(), weight: w, at: now }; ledger.entries.push({ t: now, w, id: reservation.id }); this.save(ledger); return reservation; }); } /** * Record the OUTCOME of a call. Settles the reservation `checkBudget` made (never charging * twice); when called without one — a direct caller, or a call made outside the guarded path — * it appends the charge itself, so spend is recorded either way. * * If the response carried `Retry-After`, a 429, or an `X-…-RateLimit-Remaining: 0` exhaustion * signal, a COOLDOWN is persisted: every later call then fails fast in `checkBudget` WITHOUT * touching the vendor. A `Retry-After` beyond the cap additionally throws — that is not something * to sleep off. */ recordCall( weight: number, headers?: Record, opts: { status?: number; reservation?: RateBudgetReservation | null } = {}, ): void { const w = Number.isFinite(weight) && weight > 0 ? weight : this.policy.defaultWeight; // The EFFECTIVE window, not the declared one. `windowMs` honours a caller's lengthening; using // the declared value would hand a caller who deliberately widened their window the SHORTER // fallback cooldown — the only loosening direction left in a class where every other clamp // tightens. // // THIS budget's clock, too, not the wall clock. An ABSOLUTE epoch reset header has to be // subtracted from the same clock the ledger is timestamped against; reading it against // `Date.now()` while the ledger runs on an injected clock silently mixes two time bases, and the // difference between them lands directly in the cooldown. const nowMs = this.now(); const backoff = backoffSeconds(headers, opts.status, this.windowMs, nowMs); const thrown = this.withLock(() => { const now = this.now(); const ledger = this.prune(this.load(now), now); const held = opts.reservation ? ledger.entries.find((e) => e.id === opts.reservation!.id) : undefined; if (held) held.t = now; // settle in place — already charged, do not charge again else ledger.entries.push({ t: now, w, id: randomUUID() }); if (backoff !== null) { const until = now + Math.min(backoff * 1000, MAX_COOLDOWN_MS); ledger.cooldownUntil = Math.max(ledger.cooldownUntil, until); } this.save(ledger); if (backoff !== null && backoff > this.maxRetryAfterSeconds) { return new RateBudgetError( 'retry-after-too-large', this.vendor, `${this.vendor} budget: the vendor asked for a ${backoff}s backoff, beyond the ${this.maxRetryAfterSeconds}s cap — ` + 'failing immediately instead of sleeping it off. The credential is being throttled hard; stop calling.', backoff * 1000, ); } return null; }); if (thrown) throw thrown; } /** Current weighted spend in the window. Reads the FILE, so it sees other processes' spend. */ spend(): number { return this.withLock(() => { const now = this.now(); return RateBudget.spendOf(this.prune(this.load(now), now)); }); } /** Everything an operator (or a test) wants to see, in one read. */ snapshot(): RateBudgetSnapshot { return this.withLock(() => { const now = this.now(); const ledger = this.prune(this.load(now), now); const since = now - RATE_BUDGET_BURST_WINDOW_MS; return { vendor: this.vendor, spend: RateBudget.spendOf(ledger), burstSpend: ledger.entries.filter((e) => e.t > since).reduce((n, e) => n + e.w, 0), ceiling: this.ceiling, burstCeiling: this.burstCeiling, windowMs: this.windowMs, cooldownUntil: ledger.cooldownUntil, entries: ledger.entries.length, path: this.path, }; }); } } /** * Seconds to back off for, or `null` if the response carried no back-off signal. * * Recognizes the two forms that are effectively universal across REST vendors — the standard * `Retry-After` header and a bare 429 — plus the widely-used `*-ratelimit-remaining: 0` / * `*-ratelimit-reset` convention, matched by SUFFIX so any vendor's prefix works without the * kernel knowing the vendor's name. Every one of them is read IF PRESENT and never assumed. */ function backoffSeconds( headers: Record | undefined, status: number | undefined, windowMs: number, nowMs: number, ): number | null { const h: Record = {}; for (const [k, v] of Object.entries(headers ?? {})) h[k.toLowerCase()] = v; const retryAfter = Number(h['retry-after']); if (h['retry-after'] !== undefined && h['retry-after'] !== '' && Number.isFinite(retryAfter) && retryAfter >= 0) { return retryAfter; } // An explicit "you have nothing left" signal, with a reset hint when one is offered. The header // NAMES vary by vendor, so match STRUCTURALLY rather than against a table of vendor spellings: // a header counts if its dash-delimited words contain a `ratelimit`/`rate-limit` token AND the // word `remaining` (or `reset`). The dimension and vendor names can appear in several positions: // • `x-ratelimit-remaining` (GitHub, PostHog, Supabase, Cal.com) // • `x--rate-limit-remaining` (Figma, Sentry) // • `-ratelimit--remaining` (Anthropic, Linear) // • `x-ratelimit-remaining-` (OpenAI) // Dropping one is a FAIL-OPEN: the ledger keeps cheerfully spending into a credential the vendor // has already told us is exhausted. The kernel still knows no vendor's name — only the shape. // // EVERY matching header is examined, not the first one found: a proxy or // CDN in front of the vendor can emit its own `x-ratelimit-remaining: 100` ahead of the vendor's // `x--rate-limit-remaining: 0`, and picking the first match would silently DROP the // exhaustion signal. If any of them says zero, we are out. const hasWord = (k: string, w: string) => new RegExp(`(^|-)${w}(-|$)`).test(k); const isLimitHeader = (k: string) => /(^|-)rate-?limit(-|$)/.test(k); const remainingKeys = Object.keys(h).filter((k) => isLimitHeader(k) && hasWord(k, 'remaining')); // A PRESENT-BUT-EMPTY value is ABSENT, not zero. `Number('') === 0` and `Number(' ') === 0`, so a // blank header from a proxy that reserves the name without filling it would otherwise read as "you // are exhausted" and refuse a perfectly healthy credential for a whole window. const numeric = (v: string | undefined): number => (v === undefined || v.trim() === '' ? NaN : Number(v)); const exhausted = remainingKeys.filter((k) => numeric(h[k]) === 0); if (exhausted.length > 0) { // Prefer the reset header that names the SAME limit as the exhausted one — pairing an // exhaustion signal with an unrelated intermediary's reset is how a full-window cooldown // becomes a 1s one. Two headers name the same limit when they agree on every word except // `remaining`/`reset`, which is word-order-independent and so survives all four shapes above. const resetKeys = Object.keys(h).filter((k) => isLimitHeader(k) && hasWord(k, 'reset')); const prefixOf = (k: string) => k.split('-').filter((w) => w !== 'remaining' && w !== 'reset').join('-'); // The LONGEST paired back-off wins, not the first one in header order: // a vendor that limits several dimensions at once (requests AND tokens) can report two exhausted // buckets with different resets, and taking whichever happened to be inserted first would obey // the 5-second one and ignore the 3,600-second one. Every candidate is converted first, because // the shortest STRING is not necessarily the shortest DURATION once units are resolved. const candidates = resetKeys .filter((k) => exhausted.some((e) => prefixOf(k) === prefixOf(e))) .map((k) => resetToSeconds(numeric(h[k]), nowMs)) .filter((s): s is number => s !== null); if (candidates.length > 0) return Math.max(...candidates); // No trustworthy reset hint. Which back-off is right depends on WHETHER THE VENDOR ACTUALLY // REFUSED: // • the response was an ERROR (4xx/5xx) ⇒ the vendor turned this call away. Back off for a // whole window. Re-probing an exhausted credential every minute is precisely what GitHub's // secondary-limit guidance warns against, and "the ledger's ceiling bounds it underneath" // only holds once the ceiling is nearly spent — exhaustion can arrive with a nearly empty // ledger when the credential is shared (a team PAT, a CI fleet). // • the response SUCCEEDED and merely reported `remaining: 0` ⇒ we got what we asked for and // the next call MIGHT be refused. Cap at the conventional bare-429 back-off, so a header // that is rounded, blank-ish or emitted by an intermediary cannot cost a healthy credential // a full hour. This is the leg that keeps the false-positive protection. return status !== undefined && status >= 400 ? windowMs / 1000 : Math.min(windowMs / 1000, DEFAULT_BARE_429_BACKOFF_S); } // A 429 with no guidance: the conventional default back-off. if (status === 429) return DEFAULT_BARE_429_BACKOFF_S; return null; } /** * A `*-ratelimit-reset` value → seconds to wait, or `null` when it cannot be trusted. * * Vendors disagree about the UNIT, and getting it wrong is not a rounding error — it is a multi-day * self-inflicted outage. Three shapes are seen in practice, distinguished by MAGNITUDE because none * of them is labelled: * • a small number → a delta, already in seconds (`x-ratelimit-reset: 45`) * • ~1e9-1e10 → an absolute epoch in SECONDS (GitHub) * • ~1e12-1e13 → an absolute epoch in MILLISECONDS (Linear documents exactly this) * * Reading a millisecond epoch as a second epoch yields a back-off of roughly fifty thousand YEARS, * which the cooldown cap then clamps to a week — so ONE exhausted response would lock the credential * out client-side for seven days and need a human to delete the ledger file. That is the module * inflicting the very outage it exists to prevent. * * Anything that still resolves to more than a day is treated as UNPARSEABLE rather than obeyed: * no real rate limit resets a day out, so such a value means the unit guess was wrong, and the * honest answer is `null` (the caller falls back to a one-window cooldown) rather than a number * nobody can justify. Non-finite and negative values are likewise `null`. */ export function resetToSeconds(reset: number, nowMs: number = clockForm.machineNow()): number | null { if (!Number.isFinite(reset) || reset <= 0) return null; const nowS = Math.floor(nowMs / 1000); // Thresholds sit between the plausible ranges, not at their edges: 1e11 s is year 5138 (so no // real epoch-seconds value reaches it) and 1e11 ms is 1973 (so every real epoch-ms value passes it). const seconds = reset > 1e11 ? Math.max(0, Math.floor(reset / 1000) - nowS) // absolute epoch, milliseconds : reset > 1e6 ? Math.max(0, reset - nowS) // absolute epoch, seconds : reset; // a delta, already seconds if (!Number.isFinite(seconds) || seconds <= 0) return null; return seconds > 24 * 60 * 60 ? null : seconds; }