/** * Azure Blob implementation of {@link StorageProvider}. * * Wraps `@azure/storage-blob`. The point of this layer is to enforce the * broker's correctness primitives (ADR-0004 lease semantics, ADR-0005 append * position from response) in one place — the broker, producer, and consumer * never call the Azure SDK directly. * * Every public method is wrapped in an OTEL span with attributes: * storage.provider = "azure" * storage.container = * storage.blob = * storage.operation = * * Counters for total calls and durations are recorded on the meter. */ import { BlobServiceClient } from '@azure/storage-blob'; import { type AppendBlockOptions, type AppendResult, type BlobHead, type BlobInfo, type CopyBlobOptions, type LeaseToken, type PutBlockBlobOptions, type RangeReadResult, type SegmentCompactionResult, type StagedUploadResult, type StoragePermission, type StorageProvider } from '../types.js'; export type AzureBlobProviderOptions = { readonly serviceClient: BlobServiceClient; readonly containerName: string; /** * When true (default), the broker constructs an internal clone of the * caller's `serviceClient` with the broker's safe retry policy * (`maxTries: 2`, `maxRetryDelayInMs: 1_000`) applied. The caller's * original client is unmodified, so any other application code sharing * the client retains its own retry tuning. * * The default `@azure/storage-blob` retry policy retains in-flight * request bodies for up to 2 minutes per attempt; at sustained high * rate this triggers a `process.memoryUsage().arrayBuffers` cascade * that exhausts the container heap. The clone defangs the cascade * without forcing the caller to change their client's policy. See * ADR-0020. * * Set `false` ONLY when you have measured your production envelope * and have a custom retry policy that's safe at your scale. The * cloned client uses the caller's URL + credential exactly, so all * authentication shapes (connection string, account key, SAS in URL, * `DefaultAzureCredential`, managed identity, workload identity, * custom `TokenCredential`) are preserved transparently. * * **Caveat:** the clone is rebuilt from the source client's `url` + * `credential` only — it does NOT carry over any custom pipeline the * caller layered onto `serviceClient` (proxy settings, additional * `RequestPolicy` factories, custom telemetry policies). If you depend * on such a pipeline, pass `applySafeRetryPolicy: false` and bake the * broker's safe retry tuning into your own client instead. * * Whatever this is set to, leased appends (the producer's data and sentinel * writes) go through a separate single-attempt clone built the same way, so * an SDK retry can never hide an attempt that committed (ADR-0030). */ readonly applySafeRetryPolicy?: boolean; }; /** * Caches one Azure **user-delegation key** so AAD / managed-identity clients * fetch it once (`getUserDelegationKey` — the only network round trip) and then * sign many per-blob SAS offline, instead of one delegation-key call per blob. * Single-flights concurrent fetches; refetches when the cached key can't cover * the requested expiry. Shared-key clients bypass this entirely (offline sign). */ export declare class UserDelegationKeyCache { private readonly fetchKey; private readonly now; /** How long the fetched key should outlive the requested SAS expiry, so a batch of mints reuses one key. */ private readonly bufferMs; /** Azure caps a user-delegation key's lifetime at 7 days from its start. */ private static readonly MAX_KEY_LIFETIME_MS; private cached; private inflight; constructor(fetchKey: (startsOn: Date, expiresOn: Date) => Promise, now?: () => number, /** How long the fetched key should outlive the requested SAS expiry, so a batch of mints reuses one key. */ bufferMs?: number); /** * Return a key whose validity covers `neededUntilMs` (the SAS expiry) and the * key's own expiry (so the caller can clamp the SAS — a delegation SAS may not * outlive its key). Fetched once and reused while it still covers callers; * concurrent gets single-flight into one fetch. */ get(neededUntilMs: number): Promise<{ key: K; expiresOnMs: number; }>; } export declare class AzureBlobProvider implements StorageProvider { private readonly options; readonly supportsMultiBlockBatches = true; private readonly container; /** Single-attempt client for leased appends (ADR-0030); see {@link BROKER_SINGLE_ATTEMPT_RETRY_OPTIONS}. */ private readonly leasedAppendContainer; private readonly tracer; private readonly meter; private readonly durationHistogram; private readonly errorCounter; private readonly shortReadRetriesCounter; /** * Capability cache for `stageBlockFromURL`. Real Azure supports it * (server-side, no bytes through the broker process); Azurite returns * 501 ("Current API is not implemented yet"). After the first 501, we * remember the lack of support and use the client-driven chunked path * for subsequent copies. Production deployments hit the server-side * path on every copy. */ private serverSideStageFromUrlSupported; /** SAS minting mode, decided on the first mintBlobUrl via the SDK's own check, then cached. */ private sasMode; /** One cached user-delegation key for AAD/MI clients → offline per-blob signing. */ private readonly delegationKeyCache; constructor(options: AzureBlobProviderOptions); createAppendBlob(path: string): Promise; acquireLease(path: string, ttlSeconds: number): Promise; renewLease(path: string, lease: LeaseToken): Promise; releaseLease(path: string, lease: LeaseToken): Promise; appendBlock(path: string, bytes: Buffer, options: AppendBlockOptions): Promise; read(path: string): Promise; rangeRead(path: string, start: number, end: number): Promise; head(path: string): Promise; segmentLength(path: string): Promise; rangeReadSegment(path: string, start: number, end: number): Promise; compactSegment(srcPath: string, dstPath: string): Promise; putBlockBlob(path: string, bytes: Buffer, options: PutBlockBlobOptions): Promise; createBlockBlobStaged(path: string, blocks: AsyncIterable): Promise; copyBlobServerSide(srcPath: string, dstPath: string, options: CopyBlobOptions): Promise; /** * Server-side staged copy: mint a read SAS on the source, then have * Azure fetch chunks from the SAS-bearing URL directly into the * destination block blob's staged blocks. The broker does NOT touch * the bytes. Used on real Azure. */ private stageFromUrlAndCommit; /** * Client-driven staged copy: range-read the source in bounded chunks, * upload each chunk as a staged block, commit the block list. Memory * peak is one chunk. Used on Azurite (which does not implement * `stageBlockFromURL`). */ private clientStageAndCommit; listPrefix(prefix: string): AsyncIterable; delete(path: string): Promise; /** * Mint a short-lived SAS-bearing URL for `blob`. This is the bridge that * lets DuckDB (or any external tool) read/write Azure Blob using the * broker's existing credential, without exposing the credential itself. * * The implementation tries account-key SAS first — works when the * `BlobServiceClient` was constructed with a `StorageSharedKeyCredential` * (connection-string clients, including Azurite's). On failure (the * client was built from an AAD / managed-identity credential and has no * shared key) it falls back to **user-delegation SAS**: requests a * delegation key from Azure via the existing credential, then signs the * SAS with that key. The fallback works on real Azure with any * supported credential type; Azurite does not implement * user-delegation SAS in all versions, so connection-string Azurite * clients always take the account-key path. * * Permissions are read with `BlobSASPermissions.parse`. Common values: * - `'r'` — read only (source archives) * - `'cw'` — create + write (DuckDB COPY destination) * - `'racwd'` — full access (rarely needed; prefer least-privilege) * * The returned URL is opaque — pass it as-is to DuckDB / curl / etc. It * contains the SAS query string already. */ /** * Build the `az://` URL DuckDB's azure extension uses to address `blob` in * this provider's container. The URL is identifier-only — DuckDB resolves * credentials via a `CREATE SECRET` separately (see * {@link mintStorageSecret}). Returned as a plain string so the * compactor / experiment harnesses can build SQL. */ buildDuckdbBlobUrl(blob: string): string; /** * Mint a **container-scoped** SAS for DuckDB's azure extension. Returns * the components a DuckDB `CREATE SECRET (TYPE AZURE, CONNECTION_STRING * 'BlobEndpoint=...;SharedAccessSignature=...')` statement needs. * * Permissions are container-level (read+create+write+list by default, * configurable). Container-scoped rather than per-blob because a * single compactor archive does both a read (source JSONL) and a * write (destination Parquet), and DuckDB's SECRET is a one-credential * abstraction — two per-blob SAS-es would require two SECRETs and * complicate the COPY. The container is the smallest scope that fits * the compactor's operations; the broker also owns the entire container * by design (one container per deployment). * * The SAS includes a 60 s clock-skew window on the start time. Caller * is expected to refresh before `expiresInSeconds` elapses. * * The returned `blobEndpoint` is the **service endpoint** (no * container path) — `https://.blob.core.windows.net` on real * Azure, `http://host:10000/devstoreaccount1` on Azurite. DuckDB's * Azure SECRET takes the endpoint + SAS pair separately; the * container component is supplied via the `az:///` * URL minted by {@link buildDuckdbBlobUrl}. */ mintStorageSecret(opts: { readonly permissions?: string; readonly expiresInSeconds: number; }): Promise<{ blobEndpoint: string; sasToken: string; }>; mintBlobUrl(opts: { readonly blob: string; readonly permissions: StoragePermission; readonly expiresInSeconds: number; }): Promise; private instrument; private baseAttrs; } /** * Classify an Azure SDK error as transient (broker-retryable) — `ServerBusy`, * `OperationTimedOut`, 5xx, socket reset, etc. Used by the provider to map * known transient codes onto {@link TransientStorageError} so the producer's * application-layer retry budget can fire on them. ADR-0020 keeps the SDK * retry tight; the broker layer adds the application-level retry around * the bounded SDK attempts. * * Exported for direct unit tests; the classification is the load-bearing * decision of C1. */ export declare function isTransientAzureError(err: unknown): boolean; /** * Validate the fields the broker depends on out of an Azure `appendBlock` * response, returning the canonical {@link AppendResult} shape. Throws * {@link AppendBlockResponseInvalidError} when either field is missing or * unparseable — ADR-0005 requires both come from the server, so falling * back to caller-supplied values would silently break the append-position * invariant and the rollover trigger respectively. * * Exported so the missing-field branches can be exercised directly in unit * tests without faking the Azure SDK. */ export declare function parseAppendBlockResponse(path: string, bytesLength: number, response: { readonly blobAppendOffset?: string; readonly blobCommittedBlockCount?: number; }): AppendResult; /** * Convenience: wrap an existing `BlobServiceClient` (from a connection string, * shared key, MSI, etc.) into a configured provider against a specific container. */ export declare function azureBlobProvider(opts: AzureBlobProviderOptions): AzureBlobProvider; //# sourceMappingURL=azureBlobProvider.d.ts.map