// The World's record of placements (ADR 0036 §2-4; architecture, "Scenarios"): what the programs that act on a World // (a run's scenario, a walk's program: `world.decide`, `world.fault`, `world.fact`) have placed, each at the World time it // was placed, and the twins' read of it. Nothing in it answers in a twin's place: a twin consumes a decision where its // vendor decides and a fault where it lands, and records both in its own log. // // This module is the placements' strict parse (`parsePlacement`, which names the vocabulary on every refusal) and the // twins' read of the record the World holds: the instance's `scenario.json`, written by world-runtime's // scenario-program.ts (or a walk's play, twin-standard's walk/world-scenario.ts) and read through the World's store at // every request as the clock is (TWIN_WORLD_SCENARIO_FILE), so a placement holds from its `at` with no reboot. import { getActiveWorldStore, worldStateFile } from './world-store.ts'; import { worldNow } from './world-clock.ts'; import { parseExactJson } from './exact-json.ts'; export const WORLD_SCENARIO_ENV = 'TWIN_WORLD_SCENARIO_FILE'; /** The outcome of a vendor's judgement at one of its decision points, for the subject it is keyed to (absent: every * subject); a model vendor's turn is the point `turn`, keyed by `on`, the pack's scenario matchers. */ export type ScenarioDecisionInput = { vendor: string; point: string; subject?: string; on?: Record; outcome: unknown; once?: boolean }; const FAULT_KINDS = { request: ['rejected', 'failed', 'lost', 'slow', 'drop', 'generation'], 'over-time': ['webhook-delay', 'webhook-duplicate', 'webhook-drop', 'lag', 'rate-limit'], network: ['reset', 'dns', 'tls', 'latency', 'loss', 'partition'], infrastructure: ['oom', 'disk-full', 'crash', 'restart'], time: ['jump', 'dst'], } as const; type FaultLayer = keyof typeof FAULT_KINDS; /** The layers asked of the machine the app runs on, through its fault door (ADR 0036 §4): its network, its * infrastructure, and its clock as the app's processes see it (the World clock's own moves are the user's). */ export const MACHINE_LAYERS: ReadonlyArray = ['network', 'infrastructure', 'time']; export type ScenarioFaultInput = { layer: FaultLayer; kind: string; /** the twin a vendor-layer fault lands in */ vendor?: string; /** a request fault's operation (the spec's operationId), or a model turn's `on`; neither: every request */ operation?: string; on?: Record; /** a point of the pack's own (`ctx.fault(point, subject)`: one item of a batch) */ point?: string; subject?: string; status?: number; message?: string; errorType?: string; metadata?: Record; partialText?: string; event?: string; retryAfterSeconds?: number; ms?: number; /** a delay or a lag: `90s`, `5m`, `12h`, `30d` */ by?: string; /** a rate limit: the vendor's bucket it switches on alone (else every one it declares), tightened to `limit` units a * `per` window where given */ bucket?: string; per?: string; limit?: number; /** a machine fault's part of the app, as the machine knows it; a reset's or a TLS failure's destination; a full disk's * volume */ target?: string; to?: string; volume?: string; between?: [string, string]; rate?: number; /** how many times it lands (default: every time, until `until`) */ times?: number; until?: string; }; /** A World fact changes at a World time: from its `at`, the fact `kind`/`key` is `value` (ADR 0036 §2-3). */ export type ScenarioFact = { kind: string; key: string; value: unknown }; /** One placement in the record: its World time, its place in the record (what a twin's record of a consumption names), * and what was placed. */ export type PlacementEntry = { at: string; index: number } & ( | { decision: ScenarioDecisionInput } | { fault: ScenarioFaultInput } | { fact: ScenarioFact } ); /** The World's record of placements, as the twins read it (TWIN_WORLD_SCENARIO_FILE): the program that began it * (`name`), the instant it began (`start`, from which `world.at` reads a duration), the browsers' entropy (`random`) and * every placement in the order it was made (`timeline`). */ export type PlacementRecord = { name: string; start: string; random: string; timeline: PlacementEntry[] }; export class PlacementError extends Error {} const fail = (where: string, message: string): never => { throw new PlacementError(`${where}: ${message}`); }; const isObject = (v: unknown): v is Record => typeof v === 'object' && v !== null && !Array.isArray(v); const onlyKeys = (value: Record, keys: readonly string[], where: string): void => { for (const key of Object.keys(value)) if (key !== '$comment' && !keys.includes(key)) fail(where, `unknown key "${key}" (valid: ${keys.join(', ')})`); }; const text = (value: unknown, where: string, name: string): string => (typeof value === 'string' && value.length > 0 ? value : fail(where, `${name} is a non-empty string`)); const instant = (value: unknown, where: string, name: string): string => { const at = text(value, where, name); return Number.isNaN(Date.parse(at)) || !/^\d{4}-\d{2}-\d{2}T/.test(at) ? fail(where, `${name} is an ISO-8601 instant, got ${JSON.stringify(at)}`) : new Date(Date.parse(at)).toISOString(); }; /** `90s`, `5m`, `12h`, `30d` in milliseconds. */ export function durationMs(by: string): number { const m = /^(\d+(?:\.\d+)?)(s|m|h|d)$/.exec(by.trim()); if (!m) throw new PlacementError(`${JSON.stringify(by)} is not (s|m|h|d)`); return Number(m[1]) * { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as 's' | 'm' | 'h' | 'd']; } const duration = (value: unknown, where: string, name: string): string => { const by = text(value, where, name); try { durationMs(by); } catch { fail(where, `${name} is a duration (90s, 5m, 12h, 30d), got ${JSON.stringify(by)}`); } return by; }; const positive = (value: unknown, where: string, name: string): number => (Number.isInteger(value) && (value as number) > 0 ? value as number : fail(where, `${name} is a positive integer`)); function parseDecision(raw: unknown, where: string): ScenarioDecisionInput { if (!isObject(raw)) return fail(where, 'decision is an object { vendor, point, subject?, on?, outcome, once? }'); onlyKeys(raw, ['vendor', 'point', 'subject', 'on', 'outcome', 'once'], `${where} decision`); if (!('outcome' in raw)) fail(where, 'decision.outcome is required: what the vendor decided'); if (raw.on !== undefined && !isObject(raw.on)) fail(where, 'decision.on is an object of the pack\'s turn matchers'); if (raw.once !== undefined && typeof raw.once !== 'boolean') fail(where, 'decision.once is boolean'); return { vendor: text(raw.vendor, where, 'decision.vendor'), point: text(raw.point, where, 'decision.point'), ...(raw.subject !== undefined ? { subject: text(raw.subject, where, 'decision.subject') } : {}), ...(raw.on !== undefined ? { on: raw.on as Record } : {}), outcome: raw.outcome, ...(raw.once !== undefined ? { once: raw.once as boolean } : {}) }; } const FAULT_KEYS: Record = { rejected: ['status', 'message', 'errorType', 'metadata', 'retryAfterSeconds'], failed: ['status', 'message', 'errorType', 'metadata', 'retryAfterSeconds'], lost: ['status', 'message', 'errorType'], slow: ['ms'], drop: ['ms'], generation: ['status', 'message', 'errorType', 'metadata', 'partialText', 'event'], 'webhook-delay': ['event', 'by'], 'webhook-duplicate': ['event'], 'webhook-drop': ['event'], lag: ['by'], // the vendor's own buckets switched on, or the one `bucket` names, its `limit` per `per` tightened where given // (scenario-consume.ts rateLimited) 'rate-limit': ['bucket', 'limit', 'per'], reset: ['target', 'to'], dns: ['target'], tls: ['target', 'to'], latency: ['target', 'ms'], loss: ['target', 'rate'], partition: ['between'], oom: ['target'], 'disk-full': ['target', 'volume'], crash: ['target'], restart: ['target'], jump: ['target', 'by'], dst: ['target'], }; function parseFault(raw: unknown, where: string): ScenarioFaultInput { if (!isObject(raw)) return fail(where, 'fault is an object { layer, kind, ... }'); const layer = raw.layer as FaultLayer; if (!(layer in FAULT_KINDS)) fail(where, `fault.layer is one of ${Object.keys(FAULT_KINDS).join(', ')}, got ${JSON.stringify(raw.layer)}`); const kinds = FAULT_KINDS[layer] as readonly string[]; if (!kinds.includes(raw.kind as string)) fail(where, `a ${layer} fault's kind is one of ${kinds.join(', ')}, got ${JSON.stringify(raw.kind)}`); const kind = raw.kind as string; const vendorLayer = layer === 'request' || layer === 'over-time'; const placement = vendorLayer ? ['vendor', 'times', 'until', ...(layer === 'request' ? ['operation', 'on', 'point', 'subject'] : ['operation'])] : ['times', 'until']; onlyKeys(raw, ['layer', 'kind', ...placement, ...FAULT_KEYS[kind]!], `${where} fault (${layer} ${kind})`); if (vendorLayer) text(raw.vendor, where, 'fault.vendor'); if (raw.operation !== undefined) text(raw.operation, where, 'fault.operation'); if (raw.on !== undefined && !isObject(raw.on)) fail(where, 'fault.on is an object of the pack\'s turn matchers'); if ([raw.operation, raw.on, raw.point].filter((v) => v !== undefined).length > 1) fail(where, 'a fault lands on one of operation, on (a model turn) or point'); if (raw.subject !== undefined && raw.point === undefined) fail(where, 'fault.subject keys a fault at a pack\'s point; name the point'); if (raw.status !== undefined && !(Number.isInteger(raw.status) && (raw.status as number) >= 400 && (raw.status as number) <= 599)) fail(where, 'fault.status is an integer 400..599: a fault is a refusal or a failure, never a success'); if (kind === 'generation' && raw.on === undefined) fail(where, 'a generation failure is a model turn\'s: name its `on`'); if (kind === 'lost' && raw.on !== undefined) fail(where, 'a lost answer lands on an operation: name its `operation`'); if (kind === 'generation' && (typeof raw.message !== 'string' || typeof raw.errorType !== 'string' || !raw.errorType || raw.status === undefined)) fail(where, 'a generation fault names its status, message and nonempty errorType'); for (const name of ['message', 'errorType', 'partialText', 'event', 'target', 'to', 'volume', 'bucket'] as const) if (raw[name] !== undefined && typeof raw[name] !== 'string') fail(where, `fault.${name} is a string`); if (raw.metadata !== undefined && !isObject(raw.metadata)) fail(where, 'fault.metadata is an object'); if (raw.ms !== undefined && !(Number.isInteger(raw.ms) && (raw.ms as number) >= 0 && (raw.ms as number) <= 600_000)) fail(where, 'fault.ms is an integer 0..600000 (milliseconds)'); if (raw.retryAfterSeconds !== undefined && !(Number.isInteger(raw.retryAfterSeconds) && (raw.retryAfterSeconds as number) >= 0)) fail(where, 'fault.retryAfterSeconds is a non-negative integer'); for (const name of ['by', 'per'] as const) if (raw[name] !== undefined) duration(raw[name], where, `fault.${name}`); if (['webhook-delay', 'lag', 'jump'].includes(kind)) duration(raw.by, where, 'fault.by'); if (MACHINE_LAYERS.includes(layer) && kind !== 'partition' && raw.target === undefined) fail(where, `a ${layer} fault names its target, the part of the app it lands on`); if (raw.limit !== undefined) positive(raw.limit, where, 'fault.limit'); if (raw.rate !== undefined && !(typeof raw.rate === 'number' && raw.rate > 0 && raw.rate <= 1)) fail(where, 'fault.rate is a fraction in (0, 1]'); if (kind === 'partition' && !(Array.isArray(raw.between) && raw.between.length === 2 && raw.between.every((s) => typeof s === 'string' && s))) fail(where, 'a partition names its two sides: between [a, b]'); if (raw.times !== undefined) positive(raw.times, where, 'fault.times'); if (raw.until !== undefined) instant(raw.until, where, 'fault.until'); return raw as ScenarioFaultInput; } function parseFact(raw: unknown, where: string): ScenarioFact { if (!isObject(raw)) return fail(where, 'fact is an object { kind, key, value }'); onlyKeys(raw, ['kind', 'key', 'value'], `${where} fact`); if (!('value' in raw)) fail(where, 'fact.value is required: the fact as it stands from this entry on'); return { kind: text(raw.kind, where, 'fact.kind'), key: text(raw.key, where, 'fact.key'), value: raw.value }; } /** A placement a program makes at the World's current time (`world.decide`, `world.fault`, `world.fact`; ADR 0036 §2), * read strictly in the shape the scenario in force holds it: every refusal names the vocabulary it expected. */ export function parsePlacement(kind: 'decision', raw: unknown): ScenarioDecisionInput; export function parsePlacement(kind: 'fault', raw: unknown): ScenarioFaultInput; export function parsePlacement(kind: 'fact', raw: unknown): ScenarioFact; export function parsePlacement(kind: 'decision' | 'fault' | 'fact', raw: unknown): ScenarioDecisionInput | ScenarioFaultInput | ScenarioFact { return kind === 'decision' ? parseDecision(raw, `world.decide`) : kind === 'fault' ? parseFault(raw, 'world.fault') : parseFact(raw, 'world.fact'); } const kept = new Map(); /** A JSON file of the active World's own (its scenario, its facts; worldStateFile), read through the World's store at * each call as the clock is, and parsed again only when it changed; null where the World names none or the file is * absent. */ export function worldJsonFile(name: 'scenario' | 'facts'): T | null { const file = worldStateFile(name); if (!file) return null; const store = getActiveWorldStore(); const raw = store.readKept ? store.readKept(file) : store.read(file); if (raw === null) return null; const held = kept.get(file); if (held?.raw === raw) return held.value as T; const value = parseExactJson(raw); kept.set(file, { raw, value }); return value as T; } /** The World's record of placements, or null where it holds none. */ function activeRecord(): PlacementRecord | null { return worldJsonFile('scenario'); } /** The decisions and vendor faults placed on one vendor, in the order they were placed. */ export function placedOn(vendor: string): PlacementEntry[] { return (activeRecord()?.timeline ?? []).filter((e) => ('decision' in e && e.decision.vendor === vendor) || ('fault' in e && e.fault.vendor === vendor)); } export type PlacedDecision = ScenarioDecisionInput & { index: number; at: string }; export type PlacedFault = ScenarioFaultInput & { index: number; at: string }; /** A World fact as it stands at `now`: the last change placed for it at or before then, else the World's own * (`world.json`'s `facts`, as the runtime hands them to its twins); undefined where the World holds none. */ export function factAt(kind: string, key: string, now: string = worldNow()): unknown { let value = worldJsonFile>>('facts')?.[kind]?.[key]; for (const e of activeRecord()?.timeline ?? []) if ('fact' in e && e.fact.kind === kind && e.fact.key === key && e.at <= now) value = e.fact.value; return value; } /** The decisions placed for a vendor's point at or before the World's now, in the order they were placed. */ export function placedDecisions(vendor: string, point: string, now: string = worldNow()): PlacedDecision[] { return placedOn(vendor).flatMap((e) => ('decision' in e && e.decision.point === point && e.at <= now ? [{ ...e.decision, index: e.index, at: e.at }] : [])); } /** The vendor faults placed on a vendor at or before the World's now and not past their `until`, in the order they were * placed. */ export function placedFaults(vendor: string, layer: 'request' | 'over-time', now: string = worldNow()): PlacedFault[] { return placedOn(vendor).flatMap((e) => ('fault' in e && e.fault.layer === layer && e.at <= now && (e.fault.until === undefined || now < new Date(Date.parse(e.fault.until)).toISOString()) ? [{ ...e.fault, index: e.index, at: e.at }] : [])); }