// How a twin consumes its World's scenario (architecture, "Scenarios"; ADR 0036 §2-4, §10): a decision where its vendor // decides and a fault where it lands. A consumption that is part of a write is recorded in the twin's own log as // bookkeeping (`_decision`, `_fault`), so the state a run reaches holds what was decided and what failed, a `once` // decision or a counted fault is used up by the log rather than by a process's memory, and a branch or a replay agrees. // A request that writes nothing (a read, a request a fault refuses before the vendor acts) leaves the log as it was: what // it consumed is counted in the twin's scenario ledger, beside the log and never in it, and noted in its request journal // (serve.ts). A twin whose head is real consults no scenario: its vendor decides and fails on its own. import { headOf } from './head.ts'; import { applyTwinWriteAtomic, noteTwinRequest, twinResources } from './serve.ts'; import { worldPaths } from './storage.ts'; import { getActiveWorldStore } from './world-store.ts'; import { ScenarioError } from './scenario.ts'; import { durationMs, placedDecisions, placedFaults, type PlacedDecision, type PlacedFault } from './placements.ts'; import type { RateBucket, RateBucketRequest, RateBudgetDeclaration, RateValues } from './rateBudget.ts'; /** What a consumption reads and writes: the twin's own bookkeeping rows, at the request's World time. `recording` is * false for a read-only request, which consumes nothing; `reads` is true for a request whose operation writes nothing, * whose consumption stays off the log. */ export type ScenarioLedger = { vendor: string; service: string; root?: string; at: string; recording: boolean; reads?: boolean; rows(type: '_decision' | '_fault'): Array>; record(type: '_decision' | '_fault', fields: Record, id?: string): Promise; }; // The twin's scenario ledger: counts by key (`rate:::…`, a vendor bucket's count in one window, its // tokens left, its requests in flight; // `fault:`, a fault's landings on requests that wrote nothing; `decision:`, a decision's uses by them), in its World's directory beside its log. Changed // under its lock, so two processes serving one World never take one count; a World with no root counts in this process. type Counts = Record; const countsInMemory = new Map(); const countsPath = (ledger: Pick): string => `${worldPaths(ledger.service, ledger.root).dir}/scenario-ledger.json`; function counts(ledger: Pick): Counts { if (ledger.root === undefined) return countsInMemory.get(ledger.service) ?? {}; return JSON.parse(getActiveWorldStore().read(countsPath(ledger)) ?? '{}') as Counts; } function changeCounts(ledger: Pick, change: (held: Counts) => T): T { if (ledger.root === undefined) { const held = countsInMemory.get(ledger.service) ?? {}; countsInMemory.set(ledger.service, held); return change(held); } const store = getActiveWorldStore(); const path = countsPath(ledger); return store.withLock(`${path}.lock`, () => { const held = JSON.parse(store.read(path) ?? '{}') as Counts; const value = change(held); store.writeAtomic(path, JSON.stringify(held)); return value; }); } const simulated = (ledger: ScenarioLedger): boolean => headOf(ledger.service, ledger.root).kind !== 'real'; const usedTimes = (ledger: ScenarioLedger, type: '_decision' | '_fault', index: number): number => ledger.rows(type).filter((r) => r.entry === index).length + (counts(ledger)[`${type === '_fault' ? 'fault' : 'decision'}:${index}`] ?? 0); const available = (ledger: ScenarioLedger, type: '_decision' | '_fault', index: number, limit: number | undefined): boolean => limit === undefined || usedTimes(ledger, type, index) < limit; const decisionLeft = (ledger: ScenarioLedger, d: PlacedDecision): boolean => available(ledger, '_decision', d.index, d.once ? 1 : undefined); const faultLeft = (ledger: ScenarioLedger, f: PlacedFault): boolean => available(ledger, '_fault', f.index, f.times); /** The vendor's judgement at `point` for `subject`: the one already taken for them, else the first decision * placed for it, else `byDefault`. Taken in a write, it is recorded in the log; in a request that writes nothing, its * use is counted in the scenario ledger and noted in the request's journal (ADR 0036 §4). */ export async function decide(ledger: ScenarioLedger, point: string, subject: string, byDefault: T): Promise { if (!simulated(ledger)) return byDefault; const taken = ledger.rows('_decision').find((r) => r.point === point && r.subject === subject); if (taken) return taken.outcome as T; const chosen = placedDecisions(ledger.vendor, point, ledger.at).find((d) => d.on === undefined && (d.subject === undefined || d.subject === subject) && decisionLeft(ledger, d)); const outcome = (chosen ? chosen.outcome : byDefault) as T; if (!ledger.recording) return outcome; if (ledger.reads) { if (chosen) changeCounts(ledger, (held) => { held[`decision:${chosen.index}`] = (held[`decision:${chosen.index}`] ?? 0) + 1; }); noteTwinRequest({ point, subject, outcome, entry: chosen?.index ?? 'default' }); } else await ledger.record('_decision', { point, subject, outcome, entry: chosen?.index ?? 'default', decidedAt: ledger.at }); return outcome; } /** The model turns placed for this vendor and not yet used up, in order: what the kernel matches a turn * against with the pack's matchers. */ export function turnDecisions(ledger: ScenarioLedger): PlacedDecision[] { if (!simulated(ledger)) return []; return placedDecisions(ledger.vendor, 'turn', ledger.at).filter((d) => decisionLeft(ledger, d)); } /** Record a turn's decision: the placed one that answered it, or the labelled default. */ export async function recordTurn(ledger: ScenarioLedger, chosen: PlacedDecision | undefined, outcome: unknown): Promise { if (ledger.recording) await ledger.record('_decision', { point: 'turn', outcome, entry: chosen?.index ?? 'default', decidedAt: ledger.at }); } /** The request faults placed on this vendor that are not used up, in order. */ export function requestFaults(ledger: ScenarioLedger): PlacedFault[] { if (!simulated(ledger)) return []; return placedFaults(ledger.vendor, 'request', ledger.at).filter((f) => faultLeft(ledger, f)); } /** Record a fault that landed: in the log where it is part of a write's history, else as `noteFault`. */ export async function recordFault(ledger: ScenarioLedger, fault: PlacedFault, where: Record): Promise { if (ledger.reads) return noteFault(ledger, fault, where); if (ledger.recording) await ledger.record('_fault', { ...where, layer: fault.layer, kind: fault.kind, entry: fault.index, landedAt: ledger.at }); } /** A fault that landed on a request that writes nothing (a read; a request refused before the vendor acts): its landing * counted in the scenario ledger, so its `times` is used up, and noted in the request's journal line. */ export async function noteFault(ledger: ScenarioLedger, fault: PlacedFault, where: Record): Promise { if (!ledger.recording) return; changeCounts(ledger, (held) => { held[`fault:${fault.index}`] = (held[`fault:${fault.index}`] ?? 0) + 1; }); noteTwinRequest({ ...where, layer: fault.layer, kind: fault.kind, entry: fault.index }); } /** A fault placed at a point of the pack's own (one item of a batch), for `subject`; recorded when it lands. */ export async function faultAt(ledger: ScenarioLedger, point: string, subject: string): Promise { const fault = requestFaults(ledger).find((f) => f.point === point && (f.subject === undefined || f.subject === subject)); if (fault) await recordFault(ledger, fault, { point, subject }); return fault; } /** A ledger over a twin's store alone, for the kernel's own paths that open no context (an event's delivery, the * idempotency layer a failure lands in). */ export function serviceLedger(input: { vendor: string; service: string; root?: string; at: string; recording: boolean; reads?: boolean }): ScenarioLedger { const rows = (type: string) => twinResources(input.service, input.root).filter((r) => r.type === type && r.deleted !== true) as Array>; return { ...input, rows, record: async (type, fields, id) => { await applyTwinWriteAtomic(input.service, (resources) => { const prefix = `${type.slice(1)}_`; const next = id ?? `${prefix}${1 + Math.max(0, ...resources.filter((r) => r.type === type && r.id.startsWith(prefix)).map((r) => Number(r.id.slice(prefix.length)) || 0))}`; return { kind: 'write', value: next, write: { operation: `${type.slice(1)}.record`, subjectType: type, subjectId: next, fields, occurredAt: input.at, actor: { kind: 'system' } } }; }, input.root); }, }; } /** The first webhook fault of `kinds` placed on this vendor for an event type, not used up: an event's write asks for a * delay or a duplicate, each attempt for a drop, so one kind never hides another. */ export function webhookFault(ledger: ScenarioLedger, type: string, kinds: readonly string[]): PlacedFault | undefined { return overTimeFaults(ledger).find((f) => kinds.includes(f.kind) && (f.event === undefined || f.event === type) && faultLeft(ledger, f)); } /** The `lag` placed on this vendor's eventually consistent operations (an `operation` names one), if any. */ export function listLag(ledger: Pick, operation: string): PlacedFault | undefined { return overTimeFaults(ledger).find((f) => f.kind === 'lag' && (f.operation === undefined || f.operation === operation)); } /** The over-time faults placed on this vendor, in order. */ function overTimeFaults(ledger: Pick): PlacedFault[] { if (headOf(ledger.service, ledger.root).kind === 'real') return []; return placedFaults(ledger.vendor, 'over-time', ledger.at); } /** One bucket a request was counted in, or refused by, and the values its templates read. */ export type RateCount = { bucket: RateBucket; values: RateValues }; /** What the vendor's switched-on buckets made of a request: the bucket that refused it, or every bucket it was counted * in; `release` ends its time in flight (a bucket's `concurrency`) once it is answered. */ export type RateOutcome = { refused?: RateCount; counted: RateCount[]; release(): void }; /** The vendor's buckets as the `rate-limit`s placed switch them on: every bucket the pack declares, or the one * a fault names, its `limit` per `per` tightened where the fault gives one (never loosened). The request is weighed and * keyed in each bucket it belongs to and, under the scenario ledger's lock, refused by the first it would exhaust * (counted in none) or counted in all. Undefined when no rate-limit is placed: nothing is counted. A read-only request is * not counted. Windows and refills run on the request's World time. */ export async function rateLimited(ledger: ScenarioLedger, request: RateBucketRequest, declared: RateBudgetDeclaration | undefined): Promise { if (!ledger.recording) return undefined; const placed = overTimeFaults(ledger).filter((f) => f.kind === 'rate-limit' && (f.operation === undefined || f.operation === request.operation) && faultLeft(ledger, f)); if (placed.length === 0) return undefined; const buckets = declared?.buckets ?? []; if (buckets.length === 0) throw new ScenarioError(`${ledger.vendor}'s pack declares no limit its vendor keeps (rateBudget.buckets): a rate-limit switches the vendor's own on`); // the buckets switched on, each by the first fault that names it (or names none), at its limit and window const on = new Map(); for (const fault of placed) { const named = fault.bucket === undefined ? buckets : buckets.filter((b) => b.name === fault.bucket); if (named.length === 0) throw new ScenarioError(`entry ${fault.index}: ${ledger.vendor} declares no bucket ${fault.bucket} (its buckets: ${buckets.map((b) => b.name).join(', ')})`); if ((fault.limit !== undefined || fault.per !== undefined) && named.length > 1) throw new ScenarioError(`entry ${fault.index}: ${ledger.vendor} keeps ${named.length} buckets; a rate-limit that tightens one names its bucket`); for (const bucket of named) { if (on.has(bucket.name)) continue; const limit = fault.limit ?? bucket.limit; const per = durationMs(fault.per ?? bucket.per); if (limit > bucket.limit || per < durationMs(bucket.per)) throw new ScenarioError(`entry ${fault.index}: ${limit} per ${fault.per ?? bucket.per} is looser than ${ledger.vendor}'s own ${bucket.name}, ${bucket.limit} per ${bucket.per}; a rate-limit only tightens it`); on.set(bucket.name, { limit, per, fault }); } } // the switched-on buckets this request belongs to, in the order declared: its key in each (a key naming a value the // request lacks leaves it out of that bucket) and its weight const values: Record = { ...request.params, credential: request.credential, account: request.account, operation: request.operation }; const mine = buckets.flatMap((bucket) => { const switched = on.get(bucket.name); if (!switched || (bucket.operations !== undefined && !bucket.operations.includes(request.operation))) return []; let missing = false; const key = bucket.key.replace(/\{(\w+)\}/g, (_, k: string) => { const v = values[k]; if (v === undefined || v === '') missing = true; return v ?? ''; }); if (missing) return []; const weight = typeof bucket.weights === 'function' ? bucket.weights(request) : (bucket.weights?.[request.operation] ?? 1); if (!(typeof weight === 'number' && Number.isFinite(weight) && weight >= 0)) throw new Error(`${ledger.vendor}: bucket ${bucket.name} weighed ${request.operation} at ${String(weight)}, not a non-negative number`); return [{ bucket, ...switched, weight, base: `rate:${encodeURIComponent(bucket.name)}:${switched.per}:${encodeURIComponent(key)}` }]; }); if (mine.length === 0) return { counted: [], release: () => undefined }; const now = Date.parse(ledger.at); const valuesOf = (bucket: RateBucket, limit: number, used: number, resetMs: number): RateValues => { const unit = (ms: number): number => (bucket.reset === 'ms' ? Math.ceil(ms) : Math.ceil(ms / 1000)); return { limit, used: Math.ceil(used), remaining: Math.max(0, Math.floor(limit - used)), reset: unit(resetMs), resetAfter: unit(Math.max(0, resetMs - now)), bucket: bucket.name, global: bucket.global === true }; }; type Taken = (typeof mine)[number]; /** A bucket's standing for this request, as the counts hold it: whether the request would exhaust it, the values its * refusal reads, and the charge that counts the request (with the values its answer's headers read). */ const standing = (held: Record, b: Taken): { exhausted: boolean; refusal: RateValues; charge(): RateValues } => { const inflight = `${b.base}#inflight`; const crowded = b.bucket.concurrency !== undefined && (held[inflight] ?? 0) >= b.bucket.concurrency; const enter = (): void => { if (b.bucket.concurrency !== undefined) held[inflight] = (held[inflight] ?? 0) + 1; }; if (b.bucket.counting === 'token-bucket') { const rate = b.limit / b.per; const tokens = Math.min(b.limit, (held[`${b.base}#tokens`] ?? b.limit) + (now - (held[`${b.base}#at`] ?? now)) * rate); const short = tokens < b.weight; return { exhausted: crowded || short, refusal: valuesOf(b.bucket, b.limit, b.limit - tokens, now + (short ? (b.weight - tokens) / rate : 0)), charge: () => { const left = tokens - b.weight; held[`${b.base}#tokens`] = left; held[`${b.base}#at`] = now; enter(); return valuesOf(b.bucket, b.limit, b.limit - left, now + (b.limit - left) / rate); }, }; } const window = Math.floor(now / b.per); const at = `${b.base}@${window}`; const used = held[at] ?? 0; const reset = (window + 1) * b.per; return { exhausted: crowded || used + b.weight > b.limit, refusal: valuesOf(b.bucket, b.limit, used, reset), charge: () => { for (const key of Object.keys(held)) if (key.startsWith(`${b.base}@`) && key !== at) delete held[key]; held[at] = used + b.weight; enter(); return valuesOf(b.bucket, b.limit, used + b.weight, reset); }, }; }; const result = changeCounts(ledger, (held): { refused: RateCount & { fault: PlacedFault } } | { counted: RateCount[] } => { const standings = mine.map((b) => ({ b, s: standing(held, b) })); const first = standings.find(({ s }) => s.exhausted); if (first) return { refused: { bucket: first.b.bucket, values: first.s.refusal, fault: first.b.fault } }; return { counted: standings.map(({ b, s }) => ({ bucket: b.bucket, values: s.charge() })) }; }); if ('refused' in result) { const { fault, ...refused } = result.refused; await noteFault(ledger, fault, { operation: request.operation, bucket: refused.bucket.name, used: refused.values.used }); return { refused, counted: [], release: () => undefined }; } const flying = mine.filter((b) => b.bucket.concurrency !== undefined); let released = flying.length === 0; return { counted: result.counted, release: () => { if (released) return; released = true; changeCounts(ledger, (held) => { for (const b of flying) { const k = `${b.base}#inflight`; held[k] = Math.max(0, (held[k] ?? 0) - 1); if (held[k] === 0) delete held[k]; } }); }, }; }