/** * vapor-chamber - Utility layer * * createChamber, createWorkflow, createReaction * * These use only the public BaseBus interface. They are optional and tree-shaken. */ import { _withCausation, disposeAll, _errResult } from './command-bus'; import { _report } from './report'; import { matchesPattern } from './pattern'; import { isThenable } from './settled'; import { countOption } from './bounds'; import { _unrecorded } from './ledger'; import type { BaseBus, Command, CommandResult, Handler, RegisterOptions, } from './command-bus'; // --------------------------------------------------------------------------- // createChamber - declarative namespace grouping // --------------------------------------------------------------------------- export type ChamberHandlers = Record; export type ChamberOptions = { /** Per-action registration options (undo, optimistic, exclusive). */ options?: Record; }; export interface Chamber { /** Namespace prefix (e.g. 'cart'). */ readonly namespace: string; /** Install all handlers on a bus. Returns uninstall function. */ install(bus: BaseBus): () => void; /** Get the prefixed action name (e.g. 'add' -> 'cartAdd'). */ actionName(shortName: string): string; } /** * createChamber - groups related handlers under a namespace. * The declarative counterpart to `useCommandGroup`. * * @example * const cart = createChamber('cart', { * add: handleCartAdd, * remove: handleCartRemove, * clear: handleCartClear, * }); * const uninstall = cart.install(bus); * // Registers: cartAdd, cartRemove, cartClear */ export function createChamber( namespace: string, handlers: ChamberHandlers, opts: ChamberOptions = {}, ): Chamber { // camelCase namespace join ('cart' + 'add' -> 'cartAdd'). Inlined, NOT a shared // helper - DO NOT consolidate, settled. Each join site keeps its own copy: // the transition bridge resolves its names at construction (transitions.ts), // useCommandGroup caches them per group (chamber.ts, `_nameCache`), and this // site runs at setup. Keep the three in sync. function actionName(shortName: string): string { return namespace + shortName.charAt(0).toUpperCase() + shortName.slice(1); } function install(bus: BaseBus): () => void { const unsubs: Array<() => void> = []; // A register that throws (a sealed bus, a naming rule, a `$` name) would // leave the handlers before it on the bus, with no uninstall to remove // them: remove them, then rethrow. tests/utilities.test.ts. try { for (const [short, handler] of Object.entries(handlers)) { const action = actionName(short); const regOpts = opts.options?.[short]; unsubs.push(bus.register(action, handler, regOpts)); } } catch (e) { disposeAll(unsubs); throw e; } return () => { disposeAll(unsubs); }; } return { namespace, install, actionName }; } // --------------------------------------------------------------------------- // createWorkflow - sequential commands with compensation (saga pattern) // --------------------------------------------------------------------------- export type WorkflowStep = { /** Action name to dispatch. */ action: string; /** If this step fails, dispatch this action to compensate previous steps. */ compensate?: string; /** Map the workflow target/payload into step-specific target. */ mapTarget?: (target: any, payload?: any) => any; /** Map the workflow target/payload into step-specific payload. */ mapPayload?: (target: any, payload?: any) => any; }; export type WorkflowResult = { ok: boolean; /** Results of each step that executed (in order). */ results: CommandResult[]; /** If failed, the step index that caused the failure. */ failedAt?: number; /** Error from the failed step. */ error?: Error; /** Results of compensation steps (in reverse order). */ compensations?: CommandResult[]; }; export interface Workflow { /** Execute the workflow. Async because compensation may involve async buses. */ run(bus: BaseBus, target: any, payload?: any): Promise; /** The step definitions. */ readonly steps: readonly WorkflowStep[]; } /** * createWorkflow - sequential commands with automatic compensation on failure. * * @example * const checkout = createWorkflow([ * { action: 'cartValidate' }, * { action: 'paymentReserve', compensate: 'paymentRelease' }, * { action: 'orderCreate', compensate: 'orderCancel' }, * { action: 'cartClear' }, * ]); * const result = await checkout.run(bus, { cartId, paymentInfo }); * // If orderCreate fails -> paymentRelease runs automatically */ export function createWorkflow(steps: WorkflowStep[]): Workflow { async function run(bus: BaseBus, target: any, payload?: any): Promise { const results: CommandResult[] = []; // The MAPPED target/payload are captured alongside the compensating action, // not just its name: a step pairing `mapTarget`/`mapPayload` with // `compensate` (deriving an order id, addressing a sub-entity) must be // compensated against what it acted on, not the workflow's original // arguments - silently wrong otherwise, and only on the failure path. const compensations_: Array<{ action: string; target: any; payload: any }> = []; for (let i = 0; i < steps.length; i++) { const step = steps[i]; const stepTarget = step.mapTarget ? step.mapTarget(target, payload) : target; const stepPayload = step.mapPayload ? step.mapPayload(target, payload) : payload; let result: CommandResult; try { const dispatched = bus.dispatch(step.action, stepTarget, stepPayload); // Handle both sync and async buses result = isThenable(dispatched) ? await dispatched : dispatched; } catch (e) { result = _errResult(e as Error); } results.push(result); if (!result.ok) { // Run compensations in reverse order const compensations: CommandResult[] = []; for (let j = compensations_.length - 1; j >= 0; j--) { const entry = compensations_[j]; try { const comp = bus.dispatch(entry.action, entry.target, entry.payload); const compResult = isThenable(comp) ? await comp : comp; compensations.push(compResult); } catch (e) { compensations.push(_errResult(e as Error)); } } return { ok: false, results, failedAt: i, error: result.error, compensations }; } if (step.compensate) { compensations_.push({ action: step.compensate, target: stepTarget, payload: stepPayload }); } } return { ok: true, results }; } return { run, steps: Object.freeze([...steps]) }; } // --------------------------------------------------------------------------- // createReaction - declarative cross-domain dispatch rules // --------------------------------------------------------------------------- export type ReactionOptions = { /** Only react when this predicate returns true. */ when?: (cmd: Command, result: CommandResult) => boolean; /** Transform the source command into the target command's target. */ map?: (cmd: Command, result: CommandResult) => any; /** Transform the source command into the target command's payload. */ mapPayload?: (cmd: Command, result: CommandResult) => any; /** * Allow `sourcePattern` to match `targetAction` - i.e. the reaction fires on * its own dispatch. Refused by default, because the loop it creates is * bounded by `maxHops` and by the dispatch depth: * * - A reaction re-dispatches synchronously from its listener, and both * buses run listeners at the dispatch's depth, so `MAX_DISPATCH_DEPTH` * halts each chain at 16 dispatches with a logged `core:exceeded:depth` * (tests/reaction-indirect-cycle.test.ts, D12). * - `maxHops` stops it earlier, and counts across every reaction on the * bus, so an indirect cycle stops too. * * Opt in only alongside a `when` guard that can actually terminate it: each * hop up to the bound still runs handlers, plugins and (with a transport * installed) HTTP requests. */ allowSelfMatch?: boolean; /** * How many reaction hops a single originating command may trigger before * the chain is refused, counted across every reaction on the bus. Catches * INDIRECT cycles (A->B, B->A), which no install-time check can see. * Default: 8. tests/reaction-indirect-cycle.test.ts. */ maxHops?: number; }; export interface Reaction { /** Install the reaction on a bus. Returns unsubscribe function. */ install(bus: BaseBus): () => void; } // Each bus's reaction hop counts, keyed by the id that caused the next hop. const hopsByBus = new WeakMap>(); /** * createReaction - declarative cross-chamber dispatch rules. * Explicit edges between domain modules. Not run on an undo, a redo or a * mirrored command (origin 'sync'): history replays the follow-up it recorded. * * @example * createReaction('cartAdd', 'inventoryCheck', { * when: (cmd, result) => result.ok, * map: (cmd) => ({ itemId: cmd.payload.itemId }), * }).install(bus); */ export function createReaction( sourcePattern: string, targetAction: string, options: ReactionOptions = {}, ): Reaction { const { when, map, mapPayload, allowSelfMatch = false } = options; const maxHops = countOption(options.maxHops, 8); // a NaN is the default (bounds.ts) const selfMatching = matchesPattern(sourcePattern, targetAction); function install(bus: BaseBus): () => void { // Statically detectable at install, so detect it at install. // `createReaction('cart*', 'cartRecalculate')` is the module's most // natural composition, not a contrived one - and it re-triggers itself on // every dispatch until a bound stops it (see ReactionOptions.allowSelfMatch). if (selfMatching && !allowSelfMatch) { _report('error', 'reaction:invalid:pattern', `Reaction "${sourcePattern}" -> "${targetAction}" matches its own target: ` + 'every dispatch would re-trigger the reaction, up to the dispatch depth bound. ' + 'Narrow the pattern, or pass { allowSelfMatch: true } with a `when` guard that terminates it. ' + 'Not installed.', ); return () => {}; } // Hop count per chain, keyed by the id of the command that CAUSED the next // dispatch. The next hop's listener sees that id as its own // `meta.causationId`, so the chain is walked through meta rather than // through the payload. // // Not in the payload: a `__reactionHops` marker cannot ride on a primitive // or an array, so `mapPayload: () => 42` would read every hop as hop 1 and // the cap would never fire (measured: an indirect cycle runs to // MAX_DISPATCH_DEPTH on either bus). The // payload marker is still written when the payload can hold keys. // // Capped like `_prefixCache` in command-bus.ts: a long-lived reaction on a // busy bus would otherwise grow this without bound. Eviction degrades a // pathological chain to "starts counting again", never to a leak. // // One map per bus, shared by every reaction installed on it: reaction // B->A must find the id reaction A->B recorded, or an indirect cycle reads // every hop as 1 (tests/reaction-indirect-cycle.test.ts). let chainHops = hopsByBus.get(bus); if (!chainHops) hopsByBus.set(bus, (chainHops = new Map())); const CHAIN_MAX = 256; return bus.on(sourcePattern, (cmd: Command, result: CommandResult) => { // Not on an undo, a redo or a mirror: history replays the follow-up it // recorded (tests/reaction-undo-redo.test.ts). if (_unrecorded(cmd.meta?.origin) || (when && !when(cmd, result))) return; const parent = cmd.meta?.causationId; const hops = (parent !== undefined ? (chainHops.get(parent) ?? 0) : 0) + 1; if (hops > maxHops) { _report('error', 'reaction:exceeded:hops', `Reaction "${sourcePattern}" -> "${targetAction}" exceeded maxHops (${maxHops}) - ` + 'refusing to continue. This is a reaction cycle; break it with a `when` guard or raise maxHops.', ); return; } const target = map ? map(cmd, result) : cmd.target; const mapped = mapPayload ? mapPayload(cmd, result) : undefined; // Propagate causation too, so a reaction chain is traceable in devtools. const marker = { __reactionHops: hops, __causationId: cmd.meta?.id }; const payload = mapped === null || mapped === undefined ? marker : typeof mapped === 'object' && !Array.isArray(mapped) ? { ...mapped, ...marker } : mapped; // Record this chain's depth against the id the NEXT hop will carry as its // causationId, then hand that id to the core's one-shot slot so the // dispatched command is attributed whatever shape its payload has. const id = cmd.meta?.id; if (id !== undefined) { if (chainHops.size >= CHAIN_MAX) chainHops.delete(chainHops.keys().next().value!); chainHops.set(id, hops); } try { _withCausation(id, () => bus.dispatch(targetAction, target, payload)); } catch (e) { _report('error', 'reaction:failed:dispatch', `Reaction "${sourcePattern}" -> "${targetAction}" threw`, e, { action: targetAction }); } }); } return { install }; }