import { C as CmdOf, o as CmdValue, f as TaggedError, a as CmdDef, p as MalformedResult, T as TimerDeps, b as Cmd } from './core-sEWVgnpI.js'; import { RetryState, AnyRetryPolicy } from './retry-backoff/index.js'; import { T as TtlCache, D as DeadlineExceeded, a as DeadlineSub } from './index-CCs-QGGu.js'; /** * @packageDocumentation * internal/resilience/circuit-breaker — per-target failure tracking as pure state + ops. * * Same shape as `../../work-queue/ops.ts`, `../rate-limit/`, and * `../../idempotency/`: a state type plus pure transition functions. * Host-agnostic by construction — no `Date.now()`, no timers, no I/O. The * caller injects the clock (`nowMs`) and wires the result into its own reducer * / interpret. This keeps the breaker inside TEA's invariant 2 (transitions are * pure: same inputs → same outputs, no `Date.now`) so a consumer can fold it * through `update` and exercise it with `replay` / the pbt fold without a fake * clock. * * Every op returns a NEW state value and never mutates its input (invariant 1 — * state is a value, not a place). `canPass` returns a `[next, allowed]` tuple so * the caller branches on the decision while threading the advanced state forward * — same convention as `rate-limit`'s `tryConsume` / `record`. `onSuccess` / * `onFailure` are the outcome-recording transitions the caller folds in once the * guarded call resolves. * * ## The phase machine * * A circuit breaker guards a fallible downstream target (an HTTP backend, a DB, * a flaky tool call). Instead of hammering a target that is already failing, it * trips OPEN after enough failures and fast-fails subsequent calls for a * cooldown, then probes with a few trial calls before fully closing again. * Three phases, each carrying ONLY its own data so impossible states are * unrepresentable (pattern 11): * * - **closed** — the healthy steady state. Calls pass through. Carries * `failures`: the count of *consecutive* failures since the last success. * A success resets it to 0; the `failureThreshold`-th failure trips the * breaker OPEN. Only `closed` has a failure counter — `open` and * `half_open` don't, because in those phases the count is irrelevant * (the breaker has already tripped / is already probing). * * - **open** — the tripped state. All calls fast-fail (no downstream load). * Carries `openedAtMs`: the clock reading at which the breaker tripped. * `canPass` compares `nowMs - openedAtMs` against `cooldownMs` to decide * when to start probing. Only `open` carries a timestamp — neither other * phase is timing anything. * * - **half_open** — the probing state. A limited number of trial calls are * allowed through to test whether the target has recovered. Carries * `probes`: the count of probes admitted so far this probing round. * `canPass` admits while `probes < halfOpenMaxProbes`, then fast-fails the * rest (so a slow target can't be flooded by every queued caller at once). * A probe success closes the breaker; a probe failure re-opens it (and * resets the cooldown clock). Only `half_open` counts in-flight probes. * * ### Transition table * * Rows are the current phase; columns are the event. `→` denotes the next * phase; `self` means unchanged. `nowMs` is the injected clock. * * | from \ event | onSuccess | onFailure | canPass (→ allowed?) | * | ------------ | -------------- | -------------------------------------- | ------------------------------------------------------------------------------------ | * | closed | closed(0) | failures+1; trip → open(nowMs) at thr. | self → true (always) | * | open | self *(¹)* | self | elapsed ≥ cooldown → half_open(1), true; else self → false | * | half_open | → closed(0) | → open(nowMs) (probe failed) | probes < max → half_open(probes+1), true; else self → false | * * *(¹)* `onSuccess` on `open` "shouldn't happen": no call was admitted while * open, so no success can be reported for one. We leave the state unchanged * rather than throw — the breaker is a coordination aid, not a correctness * gate, and a spurious success report (e.g. a late-arriving result from before * the trip) must not silently un-trip the breaker. `onFailure` on `open` is * likewise a no-op: the breaker is already tripped; the `open` clock is anchored * at the trip, not bumped by late failures. * * ### The probe-admission asymmetry * * Entering `half_open` happens inside `canPass`, not `onSuccess` / `onFailure`, * because the cooldown is a *time* condition and only `canPass` reads the clock * against `openedAtMs`. The first `canPass` after the cooldown elapses both * transitions the phase AND admits the probe (`[half_open(1), true]`) — one * caller drives the recovery attempt. Subsequent `canPass` calls in the same * round admit up to `halfOpenMaxProbes` total, then fast-fail until a probe * resolves and `onSuccess` / `onFailure` moves the phase out of `half_open`. * * This module is a textbook three-state machine — a clean `/machine-viz` demo. * * Internal to the package (`src/internal/resilience/`), not a published * subpath (#46); same one-shape-per-module rule as `work-queue`, `rate-limit`, * and `idempotency`. */ /** * Circuit-breaker policy — pure configuration, no mutable state. One policy is * shared across all the calls guarded by one logical breaker (often a * module-scope const). `CircuitState` carries the mutable counts; this carries * the thresholds those counts are compared against. */ interface CircuitPolicy { /** * Consecutive failures in `closed` that trip the breaker `open`. The * `failureThreshold`-th failure is the one that trips — with a threshold of * 5, the breaker survives 4 failures and opens on the 5th. */ readonly failureThreshold: number; /** * How long the breaker stays `open` before `canPass` starts admitting * probes, in milliseconds. Measured from `openedAtMs`; the cutoff is * half-open (`elapsed >= cooldownMs` admits), matching `rate-limit` / * `idempotency` window edges — a breaker opened at `t` first probes at * `t + cooldownMs`. */ readonly cooldownMs: number; /** * How many probe calls `half_open` admits before fast-failing the rest of * the round. Caps the load on a recovering target — a single slow probe * can't be joined by every queued caller. The round ends when a probe * resolves: success closes the breaker, failure re-opens it. */ readonly halfOpenMaxProbes: number; } /** * Sensible defaults: trip after 5 consecutive failures, cool down for 30s, * admit a single probe before deciding. Tuned for guarding a network backend; * override per call site rather than mutating this shared const. */ declare const defaultCircuitPolicy: CircuitPolicy; /** * The breaker's phase. A discriminated union on `phase` so each phase carries * ONLY its own data and impossible combinations are unrepresentable (pattern * 11): there is no state with both a failure count AND an open timestamp, * because such a state is meaningless. `phase` is the discriminant; every field * is `readonly` so the whole value is trivially JSON-serializable into a * consumer's `Store` and safe to thread through a pure reducer. * * - `closed` carries `failures` — consecutive failures since last success. * - `open` carries `openedAtMs` — clock reading when it tripped. * - `half_open` carries `probes` — probes admitted this round. */ type CircuitState = { readonly phase: "closed"; readonly failures: number; } | { readonly phase: "open"; readonly openedAtMs: number; } | { readonly phase: "half_open"; readonly probes: number; }; /** The starting state: closed with zero recorded failures. */ declare function initCircuit(): CircuitState; /** * Record a successful guarded call. PURE — returns a new state; the input is * never mutated. * * - `closed` → reset `failures` to 0 (a success breaks the consecutive run). * - `half_open` → the probe succeeded; the target has recovered → `closed`. * - `open` → unchanged. A success "shouldn't happen" while open (no call * was admitted to produce one); a late/spurious success must * not silently un-trip the breaker. See module header note ¹. */ declare function onSuccess(state: CircuitState, _policy: CircuitPolicy): CircuitState; /** * Record a failed guarded call. PURE — returns a new state; the input is never * mutated. `nowMs` is the injected clock, stamped onto the `open` phase when the * breaker trips so `canPass` can measure the cooldown later. * * - `closed` → `failures + 1`; if that reaches `failureThreshold`, trip to * `open(nowMs)`. The threshold-th failure is the one that trips. * - `half_open` → the probe failed; the target is still unhealthy → * `open(nowMs)`, restarting the cooldown clock so a fresh * cooldown elapses before the next probe round. * - `open` → unchanged. The breaker is already tripped; the `open` clock * is anchored at the original trip, not bumped by late * failures. See module header note ¹. */ declare function onFailure(state: CircuitState, policy: CircuitPolicy, nowMs: number): CircuitState; /** * Decide whether a call may pass, advancing the phase as a side effect of the * decision. PURE — returns `[next, allowed]`; the input is never mutated. * Branch on the boolean, thread the state forward regardless: * * const [c1, allowed] = canPass(state.circuit, policy, nowMs); * if (!allowed) return [{ ...state, circuit: c1 }, [fastFailCmd]]; * return [{ ...state, circuit: c1 }, [doGuardedCallCmd]]; * * - `closed` → `[state, true]` — always passes; failures are recorded by * `onFailure` once the call resolves, not gated here. * - `open` → if `nowMs - openedAtMs >= cooldownMs` the cooldown has * elapsed → enter `half_open` and admit this caller as the * first probe: `[half_open(1), true]`. Otherwise still cooling * down → `[state, false]` (fast-fail, no downstream load). * - `half_open` → admit while `probes < halfOpenMaxProbes`, incrementing the * count: `[half_open(probes+1), true]`. Once the cap is hit → * `[state, false]` until a probe resolves and `onSuccess` / * `onFailure` moves the phase out of `half_open`. * * Entering `half_open` lives here (not in `onSuccess` / `onFailure`) because the * cooldown is a time condition and only `canPass` reads `nowMs` against * `openedAtMs`. See the module header's probe-admission note. */ declare function canPass(state: CircuitState, policy: CircuitPolicy, nowMs: number): readonly [CircuitState, boolean]; /** * internal/resilience/rate-limit — two rate limiters as pure state + ops. * * Same shape as `../../work-queue/ops.ts`: a state type plus pure * transition functions. Host-agnostic by construction — no `Date.now()`, no * timers, no I/O. The caller injects the clock (`nowMs`) and wires the result * into its own reducer / interpret. This keeps the limiters inside TEA's * invariant 2 (transitions are pure: same inputs → same outputs, no `Date.now`) * so a consumer can fold them through `update` and exercise them with `replay` * / the pbt fold without a fake clock. * * Every op returns a NEW state value and never mutates its input (invariant 1 — * state is a value, not a place). The `tryConsume` / `record` ops return a * `[next, ok]` tuple so the caller branches on the decision while threading the * advanced state forward; `refill` / `remaining` are read-shaped helpers. * * Two complementary algorithms, picked by the cost the caller wants to pay: * * - **Token bucket** — O(1) state (four numbers), smooths bursts against a * steady refill rate. Allows a burst up to `capacity`, then throttles to * `refillPerSec`. Cheapest; the default choice. * - **Sliding window log** — O(limit) state (one timestamp per in-window * hit), exact "no more than `limit` events per `windowMs`". Pay the memory * for precise window edges when a token bucket's continuous refill would * let through too many at a boundary. * * Internal to the package (`src/internal/resilience/`), not a published * subpath (#46); same one-shape-per-module rule as `work-queue` and `do`. */ /** * A token bucket: `tokens` of `capacity` available now, replenished at * `refillPerSec` tokens per second. `lastRefillMs` is the clock reading at * which `tokens` was last computed — `refill` advances it. All four fields are * plain numbers so the whole bucket is trivially JSON-serializable into a * consumer's `Store`. */ interface TokenBucket { readonly tokens: number; readonly capacity: number; readonly refillPerSec: number; readonly lastRefillMs: number; } /** * Create a full bucket. Starts at `capacity` tokens (the conventional "a fresh * limiter lets the first burst through" behavior) and stamps `lastRefillMs` * with the caller's clock so the first `refill` measures elapsed time from * boot, not from epoch 0. */ declare function initBucket(capacity: number, refillPerSec: number, nowMs: number): TokenBucket; /** * Add the tokens accrued since `lastRefillMs`, clamped to `capacity`, and * advance `lastRefillMs` to `nowMs`. PURE — returns a new bucket; the input is * untouched. * * A `nowMs` at or before `lastRefillMs` (clock not advanced, or skewed * backwards) adds a non-positive amount; `Math.max(0, …)` floors the elapsed * term so a backwards clock can never *remove* tokens. `lastRefillMs` still * advances to `nowMs` so the bucket tracks the latest reading the caller * presented — the next forward step measures from there, not from a stale * future timestamp. */ declare function refill(bucket: TokenBucket, nowMs: number): TokenBucket; /** * Refill against `nowMs`, then attempt to take `n` tokens (default 1). * * On success returns `[next, true]` with `n` subtracted; on failure returns * `[refilled, false]` — the refilled bucket (so the caller keeps the advanced * clock + accrued tokens) with no tokens spent. Branch on the boolean, thread * the bucket forward regardless: * * const [b1, ok] = tryConsume(bucket, nowMs); * return ok ? [{ ...state, bucket: b1 }, [doWork]] : [{ ...state, bucket: b1 }, []]; * * PURE — input bucket is never mutated. */ declare function tryConsume(bucket: TokenBucket, nowMs: number, n?: number): readonly [TokenBucket, boolean]; /** * A sliding-window log: the timestamps of every hit still inside the trailing * `windowMs`, capped at `limit` events per window. `hits` is `readonly` and * kept oldest-first (pruning slices the stale prefix off the front, recording * appends to the back), so the array is its own sorted index. Exact at the * window edge — unlike a token bucket's continuous refill, a hit leaves the * count the instant it ages past `windowMs`. */ interface SlidingWindow { readonly hits: readonly number[]; readonly windowMs: number; readonly limit: number; } /** Create an empty window. No hits recorded yet. */ declare function initWindow(windowMs: number, limit: number): SlidingWindow; /** * Prune hits older than `nowMs - windowMs`, then record `nowMs` if there is * room. Returns `[next, true]` with the hit appended when `hits.length < limit` * after pruning, else `[pruned, false]` — the pruned window (capacity recovers * as old hits age out) with nothing appended. * * The cutoff is half-open (see {@link prune}): a hit exactly `windowMs` old is * pruned, so a hit recorded at `t` no longer counts at `t + windowMs`. That * makes the window's capacity fully recover `windowMs` after the last hit, the * behavior tests pin. * * PURE — input window is never mutated; `hits` is rebuilt by `filter` + * spread. */ declare function record(window: SlidingWindow, nowMs: number): readonly [SlidingWindow, boolean]; /** * How many more hits `record` would accept at `nowMs` without blocking — * `limit` minus the live (post-prune) hit count, floored at 0. Read-only: it * prunes a local copy to answer but returns no new window. Use it to render a * "N requests remaining" affordance without committing a hit. */ declare function remaining(window: SlidingWindow, nowMs: number): number; /** Circuit-breaker knob — only the two numbers a consumer ever tunes. */ interface CircuitConfig { /** Consecutive failures that trip the breaker open. */ readonly threshold: number; /** How long the breaker stays open before admitting a probe, in ms. */ readonly cooldownMs: number; /** * Probes admitted in `half_open` before fast-failing the rest of the round. * Defaults to 1 (a single probe decides recovery) — matches the circuit- * breaker module's `defaultCircuitPolicy`. */ readonly halfOpenMaxProbes?: number; } /** Token-bucket rate-limit knob. */ interface RateLimitConfig { /** Burst size — the bucket starts full at `capacity`. */ readonly capacity: number; /** Steady-state refill rate, tokens per second. */ readonly refillPerSec: number; } /** Per-entry TTL cache knob. */ interface CacheConfig { /** How long a cached success stays fresh, in ms. */ readonly ttlMs: number; } /** * Overall deadline knob — a budget of IN-PROCESS time per in-flight call. * * The budget is charged in elapsed time this process actually observed, not by * a position on the host's wall clock. Time in which no process exists — a DO * eviction, a crash between attempts, a redeploy — is NOT charged: `resume` * re-anchors every live call's charging clock, so downtime lands outside every * segment. A timeout therefore means "the tool took too long", never "the host * was away too long" (#144). */ interface DeadlineConfig { /** Budget of in-process time from the moment a call starts, in ms. */ readonly ms: number; } /** * The family every unnamed knob speaks: `resilient_run` / `resilient_run_ok` / * `resilient_run_err`. Identical to the `MsgType.Resilient*` literals, which * stay the vocabulary of every knob that passes no name. */ declare const DEFAULT_RESILIENT_NAME = "resilient"; /** * The Msg-name family a resilient call uses when it is given no name: * `resilient`. */ type DefaultResilientName = typeof DEFAULT_RESILIENT_NAME; /** The run Cmd's `_tag` for the `N` family. */ type ResilientRunType = `${N}_run`; /** The success settle Msg's `_tag` for the `N` family — minted by the engine. */ type ResilientOkType = `${N}_run_ok`; /** The failure settle Msg's `_tag` for the `N` family — minted by the engine. */ type ResilientErrType = `${N}_run_err`; /** * The resilience knob. EVERY field is optional: omit a brick and its gate is * skipped entirely (the slice still carries a default brick state so the shape * stays uniform across configs, but the gate is never consulted). An empty * config `{}` is a valid pass-through — a bare effect with no resilience at all. * * `N` is the knob's Msg-name family (see {@link ResilientName}); it is carried on * the config so the run Cmd and the two settle Msgs are named from ONE place. */ interface ResilientConfig { /** * What this knob's Cmd and settle Msgs are called: `_run`, and the * `_run_ok` / `_run_err` the engine mints from the run handler's * outcome. Omit it and the family is `resilient` — `resilient_run` / * `resilient_run_ok` / `resilient_run_err`. * * Name a knob when a machine holds more than one of the resilient family. * Two unnamed knobs meet in ONE `resilient_run_ok` cell whose payload is the union * of both results, and the consumer discriminates by hand on `key` — which the * type checker cannot see. Under distinct names each knob settles into its own * cell, already narrowed to its own payload. * * The name is a value AND a type: the settle Msg types are generic in `N`, and * `N` is not inferable from `I` / `R`, so an opted-in knob spells all three * type arguments — `createResilientCall({ name: "jev", … })`. * The `name` field is typed at `N`, so the two cannot drift apart. */ readonly name?: N; /** * The backoff brick. Omit and a failure is terminal (no backoff, no timer). * * Any bound the `../retry-backoff` union admits: a count (`RetryPolicy`), a * wall-clock outage budget (`DurationRetryPolicy`), or explicit * `unbounded: true`. A duration bound needs no extra wiring: every path that * records a failure already holds the instant it was observed as DATA — * `settle`'s `msg.at` (stamped at the interpret boundary) and `gate`'s `at` * (the caller's `attempt` / the retry timer's `atMs`) — so the streak clock * is fed from a Msg, never from a `Date.now()` inside a verb (invariant 2). */ readonly retry?: AnyRetryPolicy; readonly circuit?: CircuitConfig; readonly rateLimit?: RateLimitConfig; readonly cache?: CacheConfig; readonly deadline?: DeadlineConfig; } /** * What is left of one call's deadline budget, and where the currently open * charging segment starts. Plain data, so it persists with the rest of the slice * — but the DURABLE fact is `remainingMs`, a duration, never an instant. * * The accounting has one rule, applied at every transition that carries a clock * (`attempt`'s `at`, a settle Msg's `at`, a timer's `atMs`): charge the segment * that just closed and open a new one at the same instant — * `remainingMs -= at - chargingSinceMs; chargingSinceMs = at`. See {@link charge}. * * `chargingSinceMs` is an IN-PROCESS anchor, not a persisted deadline. It is * meaningful only while the process that wrote it is alive, and `resume` re-bases * it on every live call before anything reads it after a reload — which is what * keeps downtime out of the budget. Nothing derives a timeout from it across a * resume; the only durable answer to "how much budget is left" is `remainingMs`. * * `remainingMs` is `0` when the `deadline` brick is absent, which is also the * "no cap armed" reading `subs` uses — a call with a real budget always has * `remainingMs > 0`, because `gate` settles a call whose budget reached zero * rather than letting it enter `running`. */ interface CallBudget { /** In-process ms left when the open segment started. `0` = no deadline brick. */ readonly remainingMs: number; /** The instant the open segment started, on the clock of the process that opened it. */ readonly chargingSinceMs: number; } /** * Per-key call phase. `key` indexes a logical call; several can be in flight at * once (the generalization of the example's single `url`). Discriminated on * `phase` so each phase carries only its own data (pattern 11): * * - `idle` — never attempted, or fully settled and forgotten. * - `running` — the effect Cmd is out; awaiting `settle`. * Carries the deadline budget ({@link CallBudget}) and the * last `input` so a retry can re-issue it. * - `waiting_retry` — a transient failure backed off; the retry timer is armed * for `retryAtMs`. Carries `input` for the re-attempt, and * the same budget — backoff is in-process time, so it is * charged like an attempt. * - `circuit_open` — the breaker fast-failed this attempt. Terminal for this * call until the consumer re-attempts after cooldown. * - `succeeded` — settled OK. `result` is the value the port produced. * - `failed` — settled Err (out of retries, or no retry brick). `error` * carries the last failure. */ type CallPhase = { readonly phase: "idle"; } | { readonly phase: "running"; readonly input: I; readonly budget: CallBudget; } | { readonly phase: "waiting_retry"; readonly input: I; readonly retryAtMs: number; readonly budget: CallBudget; } | { readonly phase: "circuit_open"; } | { readonly phase: "succeeded"; readonly result: R; } | { readonly phase: "failed"; readonly error: unknown; }; /** * The slice. `circuit` / `bucket` are SHARED across keys (one downstream target * → one breaker, one bucket). `retry` and `cache` are PER KEY (each logical call * has its own backoff count + cached result), as is the per-call `CallPhase`. * Every field is plain data → the whole slice serializes into a `Store`. * * `retry` / `cache` keep a default brick value even when the corresponding * config brick is omitted, so the slice shape is identical regardless of which * bricks the consumer enabled — the verbs simply never consult the unused brick. */ interface ResilientState { readonly circuit: CircuitState; readonly bucket: TokenBucket; /** * Per-key backoff counter. Entries minted by `backoff` are `TimedRetryState`s * (they carry the streak's `firstFailureAtMs`, since every failure path holds * the observation instant); the field is typed at the `RetryState` supertype * because a key that has never failed has no streak, and a slice persisted * before the origin existed rehydrates without one. Still plain data. */ readonly retry: Readonly>; readonly cache: TtlCache; readonly calls: Readonly>>; /** * The instant of the latest clocked transition this slice saw — the `at` of * the last `attempt` / `resume` / `settleFailed`, settled Msg or timer fire. * `timer` counts the soonest deadline down from it, so the built-in `timer` * Sub gets a relative `ms` without anything reading a clock. `0` until the * first clocked transition. */ readonly clockMs: number; } /** * The failures a run handler may return (ADR 0021). `port_rejected` is the * work failing — carry the cause beside the tag (`err({ _tag: "port_rejected", * cause })`); `deadline_exceeded` is a handler that timed the work out itself. * Either one settles as `_run_err` and feeds the retry / breaker. Any * other failure is a contract breach and goes to the error sink. */ type RunErr = TaggedError<"port_rejected" | "deadline_exceeded">; /** * The one effect this knob emits: "run the work for `key` with `input`". It is * `Cmd.define`d, so the handler you write for it returns an outcome and the * engine mints `_run_ok` / `_run_err` (ADR 0021). It carries no * closure — `input` is plain data (invariant 3). */ declare function runCmdDef(name?: N, settledCmd?: (cmd: CmdValue, { readonly key: string; readonly input: I; }, R, RunErr>) => CmdValue, { readonly key: string; readonly input: I; }, R, RunErr>): CmdDef<`${N}_run`, { readonly key: string; readonly input: I; }, R, { readonly [detail: string]: unknown; readonly _tag: "deadline_exceeded"; } | { readonly [detail: string]: unknown; readonly _tag: "port_rejected"; }>; /** * The type of the `Cmd.define` definition that `runCmdDef` returns for a * resilient call's run Cmd. */ type RunCmdDef = ReturnType>; /** * The run Cmd value. `R` is its settle value — `unknown` reads any knob's run * Cmd; the knob's own verbs emit it at their `R`, which is what lets a machine * list `cmds: [rc.run]` and take the verbs' Cmds as its own. */ type RunCmd = CmdOf>; /** * The settle Msgs the engine mints from a run handler's outcome: * `_run_ok` carrying the handler's `value`, `_run_err` carrying its * declared `error`. Each carries the run Cmd it settles (`cmd.key` names the * call) and the `at` the engine stamped. Both are generic in the knob's name * family `N`, so two knobs named apart land in two `update` cells whose * payloads are already narrowed. * * They are the `SettledOk` / `SettledErr` pair `Cmd.define` mints, spelled out * so a helper that folds the error into a richer type of its own (llm-call's * `LlmErr`, jev-ask's `JevAskErr`) can hand `settle` its Msg with `E` widened. */ type SucceedMsg = { readonly _tag: ResilientOkType; readonly cmd: RunCmd; readonly value: R; readonly at: number; }; /** * The Msg the engine mints when a resilient call's handler fails: * `_run_err`, carrying the Cmd and the error. */ type FailMsg = { readonly _tag: ResilientErrType; readonly cmd: RunCmd; readonly error: E; readonly at: number; }; /** * What `settle` reads off a settled Msg: the call's `key` (on `cmd`), the * engine's `at`, and the handler's `value` or `error`. {@link SucceedMsg} and * {@link FailMsg} are both one of these, so an engine-minted Msg passes * straight in; a helper that settles from its own data (a fallback answer, a * compaction summary) builds the record without inventing a whole run Cmd. */ type SettleMsg = { readonly _tag?: ResilientOkType; readonly cmd: { readonly key: string; }; readonly value: R; readonly at: number; } | { readonly _tag?: ResilientErrType; readonly cmd: { readonly key: string; }; readonly error: unknown; readonly at: number; }; /** * How a settled call ended — the third thing `settle` hands back, and the only * place the port's value can be read from. * * - `done` — the port answered; `value` is its result. * - `failed` — no retry is left (or no retry brick); `error` is the last * failure. * - `retrying` — backed off; the retry timer is armed and the call is still * live. */ type SettleOutcome = { readonly kind: "done"; readonly value: R; } | { readonly kind: "failed"; readonly error: unknown; } | { readonly kind: "retrying"; }; /** * What `settle` returns: the settled slice, the Cmds it emitted, and the * {@link SettleOutcome}. One record, so the slice update and the result read * cannot be split apart in a hand-wired `update` cell. */ interface SettleResult { readonly call: ResilientState; readonly cmds: readonly RunCmd[]; readonly outcome: SettleOutcome; } /** * The deadline Msg tag this knob's timers dispatch, derived from its name the * same way the settle Msgs are. The DEFAULT family keeps the bare * `"deadline_exceeded"` literal. */ type ResilientDeadlineType = N extends DefaultResilientName ? "deadline_exceeded" : `${N}_deadline`; /** * The name a deadline carries for the `N` family — `undefined` for the * default family (no name at all, so the bare literal is dispatched), the name * itself otherwise. One conditional, so the value and {@link * ResilientDeadlineType} can never disagree about which family is unnamed. */ type DeadlineNameOf = N extends DefaultResilientName ? undefined : N; /** * The retry / deadline timer Msg — a `DeadlineExceeded` whose tag is this * knob's ({@link ResilientDeadlineType}), keyed by the call `key` through the * Sub `id`. Bare `ResilientTimerMsg` is the default family's, so it is the same * `DeadlineExceeded` it has always been. */ type ResilientTimerMsg = DeadlineExceeded>; /** * The plain-data error a deadline-failed call settles with. A `{_tag, ...}` * sentinel — NEVER a `new Error(...)` — so the slice stays JSON-serializable * (Error objects round-trip to `{}` and carry a stack trace, both of which break * the slice's durability invariant). `id` / `atMs` echo the timer that fired so * a consumer can attribute the failure to its deadline. */ type DeadlineExceededError = { readonly _tag: "deadline_exceeded"; readonly id: string; readonly atMs: number; }; /** * Build a resilient-call knob from `config`. `rng` is injected for retry * jitter — pass a fixed `() => 0.5` in tests to pin backoff; defaults to * `Math.random` (read at the verb boundary, never inside a brick op). It is * curried onto the factory rather than threaded through every verb so callers * spell the determinism choice once. * * Returns plain functions and the run Cmd def (ADR 0022) — see the module doc * for the wiring. `I` is the work's input type, `R` its result type. */ declare function createResilientCall(config: ResilientConfig & { readonly settledCmd?: (cmd: CmdValue, { readonly key: string; readonly input: I; }, R, RunErr>) => CmdValue, { readonly key: string; readonly input: I; }, R, RunErr>; }, rng?: () => number): { name: N; /** The `Cmd.define`d run Cmd; list it in the machine's `cmds`. */ run: CmdDef<`${N}_run`, { readonly key: string; readonly input: I; }, R, { readonly [detail: string]: unknown; readonly _tag: "deadline_exceeded"; } | { readonly [detail: string]: unknown; readonly _tag: "port_rejected"; }>; init: () => ResilientState; attempt: (s: ResilientState, key: string, input: I, at: number) => readonly [ResilientState, readonly RunCmd[]]; resume: (s: ResilientState, at: number) => ResilientState; settle: (s: ResilientState, msg: SettleMsg) => SettleResult; settleFailed: (s: ResilientState, key: string, error: unknown, at: number) => readonly [ResilientState, readonly RunCmd[]]; onTimer: (slice: ResilientState, msg: { readonly id: string; readonly atMs: number; }) => readonly [ResilientState, readonly RunCmd[]]; deadlines: (s: ResilientState) => readonly DeadlineSub>[]; timer: (s: ResilientState) => TimerDeps> | null; }; /** * Lift a knob result `[slice, cmds]` into a host `[State, cmds]` where the * slice lives at `state.resilience`. A convenience for the common single-slice * host; consumers with a differently-named field spread by hand. Pure — a thin * record rebuild, no clock / RNG. * * The record rebuild itself is `liftSlice` from the root entry (#231) — this * stays as the named, pre-keyed convenience for the `state.resilience` field, * unchanged in name, signature and subpath. */ declare function liftResilience; }, I, R, C extends Cmd>(state: S, result: readonly [ResilientState, readonly C[]]): readonly [S, readonly C[]]; export { initBucket as A, initCircuit as B, type CacheConfig as C, type DefaultResilientName as D, initWindow as E, type FailMsg as F, liftResilience as G, onFailure as H, onSuccess as I, record as J, refill as K, remaining as L, runCmdDef as M, tryConsume as N, type RunCmd as R, type SucceedMsg as S, type TokenBucket as T, type ResilientTimerMsg as a, type ResilientState as b, type DeadlineNameOf as c, type ResilientConfig as d, type CallBudget as e, type CallPhase as f, type CircuitConfig as g, type CircuitPolicy as h, type CircuitState as i, DEFAULT_RESILIENT_NAME as j, type DeadlineExceededError as k, type RateLimitConfig as l, type DeadlineConfig as m, type ResilientDeadlineType as n, type ResilientErrType as o, type ResilientOkType as p, type ResilientRunType as q, type RunCmdDef as r, type RunErr as s, type SettleMsg as t, type SettleOutcome as u, type SettleResult as v, type SlidingWindow as w, canPass as x, createResilientCall as y, defaultCircuitPolicy as z };