/** * `.index.jsonl` append/read protocol. * * This module is the typed, OTEL-instrumented gateway to the broker's single * linearization point: the `.index.jsonl` append blob that records every * segment-lifecycle event for a topic (ADR-0006). One JSON object per line, * each line written by exactly one `AppendBlock` call — atomic per Azure * semantics — so the index can never tear mid-write. * * Read discipline (ADR-0006): hot code paths consult `.index.jsonl` and never * enumerate the substrate via `listPrefix`. This module is the only sanctioned * way to do that consultation. * * Write discipline (ADR-0007): the producer process is the broker. It is the * sole writer of `.index.jsonl` (the compaction worker runs *inside* the * producer process). Consequently `.index.jsonl` itself is NOT leased: the * producer-process already holds the lease on `current-N`, which fences the * only competing identity. `appendIndexRecord` takes `expectedPosition` * directly so the producer's in-memory committed-length counter drives * idempotent retry the same way it does for the data blob. * * Every public function is wrapped in an OTEL span `index.` with * `storage.blob` set to the index path. Append-record events increment a * counter keyed by event type; reads record a histogram of wall-clock latency. */ import { type AppendResult, type StorageProvider } from '../storage/types.js'; /** * Emitted when a brand-new `current-N.jsonl` is opened (either the very first * generation for a topic, or the new generation that the matching `rollover` * event sealed in the previous gen). Recorded as a standalone line only for * the very first generation; for later rollovers the `rollover` event carries * both the seal and the open atomically. */ export type CurrentOpenedRecord = { readonly event: 'current_opened'; readonly gen: number; readonly path: string; /** Record-counter offset (BigInt — serialized as decimal string on the wire). */ readonly start_offset: bigint; readonly at: string; }; /** * A single atomic rollover event combining `current_sealed` and the next * generation's `current_opened`. Written as one `AppendBlock` so consumers * never observe a half-rollover. */ export type RolloverRecord = { readonly event: 'rollover'; readonly sealed_gen: number; /** Last offset written to the sealed generation. */ readonly sealed_end_offset: bigint; readonly opened_gen: number; readonly opened_path: string; /** First offset of the new generation. */ readonly opened_start_offset: bigint; readonly at: string; }; /** * Emitted by the compaction worker — the second linearization point — once a * sealed generation's JSONL variant, and its Parquet variant when one was * produced, are durably uploaded and verified. * * `parquet_path` and `parquet_sha256` are null when the generation is * archived JSONL-only: Parquet is disabled, or its conversion failed or was * skipped. */ export type SegmentArchivedRecord = { readonly event: 'segment_archived'; readonly gen: number; readonly jsonl_path: string; readonly parquet_path: string | null; readonly jsonl_sha256: string; readonly parquet_sha256: string | null; /** Data frames in the archive (from 0.5.0; earlier archives counted every line). */ readonly row_count: number; readonly at: string; }; /** * Emitted after the 24-hour grace deletion of an old `current-N.jsonl`. The * sealed `segments/...` files remain — only the redundant `current-N` append * blob is gone. */ export type SegmentDeletedRecord = { readonly event: 'segment_deleted'; readonly gen: number; readonly at: string; }; /** Discriminated union of every line shape that may appear in `.index.jsonl`. */ export type IndexRecord = CurrentOpenedRecord | RolloverRecord | SegmentArchivedRecord | SegmentDeletedRecord; /** Summary view of a sealed (rollover'd) generation that has also been archived. */ export type SealedSegment = { readonly gen: number; readonly jsonlPath: string; readonly parquetPath: string | null; readonly startOffset: bigint; readonly endOffset: bigint; readonly rowCount: number; }; /** * Folded state of an `.index.jsonl` history, suitable for the producer's * startup recovery, the consumer's catch-up walk, and the compactor's * pending-seal scan. */ export type IndexState = { /** The current generation per the most recent `current_opened` or `rollover`. Null on a fresh topic. */ readonly currentGen: number | null; /** Blob path of the currently-open `current-N.jsonl`. Null on a fresh topic. */ readonly currentPath: string | null; /** First offset of the current generation. Null on a fresh topic. */ readonly currentStartOffset: bigint | null; /** Sealed generations that are archived AND not deleted, in append order. */ readonly sealedSegments: readonly SealedSegment[]; /** * Sealed-but-not-yet-archived generations (the compactor's worklist). * Each entry is the generation number; the start offset for each lives in * the source records, which the compactor re-reads when it needs them. */ readonly pendingSeals: readonly number[]; /** * Per-generation start/end offsets folded from `current_opened` / `rollover` * lines. Includes EVERY gen ever opened (live, pending, sealed) until a * `segment_deleted` removes it. `endOffset` is `null` for the still-open * gen and any gen that crashed mid-rollover. The consumer uses this to * skip already-dispatched pending seals on subsequent catchup invocations, * avoiding quadratic I/O when the compactor lags. */ readonly genOffsets: ReadonlyMap; /** Per-gen producer-emission envelope from current_opened/rollover `at` (sealedAt null = open). Approximate wall-clock — best-effort seek only. */ readonly genTimeBounds: ReadonlyMap; }; /** * Thrown by {@link readIndex} when a line in `.index.jsonl` cannot be parsed * or fails minimal shape validation. The module is the single source of truth * for the index format (ADR-0006), so a malformed line is a hard error — not * something to skip past silently. */ export declare class IndexCorruptedError extends Error { readonly indexPath: string; readonly byteOffset: number; readonly rawLine: string; readonly cause?: unknown | undefined; constructor(indexPath: string, byteOffset: number, rawLine: string, cause?: unknown | undefined); } /** * Append a record to `.index.jsonl` with bounded retry on * `AppendPositionMismatchError`. Producer (rollover) and compactor * (segment_archived / segment_deleted) both write to the same index, so * each can lose the position race against the other. A single retry is * not enough when both attempt to retry concurrently — they can race the * retry too. This helper loops with HEAD-and-retry up to `maxRetries` * (default 8) attempts. * * Returns the final committedLength so the caller can update its own * counter. The caller passes the current view of `committedLength` for * the FIRST attempt; this helper refreshes via HEAD on each retry. */ export declare function appendIndexRecordRobust(provider: Pick, indexPath: string, record: IndexRecord, initialExpectedPosition: number, maxRetries?: number): Promise<{ committedLength: number; }>; /** * Append a `rollover` line only while the index still says its `sealed_gen` is * current (ADR-0030 §6), so a paused, deposed producer can never move * `currentGen` backwards. `knownLength` is a length at which the caller knows * `sealed_gen` was current. Each attempt reads the lines after it and the * length they cover together, then appends, single-attempt, at exactly that * length. An identical line already there (same gens and offsets) is an * earlier attempt that landed, and counts as success even with compactor lines * after it; any other line that changes `currentGen` throws * {@link IndexInconsistencyError}. */ export declare function appendRolloverRecordGuarded(provider: Pick, indexPath: string, record: RolloverRecord, knownLength: number, maxAttempts?: number): Promise<{ committedLength: number; }>; /** * Range-read the entire `.index.jsonl` and parse every line into an * {@link IndexRecord}. * * Returns `[]` when the blob does not exist — the caller treats that as a * fresh topic with no prior state. Throws {@link IndexCorruptedError} on the * first malformed line: the index is the linearization point and trusting a * malformed entry would corrupt every downstream view of "what exists". * * @see ADR-0006 for why this is the only sanctioned enumeration primitive. */ export declare function readIndex(provider: Pick, indexPath: string): Promise; /** * Like {@link readIndex}, but also returns the blob length that the returned * records actually cover — i.e. the `head.length` used for the range read. * * Callers that cache the index and want to detect future growth incrementally * MUST seed their committed-length cursor from this value rather than issuing * a SECOND `head()` after the read. A re-HEAD opens a TOCTOU window: an index * append landing between the read and the re-HEAD makes the cursor claim to * cover bytes the cache is missing, and the consumer then sees "length * unchanged" forever and never parses them (H3). */ export declare function readIndexWithLength(provider: Pick, indexPath: string): Promise<{ records: IndexRecord[]; length: number; }>; /** * Append a single {@link IndexRecord} to `.index.jsonl` as exactly one JSON * line terminated by `\n`. Each call is one `AppendBlock` — atomic per Azure * semantics, so the index can never tear mid-write. * * `expectedPosition` is the producer's view of the index blob's current * committed length. The producer keeps this counter in-memory because it is * the only writer of `.index.jsonl` — there is no separate lease on the index * blob, and there does not need to be (see ADR-0007: the producer process is * the broker, and the existing lease on `current-N.jsonl` already fences the * sole identity that may write to either blob). Idempotent retry on transient * provider errors works exactly the same way it does for record appends to * `current-N`: re-issue with the same `expectedPosition` after refreshing via * `head()` if necessary. * * @see ADR-0007 — producer-equals-leader: no separate writer of the index. */ export declare function appendIndexRecord(provider: Pick, indexPath: string, record: IndexRecord, expectedPosition: number, options?: { readonly singleAttempt?: boolean; }): Promise<{ committedLength: number; record: IndexRecord; appendResult: AppendResult; }>; /** * Fold an in-order sequence of {@link IndexRecord}s (as returned by * {@link readIndex}) into a snapshot of "what exists right now". * * Pure function — no I/O, no allocation beyond the result. The fold rules: * * - `current_opened` (only seen at gen=1 in practice): sets `currentGen`, * `currentPath`, `currentStartOffset`. * - `rollover` N → N+1: moves gen N into `pendingSeals` and sets the current * fields to gen N+1's opened state. The fold also records gen N's * `(start, end)` offsets so the matching `segment_archived` event can * compute the segment span without a second pass. * - `segment_archived` for gen N: removes N from `pendingSeals`, adds a * {@link SealedSegment} entry using the offsets captured at rollover time. * - `segment_deleted` for gen N: removes N from `sealedSegments`. * * Tolerates out-of-order observations conservatively: a `segment_archived` * for a gen we have no offset memo for (because the index was truncated by a * future snapshot mechanism, say) is dropped from `pendingSeals` and added to * `sealedSegments` with zero offsets — the prototype simply does not truncate * yet. */ export declare function summariseIndex(records: readonly IndexRecord[]): IndexState; /** * `//current-NNNNNN.jsonl` (six-digit zero-padded generation). * e.g. `current-000007.jsonl`. */ export declare function currentBlobPath(tenant: string, topic: string, gen: number): string; /** * `//segments/NNNNNN-startOffsetX.` — the immutable sealed * variant (JSONL or Parquet). e.g. `segments/000001-startOffset12345.jsonl`. */ export declare function segmentBlobPath(tenant: string, topic: string, gen: number, startOffset: bigint, ext: 'jsonl' | 'parquet'): string; /** `//.index.jsonl` — the per-topic linearization point. */ export declare function indexBlobPath(tenant: string, topic: string): string; /** `//.consumer_groups/.offset` — leased per active consumer in a group. */ export declare function consumerGroupOffsetPath(tenant: string, topic: string, group: string): string; /** * `//.dead-letter/gen-NNNNNN-byte-BBBBBBBBBB.bin` — one * block blob per poison-frame incident. The key is deterministic on * `(gen, byte)` (no timestamp), so re-encountering the same poison frame * after a consumer restart is an idempotent `putBlockBlob`-with- * `ifNoneMatch` no-op (or, with overwrite, simply re-stamps the same * blob) rather than producing duplicates. * * The `ts` parameter is preserved in the function signature so callers * can still stamp the timestamp into the blob's metadata (see * Consumer.writeDeadLetter). */ export declare function deadLetterPath(tenant: string, topic: string, _ts: Date, gen: number, byte: number): string; /** * Wire schema version emitted on every `.index.jsonl` line. Bumped when a * new event type is added or an existing event's required fields change. * Consumers running an older library version see records with a higher * `v` and skip-with-counter rather than hard-erroring. Currently `1`. */ export declare const INDEX_SCHEMA_VERSION = 1; /** * Serialise an {@link IndexRecord} to its JSON wire form. Offsets (BigInt) * are emitted as decimal strings — see frame.ts file header for the rationale. * * Every record carries the `v` schema-version field so future readers * can identify lines emitted by older / newer libraries and apply * graceful-skip semantics for unknown event types. */ export declare function encodeIndexRecord(record: IndexRecord): string; /** * Parse a UTF-8 buffer containing the raw bytes of `.index.jsonl` (or any * suffix of it) into an array of typed records. Splits on `\n`. Trailing * newline is tolerated (the final empty line is ignored). Each non-empty * line MUST parse to a valid IndexRecord — otherwise an * {@link IndexCorruptedError} is thrown that includes the byte offset of * the malformed line. * * Exported so callers performing incremental index refresh (Consumer * wake-up loop) can parse the delta bytes without re-reading the whole * blob through {@link readIndex} every tick. */ export declare function parseIndexBytes(indexPath: string, bytes: Buffer): IndexRecord[]; //# sourceMappingURL=indexFile.d.ts.map