/** * Producer — the user's process IS the broker. * * Per ADR-0007 there is no separate broker service. `Producer.start()` runs * inside the user's Node process, reads `.index.jsonl` (ADR-0006), acquires * the Azure Blob lease on `current-N.jsonl` (ADR-0004), and writes batched * `AppendBlock`s with conditional `appendpos` (ADR-0005). Records published * via {@link Producer.send} are coalesced into a single `AppendBlock` per * 5–10 ms window (ADR-0008) to dodge Azure's 50 000-blocks-per-blob ceiling * and amortise per-call RTT. * * What this file does NOT contain: * - **Sealed-segment archival**. The rollover path here implements the * seal + open + index-line steps only; sealed `current-N` blobs sit * waiting for the compactor (`compactor.ts`), which copies them into * `segments/` and deletes the source after the grace window. * - **`listPrefix` enumeration**. Hot code reads `.index.jsonl`. On * leader-recovery this file asks the substrate only for the current * generation's `segmentLength` and reads it with `rangeReadSegment` * (ADR-0005, ADR-0025). * * Concurrency model: `send()` is fully async-safe. All mutation of * `pendingRecords` and the committed-state fields happens on the JS event * loop's single thread — no locks needed. Flushes are mutually exclusive via * a `flushInFlight` promise; while one batch is on the wire, new `send()`s * append to `pendingRecords` and the in-flight batch's completion triggers * the next flush if anything is queued. An atomic batch (`openBatch` / * `sendBatch`, ADR-0030) holds a separate `writeSlot`, granted once no flush * is in flight and the records queued before it are written. While it is * held no flush starts, so `send()`s and other batches queue behind it. * * @see ADR-0004 (lease on current blob, not a separate lock). * @see ADR-0005 (append position from response, not local counter). * @see ADR-0006 (`.index.jsonl` is the only enumeration path). * @see ADR-0007 (producer equals leader, no broker service). * @see ADR-0008 (batched appends with 5–10 ms coalescing window). */ import type { Pool } from 'pg'; import { type StorageProvider } from '../storage/types.js'; import { type UserRecord } from './frame.js'; /** * `send()` was called when the in-process queue already held * `maxQueueDepth` records. Honest back-pressure per ADR-0007 / ADR-0008. */ export declare class QueueFullError extends Error { readonly currentDepth: number; readonly cap: number; constructor(currentDepth: number, cap: number); } /** * A single record's encoded size exceeded `maxBatchBytes`. The producer * cannot split a single record across multiple `AppendBlock` calls — Azure's * append semantics demand whole-line atomicity for the `.index.jsonl` * linearisation story to hold for `current-N.jsonl` too. */ export declare class RecordTooLargeError extends Error { readonly recordId: string; readonly bodyBytes: number; readonly cap: number; constructor(recordId: string, bodyBytes: number, cap: number); } /** * Why a producer closed: an explicit `close()`, a lost lease, an append whose * outcome could not be determined, a failed batch whose `_abort` could not be * written, or storage that contradicts the index during a rollover. */ export type ProducerClosedReason = 'closed' | 'lease-lost' | 'append-outcome-unknown' | 'batch-abort-failed' | 'index-inconsistent'; /** Which limit a {@link BatchTooLargeError} hit. */ export type BatchTooLargeLimit = 'maxSendBatchBytes' | 'maxBatchBytes' | 'generationCapacity'; /** * A batch is too large: `sendBatch` past `maxSendBatchBytes`, a batch past one * block without `allowMultiBlockBatches`, or a multi-block batch that does not * fit the generation's remaining capacity (which aborts it). */ export declare class BatchTooLargeError extends Error { readonly records: number; readonly bytes: number; readonly cap: number; readonly limit: BatchTooLargeLimit; constructor(records: number, bytes: number, cap: number, limit: BatchTooLargeLimit); } /** Why a batch no longer accepts calls. */ export type BatchClosedReason = 'committed' | 'aborted' | 'idle-timeout' | 'failed'; /** `append`, `commit` or `abort` was called on a batch that has already finished. */ export declare class BatchClosedError extends Error { readonly batchId: string; readonly reason: BatchClosedReason; constructor(batchId: string, reason: BatchClosedReason); } /** * `send()` was called on a producer that has been closed (either by an * explicit `close()` or after a fatal error). */ export declare class ProducerClosedError extends Error { readonly reason: ProducerClosedReason; constructor(reason: ProducerClosedReason); } /** * An append failed and the producer could not tell whether it landed, so the * records may have been written. The producer closes; reconcile by replaying * from `firstOffset` and matching on record ids (or `batchId`). */ export declare class AppendOutcomeUnknownError extends Error { readonly gen: number; readonly firstOffset: bigint; readonly lastOffset: bigint; readonly cause: Error; readonly batchId?: string | undefined; constructor(gen: number, firstOffset: bigint, lastOffset: bigint, cause: Error, batchId?: string | undefined); } export { IndexInconsistencyError } from './errors.js'; /** * Configuration for {@link Producer.start}. The only required fields are * `storage`, `tenant`, and `topic`; everything else has documented defaults. */ export type ProducerOptions = { readonly storage: StorageProvider; readonly tenant: string; readonly topic: string; /** * When set, the producer wires a {@link SignalEmitter} and emits NOTIFY + * `topic_heads` upsert after every successful AppendBlock. Postgres is * OPTIONAL — without it consumers fall back to polling. */ readonly postgres?: { readonly pool: Pool; readonly leaderId?: string; /** * Schema containing `topic_heads`. Must match the `schemaName` passed * to `applyMigrations` (default `streams`). The library does not infer * this from the database at runtime — if migrations went into a * non-default schema, pass the same name here. */ readonly schemaName?: string; /** * Minimum interval between successive `pg_notify` + `topic_heads` emits * for this producer. Default 200 ms (= 5 emits/s/producer). The * `pendingEmitPayload` coalescing already collapses many flushes into a * single in-flight emit; this throttle adds a wait-floor between emits * so that under sustained high flush rate the producer doesn't pound * Postgres at the AppendBlock cadence (which can saturate a Burstable * Postgres tier and add wake-up CPU pressure on every subscribed * consumer's pg-listen path). Set 0 to disable. * * Trade-off: a record's NOTIFY can be up to `minEmitIntervalMs` later * than the AppendBlock ack. Consumer wake-up latency rises by ≤ that * value. At 100–500 evt/s the wake-up latency is well under SLA even * with a 200 ms throttle; at thousands of evt/s the throttle is moot * because the polling fallback dominates anyway. */ readonly minEmitIntervalMs?: number; }; /** Batch coalescing window. Default 10 ms (ADR-0008). */ readonly coalesceWindowMs?: number; /** Flush early when the in-batch record count reaches this threshold. Default 500 (ADR-0008). */ readonly maxBatchRecords?: number; /** Reject `send()` when the queue holds this many records or more. Default 10 000 (ADR-0008). */ readonly maxQueueDepth?: number; /** Azure lease TTL in seconds. Azure's max is 60 for renewable leases (ADR-0004). */ readonly leaseTtlSeconds?: number; /** * Per-call timeout for `acquireLease()` operations (in milliseconds). Default * 30 000 ms. The producer issues `acquireLease` at three points: bootstrap * (`Producer.start` against the current generation's blob), takeover after a * deposed leader, and rollover (acquiring the lease on the freshly-created * `current-(N+1).jsonl`). Each call is bounded by this timeout; on expiry * the broker rejects with `LeaseAcquisitionTimeoutError` so callers can bail * cleanly instead of hanging on long-tail Azure responses. Set 0 to disable. */ readonly leaseAcquisitionTimeoutMs?: number; /** Flush early when accumulated body bytes approach Azure's 4 MiB AppendBlock cap. Default 3 MiB. */ readonly maxBatchBytes?: number; /** * Block-count threshold that triggers a rollover. Defaults to 40 000 — well * under Azure's 50 000-blocks-per-blob ceiling. The threshold is exposed * primarily so tests can force a rollover at small block counts; production * deployments should leave it at the default. */ readonly maxBlockCountBeforeRollover?: number; /** Byte-size threshold that triggers a rollover. Default 256 MiB. */ readonly maxBytesBeforeRollover?: number; /** * Part-count threshold that triggers a rollover (ADR-0024): the producer * rolls once it has written this many `appendBlock`s (coalesced batches) into * the current generation. Default 4096. This is the lever that bounds * parts-per-generation on substrates with no block-count ceiling (the S3 * `object-per-batch` strategy — ADR-0023): without it a chatty small-record * topic could accrue ~65 000 tiny parts before the 256 MiB byte trigger fired, * blowing up the live read fan-out and the per-gen compaction join. On Azure * it is dormant in practice (the byte/elapsed triggers fire first in the * regimes Azure runs in). Exposed primarily so tests can force a small value; * production deployments should leave it at the default. The count restarts at * 0 when a producer takes over a live generation (same restart semantics as * `maxElapsedMsBeforeRollover`, ADR-0011). */ readonly maxPartsBeforeRollover?: number; /** * Monotonic-elapsed threshold that triggers a rollover, **gated by * `minBytesBeforeElapsedRollover`**: it fires only once the segment has * reached that size, so a moderately-active topic seals on time while a * low-volume one is deferred to the hard backstop. Default 24 h. Seeded from * `process.hrtime.bigint()` at every `_open` so wall-clock skew (NTP storms, * container clock drift, leader-handover skew) never gates rollover. * * The predicate is evaluated **only after an AppendBlock** — a cold topic * that has gone past the threshold without a `send()` does not roll until * the next `send()` arrives. The trigger's contract is "the next record * after the threshold causes a rollover", not "wake up at threshold + 1 ms". * * Tests typically force a small value (e.g. 50 ms). See ADR-0011. */ readonly maxElapsedMsBeforeRollover?: number; /** * Size floor for the elapsed trigger: `maxElapsedMsBeforeRollover` fires only * once `current-N` has reached this many bytes, so a low-volume topic does * not seal a one-record segment every elapsed window (which would make a * full-stream read fetch hundreds of tiny files). Default 4 MiB. Set 0 to * disable the gate; the hard backstop still guarantees eventual archival. */ readonly minBytesBeforeElapsedRollover?: number; /** * Hard elapsed backstop: roll regardless of size once this long has elapsed * (on the next `send()`), so a topic that never reaches * `minBytesBeforeElapsedRollover` still seals + archives. Default 7 d. Must * be ≥ `maxElapsedMsBeforeRollover`. */ readonly maxElapsedMsHardBackstop?: number; /** * Maximum number of `appendBlock` attempts (including the first) when * the storage provider raises {@link TransientStorageError}. Default 5. * The retry uses exponential backoff between * `transientRetryBaseMs` and `transientRetryCapMs` with jitter; the * cumulative worst-case wait is bounded by * `transientRetryBaseMs * (2^attempts - 1)`. Set to 1 to disable * application-layer retry and propagate transient errors immediately. */ readonly transientRetryMaxAttempts?: number; /** Base backoff for transient retries in milliseconds. Default 50 ms. */ readonly transientRetryBaseMs?: number; /** Backoff ceiling for transient retries in milliseconds. Default 2 000 ms. */ readonly transientRetryCapMs?: number; /** * Let a batch span several append blocks, committed by a `_commit` sentinel * (ADR-0030). Default `false`. Readers older than 0.5.0 cannot read such * batches. Azure only: rejected for a provider without `supportsMultiBlockBatches`. */ readonly allowMultiBlockBatches?: boolean; /** Largest estimated size of the records `sendBatch` accepts, since it holds them all in memory. Default 64 MiB. */ readonly maxSendBatchBytes?: number; /** An open batch with no `append` for this long is aborted. Default 60 000 ms. */ readonly batchIdleTimeoutMs?: number; /** * Compaction sub-options. Per ADR-0013 the compactor runs in this process * as a `setInterval` task; per ADR-0014 it deletes old `current-N` blobs * after a grace window. Defaults are production-sane (30 s tick, 24 h * grace); tests force small values for deterministic behaviour. Pass * `enabled: false` to disable compaction entirely (useful for unit tests * that exercise the producer in isolation). */ readonly compaction?: { readonly enabled?: boolean; readonly intervalMs?: number; readonly gracePeriodMs?: number; readonly now?: () => number; /** * Producer-queue-depth threshold at which the compactor defers its * tick. Default 5 000 (half the default `maxQueueDepth`). Compactor * skips with a counter increment; archival work catches up when the * queue drains. Correctness-safe because the unarchived sealed blob * remains readable until 24 h after `segment_archived` lands in the * index (ADR-0014). Set to 0 to disable deferral. */ readonly deferQueueDepthThreshold?: number; /** * Parquet conversion via DuckDB (ADR-0012). Default `true` when the * storage provider supports DuckDB URL building (currently only the * Azure implementation). Set `false` to ship JSONL-only archives. * * The conversion runs in an isolated child process (ADR-0028); the * `memoryLimit` / `threads` / `workerTimeoutMs` knobs tune that child. */ readonly parquet?: { readonly enabled?: boolean; readonly secretTtlSeconds?: number; /** DuckDB `memory_limit` for the conversion child. Default `'1GB'`. */ readonly memoryLimit?: string; /** DuckDB `threads` for the conversion child. Default `2`. */ readonly threads?: number; /** Hard cap before a stuck conversion child is killed (→ JSONL-only). Default 5 min. */ readonly workerTimeoutMs?: number; }; }; }; /** Options for {@link Producer.openBatch}. */ export type OpenBatchOptions = { /** Caller-chosen batch id, at most 256 characters. Default `--`. */ readonly batchId?: string; /** The batch's expected encoded size, so the producer can roll over first if it will not fit the current generation. */ readonly expectedBytes?: number; }; /** Options for {@link Producer.sendBatch}. */ export type SendBatchOptions = { /** Caller-chosen batch id, at most 256 characters. Default `--`. */ readonly batchId?: string; }; /** Result of {@link ProducerBatch.commit}. */ export type BatchCommitResult = { readonly offsets: readonly [first: bigint, last: bigint]; readonly count: number; readonly batchId: string; }; /** Result of {@link Producer.sendBatch}; `offsets` are in record order. */ export type SendBatchResult = { readonly offsets: bigint[]; readonly batchId: string; }; /** * An open atomic batch (ADR-0030). It holds the producer's write slot until it * commits or aborts; calls are serialised in the order they are made. */ export type ProducerBatch = { readonly batchId: string; /** Add records to the batch, writing full blocks as they fill. Nothing is delivered until `commit`. */ append(records: readonly UserRecord[]): Promise; /** Write the rest of the batch and commit it. */ commit(): Promise; /** Abandon the batch. Records already written are marked aborted and never delivered. */ abort(): Promise; }; /** * Single-topic producer. Constructed via {@link Producer.start}. The * constructor is private — start performs the lease acquisition, fresh-topic * bootstrap, and recovery dance, and we want the public API to make that * I/O explicit. */ export declare class Producer { private readonly opts; private currentGen; private currentPath; private currentLease; private committedLength; private committedBlockCount; /** `committedBlockCount` is a resumed generation's line count, not yet replaced by an append response's count. */ private committedBlockCountEstimated; private committedIndexLength; private nextOffset; /** The last offset a reader can be delivered: past an aborted batch's offsets, NOTIFY must not announce them. */ private deliveredOffset; /** * Monotonic timestamp (`process.hrtime.bigint()` nanoseconds) at which the * current generation was opened from THIS producer's perspective. Drives the * `maxElapsedMsBeforeRollover` trigger (ADR-0011). Seeded at producer * bootstrap and re-seeded after every `_open` write in `rollover()`. * * **Restart semantics**: this is process-local. A producer that takes over * mid-generation (after the previous leader died) starts a fresh elapsed * window from its own startup — the previous leader's elapsed time is not * preserved. ADR-0011 §Consequences explains why this is acceptable: * the trigger's purpose is "cold topic eventually rolls", not "exactly N * hours wall-clock". */ private openedAtMonotonic; /** * Number of `appendBlock`s (coalesced batches == parts) written into the * current generation. Drives the `maxPartsBeforeRollover` trigger (ADR-0024) — * the only rollover bound on substrates with no block-count ceiling (S3 * `object-per-batch`). Incremented after every successful data append, reset * to 1 (the `_open` part) after every rollover, and seeded at bootstrap: 1 for * a fresh topic, 0 on resume (a taking-over producer cannot cheaply recover the * prior part count, so it restarts the window — the same process-local restart * semantics as {@link openedAtMonotonic}; the byte trigger still bounds the * worst case). */ private partsThisGen; /** The current gen holds a multi-block batch or a stale seal, so its `_seal` carries `has_batch_markers` (ADR-0030). */ private genHasBatchMarkers; private leaseRenewer; private compactor; private readonly signal; private readonly pendingRecords; private coalesceTimer; private flushInFlight; private rolloverInFlight; /** * Held by an open batch (ADR-0030): while set, no flush runs and queued * records wait. `released` resolves when the batch commits or aborts. */ private writeSlot; /** `openBatch` and `sendBatch` calls waiting for the write slot, in call order. */ private readonly batchWaiters; /** The batch holding the write slot, until it ends; `close()` aborts it if an `openBatch` handle still holds it open. */ private activeBatch; /** * The new generation's lease while a rollover is mid-flight, so a retried * rollover reuses it while it is still held instead of failing to acquire * a lease this producer already holds. Cleared when the rollover completes. */ private pendingRollover; /** Set once this generation's `_seal` has landed: no data may follow it, so the rollover must finish first. */ private sealedEndOffset; /** * Coalesced background emit. `pendingEmitPayload` holds the most recent * `(gen, offset, byte, at)` tuple the producer wants to push to Postgres. * The drainer fires one emit at a time; if more flushes happen while an * emit is in flight, they overwrite `pendingEmitPayload`. When the in-flight * emit completes, the drainer fires ONE more emit with whatever the latest * payload is — never the intermediates. * * Why this is safe: `topic_heads.head_offset` is UPSERTed (only the latest * value matters). The NOTIFY is a wake-up signal — the consumer reads the * blob to find out what's actually there, so dropping intermediate wake-ups * doesn't lose records; the consumer's read shows the same final state * either way. * * Worst-case queue depth: 2 (one in flight, one pending). Under a burst of * 100 sends arriving while one emit is in flight, we run 2 emits, not 100. */ private pendingEmitPayload; private emitDrainer; /** * Wall-clock ms at which the last `signal.emit` resolved. Used together * with `opts.postgres.minEmitIntervalMs` to throttle the emit drainer so * a producer flushing at AppendBlock rate (~100/s) doesn't emit a * `pg_notify` per flush — under sustained high rate the upstream Postgres * (Burstable) saturates and every consumer's `pg-listen` path takes the * per-notification CPU hit. Default is 5 emits/s/producer * (`minEmitIntervalMs: 200`). */ private lastEmitAt; private closed; private closedReason; /** * Shared promise for an in-flight `close()` so concurrent callers * receive the same outcome and the cleanup logic runs exactly once. */ private closingPromise; /** Cleanup started by a fatal close; a later `close()` waits on it instead of running again. */ private fatalCleanup; /** The unknown-outcome error that closed the producer, so a draining `close()` can reject with it. */ private fatalError; private readonly tracer; private readonly meter; private readonly flushDuration; private readonly sendToFlush; private readonly recordsCounter; private readonly rolloversCounter; /** A non-zero rate means a rollover is stuck. */ private readonly rolloverRetryCounter; private readonly leaseLostCounter; /** * Application-layer retries of `appendBlock` against * {@link TransientStorageError}. Tagged with the 1-indexed attempt * number so dashboards can distinguish "first retry recovered" (cheap, * expected under spiky Azure load) from "third retry recovered" * (signals a sustained substrate issue). */ private readonly appendRetryCounter; /** * Wall-clock duration of a retried `appendBlock` cycle (first attempt * through last). Tagged `outcome=recovered|exhausted`. */ private readonly appendRetryDurationHistogram; /** * Regular Gauge for queue depth, recorded explicitly at every enqueue * and dequeue. A regular Gauge (vs ObservableGauge) has no persistent * callback — `record()` is the only way values appear — so a closed * Producer does not leak a per-instance closure. */ private readonly queueDepthGauge; /** * Regular Gauge for the active current-N's committed block count. Same * no-closure-leak rationale as {@link queueDepthGauge}. Recorded after * every successful `appendBlock` (writeBatch's Phase 2) and after a * rollover swaps generations. */ private readonly currentBlockCountGauge; private constructor(); /** * Start a producer for `(tenant, topic)`. Reads `.index.jsonl`, identifies * (or bootstraps) the current generation, acquires the lease on the current * `current-N.jsonl`, and starts the lease renewer + coalescer. Per * ADR-0007, a `LeaseAlreadyHeldError` propagates to the caller — that * means someone else is the producer for this topic, and the calling * process should exit. */ static start(opts: ProducerOptions): Promise; /** * Enqueue a record for publication. The returned promise resolves with the * record's assigned offset once the next `AppendBlock` ack arrives (ADR-0008). * Back-pressure: when the queue holds `maxQueueDepth` records, `send()` * rejects synchronously with {@link QueueFullError} (ADR-0007). * * Reserved-field validation (ADR-0008 wire format / `frame.ts`): a record * carrying a top-level `_seal` or `_open` key throws synchronously via * `assertNoReservedFields`. */ send(record: UserRecord): Promise<{ offset: bigint; }>; /** * Open an atomic batch (ADR-0030). Resolves once records queued before it are * written; later `send()`s and batches wait until it commits or aborts. A * batch past one block needs `allowMultiBlockBatches`. */ openBatch(options?: OpenBatchOptions): Promise; /** * Wait for the write slot, finish any pending rollover, reserve the space * `plan` asks for (rolling over first if the current generation lacks it), * then start the batch. `plan` sees the batch's id and first offset and may * throw to refuse the batch before anything is written. A `sendBatch` granted * the slot while the producer closes still runs; an `openBatch` handle does not. */ private openBatchWith; /** * Write `records` as one atomic batch. Throws {@link BatchTooLargeError} past * `maxSendBatchBytes`, or {@link RecordTooLargeError} when one record cannot * fit a block, before writing anything. */ sendBatch(records: readonly UserRecord[], options?: SendBatchOptions): Promise; /** * Let an in-flight or queued `sendBatch` commit, abort a batch open through * an `openBatch` handle, flush any pending records, stop the lease renewer, * release the lease, and close the signal emitter. After `close()`, * subsequent `send()` calls reject with {@link ProducerClosedError}. Idempotent. */ close(): Promise; private closeInternal; /** * Stop the background workers, release leases and drain + close the signal * emitter. Shared by `close()` and every fatal close; each step is * best-effort and clears its field, so running it twice is harmless. */ private releaseResources; /** Current generation number (the `N` in `current-N.jsonl`). */ get generation(): number; /** Path of the currently-open `current-N.jsonl`. */ get currentBlob(): string; /** Next offset that the producer would assign on the next `send()`. */ get nextOffsetForTesting(): bigint; /** Current pending-queue depth. Exposed primarily for diagnostics. */ get queueDepth(): number; /** * `true` once `close()` has been called or a fatal error (lease loss, an * unknown append outcome) closed this producer. Subsequent `send()` calls reject with * {@link ProducerClosedError}. Mirrors `Consumer.isClosed` for symmetry. */ get isClosed(): boolean; /** If {@link isClosed} is `true`, the reason it closed. Otherwise `undefined`. */ get closedReasonOrUndefined(): ProducerClosedReason | undefined; private scheduleFlush; private triggerFlushSoon; /** Start whatever write is due next: a waiting batch whose turn has come, else a flush of queued records. */ private pumpWriteSlot; /** Hand the write slot to the first waiting batch once nothing is in flight and the records queued before it are written. */ private grantWriteSlot; private releaseWriteSlot; /** * Take a snapshot of pending records, encode them, append in one `AppendBlock`, * resolve promises, fire the optional signal. Settles every append failure * against the segment per ADR-0030; treats `LeaseLostError` as fatal per * ADR-0004 / ADR-0007. * * Splits oversized batches in half and rejects single records that exceed * `maxBatchBytes`. */ private flushOnce; /** * Take everything currently pending, up to `maxBatchRecords` and never past * the first waiting batch, into an exclusive snapshot. Items in the snapshot * have been removed from the queue — resolving their promises is now the * snapshot's responsibility. */ private takeSnapshot; /** * Encode a snapshot's records exactly once, baking each record's assigned * offset (`nextOffset + index`) into its wire line. Bisect preserves these * offsets because the single-in-flight-flush invariant (H1) means * `nextOffset` only advances via this snapshot's own `writeBatch` calls * (front-half before back-half), so `nextOffset + index` is exactly the * offset each `writeBatch` would otherwise compute. `ts` is stamped here, * once — a constant-length ISO string, so the byte-length sizing below is * stable regardless of when within the flush it is stamped (M3). */ private encodeSnapshot; /** * Attempt to publish `items` as a single `AppendBlock`. If the encoded body * exceeds `maxBatchBytes`, split in half and recurse. If a single record * exceeds the cap, reject that record with {@link RecordTooLargeError} and * publish whatever is left. */ private flushSnapshot; /** * Append `bytes` to `target` and settle the outcome before anything else is * appended (ADR-0030). Every failure is read back: this attempt's own bytes at * the expected position mean it committed; anything other than an unchanged * segment end is unknown. With nothing there, a lost lease or a validation 4xx * is a definite failure only if no earlier attempt was ambiguous; any other * error (a mismatch included) is ambiguous and retried within the transient * budget (ADR-0020), so a request that lands late is recognised by a later * read-back, and running out of attempts is unknown. */ private appendWithVerifiedOutcome; /** * What the segment at `path` holds at `position`: these exact bytes, nothing * yet, or something else. A read that keeps failing is `unknown`. */ private verifyAppend; /** Exponential backoff with jitter, floored at 1 ms so a misconfigured base does not busy-spin. */ private retryDelayMs; private recordAppendRetryDuration; /** * Write `items` as one `AppendBlock` against `currentPath`, then advance * committed state. A lost lease closes the producer; an unknown outcome * rejects the batch with {@link AppendOutcomeUnknownError} and closes it; a * proven rejection rejects the batch and rethrows, leaving offsets unadvanced. */ private writeBatch; /** * Best-effort NOTIFY/topic_heads emit of the last deliverable `offset` and the committed byte length. * Coalesced fire-and-forget — see `pendingEmitPayload` JSDoc above. */ private emitHead; /** Roll over when any trigger has fired. Runs only between writes, never inside a batch. */ private rolloverIfDue; private rolloverNow; private rejectItems; /** * Lease loss (ADR-0004 / ADR-0007) and an unknown append outcome (ADR-0030) * are fatal. Mark the producer closed and reject every queued record at once, * then run the same cleanup as `close()`. Subsequent `send()` calls reject * with `ProducerClosedError`, and a later `close()` is a no-op that waits for * this cleanup. The caller's orchestrator decides whether to restart. */ private markClosedFatally; /** Close fatally after an unknown outcome; a lease lost after an ambiguous attempt closes as lease-lost. */ private closeOnUnknownOutcome; /** * Drainer for the coalesced background emit. Loops while there's a pending * payload, firing one `signal.emit` at a time and picking up whatever the * latest payload is on each iteration. Errors are swallowed because the * emitter is best-effort per ADR-0003 — propagating up here would just * crash the background task. * * Concurrency note: Node is single-threaded but async/await yields at every * `await` point, so the `writeBatch` site could race with the drainer's * exit. We unset `emitDrainer` in the body's synchronous `finally` (NOT in * a chained `.finally()`) so the unset happens BEFORE the returned Promise * resolves — closing the window where `writeBatch` could see "drainer * already running" while the loop has actually exited. */ private drainPendingEmits; /** Create the batch that now holds the write slot. */ private startBatch; /** * Encode `sendBatch`'s records with the batch's real id and offsets, and work * out the blocks the writer will pack them into, so the size check and the * capacity reservation are exact. Encoding stops at the first record past * `maxSendBatchBytes`, so an oversized array is never encoded whole. Throws * before anything is written. */ private planSendBatch; /** Encode a batch's `index`th record, rejecting it if it cannot fit a block. */ private encodeBatchRecord; /** Run one batch call after the calls before it, with the idle timer paused while it runs. */ private runBatchCall; private armBatchIdleTimer; /** * Check every record before accepting any, so a rejected `append` leaves the batch as it was, then encode and * buffer them one at a time, so no more than about a block of encoded lines is held whatever the array's size. * Both passes read one snapshot of each record's fields, so neither the caller's array nor a record's getters * can change what was checked. */ private appendToBatch; /** Buffer encoded lines, all or none past the size check, writing full blocks as the buffer outgrows one. */ private bufferBatchLines; /** Without multi-block batches, refuse `count` more records of `bytes` that would outgrow one block. */ private assertBatchFits; /** Buffer one encoded line, writing full blocks first when it would outgrow one. */ private bufferBatchLine; /** Write blocks from the front of the buffer until `keepRoom` more bytes fit beside what remains. */ private writeFullBatchBlocks; /** * Write the rest of the batch: one block for a single-block batch, or the * final block ending in `_commit` for a multi-block one. */ private commitBatch; /** * Append one block of the batch, settling its outcome (ADR-0030 §1). A * multi-block batch first checks the generation still has room for the * block and the sentinels after it. A definite failure ends the batch * uncommitted; a lost lease or unknown outcome closes the producer. */ private writeBatchBlock; /** * End a batch that will not commit. If any of it was written, append `_abort` * over the written range and move `nextOffset` past it, so those offsets are * never reused. When `_abort` cannot be written the producer closes and the * next lease holder writes it on resume. */ private endUncommittedBatch; /** Release the write slot once a batch ends, checking rollover first: no rollover ever runs inside a batch. */ private finishBatch; /** * Before a multi-block batch of `expectedBytes` in `blocks` appends, roll over * if it will not fit the current generation, and throw if it would not fit an empty one. */ private reserveGenerationFor; /** Whether the current generation can take `blocks` more blocks of `bytes` and still fit the batch sentinels and `_seal`. */ private generationHasRoom; /** Blocks a generation can hold: Azure's hard limit. `maxBlockCountBeforeRollover` is only a rollover trigger. */ private batchBlockCap; /** Approximate bytes a multi-block batch can hold in an empty generation, for {@link BatchTooLargeError}. */ private emptyGenerationCapacityBytes; /** Advance committed state after an append to the current generation; one append is one part (ADR-0024). */ private recordAppend; /** * Roll over `current-N` → `current-(N+1)`. Seals the old current with a * `_seal` sentinel, creates and leases the new current, writes its `_open` * sentinel, and appends the `rollover` line to `.index.jsonl` — that index * append is the linearisation point. The archive of the sealed generation * to `segments/` is the compactor's job. * * **Resumability** (ADR-0030 §5): every step is idempotent under retry, and a * rollover that throws partway is retried before any further data append. A * landed `_seal` is not written again; the new generation's lease is renewed * alongside the current one and reused only while still held; what the new * generation already holds decides whether `_open` is written, kept or * superseded; and the index line goes through the guarded append. */ private rollover; /** * The new generation's lease: an earlier attempt's while it is still held, * else a fresh one, waiting up to the lease TTL for another holder's to * expire. It is renewed alongside the current lease until the swap. A lease * that was lost or may have expired is never reused; failing to reacquire it * closes the producer, releasing the current lease. */ private leaseNextGeneration; /** Whether a stashed lease is still this producer's: not lost, renewed within its TTL, and renewable now. */ private stillHolds; /** Stop renewing a stashed rollover lease and release it, best-effort. */ private dropPendingRollover; /** * Make the new generation start with an `_open` at this producer's next * offset. An empty blob gets one. A blob already opened at that offset (an * earlier attempt landed) is kept. One holding only older `_open`s, left * when the old generation gained data after a failed rollover, gets a * superseding `_open`: readers take the last `_open` before the first data * frame. Anything else closes the producer with {@link IndexInconsistencyError}. */ private openNextGeneration; /** * Finish what a predecessor left at the tail of the resumed generation * (ADR-0030 §5): abort a multi-block batch it never committed, then complete * a rollover it sealed but never recorded in the index. */ private finishInterruptedWrites; /** * Append `_abort` over a multi-block batch a predecessor left open, so its * frames are never delivered and its offsets never reused. If something else * lands first — the deposed producer's `_commit`, say — the tail is re-scanned * and the abort written only if the batch is still open. Returns the seal now * at the tail, if any. */ private abortOpenBatchAtTail; /** Return a settled sentinel append's result, or close the producer as a data append would and throw. */ private settleSentinelAppend; private startLeaseRenewerForCurrent; } /** * {@link ProducerOptions} plus a test seam that is not part of the public API: * a generation's hard block capacity, so tests can reach it with a few blocks. */ export type InternalProducerOptions = ProducerOptions & { readonly generationBlockCapForTesting?: number; }; //# sourceMappingURL=producer.d.ts.map