/** * `Consumer` — the embedded consumer library. * * Consumer is a library that runs inside the user's process. There is no * separate broker service — same as the producer, there is no SDK ↔ broker * RPC. The consumer: * * 1. Elects itself the single active consumer in `consumerGroup` by * acquiring an Azure lease on `.consumer_groups/.offset` * (ADR-0009). Other consumers in the same group block on the lease. * 2. Reads `.index.jsonl` to discover sealed segments and the active * generation (ADR-0006 — `.index.jsonl` is the only enumeration path). * 3. Catches up: walks sealed segments after the last committed offset, * then range-reads the tail of `current-N.jsonl`. * 4. Enters a wake-up loop: * - Polling mode (no Postgres): polls `head(currentPath)` every * `pollIntervalMs`; on a length increase, range-reads the delta. * - NOTIFY mode (Postgres configured): subscribes to the per-topic * Postgres channel via `createSignalListener`. On each NOTIFY * schedules a read up to `payload.byte`. A backstop poll runs at * `pollIntervalMs * 5` against lost NOTIFYs — `pg_notify` is not * buffered. * - On reconnect (NOTIFY mode), always triggers a full re-read of * `.index.jsonl` + catch-up. * 5. On a `SealFrame` (or 404 on the current path, or a NOTIFY with * `gen` ahead of locally-tracked), re-reads `.index.jsonl`, finishes * the old generation via the sealed-segments path, switches * `currentPath` to the new generation and continues. * 6. Commits the offset to `.consumer_groups/.offset` every * `commitEveryN` records. The offset blob is an overwrite **block blob** * containing exactly one JSON line `{ "offset": N, "at": ISO }` * (ADR-0010). `putBlockBlob` is atomic and the lease is enforced * server-side, so a deposed standby cannot overwrite a held offset. * 7. Poison frames (`PoisonFrameError` from `decodeFrame`) are written to * `.dead-letter/gen-NNNNNN-byte-BBBBBBBBBB.bin` and skipped. * `deadLetterPolicy='fail-fast'` closes the consumer instead. * * Errors are surfaced as typed exceptions: `OffsetBlobCorruptedError`, * `ConsumerClosedError`, `IndexInconsistencyError`. `LeaseLostError` from * the provider is propagated by `commitOffset` and is fatal — the consumer * closes and the orchestrator must restart it (same shape as the producer's * fatal-lease-loss rule, ADR-0004 / ADR-0009). * * See ADR-0003, ADR-0004, ADR-0006, ADR-0009. Wire format: * `src/broker/frame.ts`. Index protocol: `src/index/indexFile.ts`. Signal * layer: `src/broker/postgresSignal.ts`. */ import { type StorageProvider } from '../storage/types.js'; import { type SignalListener, type SignalListenerConnection } from './postgresSignal.js'; /** * Deterministic sampling decision for the `consumer.dispatch` span covering * offsets `[firstOffset, lastOffset]` (one record, or one batch). Sampled when * any offset in the range is a multiple of the bucket, so a given offset always * samples the same way — making percentile reasoning on the resulting samples * sound (vs `Math.random()`, which biases under bursty arrival) — and batch * sampling follows the records it holds, not where the batch happens to start. * * @internal Exported for unit tests only; not part of the public API. */ export declare function shouldSampleDispatch(firstOffset: bigint, lastOffset: bigint, sampleRate: number): boolean; /** * The handler signature passed to `Consumer.start`. Invoked once per data * frame in offset order. The consumer awaits the return value; back-pressure * flows back into the read loop naturally. */ /** * Per-record handler. **The at-least-once contract is driven by this function's * return / throw behaviour** — see below. * * ## At-least-once contract — what the consumer guarantees, and what your handler MUST do * * For every record `r` the producer's `send()` Promise resolved with, this * handler is invoked at least once per `(tenant, topic, group)` for every * group that ever runs. The broker advances its offset state based **only** on * the handler's settle outcome: * * - **Handler returns** (resolves, doesn't throw): the broker counts the * record as "processed", increments its internal `pendingDispatchedSinceCommit` * counter, and — every `commitEveryN` successful returns — overwrites the * offset blob (`.consumer_groups/.offset`, ADR-0010) with the new * committed offset. Until that overwrite happens, **no offset progress is * durable**: if the process dies between commits, the next consumer in the * group resumes from the last committed offset and re-dispatches every record * in the in-flight window. This is by design. * * - **Handler throws** (rejects): the broker does not advance and does not * commit. It retries the same record with exponential backoff per * `handlerRetry`; once `handlerRetry.maxConsecutiveFailures` is reached the * record is dead-lettered and dispatch moves past it. If the consumer closes * or dies mid-retry, the next consumer in the group resumes from the last * committed offset and invokes the handler again. Throw whenever your * downstream persist failed — including transient failures you want * re-attempted. * * ## What this means for your handler * * **Your handler MUST `await` every downstream side-effect to durable * completion BEFORE returning.** If you write to a database, await the commit. * If you call an HTTP endpoint, await the success response. If you write to a * blob, await the upload. If your handler returns *before* the side-effect is * durable and the process then crashes, the broker may commit an offset past * a record whose downstream effect was lost — silent data loss in your sink * even though the broker's substrate held the bytes correctly. * * **Your handler MUST be idempotent** for the same `record.id`. Across normal * operation, chaos restarts, lease handovers, and replays, the broker may * dispatch the same record multiple times — up to `commitEveryN` records of * replay per consumer restart, and unbounded replay across deliberate * `Consumer.replay({...})` invocations. Use `record.id` as a deduplication key * (UPSERT on a unique constraint, idempotency table, transactional outbox keyed * on `record.id`, etc.). * * ## Why no explicit `commit()` callback * * The broker's commit cadence is driven by `commitEveryN` only — there is no * `handler: (record, ctx) => { ...; await ctx.commit() }` escape hatch. The * handler-await model is sufficient for the SMB scope the prototype targets; * a manual-commit API would only be needed for downstream systems where the * caller wants commit batching tighter than (or differently shaped from) the * record-count threshold. For now, lowering `commitEveryN` (down to `1` for * commit-per-record) is the available knob. * * If your sink is much cheaper per call when it receives many records at once * (Kafka produce, bulk insert), use {@link ConsumerBatchHandler} via * `batchHandler` instead. */ export type ConsumerHandler = (record: ConsumerRecord) => Promise | void; /** A data record as delivered to a {@link ConsumerHandler} or {@link ConsumerBatchHandler}. */ export type ConsumerRecord = { readonly offset: bigint; readonly id: string; readonly body: string; readonly ts: string; /** Id of the `openBatch` / `sendBatch` batch that wrote the record; absent for `send()` records. */ readonly batchId?: string; }; /** * Batch handler — the opt-in alternative to {@link ConsumerHandler}, passed as * `batchHandler` to `Consumer.start` (ADR-0029). Receives records in offset * order, at most `maxBatchRecords` per call, and is awaited per batch. * * ## How batches are formed * * A batch holds only records the consumer has already read. The consumer never * waits for more records to fill a batch: when it reaches the end of the bytes * it has read (end of a read chunk, end of the live tail, or a generation * seal), it delivers what it has. At low volume a batch is often one record, so * latency is the same as with `handler`. Batches never span a generation * boundary. * * ## At-least-once contract * * The contract of {@link ConsumerHandler} applies to the batch as a unit: * * - **Resolves**: every record in the batch counts as processed. The * in-memory dispatched tip moves to the last record of the batch. * - **Rejects**: no record in the batch counts as processed and no offset * moves. The same batch is delivered again with the `handlerRetry` backoff. * Once `handlerRetry.maxConsecutiveFailures` is reached, every record in the * batch is dead-lettered (one dead-letter blob per record) and dispatch moves * past the batch. * * Resolve only after every record in the batch is durable downstream (for * Kafka: after the producer `send` for the whole batch is acknowledged). A * retried batch can contain records your sink already accepted from the failed * attempt, so the handler MUST be idempotent on `record.id`. * * ## Offset commits * * `commitEveryN` counts records, but commits happen only at batch boundaries: * after a batch resolves, if at least `commitEveryN` records have resolved * since the last commit, the consumer commits the offset of the last record of * that batch. A commit never covers a record from a batch that has not * resolved. With the defaults (`commitEveryN` 100, `maxBatchRecords` 500) every * full batch is followed by one commit. After a crash, up to * `commitEveryN - 1 + maxBatchRecords` records can be delivered again. */ export type ConsumerBatchHandler = (records: readonly ConsumerRecord[]) => Promise | void; /** * Behaviour on a `PoisonFrameError`. * * `'log-and-skip'` (default): write the raw bad bytes to `.dead-letter/` and * continue with the next frame. Operators get OTEL alerts on dead-letter * growth. * * `'fail-fast'`: surface the error, stop the wake-up loop, release the lease. * Closes the consumer. */ export type DeadLetterPolicy = 'log-and-skip' | 'fail-fast'; /** * Options for {@link Consumer.replay}. Replay is a one-shot historical read * over the sealed `segments/*.jsonl` archives (plus optionally the live * `current-N.jsonl` tail), bounded by offset and/or timestamp range. Replay * does NOT acquire a lease, does NOT commit offsets, and does NOT subscribe * to future records — it is a pure "play me these records once" operation * that returns when the requested range has been fully dispatched. * * Replay is the natural primitive for: backfilling a new consumer with * historical state, re-processing after fixing a handler bug, audit / * forensic queries, and replay-by-timestamp. */ export type ReplayOptions = { readonly storage: StorageProvider; readonly tenant: string; readonly topic: string; /** * Invoked once per data frame in offset order. Awaited per record. Replay * has no batch mode: it never commits offsets, so a caller that wants * batches can buffer inside this handler and flush after replay returns. */ readonly handler: ConsumerHandler; /** Inclusive lower bound on data-frame offset. Default `0n`. */ readonly fromOffset?: bigint; /** * Inclusive upper bound on data-frame offset. When omitted, the upper * bound is "everything currently available" — including the live * `current-N.jsonl` tail at replay start. The replay is a snapshot, not * a subscription: records appended to `current-N` after replay begins * are NOT included; rerun replay to pick them up. */ readonly toOffset?: bigint; /** * Inclusive lower bound on the data frame's `ts` field (ISO 8601). * **Best-effort** per ADR-0011: the `at` / `ts` field is producer * wall-clock and is not strictly monotonic across leader handovers. For * exact bounds, prefer offset-based filtering. */ readonly fromTimestamp?: string; /** Inclusive upper bound on the data frame's `ts` field. Best-effort. */ readonly toTimestamp?: string; /** * Slack added to the timestamp window when deciding which segments to *open* * (best-effort, absorbs cross-leader clock drift — ADR-0011). Frame-level `ts` * filtering is unaffected and stays precise. Default 5 min. */ readonly clockDriftSlackMs?: number; /** * Poison-frame disposition. Default `'log-and-skip'`. **Replay never * writes a `.dead-letter/` blob** — the original consumer's read of the * source segment would have written the dead letter on first * encounter; replay just skips past the same bytes (or fail-fasts). */ readonly deadLetterPolicy?: DeadLetterPolicy; }; /** Result returned from {@link Consumer.replay}. */ export type ReplayResult = { /** Total data frames passed to the handler. */ readonly recordsDispatched: number; /** Sealed segments walked. */ readonly segmentsRead: number; /** Whether the live `current-N` was included in this replay's range. */ readonly liveTailRead: boolean; /** Offset of the last frame dispatched, or `undefined` if no frames matched. */ readonly lastOffset: bigint | undefined; }; /** On-disk encoding a {@link StreamFile} points at. */ export declare enum StreamFileFormat { Jsonl = "jsonl", Parquet = "parquet" } /** Caller's format-selection policy for {@link Consumer.getStreamManifest}. */ export type StreamManifestFormat = 'prefer-parquet' | 'parquet-only' | 'jsonl-only'; /** * Options for {@link Consumer.getStreamManifest}. * * `fromTimestamp` / `toTimestamp` are **producer emission wall-clock** (the * frame `ts`), NOT any event-time inside a record's body, and are * **best-effort**: matching uses per-gen open/seal boundaries widened by * `clockDriftSlackMs`, and producer clocks are non-monotonic across leader * changes (ADR-0011). The manifest returns a **file-level superset** — the * caller MUST further-filter the records it reads by `ts`. */ export type StreamManifestOptions = { readonly storage: StorageProvider; readonly tenant: string; readonly topic: string; /** Default `'prefer-parquet'`. */ readonly format?: StreamManifestFormat; /** Inclusive lower offset bound; files entirely below are omitted. Default `0n`. */ readonly fromOffset?: bigint; /** Best-effort producer-emission-clock lower bound (ISO 8601). See the type note. */ readonly fromTimestamp?: string; /** Best-effort producer-emission-clock upper bound (ISO 8601). See the type note. */ readonly toTimestamp?: string; /** Slack added to the timestamp window to absorb cross-leader clock drift. Default 5 min. */ readonly clockDriftSlackMs?: number; /** TTL for minted read URLs (seconds). Default 3600 (1 h); validated to 1..604800 (7 days — Azure's user-delegation-key ceiling), even when the provider can't mint URLs (in which case no URL is produced). */ readonly sasTtlSeconds?: number; }; /** One file in a {@link StreamManifest}. */ export type StreamFile = { readonly gen: number; readonly format: StreamFileFormat; /** Blob path within the container. */ readonly path: string; /** Read SAS / presigned URL, or `null` when the provider has no `mintBlobUrl` (read with your own credentials). */ readonly url: string | null; readonly startOffset: bigint; /** `null` for the still-open live tail. */ readonly endOffset: bigint | null; /** Data-frame count from the index for sealed segments; `null` for pending/live. */ readonly rowCount: number | null; /** sha256 of the archived blob for sealed segments; `null` for pending/live. */ readonly sha256: string | null; /** `true` = immutable `segments/` archive; `false` = live/pending `current-N` append blob. */ readonly sealed: boolean; /** `true` only for the live tail — its bytes may still grow after `asOf`, so treat it as a moving target (re-read for the latest). Sealed segments and pending seals are frozen. */ readonly volatile: boolean; /** * `true` when this file is a **logical multi-part segment** (an un-compacted * `current-N` generation on the S3 `object-per-batch` strategy — ADR-0023/0025): * its bytes are spread across part objects under the `path` prefix, so `url` is * always `null` (a single presigned URL cannot address a prefix) and it must be * read through the broker's {@link Consumer}/{@link Consumer.replay} API, which * stitches the parts, rather than a direct object read. `false` for every * single-object file: all sealed `segments/` archives (the compactor joined any * parts into one object at seal time) and all Azure files. */ readonly multiPart: boolean; /** Approximate producer-emission window; `approxSealedAt` null = still open. Not precise. */ readonly approxOpenedAt: string | null; readonly approxSealedAt: string | null; }; /** * Ordered set of files to read a topic's full stream as of {@link StreamManifest.asOf}. * Returned by {@link Consumer.getStreamManifest}. */ export type StreamManifest = { readonly tenant: string; readonly topic: string; /** ISO timestamp the manifest was computed (the snapshot point). */ readonly asOf: string; readonly format: StreamManifestFormat; /** Files in strict offset order. */ readonly files: readonly StreamFile[]; readonly fromOffset: bigint; /** `true` when the open gen's live `current-N` is in {@link StreamManifest.files}. */ readonly includesLiveTail: boolean; /** `true` when entries were dropped because `format` couldn't represent them (e.g. `'parquet-only'` skipping the unsealed tail). */ readonly omittedUnrepresentable: boolean; /** ISO expiry of the minted URLs, or `null` when none were minted. */ readonly urlsExpireAt: string | null; }; /** Per-record dispatch: the default mode. */ export type ConsumerRecordDispatchOptions = { /** Invoked once per record. See {@link ConsumerHandler}. */ readonly handler: ConsumerHandler; readonly batchHandler?: never; readonly maxBatchRecords?: never; }; /** Batch dispatch: opt-in alternative to `handler` (ADR-0029). */ export type ConsumerBatchDispatchOptions = { readonly handler?: never; /** Invoked once per batch of records. See {@link ConsumerBatchHandler}. */ readonly batchHandler: ConsumerBatchHandler; /** Maximum number of records in one batch. Integer in `[1, 100000]`. Default 500. */ readonly maxBatchRecords?: number; }; /** * Options for `Consumer.start`. Pass exactly one of `handler` (per record) or * `batchHandler` (per batch, with `maxBatchRecords`). */ export type ConsumerOptions = ConsumerBaseOptions & (ConsumerRecordDispatchOptions | ConsumerBatchDispatchOptions); /** The options of `Consumer.start` that are shared by per-record and batch dispatch. */ export type ConsumerBaseOptions = { readonly storage: StorageProvider; readonly tenant: string; readonly topic: string; readonly consumerGroup: string; /** * Optional Postgres connection — enables NOTIFY mode. Accepts either a * libpq connection string OR a `pg.ClientConfig` (the right shape for * managed-identity / AAD callers; `password` may be `() => Promise` * for token refresh — see `CLAUDE.md` §Credentials and authentication). */ readonly postgres?: { readonly connection: SignalListenerConnection; }; /** HEAD polling cadence in polling mode; backstop cadence in NOTIFY mode (× 5). Default 1000 ms. */ readonly pollIntervalMs?: number; /** * Offset commit batching — the broker writes the committed offset to the * offset blob (`.consumer_groups/.offset`) once every `commitEveryN` * **successful** handler returns. Default 100. * * This is the size of the at-least-once duplicate window after a crash: up * to `commitEveryN - 1` records may be re-dispatched by the next consumer * in the group, because the offset blob only catches up to reality at the * commit boundary. Lower values shrink the duplicate window at the cost of * more frequent overwrite-block-blob writes (each `commitEveryN = 1` means * one extra blob write per record processed). The default `100` is a * tradeoff suited to ~1 second of duplicate work at 100 evt/s; tune * downwards for expensive handlers, upwards for cheap idempotent handlers. * * With `batchHandler`, the count is in records but commits happen only at * batch boundaries, never inside a batch that has not resolved (see * {@link ConsumerBatchHandler}). * * See {@link ConsumerHandler} for the full at-least-once contract. */ readonly commitEveryN?: number; /** Lease TTL on the offset blob. Default 60 s. */ readonly leaseTtlSeconds?: number; /** * Per-call timeout for `acquireLease()` on the offset blob (in milliseconds). * Default 30 000 ms. The consumer may retry inside `start()` while waiting * for an active consumer in the same group to die (`waitForLease: true`, * the default); each individual attempt is bounded by this timeout. On * expiry the broker throws `LeaseAcquisitionTimeoutError` so callers can * bail cleanly instead of hanging on long-tail Azure responses. Set 0 to * disable. */ readonly leaseAcquisitionTimeoutMs?: number; /** * Sample rate for the per-record `consumer.dispatch` span (0..1). Default * 1.0 (every dispatch creates a span). Set < 1 to reduce per-record OTEL * overhead at high throughput; the broker uses a deterministic * (offset % bucket) decision so percentile reasoning on the resulting * samples stays sound. Records / commits / wake-up histograms continue to * fire unconditionally — only the per-dispatch span (which is the noisy, * O(records) one) is sampled. */ readonly consumerDispatchSpanSampleRate?: number; /** * Diagnostic: when `true`, log a line to stdout each time the * `frame.offset > lastDispatchedOffset` filter skips a record in * `streamReadAndProcess`. Default `false`. The counter * `consumer.records_skipped_by_offset_filter_total` always fires * regardless of this flag. Use for forensic investigation of rare * edge cases under chaos when concrete recordId + offset evidence is * needed on the next reproduction. */ readonly logRecordsSkippedByOffsetFilter?: boolean; /** Poison-frame disposition. Default `'log-and-skip'`. */ readonly deadLetterPolicy?: DeadLetterPolicy; /** * When `true` (default), `start()` blocks until the offset-blob lease is * available — the natural consumer-group-standby pattern (ADR-0009). When * `false`, `start()` rejects with the underlying `LeaseAlreadyHeldError` * and the orchestrator decides. */ readonly waitForLease?: boolean; /** * Invoked synchronously when the wake-up loop exits due to a fatal error * (`LeaseLostError`, `OffsetBlobCorruptedError`, `IndexInconsistencyError`, * or any unknown error promoted via {@link markFatallyClosed}). The * `reason` discriminant tells the host which class of failure happened so * the orchestrator can take the right recovery action (typically: log, * alert, exit the process and let the orchestrator restart). * * **Why this exists**: without this option, a consumer that died * mid-stream surfaces only via `isClosed === true` if the host happens * to poll it — operational dashboards do not. * * **Callback contract**: exceptions thrown from the callback are caught * and logged via OTEL — they cannot prevent the consumer from shutting * down cleanly. The callback runs at most once per `Consumer` instance. * If you need a promise-shaped signal too, use {@link Consumer.fatalError}. */ readonly onFatalError?: (err: Error, reason: ConsumerFatalReason) => void; /** * Handler retry budget. A thrown handler triggers exponential backoff * with jitter; after `maxConsecutiveFailures` consecutive failures the * record is dead-lettered and dispatch advances past it so a * permanently-broken handler (DB down) cannot pin the consumer in an * unbounded tight loop. With `batchHandler` the unit of retry and * dead-lettering is the whole batch. * * - `maxConsecutiveFailures` (default 10): how many times the same * record may be retried before being dead-lettered. Reset to 0 on * the next successful handler return. * - `backoffMs` (default 200): first-retry delay in ms. * - `backoffCapMs` (default 30 000): exponential backoff ceiling. * - `backoffFactor` (default 2): per-attempt multiplier. */ readonly handlerRetry?: { readonly maxConsecutiveFailures?: number; readonly backoffMs?: number; readonly backoffCapMs?: number; readonly backoffFactor?: number; }; /** * **Internal library use only — a testing seam, not public API.** The * leading underscore marks it as private to the library; it is exempt from * semver and may change or be removed without notice. Inject a pre-built * {@link SignalListener} instead of connecting to Postgres so NOTIFY-mode * unit tests can drive `onSignal`/`onReconnect` deterministically with a * fake listener (CLAUDE.md §Testing philosophy explicitly endorses a fake * Postgres listener as a valid test double). When set, NOTIFY mode is * enabled without `postgres`. Never set this in production — there is no * supported production use case (see the design discussion: managed-identity * is covered by `postgres.connection`, and alternative wake-up transports * are a separate, out-of-scope workstream). */ readonly _signalListenerForTesting?: SignalListener; }; /** * Discriminant for {@link ConsumerOptions.onFatalError} and * {@link Consumer.fatalError}. */ export type ConsumerFatalReason = 'lease-lost' | 'offset-corrupt' | 'index-inconsistent' | 'unknown-fatal'; /** * Thrown by `Consumer.start` when the offset blob exists but its bookkeeping * cannot be parsed. The offset blob is OUR own state — corruption here is * fatal and is NOT the same as a `PoisonFrameError` on the data wire. */ export declare class OffsetBlobCorruptedError extends Error { readonly offsetPath: string; readonly cause: unknown; constructor(offsetPath: string, cause: unknown); } /** * Thrown when an API is called on a closed (or lease-lost) consumer. A * lost-lease consumer is functionally closed — the only correct response is * a fresh `Consumer.start()` from the orchestrator. */ export declare class ConsumerClosedError extends Error { readonly reason: string; constructor(reason: string); } export { IndexInconsistencyError } from './errors.js'; /** * `Consumer.start({ ... })` is the only public construction path. The * returned instance is a `Promise` because the election (lease * acquire) is asynchronous and must complete before any records flow. */ export declare class Consumer { private readonly opts; private readonly offsetPath; private readonly indexPath; private lease; private leaseRenewer; private signalListener?; /** * Durable last-committed offset — only ever advanced by * {@link commitOffsetDirect} on a successful offset-blob write. The * offset-lag gauge and the catch-up logic both read this. On a transient * commit failure, {@link lastDispatchedOffset} is rolled back to this * value so the affected records are re-dispatched. */ private lastCommittedOffset; /** * In-memory "last record we handed to the user's handler". Advances on * every successful handler return; rolls back to {@link lastCommittedOffset} * on commit failure. The streamReadAndProcess dedup filter * (`frame.offset > lastDispatchedOffset`) reads this so a rollover * catch-up re-walk does not re-dispatch records we already gave the * handler. Both fields are initialised together from the offset blob in * {@link restoreLastCommittedOffset}. */ private lastDispatchedOffset; /** Number of data frames dispatched since the last commit — drives `commitEveryN`. */ private pendingDispatchedSinceCommit; private state; /** * Incremental `.index.jsonl` cache. `undefined` until the first * `refreshIndexState` call; populated thereafter and grown by appending * parsed delta bytes from each tick's HEAD-then-rangeRead. Lets the * wake-up loop probe for new index entries with one HEAD per tick * instead of re-pulling the full index every time. * * NOTE: this cache grows unboundedly in memory and `summariseIndex` * re-folds the whole cache on every index delta — fine at SMB scale (the * in-memory twin of the deferred ADR-0015 index snapshot/truncate work). * If/when ADR-0015 lands, the on-disk truncation should drive an * equivalent in-memory cache reset here. */ private indexRecordsCache; /** Committed length of `.index.jsonl` at the last incremental refresh. */ private indexCommittedLength; /** Byte offset within the active `current-N.jsonl` past which we have already dispatched. */ private currentReadByte; /** Batch state of the segment last read: the latest batch scan (so a held batch's next poll scans only new bytes) and its abandoned batch ids. */ private batchRead; /** Approximate latency tracking: when did NOTIFY/poll prompt the current dispatch loop iteration? */ private wakeupOriginTs; private wakeupOriginKind; private closed; private closeReason; private wakeupSignal?; /** * Set by {@link signalWakeup} when a NOTIFY arrives while `wakeupSignal` is * undefined — i.e. mid-tick, between a wake-up resolving and the loop * re-parking. The loop consumes it before parking so a NOTIFY that lands in * that window is honoured immediately instead of waiting for the backstop * poll (M1). */ private pendingWakeup; private loopPromise?; private tickCounter; /** * Set by `close()` for the duration of its final-commit attempt. Gates * `markFatallyClosed` so a transient LeaseLost during the graceful * shutdown's last commit does not fire the user's `onFatalError` * callback — the consumer is already being shut down deliberately, * and at-least-once re-delivery on the next active consumer covers * any records that didn't make it into the offset blob. */ private gracefulCloseInProgress; /** * Backing for {@link Consumer.fatalError}. Settled at most once when the * wake-up loop exits via a fatal path; remains pending across `close()` * triggered by the caller (graceful shutdown is not a fatal error). */ private readonly fatalErrorDeferred; private readonly tracer; private readonly meter; private readonly recordsDispatchedCounter; private readonly recordsSkippedByOffsetFilterCounter; private readonly deadLetterCounter; private readonly handlerFailureCounter; private readonly handlerRetryCounter; private readonly handlerDeadLetteredCounter; private readonly commitsCounter; private readonly pollToDispatchHistogram; private readonly notifyToDispatchHistogram; /** * Regular Gauge for the offset lag, recorded at every dispatch and * every commit. A regular Gauge (vs ObservableGauge) has no persistent * callback — `record()` is the only way values appear — so a closed * Consumer does not leak a per-instance closure. */ private readonly offsetLagGauge; private constructor(); /** * Update the offset-lag gauge from current state. Called at every * dispatch and every commit — the two events that change either * operand of the lag computation. After `close()` no further calls * happen, so the gauge becomes silent. */ private recordOffsetLag; /** * Start the consumer. Performs lease election, catch-up, and begins the * wake-up loop. Resolves once the loop is running; the loop continues in * the background until {@link close} is called or a fatal error occurs. */ static start(opts: ConsumerOptions): Promise; /** * Play back data frames in `[fromOffset, toOffset]` (and/or * `[fromTimestamp, toTimestamp]`) once, in offset order, then return. * See {@link ReplayOptions} for full semantics — replay is a snapshot, * not a subscription; it does not lease the offset blob, does not write * commit lines, and does not include records appended after the * replay's read of `current-N`. * * Segments outside the offset bound are skipped without I/O (the index * records each sealed segment's `[startOffset, endOffset]`). Timestamp * bounds force every in-offset-range segment to be read because the * index does not record per-segment `at` ranges in this version of the * schema; a future enhancement may add that to speed up timestamp-only * replays. */ static replay(opts: ReplayOptions): Promise; /** * Build a {@link StreamManifest}: the ordered list of files — sealed * `segments/` archives, not-yet-archived pending seals, and the live tail — * that together make up the topic's full stream as of now, each with a read * URL, format, and cheap index-derived metadata. Read-only and lease-free * (like {@link Consumer.replay}); needs no consumer group. * * Hand the result to an external reader (BI / bulk export / DuckDB) to read * the whole stream without running a {@link Consumer}. Seek-by-date * (`fromTimestamp`/`toTimestamp`) is best-effort and file-level — see * {@link StreamManifestOptions}. */ static getStreamManifest(opts: StreamManifestOptions): Promise; /** * Instance convenience for {@link Consumer.getStreamManifest} using this * consumer's storage/tenant/topic. Pure read — does not touch the lease or * offset blob, and works before or after {@link start}. */ getStreamManifest(opts?: Omit): Promise; /** * Stop the wake-up loop, commit the latest seen offset one last time, * release the lease, and tear down the Postgres listener if any. * Idempotent. */ /** Diagnostic — true when the consumer has stopped its wake-up loop (graceful close OR fatal error). */ get isClosed(): boolean; /** * Diagnostic — the reason the consumer closed, or empty string if still * running. Set by `close()`, `markClosed*`, or the wake-up loop's fatal * paths (LeaseLostError / OffsetBlobCorruptedError / IndexInconsistencyError). * Surfaces in operator dashboards via OTEL spans too; this getter exists * for in-process callers (experiment harnesses, tests). */ get closedBecause(): string; /** Diagnostic — wake-up loop tick count. Increments once per loop iteration. */ get tickCount(): number; /** * Promise that rejects when the wake-up loop exits due to a fatal error * (`LeaseLostError`, `OffsetBlobCorruptedError`, `IndexInconsistencyError`). * Remains pending if the consumer is closed gracefully via {@link close}. * Use with `Promise.race` for host-process supervision: * * ```ts * const consumer = await Consumer.start({ ... }); * await Promise.race([consumer.fatalError, ...]); * // Reaching here implies fatal — log + exit. * ``` * * The promise is already wired with a no-op `.catch` so an unawaited * fatal close cannot raise a process-level unhandled-rejection warning. */ get fatalError(): Promise; /** * Set `closed`, set `closeReason`, settle {@link fatalError}, and invoke * the user's `onFatalError` callback exactly once. Exceptions thrown by * the callback are caught and recorded — they cannot prevent the * consumer's shutdown path from running. */ private markFatallyClosed; /** Diagnostic — current state's currentGen + currentReadByte snapshot. */ get diagnostics(): { readonly currentGen: number | null; readonly currentReadByte: number; readonly lastCommittedOffset: bigint; readonly lastDispatchedOffset: bigint; readonly observedHeadOffset: bigint | undefined; readonly sealedSegmentCount: number; readonly pendingSealCount: number; }; close(): Promise; private bootstrap; private teardownAfterFailedStart; private acquireLeaseWithOptionalWait; private restoreLastCommittedOffset; /** * Refresh `state` from `.index.jsonl`. **Incremental.** The first call * (or any call after a snapshot/truncate per ADR-0015) reads the whole * blob; subsequent calls HEAD the blob, and only `rangeRead` the delta * if the committed length grew. Avoids re-pulling and re-parsing the * full index every wake-up tick — at SMB peak the index grows * ~400 MB/year/topic, so a 1 s polling cadence with full re-read would * burn ~1.1 TB/year/topic on the wire to discover one new line of * a few hundred bytes. * * Behaviour: * - First call: full read via {@link readIndex}, cache populated. * - Length unchanged: HEAD only; no rangeRead, no state update. * - Length grew: rangeRead the new tail bytes, parse, append to * cache, re-fold `state` via {@link summariseIndex}. * - Length shrank: implies a snapshot/truncate happened * (ADR-0015 — not built yet, but the wire shape is reserved). * Discard cache and full re-read. */ private refreshIndexState; /** * Catch-up phase. Walks all sealed segments with * `endOffset > lastDispatchedOffset`, then walks `pendingSeals` (gens that * the producer has rolled over but the compactor hasn't yet archived — * the original `current-N` append blob is still around because deletion * only happens after the 24 h grace window per ADR-0014), then range-reads * the tail of the live `current-N.jsonl` from byte 0 (or from the * already-tracked `currentReadByte`, if we've consumed some of it already). * * **Why pendingSeals are walked here**: a fast-rolling producer (or a * slow compactor) can leave several gens in the pendingSeals state at * once. Skipping them creates a gap that consumers never recover from * unless the compactor catches up. Walking the still-existing * append-blob path closes this gap honestly — `streamReadAndProcess`'s * `frame.offset > lastDispatchedOffset` filter dedupes any frames a * subsequent re-walk encounters (e.g. after the segment gets archived * and lands in `sealedSegments`). */ private runCatchup; private dispatchSealedSegment; /** * Range-read the live `current-N.jsonl` from `currentReadByte` to its * current length and dispatch every data frame past `lastDispatchedOffset`. * Returns immediately if the blob has not grown. * * Detects `SealFrame` and triggers a generation rollover. */ private readCurrentTail; /** * Stream-read `[startByte, totalLength)` of `path` through {@link readSegment}, * dispatching each data frame past `lastDispatchedOffset`. * * **Why chunking matters.** When a consumer falls behind under Azure * throttle and the next poll would read a multi-hundred-megabyte * delta in ONE rangeRead, the resulting full-blob `Buffer.concat` * allocation cascades `process.memoryUsage().arrayBuffers` past * typical container heap limits and OOM-kills the process. Chunked * streaming bounds peak transient allocation to one chunk (~4 MiB) * regardless of how far behind the consumer has fallen. * * **Multi-block batches (ADR-0030).** A batch is delivered only once its * validation scan finds a valid `_commit`. While it is still open on the * live tail the cursor holds at its first frame (`nextByteToRead` stays * there), so a failed offset commit re-reads from the hold and the committed * offset never passes an undelivered batch. An abandoned batch is skipped; * an invalid one falls under `deadLetterPolicy` as a unit. * * `bound.frozen` marks a generation that can no longer grow (a pending seal * or an archived segment): it is read to `bound.endOffset`, the index's end * for the gen, so a stale in-band `_seal` is skipped and legacy data after it * is delivered. A live read stops at the first `_seal` and lets * {@link handleGenerationRollover} consult the index. * * `multiPart` selects the read view (ADR-0025): a live or pending-seal * `current-N` generation is a LOGICAL segment (a set of part objects on the * S3 `object-per-batch` strategy) and is read through `rangeReadSegment`; an * archived sealed segment (`segments/*.jsonl`) is always a single object and is * read through the mechanical `rangeRead`. On Azure the two coincide * (`rangeReadSegment` is a `rangeRead` pass-through), so this flag is a no-op * there. */ private streamReadAndProcess; /** Count, and optionally log, a frame already dispatched; expected only on catch-up re-walks. */ private recordSkippedByOffsetFilter; /** * Batch state carried across reads of `path`: one batch scan, replaced when * the next batch starts, and the abandoned batch ids, reset with the path. */ private batchStateFor; /** * Counter of consecutive handler failures across dispatches. Reset to 0 * on the first successful handler return. When this reaches the * `handlerRetry.maxConsecutiveFailures` ceiling the offending record (or * every record of the offending batch) is written to the dead-letter and * the consumer advances past it. */ private consecutiveHandlerFailures; /** * Wrap the user's handler in a bounded retry-with-backoff. Each throw * triggers `handlerRetry.backoffMs * 2^attempt` (with a `backoffCapMs` * ceiling and jitter); after `handlerRetry.maxConsecutiveFailures` * consecutive failures the entries are dead-lettered and dispatch * advances past them so a permanently-broken handler (DB down, * downstream timeout) cannot pin the consumer in a tight loop at * `pollIntervalMs` granularity. Sets `consecutiveHandlerFailures = 0` * on the first successful return. * * `entries` is one record in per-record mode, or one whole batch in batch * mode; a retry always re-delivers the same entries. */ private invokeHandlerWithRetry; /** * Hand `entries` (ascending offsets) to the handler as one unit — one * record in per-record mode, one batch in batch mode — then advance the * dispatched tip to the last entry and commit if `commitEveryN` is reached. * Nothing advances unless the handler call settles successfully, so a * commit never covers an entry whose handler call has not resolved. */ private dispatchEntries; /** Dispatch and empty the pending batch. No-op when it is empty. */ private flushBatch; /** * Commit the offset by appending one JSON line to the offset blob. * Throws `LeaseLostError` (propagated from the provider) when our lease * has expired — consumer must close. */ private commitOffset; /** * Append a commit line directly. Used by both the regular {@link commitOffset} * (after the `closed` gate) and by {@link close} for its final commit (which * runs after `closed` is set). On `LeaseLostError`, marks the consumer closed * but still propagates the error. */ private commitOffsetDirect; /** * A `SealFrame` was observed (or HEAD on currentPath came back 404). Re-read * `.index.jsonl`, switch to the new generation, and run catch-up for the gap. */ private handleGenerationRollover; /** * Wake the loop on a NOTIFY. If the loop is parked, resolve its wait * directly. If it's mid-tick (`wakeupSignal` undefined — between a wake-up * resolving and re-parking), latch `pendingWakeup` so the loop honours the * signal before parking again instead of dropping it (M1). Single-threaded * JS guarantees the check-then-park sequence in the loop is atomic with * respect to this callback, so no signal can slip through the gap. */ private signalWakeup; /** * The wake-up loop. Runs until `closed` is true. Polling mode polls at * `pollIntervalMs`; NOTIFY mode waits on the signal listener with a * backstop poll at `pollIntervalMs * 5`. */ private runWakeupLoop; /** * Persist a single poison-line's raw bytes to `.dead-letter/gen-NNNNNN-byte-BBBBBBBBBB.bin`. * The line is already isolated (between two newlines) by the caller — we cap at * {@link DEAD_LETTER_SCAN_CHUNK_BYTES} bytes for safety. */ private writeDeadLetter; /** * Highest offset the consumer has observed from any source — the last * dispatched frame, the most recent NOTIFY payload, or the current * gen's `start_offset` as a floor. Used by the offset-lag gauge: lag * is `max(observedHead - lastCommittedOffset, 0)`. */ private observedHeadOffset; /** * Highest offset observed via inbound NOTIFY payloads. Updated by the * signal listener (`onSignal`). Combined with `lastDispatchedOffset` in * {@link observedHeadOffset} so the lag gauge reflects "what the * producer is publishing", not just "what this consumer has dispatched". */ private maxNotifyOffset; private baseSpanAttrs; private metricLabels; } //# sourceMappingURL=consumer.d.ts.map