import { C as CmdOf, a as CmdDef, e as SettledErr, f as TaggedError, d as SettledOk, T as TimerDeps, b as Cmd } from '../core-sEWVgnpI.js'; import { M as MsgType } from '../protocol-CqdURF0g.js'; import { a as DeadlineSub } from '../index-CCs-QGGu.js'; export { A as ArmTimer, e as CacheEntry, c as CacheEvictMsg, f as CacheEvictionDeps, C as CacheEvictionSub, D as DeadlineExceeded, g as DeadlineMsgType, h as DeadlineOpts, b as DeadlinesSub, T as TtlCache, i as cacheEvictMsg, j as cacheEvictionSub, k as cacheEvictionSubscribe, d as deadlineExceeded, l as deadlineMsgType, m as deadlineSub, n as deadlines, o as deadlinesSub, p as evictExpired, q as get, r as has, t as initCache, u as nextTimer, v as remove, w as set, x as setTimeoutArmTimer, s as subscribeDeadline, y as subscribeWith } from '../index-CCs-QGGu.js'; import { d as ResilientConfig, b as ResilientState, R as RunCmd, S as SucceedMsg, F as FailMsg, a as ResilientTimerMsg } from '../index-C1BK3MNo.js'; export { C as CacheConfig, e as CallBudget, f as CallPhase, g as CircuitConfig, h as CircuitPolicy, i as CircuitState, j as DEFAULT_RESILIENT_NAME, k as DeadlineExceededError, c as DeadlineNameOf, D as DefaultResilientName, l as RateLimitConfig, m as ResilientCallDeadlineConfig, n as ResilientDeadlineType, o as ResilientErrType, p as ResilientOkType, q as ResilientRunType, r as RunCmdDef, s as RunErr, t as SettleMsg, u as SettleOutcome, v as SettleResult, w as SlidingWindow, T as TokenBucket, x as canPass, y as createResilientCall, z as defaultCircuitPolicy, A as initBucket, B as initCircuit, E as initWindow, G as liftResilience, H as onFailure, I as onSuccess, J as record, K as refill, L as remaining, M as runCmdDef, N as tryConsume } from '../index-C1BK3MNo.js'; import { Rng, RetryPolicy } from '../retry-backoff/index.js'; import '@standard-schema/spec'; import '../types-CtM4tWPp.js'; /** * A minted credential: the opaque `value` to send on the wire, and the absolute * `expiresAt` (epoch milliseconds — the `Date.now()` scale) the issuer stamped * it with. Both fields are plain data so a `Token` is trivially serializable * into a consumer's `Store`. * * `value` is `string` because that is the universal shape of a bearer token / * API key / session cookie on the wire. A consumer whose refresh port yields a * richer object can JSON-encode it into `value`, or keep this module's slice as * the "is it fresh?" gate and hold the richer object elsewhere in their Model. */ interface Token { /** The opaque credential to present on each request (bearer token, API key). */ readonly value: string; /** Absolute expiry instant, epoch milliseconds. The `Date.now()` scale. */ readonly expiresAt: number; } /** * Pure configuration — the knob's only field. Carries no mutable state; * `TokenState` does. One config is shared across all the refreshes of one * logical credential (often a module-scope const). */ interface TokenRefreshConfig { /** * Refresh-ahead skew, in milliseconds. A token is treated as needing a * refresh once `at >= expiresAt - skewMs`, i.e. `skewMs` BEFORE its hard * expiry. This buys headroom so a call that starts just under the wire never * races a token that lapses mid-flight, and absorbs small client/server clock * disagreement. `0` means "refresh exactly at expiry"; a negative value is * clamped to `0` (a skew that pushes the trigger past expiry is meaningless). * * @default 0 */ readonly skewMs?: number; } /** * The token slice this knob owns — the Model field a consumer spreads in via * `init()`. A two-field record rather than a phase union because the two * dimensions are orthogonal: a token can be present-and-fresh, present-but-stale * (a 401 came back), absent, or absent-and-stale (cleared after a failed * refresh). Every combination is meaningful, so neither field implies the * other's value and a discriminated union would only manufacture impossible * arms. * * - `token` — the currently held credential, or `null` when none has been * minted yet (fresh boot) or the last refresh failed. * - `stale` — set by `on401` when the server rejected a request the client * believed valid. Forces the next `needsRefresh` to true regardless of * `expiresAt`; cleared by `refreshed` once a new credential lands. * * Both fields `readonly` so the whole slice threads safely through a pure * reducer and serializes into a `Store`. */ interface TokenState { /** The held credential, or `null` if none is available (boot / failed refresh). */ readonly token: Token | null; /** Whether a 401 has marked the held token unusable ahead of its `expiresAt`. */ readonly stale: boolean; } /** * The starting slice: no token held, not stale. The first `needsRefresh` after * this returns `true` (no token), so a consumer's first guarded call mints a * credential before going out. */ declare function initTokenRefresh(): TokenState; /** * The Cmd this knob emits to ask the runtime to mint a fresh token. Plain data * (no closure — invariant 1) carrying nothing: the refresh takes no input, and * the slice the result installs is read off the settled Msg, not this Cmd. * List it in the machine's `cmds`; its handler returns `ok(token)` or * `err({ _tag: "token_refresh_failed", … })`, and the engine mints * `refresh_token_ok` / `refresh_token_err`. */ declare const refreshToken: CmdDef<"refresh_token", Record, Token, { readonly [detail: string]: unknown; readonly _tag: "token_refresh_failed"; }>; /** The `refresh_token` Cmd value that `refreshTokenCmd` builds. */ type RefreshTokenCmd = CmdOf; /** Construct a `refresh_token` Cmd. */ declare function refreshTokenCmd(): RefreshTokenCmd; /** * The Msg the engine mints when the `refresh_token` handler returns * `ok(token)`: `value` is the freshly minted `Token`. Fold it with * `refreshed(state, msg.value)`. */ type TokenRefreshedMsg = SettledOk<"refresh_token", RefreshTokenCmd, Token>; /** * The Msg the engine mints when the handler returns * `err({ _tag: "token_refresh_failed", … })` — errors are data, never * swallowed. The slice is left untouched by a failed refresh: the held token * (if any) stays held and stale stays set, so the consumer can retry; clearing * it is the consumer's policy, expressed in their reducer. */ type TokenRefreshFailedMsg = SettledErr<"refresh_token", RefreshTokenCmd, TaggedError<"token_refresh_failed">>; /** The two Msgs a refresh can settle with. Union for a consumer's Msg type. */ type TokenRefreshMsg = TokenRefreshedMsg | TokenRefreshFailedMsg; /** * The knob: hand it a config, get back the slice initializer and the pure * verbs, plus the `refresh_token` Cmd def (`run`) to list in `cmds`. * * @example * ```ts * import { createTokenRefresh } from "@demlik/tea/resilience"; * * const tr = createTokenRefresh({ skewMs: 30_000 }); * const s0 = tr.init(); * const [s1, cmds] = tr.ensureFresh(s0, Date.now()); // cmds = [refreshTokenCmd()] * ``` */ declare function createTokenRefresh(config?: TokenRefreshConfig): { /** The `refresh_token` Cmd def — list it in the machine's `cmds`. */ run: CmdDef<"refresh_token", Record, Token, { readonly [detail: string]: unknown; readonly _tag: "token_refresh_failed"; }>; /** The slice initializer — spread into the consumer's `init`. */ init: typeof initTokenRefresh; needsRefresh: (state: TokenState, at: number) => boolean; on401: (state: TokenState) => TokenState; refreshed: (state: TokenState, token: Token) => TokenState; ensureFresh: (state: TokenState, at: number) => readonly [TokenState, readonly RefreshTokenCmd[]]; }; /** The shape `createTokenRefresh` returns — useful for typing a held knob. */ type TokenRefresh = ReturnType; /** * The authed-call knob. It is `ResilientConfig` widened by the token dimension: * * - `skewMs` — token-refresh's refresh-ahead skew (optional, defaults to 0). * - every `ResilientConfig` field (`retry` / `circuit` / `rateLimit` / * `cache` / `deadline`) — passed straight through to the resilient-call * knob, each still optional, each still "omit a brick → omit its gate". * * The token mint is not on the config: it is the `refresh_token` Cmd, and its * handler is yours. */ type AuthedConfig = ResilientConfig & TokenRefreshConfig; /** * The composed slice. Three plain-data fields, no closures: * * - `resilience` — resilient-call's entire slice (circuit, bucket, retry, * cache, calls). Owned and mutated only via resilient-call's verbs. * - `auth` — token-refresh's `{ token, stale }` slice. Owned and mutated only * via token-refresh's verbs. * - `authRetry` — per-key count of auth-retries (401 → refresh → retry) spent * on a call. Caps the dance at one retry per call so a credential the server * keeps rejecting cannot spin forever. A key absent from the record has * spent zero. Cleared when a call settles or a fresh `attempt` starts. * * `pendingAuthRetry` carries the inputs of calls parked waiting for the refresh * to land, keyed so `onRefreshed` can re-issue exactly those calls. Plain data — * `input` is the same payload the call was issued with. */ interface AuthedState { readonly resilience: ResilientState; readonly auth: TokenState; readonly authRetry: Readonly>; readonly pendingAuthRetry: Readonly>; } /** The two effects this knob emits: resilient-call's run, token-refresh's mint. */ type AuthedCmd = RunCmd | RefreshTokenCmd; /** * Every Msg the knob's verbs fold. Resilient-call's settle + timer Msgs, token- * refresh's refresh-result Msgs, and the 401 trigger the consumer dispatches * when a guarded call comes back unauthorized. */ type Unauthorized = { readonly _tag: typeof MsgType.Unauthorized; readonly key: string; readonly at: number; }; /** * The plain-data error a 401 we cannot fix settles with. A `{_tag, ...}` * sentinel — NEVER a `new Error(...)` — so the slice stays JSON-serializable * (an Error object round-trips to `{}` under JSON and carries a stack trace, * both of which break the slice's durability invariant once it is persisted * into a `Store` and reloaded). Mirrors resilient-call's `DeadlineExceededError` * sentinel discipline. `key` echoes the call that was rejected so a consumer can * attribute the failure. */ type UnauthorizedError = { readonly _tag: "unauthorized"; readonly key: string; }; /** * Build an authed-call knob from `config`. `rng` is injected for retry jitter * and threaded straight into the underlying resilient-call knob — pass a fixed * `() => 0.5` in tests to pin backoff; defaults to `Math.random` (read only at * the verb boundary inside resilient-call, never in a brick op). * * Returns the uniform L2 knob contract, widened by the auth verbs (`on401`, * `onRefreshed`, `installToken`). `I` is the port input type, `R` the result. */ declare function createAuthedCall(config?: AuthedConfig, rng?: () => number): { /** The call's `Cmd.define`d run Cmd — list it in `cmds`. */ run: CmdDef<"resilient_run", { readonly key: string; readonly input: I; }, R, { readonly [detail: string]: unknown; readonly _tag: "deadline_exceeded"; } | { readonly [detail: string]: unknown; readonly _tag: "port_rejected"; }>; /** token-refresh's `refresh_token` Cmd def — list it in `cmds`. */ refresh: CmdDef<"refresh_token", Record, Token, { readonly [detail: string]: unknown; readonly _tag: "token_refresh_failed"; }>; init: () => AuthedState; attempt: (s: AuthedState, key: string, input: I, at: number) => readonly [AuthedState, readonly AuthedCmd[]]; succeed: (s: AuthedState, msg: SucceedMsg) => readonly [AuthedState, readonly AuthedCmd[]]; fail: (s: AuthedState, msg: FailMsg) => readonly [AuthedState, readonly AuthedCmd[]]; on401: (s: AuthedState, key: string, at: number) => readonly [AuthedState, readonly AuthedCmd[]]; installToken: (s: AuthedState, token: Token) => AuthedState; onRefreshed: (s: AuthedState, at: number) => readonly [AuthedState, readonly AuthedCmd[]]; onTimer: (s: AuthedState, msg: ResilientTimerMsg | { readonly id: string; readonly atMs: number; }) => readonly [AuthedState, readonly AuthedCmd[]]; /** token-refresh's call-boundary verb, re-exposed for proactive expiry refresh. */ needsRefresh: (s: AuthedState, at: number) => boolean; deadlines: (s: AuthedState) => readonly DeadlineSub[]; timer: (s: AuthedState) => TimerDeps> | null; }; /** The shape `createAuthedCall` returns — useful for typing a held knob. */ type AuthedCall = ReturnType>; /** * Lift a knob result `[slice, cmds]` into a host `[State, cmds]` where the slice * lives at `state.authed`. 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. */ declare function liftAuthed; }, I, R, C extends Cmd>(state: S, [slice, cmds]: readonly [AuthedState, readonly C[]]): readonly [S, readonly C[]]; /** * internal/resilience/retry-to-success — run a fallible async port through BOUNDED * retry + exponential backoff to success-or-terminal-give-up, and hand the * caller a `Promise` that resolves on the first success or REJECTS with a * checkable {@link RetryExhaustedError} the moment the retry bound is hit. * * This is the retry-side parallel to `./await-terminal`. `runToTerminal` gives a * caller with a one-shot decision *machine* a fire-and-await `Promise` * without wiring `observe`; this gives a caller with a one-shot fallible *port* * a fire-and-await `Promise` without either hand-folding the * `./retry-backoff` primitives (`recordFailure` / `shouldRetry` / `nextDelayMs`) * into their own reducer each time, or standing up the full `./resilient-call` * verb contract (`init` + `attempt`/`succeed`/`fail`/`onTimer` + `subs` + * `handlers`) when they want retry only and none of cache / circuit / rate-limit * / deadline. * * It adds NO new runtime capability and NO new backoff math — the whole retry * decision is `./retry-backoff` exactly as `resilient-call`'s `backoff` verb * wires it: * - `initRetry()` seeds the per-call attempt counter. * - `recordFailure(retry, error)` folds each thrown failure (attempt++). * - `shouldRetry(retry, policy)` is the terminal-at-`maxAttempts` bound — the * `maxAttempts`-th recorded failure refuses another attempt (attempts * `0 .. maxAttempts-1` run; the port is invoked at most `maxAttempts` times). * - `nextDelayMs(retry, policy, rng)` is the exp+jitter+cap delay before the * next attempt, computed on the incremented state — same call order as * `resilient-call`. * * Where the clock / RNG live: injected, never read on the module's own behalf, * mirroring `retry-backoff`'s purity discipline. `rng` is an {@link Rng} (branded * `[0, 1)` via `asRng` at the caller boundary) threaded straight into * `nextDelayMs`; the wait itself is a `sleep(ms)` port defaulting to a real * `setTimeout`, injectable so a test can drive the backoff schedule * deterministically without touching wall-clock timers. * * Exhaustion is NEVER a silent swallow: at the bound the returned promise * rejects with {@link RetryExhaustedError} (carrying the attempt count and the * final failure), the retry-side dialect of `await-terminal`'s * `TerminalTimeoutError` — a distinct `instanceof`- and `_tag`-checkable * rejection. * * NOT a substrate primitive: it depends on nothing from `../index`, only on the * leaf `retry-backoff` utility. Internal to the package * (`src/internal/resilience/`, #46), not a published subpath. */ /** * Raised when `retryToSuccess` exhausts the retry bound without a success — the * `maxAttempts`-th recorded failure refuses another attempt. Follows the tea * error dialect (`override readonly name`) and carries a `_tag` discriminant, so * a caller can branch on it by `instanceof` or on the tag. It carries the number * of attempts made and the final failure (`lastError`) so the terminal give-up * is a distinct, checkable rejection — never a silent resolve, and never a * swallowed error. */ declare class RetryExhaustedError extends Error { /** How many times the port was invoked before giving up (= `policy.maxAttempts`). */ readonly attempts: number; /** The failure the final attempt threw — carried, never interpreted. */ readonly lastError: unknown; readonly name = "RetryExhaustedError"; readonly _tag: "RetryExhaustedError"; constructor( /** How many times the port was invoked before giving up (= `policy.maxAttempts`). */ attempts: number, /** The failure the final attempt threw — carried, never interpreted. */ lastError: unknown); } /** Options for {@link retryToSuccess}. */ interface RetryToSuccessOptions { /** * The `[0, 1)` jitter source threaded into `nextDelayMs`, branded via * `asRng` at construction (a raw `() => number` is rejected by the type). * Injected for deterministic backoff in tests; defaults to `defaultRng` * (`Math.random`), read only at the delay boundary — never inside the loop's * decision. */ readonly rng?: Rng; /** * The wait between attempts, given the backoff delay in ms. Injectable so a * test can drive the retry schedule without wall-clock timers (and assert the * exact delays); defaults to a real `setTimeout`. The delay value is always * `./retry-backoff`'s `nextDelayMs` — this port only realizes the wait. */ readonly sleep?: (ms: number) => Promise; /** * Whether a thrown failure may be retried. Defaults to `() => true`. When it * returns `false` the failure is terminal at once: `retryToSuccess` rejects * with the thrown error itself (not a {@link RetryExhaustedError}), and the * failure consumes no budget. A `retryable` that throws replaces the failure * it was asked about: its throw is what rejects. */ readonly retryable?: (error: unknown) => boolean; } /** * Fire-and-await bounded retry: invoke the fallible `port`, and on each thrown * failure fold it through `./retry-backoff` — record it, and if the policy * still permits an attempt, back off `nextDelayMs` and retry; otherwise REJECT * with {@link RetryExhaustedError}. Resolves with the port's value on the first * success. * * The port is invoked at most `policy.maxAttempts` times (attempts * `0 .. maxAttempts-1`); the `maxAttempts`-th failure is terminal. Every failure * is either retried or surfaced on the rejection's `lastError` — none is * swallowed. A failure `opts.retryable` refuses is rethrown as it is, at once. * * @param port the fallible work — throws on failure, resolves with `R` on success. * @param policy the bounded-retry curve (`baseMs` / `factor` / `capMs` / * `maxAttempts` / `jitter`) from `./retry-backoff`. * @param opts optional injected `rng` (jitter) and `sleep` (the wait) — see * {@link RetryToSuccessOptions}. */ declare function retryToSuccess(port: () => Promise, policy: RetryPolicy, opts?: RetryToSuccessOptions): Promise; export { type AuthedCall, type AuthedCmd, type AuthedConfig, type AuthedState, DeadlineSub, FailMsg, type RefreshTokenCmd, ResilientConfig, ResilientState, ResilientTimerMsg, RetryExhaustedError, type RetryToSuccessOptions, RunCmd, SucceedMsg, type Token, type TokenRefresh, type TokenRefreshConfig, type TokenRefreshFailedMsg, type TokenRefreshMsg, type TokenRefreshedMsg, type TokenState, type Unauthorized, type UnauthorizedError, createAuthedCall, createTokenRefresh, initTokenRefresh, liftAuthed, refreshToken, refreshTokenCmd, retryToSuccess };