import { b as Cmd, P as Port } from './core-sEWVgnpI.js'; import { Q as QueueItem } from './index-DmoyvP-O.js'; /** * internal/flow/fan-out — scatter-gather over a bounded-concurrency work list. * * The Level-2 combinator that fans a batch of items out across at most * `concurrency` in-flight effects, gathers each item's result (or error), and * — once every item has settled — fires an optional `join` over the collected * results. It is the "map a list through an effect, but never run more than N * at once" knob. * * The recipe (which bricks it composes): * - `../work-queue` — fan-out's tracked items ARE work-queue items. Each * item carries the same `{ id, status, input }` lifecycle vocabulary * (`pending → running → done | failed`). The slice this knob owns is four * partitions over that one lifecycle, so the work-queue's status taxonomy * is the substrate rather than a parallel invention. We reuse its * `QueueItem` / `QueueItemStatus` TYPES and delegate the ledger * transitions to the `QueueAdapter` verbs (`../work-queue/adapter`): * `scatter` mints each pending record with `queue.enqueue`, and `launchUpTo` * flips `pending → running` with `queue.claim` (one positional claim per * launch). The lone exception is `settleOne`'s `running → done|failed` * flip — it must match "first id-match that is still `running`" to settle * exactly one of a DUPLICATE id, a status predicate the adapter verbs can't * express, so fan-out owns that one index (see `settleOne`). The async * `createQueue(store)` adapter is NOT used here because its `load → mutate * → save` reads the clock and lives at an I/O boundary, while a combinator's * verbs must be pure (invariant 2) — fan-out binds the pure `QueueAdapter` * to its in-Model ledger instead, the same route `monitored-run` / * `idempotent-intake` / `saga` take. The slice lives in the Model instead — * durable + replayable, the two non-negotiables every knob preserves. * * Typical wiring (combinator form — splice the hooks into your machine): * * const fan = createFanOut({ * concurrency: 4, * idOf: (url) => url, // stable, pure identity * of: (url) => ({ _tag: "crawl", url }), // the per-item effect, as data * join: (results) => ({ _tag: "report_done", results }), * }); * * // in `update`: * start_crawl: (s, m) => { const [fanOut, cmds] = fan.scatter(s.fanOut, m.urls); * return [{ ...s, fanOut }, cmds]; }, * crawl_ok: (s, m) => { const [fanOut, cmds] = fan.itemOk(s.fanOut, m.id, m.report); * return [{ ...s, fanOut }, cmds]; }, * crawl_err: (s, m) => { const [fanOut, cmds] = fan.itemErr(s.fanOut, m.id, m.error); * return [{ ...s, fanOut }, cmds]; }, * * Every verb is PURE: it returns a NEW slice plus the Cmds to perform (the * `of(item)` effects for newly-launched items, and at most one `join` Cmd when * the batch completes). The reducer never reads a clock or RNG — item identity * is supplied by the caller's `idOf` so `scatter` is deterministic, and the * launch effects are plain data the runtime performs (invariant 3). * * Fan-out does NOT own the interpret handler for a launched `of(item)` Cmd: `of` * already produces a fully caller-defined Cmd, so the consumer's own * `interpret` performs the effect and routes Ok/Err back to the `itemOk` / * `itemErr` verbs. `completion(ports)` is the one piece fan-out CAN pre-wire * generically: emitting the gathered batch onto a typed Port when the batch * completes, for consumers that observe completion out-of-band rather than * through the `join` Cmd. * * NOT a substrate primitive: it depends only on `../work-queue`'s pure types + * blessed ops and the core `Cmd` / `Port` types. Internal since #48 — not * published on any subpath; reached from inside the package as * `internal/flow/fan-out`. */ /** * One settled-OK item: the original `input` and the `result` its effect * produced. Mirrors the spec slice's `done: {item, result}[]` — `item` is the * caller's input value (not the internal `QueueItem` envelope), so a consumer * reading `done` gets back exactly what it scattered. */ interface FanOutDone { /** The original scattered input value. */ readonly item: I; /** The result the item's effect produced, routed in via `itemOk`. */ readonly result: R; } /** * One settled-error item: the original `input` and the `error` its effect * surfaced. `error` is `unknown` — fan-out carries it forward verbatim (an * `Error`, a tagged result, a string) for the consumer's reducer to read, * never interpreting it (same discipline as `retry-backoff`'s `lastError`). */ interface FanOutFailed { /** The original scattered input value. */ readonly item: I; /** The error the item's effect surfaced, routed in via `itemErr`. Carried, never interpreted. */ readonly error: unknown; } /** * The slice this knob owns — four partitions over the work-queue item * lifecycle, plus the work-queue records the verbs thread the lifecycle * through. * * Why both the spec's four arrays AND `items`: * - The four arrays (`pending` / `running` / `done` / `failed`) are the * SPEC's public read surface — what a consumer's view renders and what * `isComplete` reads. They hold caller-facing values (`I`, or * `FanOutDone` / `FanOutFailed`), not the internal id-bearing envelope. * - `items` is the work-queue ledger: one `QueueItem` per scattered item, * carrying the stable `id` (from `config.idOf`) that `itemOk` / `itemErr` * address and the `status` that decides launch-eligibility. It is the * single source of truth; the four arrays are a derived projection kept in * lockstep so consumers never re-scan `items` to render a partition. * * Every field is `readonly` and the whole slice is JSON-serializable (plain * arrays + the work-queue's plain `QueueItem` records), so it round-trips * through a consumer's `Store` unchanged — durable across DO eviction. */ interface FanOutState { /** Items accepted but not yet launched (queue back-pressure beyond `concurrency`). */ readonly pending: readonly I[]; /** Items whose `of(item)` effect is in flight (size never exceeds `concurrency`). */ readonly running: readonly I[]; /** Items whose effect resolved OK, with the result it produced. */ readonly done: readonly FanOutDone[]; /** Items whose effect failed, with the error it surfaced. */ readonly failed: readonly FanOutFailed[]; /** * The work-queue ledger: one record per scattered item, keyed by the * caller's `idOf`. The single source of truth the four arrays project from. */ readonly items: readonly QueueItem[]; /** * Index into `done` where the CURRENT wave's OK results begin. `done` is * append-only and accumulates across every wave (so a consumer reading * `done` sees the full history), but `join` must fold only the wave that * just drained — not the cumulative total. A wave opens when `scatter` * enqueues into a slice with nothing in flight; this marks `done.length` at * that moment so `join` receives exactly `done.slice(waveDoneFrom)`. */ readonly waveDoneFrom: number; /** * Index into `failed` where the current wave's failures begin. Symmetric to * `waveDoneFrom` — the wave boundary over the failure partition. Carried for * a consumer that wants to read only the current wave's failures; `join` * itself folds only OK results. */ readonly waveFailedFrom: number; /** * Whether the current wave has already fired its `join`. `join` fires at most * once per wave — set `true` at the completion edge so a stale settle that * re-reaches `isComplete` cannot re-fire it. A new `scatter` that opens a wave * resets it to `false`. */ readonly joined: boolean; } /** * The knob. `concurrency` caps how many `of(item)` effects are in flight at * once; `idOf` mints a stable, PURE identity per item (so `scatter` is * deterministic and `itemOk` / `itemErr` can address an item by id); `of` * turns an item into the launch Cmd; `join` (optional) turns the gathered * results into a single completion Cmd fired exactly once when every item has * settled. * * Field optionality follows the resilient-call rule — omit `join`, omit the * completion Cmd (a consumer that observes `isComplete` itself, or wires the * `completion` Port, doesn't need one). */ interface FanOutConfig { /** Max in-flight `of(item)` effects. Clamped to `>= 1` (a 0/negative cap would deadlock). */ readonly concurrency: number; /** * Stable, deterministic identity for an item. PURE — no clock, no RNG. The * id is what `itemOk` / `itemErr` address, so it must survive a round-trip * through the durable slice and match across the launch → settle gap. For * value-unique inputs (URLs, ids) this is often the identity function; for * structural inputs, a content hash or a caller-assigned key. */ readonly idOf: (item: I) => string; /** The per-item effect, as data. Performed by the consumer's own `interpret`. */ readonly of: (item: I) => C; /** * Optional: fold the gathered done-results into a single completion Cmd, * fired exactly once at the transition that empties `pending` + `running`. * Omit to drive completion off `isComplete` (or the `completion` Port) instead. */ readonly join?: (results: readonly R[]) => J; } /** The starting slice: nothing scattered yet. */ declare function initFanOut(): FanOutState; /** * Whether every scattered item has settled (no `pending`, no `running`). * Derived — reads the slice, never mutates. The verbs use it to decide when to * fire `join`; consumers can read it directly to branch their own phase. * * An empty fan-out (nothing ever scattered) is NOT complete: completion is "a * non-empty batch fully drained," so `isComplete(initFanOut())` is `false` and * a `scatter([])` of zero items also reads `false` (there was no batch to * complete). This keeps `join` from firing on a degenerate empty scatter. */ declare function isComplete(state: FanOutState): boolean; /** * Optional Port for observing batch completion out-of-band. When a consumer * passes `completion(ports)` a `complete` Port, the runtime side can emit the * gathered results onto it the moment `isComplete` flips true — distinct from * the in-band `join` Cmd (which threads back through `update`). Use the Port * for "tell the outside world the batch finished" without folding a completion * signal into the consumer's Msg union. */ interface FanOutPorts { /** Fires once with every gathered done-result when the batch completes. */ readonly complete: Port; } /** * Build the fan-out knob from `config`. Returns the uniform combinator * contract: `init` for the owned slice, the three settle verbs + the derived * `isComplete`, and `completion` for the optional out-of-band completion Port. * * No `subs` — fan-out runs no timers (the spec pins "Subs: none"). The * per-item effect's lifetime is owned by the consumer's `interpret`, and * completion is a pure function of the settle Msgs, so there is nothing * continuous to subscribe to. */ declare function createFanOut(config: FanOutConfig): { init: () => FanOutState; scatter: (state: FanOutState, items: readonly I[]) => readonly [FanOutState, readonly C[]]; itemOk: (state: FanOutState, id: string, result: R) => readonly [FanOutState, readonly (C | J)[]]; itemErr: (state: FanOutState, id: string, error: unknown) => readonly [FanOutState, readonly (C | J)[]]; isComplete: typeof isComplete; completion: (ports: FanOutPorts) => { /** * Emit the gathered done-results onto `ports.complete` iff `state` is a * just-completed batch. Idempotency is the caller's concern (call it once * per transition via `observe`); emitting to a Port with no subscribers * is a no-op at the runtime, so an extra call is harmless. */ emitOnComplete(emit: (port: Port, value: T) => void, state: FanOutState): void; }; }; export { type FanOutState as F, type FanOutConfig as a, type FanOutDone as b, type FanOutFailed as c, type FanOutPorts as d, createFanOut as e, isComplete as f, initFanOut as i };