import { b as Cmd, a as CmdDef, T as TimerDeps } from '../core-sEWVgnpI.js'; import { RetryPolicy } from '../retry-backoff/index.js'; import { a as DeadlineSub } from '../index-CCs-QGGu.js'; import { b as ResilientState, a as ResilientTimerMsg, R as RunCmd, F as FailMsg, S as SucceedMsg, g as CircuitConfig, l as RateLimitConfig, m as DeadlineConfig } from '../index-C1BK3MNo.js'; import '@standard-schema/spec'; import '../types-CtM4tWPp.js'; /** * internal/paginate/paginator — the cursor/offset/page-token walk loop as pure * state + ops. * * Same shape as `../../../retry-backoff`, `../../resilience/circuit-breaker`, * and `../../resilience/rate-limit`: a state type plus pure transition functions, * host-agnostic by construction. Nothing here reads the clock, the RNG, or any * I/O on its own behalf — the consumer fetches a page out-of-band and folds the * *result* back in through `recordPage`. That keeps every function inside TEA's * invariant 2 (transitions are pure: same inputs → same outputs) so a consumer * can thread the walk through `update` and exercise it with `replay` / the pbt * fold without a fake network. * * Every op returns a NEW state value and never mutates its input (invariant 1 — * state is a value, not a place). All fields are `readonly` and plain data, so * the whole walk is trivially JSON-serializable into a consumer's `Store` * and survives a Durable-Object eviction / reload mid-walk: the cursor lives in * the Model, not a closure (the durability + replay non-negotiables every TEA * knob preserves). * * ## The cursor is opaque, and the consumer advances it * * A paginated API hands back a *next cursor* however it likes: an offset * (`?offset=40`), a page token (`?pageToken=ey…`), a "next" URL, or `null` at * the end. This module is generic in `Cursor` and never inspects it — it only * carries it forward. The consumer (who alone knows the API's shape) reads the * next cursor off the just-fetched page and passes it to `recordPage`: * * const next = page.nextPageToken ?? null; // consumer-specific extraction * const walk = recordPage(state.walk, page.items.length, next); * * Passing `next: null` (or a missing `undefined` cursor — the op compares with * loose `== null`) means "the API said there is no next page" → the walk * finishes (`done`). Passing a `Cursor` means "fetch this one next" → the walk * either keeps `fetching` or `pauses` for backpressure (below). Decoupling the * extraction from the op is the same discipline `circuit-breaker` uses for the * clock: the impure / domain-specific bit (`nextCursor(page)`) lives at the * call site; the op stays a pure fold over the extracted value. * * ## The phase machine * * Four phases, each a discriminated-union arm carrying ONLY the data that phase * needs so impossible states are unrepresentable (pattern 11): * * - **idle** — created, not started. No cursor is armed yet; `start` arms the * first one. Carries the running `seen` / `pages` counters (both 0 here, but * present on every phase so a consumer reads them uniformly). * * - **fetching** — a page request for `cursor` is outstanding. The walk sits * here while the consumer's fetch is in flight; `recordPage` resolves it. * Carries the `cursor` being fetched so a post-eviction resume re-issues the * SAME request (idempotent retry) rather than skipping a page. * * - **paused** — backpressure tripped. The API still has more pages (a non-null * next cursor), but `seen` has reached `highWaterMark` and the consumer has * not drained yet. Carries the `cursor` to resume from. No fetch is * outstanding — the loop is deliberately idle until `resume`. This is the * valve that stops a fast producer (the API) from outrunning a slow consumer * (whatever processes each page) and blowing memory. * * - **done** — the API returned a null next cursor; the walk is exhausted. A * terminal phase: `start` / `recordPage` / `resume` are all no-ops on it * (idempotent completion — a late duplicate result can't un-finish a walk). * * ### Transition table * * Rows are the current phase; columns are the op. `→` denotes the next phase; * `self` means unchanged (a no-op for that (phase × op) pair). `next` is the * cursor the consumer extracted from the page; `hwm` is `highWaterMark`. * * | from \ op | start | recordPage(count, next) | resume | * | ----------- | -------------- | -------------------------------------------------------------------- | ------------------------------ | * | idle | → fetching(c0) | self *(¹)* | self | * | fetching | self | seen=max(0,seen+count), pages+=1; next==null → done; seen≥hwm → paused(next); else → fetching(next) | self | * | paused | self | self *(¹)* | seen= hwm` is satisfied vacuously only when * `hwm <= 0` would pause immediately, so we treat `hwm <= 0` as "unbounded" and * never pause. The walk then runs flat-out, `fetching → fetching` until `done`. * * Internal since #47 — not published on any subpath; reached from inside the * package as `internal/paginate/paginator`. Same one-shape-per-package rule as `work-queue`, `retry-backoff`, * `circuit-breaker`, and `rate-limit`. It is the L1 escape hatch the * `paginated-walk` composition builds its walk loop on. */ /** * Paginator policy — pure configuration, no mutable state. One policy is shared * across the whole walk (often a module-scope const). `PaginatorState` carries * the cursor + counters; this carries the knobs they're compared against. * * Generic in `Cursor` so `firstCursor` matches whatever the API's cursor shape * is — an offset `number`, a page-token `string`, a `{ after: string }` record, * etc. The module never inspects the cursor; the type just threads through. */ interface PaginatorPolicy { /** * The cursor the walk fetches first, armed by `start`. For an offset API this * is typically `0`; for a token API, `null`-or-empty-meaning-"first page" is * the API's call, so pass whatever sentinel the API treats as page one. */ readonly firstCursor: Cursor; /** * Backpressure threshold: the number of un-drained items at which the walk * pauses instead of fetching the next page. `recordPage` parks in `paused` * once `seen >= highWaterMark`; `drain` + `resume` re-open the valve. * * A non-positive value (`<= 0`) disables backpressure — the walk never pauses * and runs `fetching → fetching` until the API exhausts. Use that when the * consumer processes each page synchronously inside `recordPage` and there is * nothing to back up. */ readonly highWaterMark: number; } /** * Sensible defaults: start from a numeric offset of `0`, pause after 1000 * un-drained items. Tuned for an offset-paginated REST API whose consumer * processes pages asynchronously; override per call site (especially * `firstCursor`, which is API-specific) rather than mutating this shared const. * * Typed as `PaginatorPolicy` because the only honest default cursor is * the numeric offset `0`; a token-based API supplies its own `firstCursor` and * its own `PaginatorPolicy`. */ declare const defaultPaginatorPolicy: PaginatorPolicy; /** * The walk'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 `done` state that still holds a pending cursor, no `idle` state * mid-fetch. 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 / a Durable-Object reload. * * Two counters ride on every phase so a consumer reads them uniformly without * narrowing first: * - `seen` — items produced by the API but not yet drained (backpressure gauge). * - `pages` — total pages recorded so far (progress / observability). * * - `idle` — not started; `start` arms `firstCursor`. * - `fetching` — a page request for `cursor` is outstanding. * - `paused` — backpressure tripped; `cursor` is the page to resume from. * - `done` — API exhausted (null next cursor); terminal. */ type PaginatorState = { readonly phase: "idle"; readonly seen: number; readonly pages: number; } | { readonly phase: "fetching"; readonly cursor: Cursor; readonly seen: number; readonly pages: number; } | { readonly phase: "paused"; readonly cursor: Cursor; readonly seen: number; readonly pages: number; } | { readonly phase: "done"; readonly seen: number; readonly pages: number; }; /** The starting state: idle, nothing seen, no pages recorded. */ declare function initPaginator(): PaginatorState; /** * Arm the first fetch. PURE — returns a new state; the input is never mutated. * * - `idle` → `fetching(firstCursor)`. This is the only phase `start` acts on. * - any other phase → unchanged. Re-arming a walk that has already begun (or * finished) would skip back to page one and double-count; a stray `start` * after launch is absorbed, not honored. Use `initPaginator()` to begin a * genuinely fresh walk. */ declare function start(state: PaginatorState, policy: PaginatorPolicy): PaginatorState; /** * Record the result of the outstanding fetch and decide what comes next. PURE — * returns a new state; the input is never mutated. * * `count` is how many items the just-fetched page yielded (added to `seen` for * backpressure accounting). `next` is the cursor the consumer extracted from the * page — a `Cursor` to fetch next, or `null`/`undefined` (a missing optional * cursor field) if the API signalled the end. * * - `fetching` → `seen = max(0, seen + count)`, `pages += 1`, then branch on * `next`: * - `next == null` → `done` (API exhausted; loose-null so a * missing/`undefined` cursor also finishes). * - `seen >= highWaterMark` → `paused(next)` (backpressure; `hwm <= 0` * disables this branch — see policy docs). * - otherwise → `fetching(next)` (keep walking). * - any other phase → unchanged. A result with no fetch outstanding (a late * duplicate, a double-dispatch) must not advance the cursor or double-count; * it is absorbed. See the module header's note ¹. * * `count` is floored into the gauge: a non-finite `count` (`NaN`/`Infinity`) is * treated as `0`, and the additive sum is clamped at `0`. A record can only hold * or raise `seen`; only `drain` lowers it. This keeps a stray negative or * non-finite count from poisoning the `seen >= highWaterMark` comparison and * silently defeating backpressure. * * The new `seen` total — not the pre-page value — is what the backpressure check * reads, so a single page large enough to cross the mark pauses immediately * rather than fetching one more first. */ declare function recordPage(state: PaginatorState, count: number, next: Cursor | null | undefined, policy: PaginatorPolicy): PaginatorState; /** * Acknowledge that the consumer finished processing `n` items, lowering the * backpressure gauge. PURE — returns a new state; the input is never mutated. * * Subtracts `n` from `seen`, floored at 0 (a consumer that over-acks, or acks a * page recorded before a reload, can never drive `seen` negative). `n <= 0` is a * no-op on the count. `drain` does NOT change the phase — it only frees * headroom; `resume` is the separate, explicit decision to re-issue a fetch once * the headroom exists. Splitting "I drained" from "I want to continue" lets a * consumer drain in several steps and resume once. * * Works on every phase: a consumer may drain while still `fetching` (the gauge * just drops, no pause was reached) or while `paused` (freeing room for a later * `resume`). On `done` the gauge can still be drained for accurate final * accounting, though it no longer gates anything. */ declare function drain(state: PaginatorState, n: number): PaginatorState; /** * Re-open the backpressure valve after a `drain`. PURE — returns a new state; * the input is never mutated. * * - `paused` AND `seen < highWaterMark` → `fetching(cursor)`: the consumer has * drained below the mark, so re-issue the parked fetch. * - `paused` but `seen >= highWaterMark` → unchanged. There is still no * headroom; the valve stays shut until a `drain` lowers `seen`. A consumer * that resumes optimistically can't defeat the backpressure. (When `hwm <= * 0` backpressure is disabled, so the walk never reaches `paused` and this * branch is unreachable — but the guard reads `< hwm` consistently, and a * non-positive `hwm` makes `seen < hwm` false for any non-negative `seen`, * correctly refusing to resume a state that should never have paused.) * - any other phase → unchanged. Resuming a walk that isn't paused (idle, * fetching, done) is a no-op. * * See the module header's note ². */ declare function resume(state: PaginatorState, policy: PaginatorPolicy): PaginatorState; /** * Whether the walk has finished (the API returned a null next cursor). PURE, * read-only. A derived predicate so a consumer's reducer can branch * (`if (isDone(walk)) return [doneState, [joinCmd]]`) without re-checking the * `phase` discriminant by hand at every call site. */ declare function isDone(state: PaginatorState): boolean; /** * The paginated-walk knob. Generic in `Cursor` (the opaque page handle the * upstream API hands back — offset, page token, "next" URL, …) and `Page` (the * shape your fetch port resolves with). * * `nextCursor` and `onPage` are PURE config functions applied at the verb * boundary, never stored in the slice or in a Cmd (invariant 3 — Cmds are * plain data, not closures). `nextCursor(page)` extracts the API's next-page * handle (or `null` at the end); `onPage(page)` yields the Cmds the consumer * wants emitted for each successfully fetched page (index rows, write to R2, * dispatch a downstream Msg — whatever; an empty array is fine). * * The resilience bricks (`retry` / `circuit` / `rateLimit` / `deadline`) are * the SAME optional knobs `resilient-call` exposes — paginated-walk extends it. * `rateLimit` is the brick that keeps the walk from 429-ing the upstream. */ interface PaginatedWalkConfig { /** * The cursor the walk fetches first. For an offset API this is typically `0`; * for a token API, whatever sentinel the API treats as "page one" (often * `null` or `""`). Threaded into `paginator`'s `firstCursor`. */ readonly firstPage: Cursor; /** * Extract the next cursor from a just-fetched page. Return a `Cursor` to keep * walking, or `null` when the API signalled the end (the walk finishes). PURE * + consumer-specific (only the consumer knows the API's pagination shape). */ readonly nextCursor: (page: Page) => Cursor | null; /** * The Cmds to emit for each successfully fetched page — the consumer's work * per page (index, persist, fan out, …). Returns plain-data Cmds; `[]` is a * valid "I process the page synchronously elsewhere" answer. PURE. */ readonly onPage: (page: Page) => readonly EmittedCmd[]; /** * How many items a page contributes to the paginator's backpressure gauge * (`seen`). Defaults to `1` per page (count pages, not items) when omitted; a * consumer that wants per-item backpressure returns `page.items.length`. PURE. */ readonly pageSize?: (page: Page) => number; /** * Backpressure threshold handed to the paginator. `seen >= highWaterMark` * parks the walk in `paused` instead of fetching the next page. Non-positive * (the default `0`) disables backpressure — the walk runs flat out until the * API exhausts. See `../paginator`'s `highWaterMark` docs. */ readonly highWaterMark?: number; /** Exponential-backoff retry policy for a transient page-fetch failure. */ readonly retry?: RetryPolicy; /** Circuit breaker around the page fetch (one upstream → one breaker). */ readonly circuit?: CircuitConfig; /** Token-bucket rate limit — the "don't 429 the upstream" knob. */ readonly rateLimit?: RateLimitConfig; /** Overall wall-clock deadline per individual page fetch. */ readonly deadline?: DeadlineConfig; } /** * The slice. `walk` is the cursor/phase/counters from `../paginator`; * `resilience` is the `../resilient-call` slice that gates the page fetch. * Every field is JSON-serializable, so the whole walk survives a reload. * * The two move in lockstep: `walk` decides WHICH cursor to fetch next, while * `resilience` decides HOW that fetch is attempted (gated, retried, backed * off). `pageOk` advances `walk`; `pageErr` defers to `resilience` and leaves * `walk` parked on the same cursor until the page truly settles. */ interface PaginatedWalkState { readonly walk: PaginatorState; readonly resilience: ResilientState; } /** * The page-fetch effect this knob emits: the inherited `resilient_run` Cmd from * resilient-call, whose `input` is the `Cursor` to fetch and whose `key` is the * fixed `PAGE_KEY`. It is `Cmd.define`d; the handler you write for it fetches * one page and returns `ok(page)` or `err({ _tag: "port_rejected", … })`. */ type FetchPageCmd = RunCmd; /** The page-settled Msgs the engine mints from that handler's outcome. */ type PageOkMsg = SucceedMsg; /** The Msg the engine mints when the page-fetch handler fails. */ type PageErrMsg = FailMsg; /** The retry / deadline timer Msg — inherited from resilient-call. */ type PaginatedWalkTimerMsg = ResilientTimerMsg; /** The single resilient-call key every page fetch runs under. */ declare const PAGE_KEY = "page"; /** * Build a paginated-walk knob from `config`. `rng` is injected for the * underlying retry jitter — pass a fixed `() => 0` in tests to pin backoff; * defaults to `Math.random` (read at the verb boundary inside resilient-call, * never in a `paginated-walk` verb). Inherited straight from resilient-call. * * Returns plain functions: `init()`, the verbs `start` / `pageOk` / `pageErr` * / `onTimer`, `deadlines(state)` / `timer(state)`, and the page-fetch Cmd def * (`fetch`) to list in the machine's `cmds`. `Cursor` is * the page handle, `Page` the fetch result, `EmittedCmd` the consumer's * per-page Cmds plus the inherited `FetchPageCmd`. */ declare function createPaginatedWalk(config: PaginatedWalkConfig, rng?: () => number): { /** The page-fetch Cmd def — list it in the machine's `cmds`. */ fetch: CmdDef<"resilient_run", { readonly key: string; readonly input: Cursor; }, Page, { readonly [detail: string]: unknown; readonly _tag: "deadline_exceeded"; } | { readonly [detail: string]: unknown; readonly _tag: "port_rejected"; }>; init: () => PaginatedWalkState; start: (s: PaginatedWalkState, at: number) => readonly [PaginatedWalkState, readonly (EmittedCmd | FetchPageCmd)[]]; pageOk: (s: PaginatedWalkState, msg: PageOkMsg) => readonly [PaginatedWalkState, readonly (EmittedCmd | FetchPageCmd)[]]; pageErr: (s: PaginatedWalkState, msg: PageErrMsg) => readonly [PaginatedWalkState, readonly (EmittedCmd | FetchPageCmd)[]]; onTimer: (s: PaginatedWalkState, msg: PaginatedWalkTimerMsg) => readonly [PaginatedWalkState, readonly (EmittedCmd | FetchPageCmd)[]]; drain: (s: PaginatedWalkState, n: number) => readonly [PaginatedWalkState, readonly (EmittedCmd | FetchPageCmd)[]]; resume: (s: PaginatedWalkState, at: number) => readonly [PaginatedWalkState, readonly (EmittedCmd | FetchPageCmd)[]]; isComplete: (s: PaginatedWalkState) => boolean; failure: (s: PaginatedWalkState) => unknown; isStuck: (s: PaginatedWalkState) => boolean; deadlines: (s: PaginatedWalkState) => readonly DeadlineSub[]; timer: (s: PaginatedWalkState) => TimerDeps> | null; }; /** * Lift a knob result `[slice, cmds]` into a host `[State, cmds]` where the slice * lives at `state.walk`. 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 liftWalk; }, Cursor, Page, C extends Cmd>(state: S, [slice, cmds]: readonly [PaginatedWalkState, readonly C[]]): readonly [S, readonly C[]]; export { type FetchPageCmd, PAGE_KEY, type PageErrMsg, type PageOkMsg, type PaginatedWalkConfig, type PaginatedWalkState, type PaginatedWalkTimerMsg, type PaginatorPolicy, type PaginatorState, createPaginatedWalk, defaultPaginatorPolicy, drain, initPaginator, isDone, liftWalk, recordPage, resume, start };