/** * Storage provider abstraction. * * The broker is provider-agnostic by design (ADR-0002). Azure Blob is the * only real implementation in the prototype; S3 is interface-only until a * later workstream. Any operation we need against the substrate goes through * this interface so the broker code never knows which substrate it is * talking to. * * Method contracts encode the non-negotiable correctness primitives: * - `appendBlock` is conditional on `expectedPosition` (ADR-0005). * - The lease is acquired on the data blob itself (ADR-0004). * - `rangeRead` handles short reads internally with retry/backoff. * - `putBlockBlob` with `ifNoneMatch=true` is the atomic "create-once" primitive * for sealed segments and the `current-(N+1)` initial creation. */ export type LeaseToken = { /** Provider-specific lease identifier. Must be presented on every mutating call against the leased blob. */ readonly id: string; /** Lease TTL in seconds, as actually granted by the provider (may differ from the requested TTL). */ readonly ttlSeconds: number; }; export type AppendResult = { /** Byte offset at which this block was written. From Azure: x-ms-blob-append-offset. */ readonly appendedAtOffset: number; /** Total committed length of the blob after this append. */ readonly committedLength: number; /** Total block count after this append. Used to enforce Azure's 50 000-block ceiling at the rollover trigger (40k). */ readonly committedBlockCount: number; }; export type RangeReadResult = { /** The bytes actually read. Length may be < (end - start + 1) only if the blob ended early. */ readonly bytes: Buffer; /** Total length of the blob at read time, per Content-Range / Content-Length. */ readonly totalLength: number; /** ETag of the blob at read time. */ readonly etag: string; }; export type BlobHead = { readonly length: number; readonly etag: string; /** Provider's last-modified timestamp. */ readonly lastModified: Date; }; /** * How a {@link StorageProvider.compactSegment} join was performed, and what it * cost. Provider-neutral (ADR-0025): Azure (and any single-object segment) reports * a `server-side-copy` that never transits the broker; S3 `object-per-batch` * reports a `download-concat` of all parts with the request count and bytes moved; * `consolidate-then-copy` is the `hybrid-rollup` fallback that had to fold a * lagging tail before the final copy. The compactor records this on its archive * span so the per-gen join cost is observable. */ export type SegmentCompactionResult = { readonly method: 'server-side-copy' | 'download-concat' | 'consolidate-then-copy'; /** Substrate requests issued for the join (LIST + GETs + the final PUT/COPY). */ readonly requests: number; /** Bytes pulled through the broker process (0 for a pure server-side copy). */ readonly bytesDownloaded: number; /** Bytes of the resulting single archived object. */ readonly bytesWritten: number; }; /** Outcome of {@link StorageProvider.createBlockBlobStaged}. */ export type StagedUploadResult = { readonly bytesWritten: number; /** Blocks (Azure) or parts (S3) the blob was committed from. */ readonly blocks: number; }; export type BlobInfo = { readonly path: string; readonly length: number; readonly etag: string; readonly lastModified: Date; }; /** * The exception class providers throw on a `412 Precondition Failed` analogue, * specifically when the supplied `expectedPosition` did not match the blob's * current committed length. The broker uses this to drive the recovery path * described in ADR-0005 (HEAD-and-reconcile). */ export declare class AppendPositionMismatchError extends Error { readonly expectedPosition: number; readonly actualCommittedLength: number | undefined; readonly path: string; constructor(expectedPosition: number, actualCommittedLength: number | undefined, path: string); } /** * Thrown by the provider when a transient substrate error (Azure * `ServerBusy`, `OperationTimedOut`, 5xx, socket reset, etc.) should be * treated as retryable at the broker layer. The provider is the only * place that classifies — the broker simply checks `instanceof * TransientStorageError` and applies its retry budget. The original * error is preserved via `cause` for diagnosis. */ export declare class TransientStorageError extends Error { readonly path: string; readonly operation: string; readonly cause: Error; constructor(path: string, operation: string, cause: Error); } /** * Thrown when the storage provider returns an `appendBlock` response that is * missing a required field (Azure's `x-ms-blob-append-offset` or * `x-ms-blob-committed-block-count`). ADR-0005 requires both come from the * server — falling back to caller-supplied or assumed values would break the * append-position invariant (a wrong offset corrupts subsequent appends) or * suppress the rollover trigger (a missing block count would freeze block * tracking at zero, letting `current-N` drift toward Azure's 50 000-block * hard ceiling without any operator-visible signal). */ export declare class AppendBlockResponseInvalidError extends Error { readonly path: string; readonly missingField: 'blobAppendOffset' | 'blobCommittedBlockCount'; constructor(path: string, missingField: 'blobAppendOffset' | 'blobCommittedBlockCount'); } /** * Thrown when a `putBlockBlob({ ifNoneMatch: true })` finds the destination * already exists. Used by the rollover flow and the sealed-segment archival * flow to make those operations idempotent. */ export declare class BlobAlreadyExistsError extends Error { readonly path: string; constructor(path: string); } /** * Thrown when a mutating operation against a leased blob is rejected because * the caller did not present the matching lease ID (or the lease has expired * and was acquired by someone else). The producer treats this as fatal: the * process must exit, the orchestrator decides whether to restart. */ export declare class LeaseLostError extends Error { readonly path: string; constructor(path: string); } /** * Thrown by `acquireLease` when another holder currently has the lease. */ export declare class LeaseAlreadyHeldError extends Error { readonly path: string; constructor(path: string); } /** * Thrown when a lease acquisition attempt exceeded the configured timeout * (`Producer.leaseAcquisitionTimeoutMs` or `Consumer.leaseAcquisitionTimeoutMs`). * * The provider call is racing against a timer at the broker layer; when this * error fires the underlying SDK request may still be in flight and may still * succeed on the substrate after we give up. Recovery: the orchestrator * restarts the process; the next attempt either sees the now-orphaned lease * (whose TTL bounds how long it can persist) or acquires cleanly. * * Motivated by observed lease re-acquisitions hanging on long-tail * Azure responses without an outer bound. */ export declare class LeaseAcquisitionTimeoutError extends Error { readonly path: string; readonly timeoutMs: number; constructor(path: string, timeoutMs: number); } export type AppendBlockOptions = { /** The committed length of the blob *before* this append. Must equal Azure's view or the call fails. */ readonly expectedPosition: number; /** * Lease to present with the append. Required when the target blob is leased * (`current-N.jsonl`, `.consumer_groups/.offset`); omitted when the * target blob is not leased by design (`.index.jsonl` — see ADR-0007: the * producer process is the broker and the sole writer, so the index does not * need its own lease). The provider passes the lease through to Azure's * `x-ms-lease-id`; when absent the call is made unconditionally on the * lease front, but still conditionally on `expectedPosition`. */ readonly lease?: LeaseToken; /** * Send one request with no SDK retry, as leased appends always are, so a retry * cannot turn an attempt that committed into a position mismatch (ADR-0030); * the caller settles the outcome itself. */ readonly singleAttempt?: boolean; }; export type PutBlockBlobOptions = { /** * When true, the call fails with `BlobAlreadyExistsError` if the destination * exists (Azure's `If-None-Match: *`). Always true for sealed segments and * `current-N` initial creation; the design relies on this being atomic. */ readonly ifNoneMatch: boolean; /** * Lease to present with the upload. Required when the target blob is leased * (see ADR-0010: the consumer-group offset blob is an overwrite block blob * fenced by a lease). Omitted when the target is a freshly-created sealed * segment that no one else holds. The provider passes it through to Azure's * `x-ms-lease-id` header; on lease mismatch the call fails with * {@link LeaseLostError}. */ readonly lease?: LeaseToken; }; export type CopyBlobOptions = { /** When true, the destination must not exist (atomic create-on-copy). */ readonly ifNoneMatchDst: boolean; }; export type StorageProvider = { /** True when consecutive conditional appends to one segment can carry a multi-block batch (ADR-0030); only Azure today. */ readonly supportsMultiBlockBatches?: boolean; /** * Create a new, empty append blob at `path`. Idempotent: succeeds whether or * not the blob already exists, but does not truncate an existing one. */ createAppendBlob(path: string): Promise; /** * Acquire a lease on `path`. The blob must already exist. TTL is clamped to * the provider's accepted range (Azure: 15–60 s, or -1 for infinite — but we * never use infinite leases, see ADR-0004 §renewal). * * Throws {@link LeaseAlreadyHeldError} if another holder currently has the * lease. */ acquireLease(path: string, ttlSeconds: number): Promise; /** * Renew an existing lease. Must be called before TTL expiry to keep ownership. * Throws {@link LeaseLostError} if the lease has expired and been taken by * someone else. */ renewLease(path: string, lease: LeaseToken): Promise; /** * Release a held lease, immediately freeing the blob for another acquirer. * Safe to call multiple times. */ releaseLease(path: string, lease: LeaseToken): Promise; /** * Append `bytes` to the append blob at `path` conditional on the current * committed length equalling `expectedPosition` (ADR-0005). The caller must * present the lease. * * Throws {@link AppendPositionMismatchError} on position mismatch (the caller * recovers via {@link head}). * * Throws {@link LeaseLostError} if the lease is no longer held. * * Azure constraints: `bytes` must be ≤ 4 MiB; the blob's block count * after this append must be ≤ 50 000. */ appendBlock(path: string, bytes: Buffer, options: AppendBlockOptions): Promise; /** * Read the entire blob at `path` in one provider round-trip. Returns `null` * when the blob does not exist (404). * * This is the right primitive when the caller knows the blob is small and * wants its full contents — typically state pointers like * `.consumer_groups/.offset` (ADR-0010) or a snapshot file. For * large blobs read incrementally (active `current-N.jsonl`, sealed * `segments/*.jsonl`), use {@link rangeRead} instead. */ read(path: string): Promise; /** * Read a byte range from `path`. If the provider returns fewer bytes than * requested (Azure's short-read on replication lag), the implementation * retries internally with backoff (~5 attempts over ~250 ms) before * returning. The returned `bytes.length` may still be < requested if the * blob genuinely ended early — callers must check. * * `start` is inclusive, `end` is inclusive (matches HTTP Range semantics). */ rangeRead(path: string, start: number, end: number): Promise; /** * Return blob length, etag, and last-modified time. Returns `null` when the * blob does not exist (404). Cheap — used by consumers in polling mode and * by the producer on recovery to re-derive `appendpos`. */ head(path: string): Promise; /** * Committed length of the logical segment at `path`. Returns 0 when the * segment is empty or absent. The parts-aware analogue of `head(path)?.length`. */ segmentLength(path: string): Promise; /** * Read bytes `[start, end]` (inclusive) of the logical segment at `path`, in * append order — the incremental tail-follow view a consumer uses to fetch * only the delta since its cursor. A ranged GET for a single-object segment; * an assembly of the overlapping part objects for a multi-part one. * `totalLength` reports the segment's committed length; `etag` is empty for a * stitched segment (no single-object identity). */ rangeReadSegment(path: string, start: number, end: number): Promise; /** * Compaction join: materialise the whole logical segment at `srcPath` as a * SINGLE object at `dstPath` — the sealed-segment archive the compactor writes * (ADR-0012). **Create-once**: throws {@link BlobAlreadyExistsError} if * `dstPath` already exists, so the compactor's crash-safety reconciliation * (ADR-0013: re-verify rather than re-copy) holds across providers. For a * single-object segment this is a server-side copy; for `object-per-batch` it * downloads + concatenates all parts and uploads one object (no server-side * concat — the parts are below S3's 5 MiB multipart minimum). Returns a * {@link SegmentCompactionResult} describing how the join was done. */ compactSegment(srcPath: string, dstPath: string): Promise; /** * Upload `bytes` as a single-shot block blob at `path`. Atomic per Azure * `PutBlob` semantics: the blob is visible whole or not at all. * * With `ifNoneMatch=true`, throws {@link BlobAlreadyExistsError} if `path` * already exists. This is the foundation of the sealed-segment archival and * `current-(N+1)` creation atomicity. */ putBlockBlob(path: string, bytes: Buffer, options: PutBlockBlobOptions): Promise; /** * Create a block blob at `path` from `blocks`, staging each block and * committing them together, so the caller never holds the whole blob in * memory (the compactor's archive rewrite, ADR-0030). Create-once: throws * {@link BlobAlreadyExistsError} if `path` already exists, before staging or * at the commit. The blob is visible whole or not at all. Blocks are pulled * one at a time; the caller may reuse a block once the next is pulled. */ createBlockBlobStaged(path: string, blocks: AsyncIterable): Promise; /** * Server-side copy from `srcPath` to `dstPath`. For Azure same-account * copies this is `Start Copy Blob`, which is typically synchronous in * practice. The promise resolves only once the destination is fully * written and visible. * * With `ifNoneMatchDst=true`, throws {@link BlobAlreadyExistsError} if * `dstPath` already exists. */ copyBlobServerSide(srcPath: string, dstPath: string, options: CopyBlobOptions): Promise; /** * List all blobs whose path starts with `prefix`. Returns an async iterable * so consumers can stream large listings without buffering. Sort order is * provider-default (Azure: lexicographic by full blob name). */ listPrefix(prefix: string): AsyncIterable; /** * Delete the blob at `path`. No-op (does not throw) if the blob does not * exist. Throws on any other provider error. */ delete(path: string): Promise; /** * **Optional.** Mint a short-lived URL bearing embedded credentials so an * external tool (DuckDB, curl, a co-located worker) can read or write * `blob` without a separate credential setup. Azure implements via * **SAS**; S3 would implement via **presigned URLs**; GCS via **signed * URLs**. The returned string is a full URL including the * credential-carrying query string. * * The broker's compactor uses this to bridge into DuckDB's blob * read/write without handing DuckDB the underlying storage credential * (preserves the CLAUDE.md §Credentials promise that the broker never * exposes caller-supplied credentials downstream). * * Optional because not every provider has a URL-with-embedded-credential * concept (e.g. test doubles, future filesystem-backed providers). * Callers gracefully degrade when this method is absent. * * `permissions` is a {@link StoragePermission} string-literal union * (currently SAS-shaped). When an S3 implementation lands the union * grows to cover IAM action strings. */ mintBlobUrl?(opts: { readonly blob: string; readonly permissions: StoragePermission; readonly expiresInSeconds: number; }): Promise; /** * **Optional.** Returns the URL DuckDB's blob extension uses to address * `blob` in this provider's container — e.g. `az:///` * (Azure), `s3:///` (S3), `gs:///` (GCS). * Defined on the interface (rather than via cast in the consumer) so * the compactor can detect Parquet-capable providers via property * presence, not runtime `typeof` checks. The broker treats the * returned string as opaque to DuckDB. */ buildDuckdbBlobUrl?(blob: string): string; /** * **Optional.** Mints a container-scoped credential for DuckDB's * `CREATE SECRET` statement (Azure: a SAS-bearing connection string; * S3 would be access-key/session pair; GCS would be a signed-URL * token). Returns the parameter body — caller wraps in the SECRET * statement. See {@link buildDuckdbBlobUrl} for the rationale on * having this on the interface. * * The return shape uses Azure-flavoured field names * (`blobEndpoint`, `sasToken`); future providers may either map their * concepts onto those fields (treating them as opaque "endpoint" + * "token" pairs) or extend the shape. */ mintStorageSecret?(opts: { readonly permissions?: StoragePermission; readonly expiresInSeconds: number; }): Promise<{ readonly blobEndpoint: string; readonly sasToken: string; }>; }; /** * Provider-neutral permissions for {@link StorageProvider.mintBlobUrl} * and {@link StorageProvider.mintStorageSecret}. * * Two provider dialects share this union: Azure SAS short-codes and S3 IAM * action strings. Each provider rejects codes outside its own subset at * runtime — passing an Azure code (`'cw'`) to the S3 provider, or an S3 * action (`'s3:PutObject'`) to the Azure provider, is both a usage error the * implementation throws on and, where the caller hard-codes a literal, a * compile-time narrowing the call site can guard. * * The two dialects are deliberately *not* unified into one abstract verb set: * SAS permissions are a packed flag string (`'racwd'` = read+add+create+ * write+delete) while IAM actions are discrete operation names, and the * minting APIs (`generateSasUrl` vs. a presigned `GetObject`/`PutObject`) * consume them differently. A lossy common enum would hide that. */ export type StoragePermission = 'r' | 'w' | 'c' | 'cw' | 'racwd' | 's3:GetObject' | 's3:PutObject' | 's3:DeleteObject' | 's3:ListBucket'; //# sourceMappingURL=types.d.ts.map