@cloudbitmaps/core 0.1.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +12 -0
- package/README.md +22 -0
- package/dist/azure/index.cjs +368 -0
- package/dist/azure/index.cjs.map +1 -0
- package/dist/azure/index.d.cts +48 -0
- package/dist/azure/index.d.ts +48 -0
- package/dist/azure/index.js +304 -0
- package/dist/azure/index.js.map +1 -0
- package/dist/cassandra/index.cjs +265 -0
- package/dist/cassandra/index.cjs.map +1 -0
- package/dist/cassandra/index.d.cts +52 -0
- package/dist/cassandra/index.d.ts +52 -0
- package/dist/cassandra/index.js +204 -0
- package/dist/cassandra/index.js.map +1 -0
- package/dist/chunk-2YDULGXS.js +203 -0
- package/dist/chunk-2YDULGXS.js.map +1 -0
- package/dist/chunk-7LMLYSVJ.js +43 -0
- package/dist/chunk-7LMLYSVJ.js.map +1 -0
- package/dist/chunk-AS6ODRLT.js +6 -0
- package/dist/chunk-AS6ODRLT.js.map +1 -0
- package/dist/chunk-NUIDEEFZ.js +91 -0
- package/dist/chunk-NUIDEEFZ.js.map +1 -0
- package/dist/chunk-SNJVZ227.js +35 -0
- package/dist/chunk-SNJVZ227.js.map +1 -0
- package/dist/dynamodb/index.cjs +731 -0
- package/dist/dynamodb/index.cjs.map +1 -0
- package/dist/dynamodb/index.d.cts +106 -0
- package/dist/dynamodb/index.d.ts +106 -0
- package/dist/dynamodb/index.js +460 -0
- package/dist/dynamodb/index.js.map +1 -0
- package/dist/gcs/index.cjs +343 -0
- package/dist/gcs/index.cjs.map +1 -0
- package/dist/gcs/index.d.cts +46 -0
- package/dist/gcs/index.d.ts +46 -0
- package/dist/gcs/index.js +279 -0
- package/dist/gcs/index.js.map +1 -0
- package/dist/index.cjs +4031 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1945 -0
- package/dist/index.d.ts +1945 -0
- package/dist/index.js +3642 -0
- package/dist/index.js.map +1 -0
- package/dist/mongodb/index.cjs +260 -0
- package/dist/mongodb/index.cjs.map +1 -0
- package/dist/mongodb/index.d.cts +45 -0
- package/dist/mongodb/index.d.ts +45 -0
- package/dist/mongodb/index.js +199 -0
- package/dist/mongodb/index.js.map +1 -0
- package/dist/mysql/index.cjs +281 -0
- package/dist/mysql/index.cjs.map +1 -0
- package/dist/mysql/index.d.cts +56 -0
- package/dist/mysql/index.d.ts +56 -0
- package/dist/mysql/index.js +211 -0
- package/dist/mysql/index.js.map +1 -0
- package/dist/ports-D3BrJ6ax.d.cts +357 -0
- package/dist/ports-D3BrJ6ax.d.ts +357 -0
- package/dist/postgres/index.cjs +273 -0
- package/dist/postgres/index.cjs.map +1 -0
- package/dist/postgres/index.d.cts +54 -0
- package/dist/postgres/index.d.ts +54 -0
- package/dist/postgres/index.js +203 -0
- package/dist/postgres/index.js.map +1 -0
- package/dist/redis/index.cjs +257 -0
- package/dist/redis/index.cjs.map +1 -0
- package/dist/redis/index.d.cts +42 -0
- package/dist/redis/index.d.ts +42 -0
- package/dist/redis/index.js +197 -0
- package/dist/redis/index.js.map +1 -0
- package/dist/s3/index.cjs +891 -0
- package/dist/s3/index.cjs.map +1 -0
- package/dist/s3/index.d.cts +112 -0
- package/dist/s3/index.d.ts +112 -0
- package/dist/s3/index.js +555 -0
- package/dist/s3/index.js.map +1 -0
- package/package.json +172 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/errors.ts","../../src/core/ports.ts","../../src/core/validate.ts","../../src/drivers/_shared/keys.ts","../../src/drivers/postgres/keys.ts","../../src/drivers/postgres/postgres-errors.ts","../../src/drivers/postgres/warm.ts"],"names":["randomUUID"],"mappings":";;;;;;;AAcA,IAAM,WAAA,mBAA6B,MAAA,CAAO,GAAA,CAAI,qBAAqB,CAAA;AACnE,IAAM,eAAA,mBAAiC,MAAA,CAAO,GAAA,CAAI,+BAA+B,CAAA;AAG1E,IAAM,iBAAA,GAAN,cAAgC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,IAAA,IAAQ,SAAS,CAAA,CAAA;AAAA,QAClF,EAAE,OAAO,GAAA;AAAI,OACf;AAAA,IACF;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors — callers learn *why* something failed, never by parsing strings. Retry is the driver\n * decorators' job, not the engine's: a driver classifies its backend's failures into this vocabulary, and\n * `withRetry` decides what is transient.\n */\n\n/**\n * Registry-symbol brands. The package ships as multiple bundles — the core entry and the `./s3` / `./dynamodb`\n * subpaths — and the builder inlines `core/errors` into each. A driver in a subpath bundle therefore throws a\n * *different* class object than the one the core engine/retry code would `instanceof`-check, so `instanceof`\n * silently returns false across that boundary in the published CJS package (defeating OCC/transient retry and\n * compaction race-handling). These `Symbol.for` brands are identity-stable across bundles/realms; classify\n * errors with the exported predicates below (never `instanceof`) anywhere an error may cross the boundary.\n */\nconst ERROR_BRAND: unique symbol = Symbol.for('cloud-roaring.error');\nconst TRANSIENT_BRAND: unique symbol = Symbol.for('cloud-roaring.error.transient');\n\n/** Base class for every error CloudRoaring throws. */\nexport class CloudRoaringError extends Error {\n /** Cross-bundle brand — see the predicates ({@link isCloudRoaringError}, …). Non-enumerable-ish (symbol key ⇒ not in JSON). */\n readonly [ERROR_BRAND] = true as const;\n constructor(message: string) {\n super(message);\n // Subclass name (works under transpilation since we set it explicitly). Also the discriminator the\n // predicates match on — a runtime string, so it survives bundling where the class identity does not.\n this.name = new.target.name;\n }\n}\n\n/** Invalid caller input (bad id, segment name, options). Raised before any storage call. */\nexport class ValidationError extends CloudRoaringError {}\n\n/** An OCC conditional write/delete lost the race — the row changed since it was read. */\nexport class WriteConflictError extends CloudRoaringError {}\n\n/** Bytes from a tier are corrupt, oversized, or fail a checksum/format check. */\nexport class IntegrityError extends CloudRoaringError {}\n\n/**\n * A requested object/row does not exist. Part of the driver error vocabulary; thrown by\n * persistent drivers from Phase 2 — the Phase-1 engine + in-memory drivers return `null` instead.\n */\nexport class NotFoundError extends CloudRoaringError {}\n\n/**\n * This build/configuration cannot perform the requested operation, though nothing is malformed. Two uses:\n * (1) **format** — the bytes are well-formed but unreadable here (an unknown `.crbm` major version, an\n * encrypted file before the crypto path exists) — distinct from `IntegrityError` (corruption); and (2)\n * **store configuration** — an operation this store's wiring doesn't support (e.g. a lifecycle helper like\n * `compact`/`eraseSubject` called on a store built without a raw cold driver + registry). Raised at\n * operation time, before any mutation.\n */\nexport class UnsupportedError extends CloudRoaringError {}\n\n/**\n * A driver cannot meet a capability the chosen topology requires (e.g. a Cold driver without range\n * reads). Raised fail-fast at wiring time, never mid-operation.\n */\nexport class CapabilityError extends CloudRoaringError {}\n\n/**\n * An operation would exceed its per-op **denial-of-wallet budget** — too many backend requests for a single\n * `count`/`iterate`/`intersect`/`subjectReport`/`eraseSubject` call — so it is refused **before** fanning out\n * (Decision #3 / invariant T3). Default-on but generous (normal ops never hit it); tune it\n * per store (`budget`) or per op, or disable with `budget: false`. Deterministic (never retried): the op is too\n * big by policy, not by luck. Each request's bytes are separately capped (the safe-deserialize ceiling), so\n * bounding the request count transitively bounds bytes. Carries the projected count + the limit, never data.\n */\nexport class BudgetExceededError extends CloudRoaringError {}\n\n/**\n * An encrypted segment's data key (DEK) cannot be unwrapped because the keystore holds none of the\n * key-encryption-keys (KEKs) its wrappings reference — the KEK was never configured, rotated away without\n * keeping the old key, or lost. Deterministic (never retried): without a KEK the ciphertext is unreadable by\n * design. The flip side of crypto-shred — when this is *intended* (a destroyed segment) the registry row is\n * already a `destroyed` tombstone; when it's *not*, restore the missing KEK (or its recovery KEK). Carries no\n * key material.\n */\nexport class KeyUnavailableError extends CloudRoaringError {}\n\n/**\n * A **transient** infrastructure fault that is safe to retry — throttling, a 5xx, a dropped connection,\n * a client-side request timeout. Drivers classify their backend's retryable faults and raise this (the\n * SDK-specific knowledge stays in the SDK-specific driver); the retry layer (`core/retry`) retries **only**\n * this class, never a deterministic error like {@link ValidationError}, {@link IntegrityError},\n * {@link NotFoundError}, or {@link WriteConflictError} (retrying those is pointless or wrong). The original\n * error is preserved in `cause` so callers can still inspect it.\n *\n * Note for logging hygiene (threat-model S12): `cause` is the **raw SDK error**, which may carry operational\n * metadata (endpoint host, request IDs, `$metadata`). The library's own `message` is identifier-only and safe\n * to log; if you serialize the whole error *chain*, be aware you're including that metadata.\n */\nexport class TransientError extends CloudRoaringError {\n /** A second brand so the whole transient subtree (incl. {@link TimeoutError}) is classifiable cross-bundle. */\n readonly [TRANSIENT_BRAND] = true as const;\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n if (options && 'cause' in options) this.cause = options.cause;\n }\n}\n\n/**\n * A single attempt exceeded its time budget. Subclass of {@link TransientError} so the retry layer treats a\n * timeout as retryable by default — a stalled request often succeeds on a fresh connection. Raised by a\n * driver whose injected client reports a request timeout — setting one on your injected client is the\n * recommended way to bound a hang.\n */\nexport class TimeoutError extends TransientError {}\n\n/**\n * Bundle-safe error predicates — use these, not `instanceof`, wherever an error may cross the core↔driver\n * (`./s3` / `./dynamodb`) boundary (and prefer them in consumer `catch` blocks too, for the same reason). They\n * match the {@link ERROR_BRAND} registry brand + the runtime `name`, both of which survive separate bundling.\n */\nfunction hasBrand(err: unknown, brand: symbol): boolean {\n return (\n typeof err === 'object' && err !== null && (err as Record<symbol, unknown>)[brand] === true\n );\n}\n\n/** Any error thrown by CloudRoaring (any tier, any bundle). */\nexport function isCloudRoaringError(err: unknown): err is CloudRoaringError {\n return hasBrand(err, ERROR_BRAND);\n}\n\n/** An OCC conditional write/delete lost the race — retry the read-modify-write, don't fail. */\nexport function isWriteConflictError(err: unknown): err is WriteConflictError {\n return isCloudRoaringError(err) && err.name === 'WriteConflictError';\n}\n\n/** A retryable transient infrastructure fault (incl. {@link TimeoutError}). The retry layer keys on this. */\nexport function isTransientError(err: unknown): err is TransientError {\n return hasBrand(err, TRANSIENT_BRAND);\n}\n\n/** A requested object/row does not exist. */\nexport function isNotFoundError(err: unknown): err is NotFoundError {\n return isCloudRoaringError(err) && err.name === 'NotFoundError';\n}\n\n/** Corrupt/oversized/failed-checksum bytes from a tier. */\nexport function isIntegrityError(err: unknown): err is IntegrityError {\n return isCloudRoaringError(err) && err.name === 'IntegrityError';\n}\n\n/** Invalid caller input. */\nexport function isValidationError(err: unknown): err is ValidationError {\n return isCloudRoaringError(err) && err.name === 'ValidationError';\n}\n","/**\n * Storage-driver contracts the engine depends on.\n *\n * Phase 1 uses the subset needed by the in-memory engine: the per-chunk Warm store (under OCC) and a\n * per-chunk read view of Cold. Drivers move opaque bytes + an OCC token; they never understand roaring,\n * `adds`/`removes`, or the `.crbm` layout. The full `IColdDriver` (blob/range) + `IRegistryDriver` arrive\n * with generations in Phase 2/3 — the `.crbm` reader will implement `ColdChunkSource`.\n */\n\nimport type { BlobSink } from './blob';\nimport type { WrappedDek } from './crypto';\n\n/** Opaque optimistic-concurrency token — unique per write, compared by equality only. */\nexport type Token = string;\n\n/** Sentinel for `putConditional` meaning \"the row must not exist yet\" (create). */\n// `Symbol.for` (the global registry), NOT `Symbol()`: the package ships multiple bundles (the core entry and\n// the `./dynamodb` / `./s3` subpaths), and tsup inlines `core/ports` into each. A plain `Symbol('no-row')`\n// would be a DISTINCT instance per bundle, so the engine's `NO_ROW` wouldn't `===` the one the DynamoDb warm\n// driver compares against — every create would misroute to the token-fenced path and fail. A registry symbol\n// is identity-stable across bundles/realms. (Invisible in tests, which share one source module graph.)\nexport const NO_ROW: unique symbol = Symbol.for('cloud-roaring.no-row');\nexport type NoRow = typeof NO_ROW;\n\nexport interface SegmentRef {\n readonly namespace?: string;\n readonly segment: string;\n}\n\nexport interface ChunkRef extends SegmentRef {\n readonly chunkKey: number;\n}\n\n/** Identifies one immutable `.crbm` object — a single generation of a segment. */\nexport interface GenKey extends SegmentRef {\n readonly generation: number;\n}\n\nexport interface WarmRow {\n readonly token: Token;\n /** Read-only: owned by the driver. Callers must NOT mutate the buffer (re-encode to write). */\n readonly bytes: Uint8Array;\n}\n\n/**\n * Read consistency for a Warm fetch (gap #9). `consistent: true` (the default — omitted ⇒ true) is a\n * strong, read-your-writes read, as the OCC read-modify-write path requires. `consistent: false` requests an\n * **eventually-consistent** read — on DynamoDB that is ~½ the RCU cost; a driver that is always strongly\n * consistent (in-memory, LocalFs) ignores it. The engine uses it only on read paths (`has`/`count`/`iterate`/\n * `intersect`) when the store opts into `warmReadConsistency: 'eventual'`, trading read-after-write for cost.\n */\nexport interface WarmReadOptions {\n readonly consistent?: boolean;\n}\n\n/** Per-chunk Warm store under optimistic concurrency. Returned byte buffers are read-only. */\nexport interface IWarmDriver {\n get(ref: ChunkRef, opts?: WarmReadOptions): Promise<WarmRow | null>;\n /** OCC write. `expected` = `NO_ROW` to create, else the token previously read. Throws `WriteConflictError` on mismatch. */\n putConditional(\n ref: ChunkRef,\n bytes: Uint8Array,\n expected: Token | NoRow,\n ): Promise<{ token: Token }>;\n /**\n * Fenced delete — only if the stored token still equals `expected`; throws `WriteConflictError`\n * otherwise. **Used by compaction (Phase 4); the Phase-1 engine never calls it** — drivers still\n * implement it to satisfy the conformance suite.\n */\n deleteConditional(ref: ChunkRef, expected: Token): Promise<void>;\n /** All dirty chunks of a segment, ascending `chunkKey`. Yielded `bytes` are read-only. */\n listChunks(\n ref: SegmentRef,\n opts?: WarmReadOptions,\n ): AsyncIterable<{ chunkKey: number } & WarmRow>;\n}\n\n/**\n * A segment's grounded on-disk footprint (Phase 5b) — the current generation's Cold object bytes, read\n * cheaply from the `.crbm` footer/index (no payload reads). Powers the grounded `costReport()`.\n */\nexport interface SegmentSize {\n readonly sizeBytes: number;\n}\n\n/** Per-chunk read view of the immutable Cold tier (implemented by the `.crbm` reader from Phase 2). */\nexport interface ColdChunkSource {\n /** Read-only bytes for the chunk, or `null` if absent. Callers must not mutate the buffer. */\n getChunk(ref: ChunkRef): Promise<Uint8Array | null>;\n listChunkKeys(ref: SegmentRef): Promise<number[]>;\n /**\n * Optional (Phase 5b): the current generation's grounded size, cheaply (from the already-parsed\n * `.crbm` index — no payload reads), or `null` if the segment has no Cold generation. Powers the\n * grounded `costReport()`.\n */\n sizeOf?(ref: SegmentRef): Promise<SegmentSize | null>;\n /**\n * Optional (Phase 5c): the current generation's **per-chunk cardinality** (`chunkKey → count`), read\n * from the already-parsed `.crbm` index with **no payload reads**, or `null` if the segment has no Cold\n * generation. Powers the cheap `count()` — a warm-delta-free chunk is counted straight from the index\n * instead of fetching + deserializing it. A source with no index (e.g. the in-memory source) omits this,\n * and `count()` falls back to fetching + merging every chunk.\n */\n cardinalities?(ref: SegmentRef): Promise<ReadonlyMap<number, number> | null>;\n /**\n * Optional (Phase B, gap #4): the segment's **current generation number** as this source resolves it right now\n * (registry `currentGen`, or the highest cold generation), or `null` if the segment has no Cold generation. The\n * engine keys its HOT chunk cache by this so a generation bump (a compaction commit) is observed — a new\n * generation misses the cache instead of serving a stale decoded chunk, and an erased id can't resurrect from a\n * cached pre-compaction chunk. Cheap: served from the source's own (short-TTL-refreshed) snapshot, **not** a\n * fresh backend read per call. A source that pins one immutable generation for its whole lifetime and never\n * refreshes may omit this — the engine then keys the cache without a generation, exactly as before.\n */\n currentGeneration?(ref: SegmentRef): Promise<number | null>;\n}\n\n/** Capabilities a Cold driver advertises; validated at wiring time, fail-fast. */\nexport interface ColdCaps {\n /** REQUIRED — the format relies on byte-range reads. */\n readonly rangeRead: true;\n /** Largest single object the backend accepts (informs single-object-vs-shard, B7 — future). */\n readonly maxObjectBytes: number;\n /** Optional: enables the pure-object `LATEST`-pointer registry variant (S3 conditional put). */\n readonly conditionalPut?: boolean;\n}\n\n/**\n * Immutable object storage for `.crbm` generations. A \"dumb byte mover\": it\n * understands neither roaring nor the `.crbm` layout, only opaque bytes addressed by a {@link GenKey}.\n * The core never reuses a key, so puts are write-once.\n */\nexport interface IColdDriver {\n capabilities(): ColdCaps;\n /**\n * Stream a new immutable generation. The driver opens a destination, hands `write` a {@link BlobSink},\n * then atomically commits (and computes the content hash). Throws if the key already exists (write-once).\n */\n putImmutable(\n key: GenKey,\n write: (sink: BlobSink) => Promise<void>,\n ): Promise<{ size: number; sha256: string }>;\n /** Range read; the caller bounds-checks. Out-of-range is rejected, never a short/adjacent read. */\n getRange(key: GenKey, offset: number, length: number): Promise<Uint8Array>;\n /** Speculative tail read: the last `min(maxBytes, size)` bytes + the total object size. */\n getTail(key: GenKey, maxBytes: number): Promise<{ bytes: Uint8Array; size: number }>;\n delete(key: GenKey): Promise<void>;\n /** Enumerate the generations present for a segment (orphan sweep / latest-gen resolution). */\n list(ref: SegmentRef): AsyncIterable<GenKey>;\n}\n\n/**\n * Lifecycle status of a segment. `active` is the steady state;\n * `compacting`/`erasing` are transient flags a daemon sets while it works (Phase 4d/4e); `destroyed` is the\n * post-crypto-shred tombstone (the row is kept for audit but the segment is logically gone). The 4c registry\n * stores and round-trips the field; the *transitions* are driven by their owning features.\n */\nexport type RegistryStatus = 'active' | 'compacting' | 'erasing' | 'destroyed';\n\n/** Free-form, JSON-serializable governance metadata (retention/residency policy); shape lands in Phase 6. */\nexport type GovernanceMeta = Record<string, unknown>;\n\n/**\n * One registry row — the authoritative per-segment record. Exactly one per segment.\n */\nexport interface RegistryRecord extends SegmentRef {\n /** **The** authoritative LATEST pointer: which immutable Cold generation is current. */\n readonly currentGen: number;\n /**\n * Per-segment data-key (DEK) wrappings for encryption-at-rest (Phase 4e): the DEK envelope-wrapped under one\n * or more KEKs (active + optional recovery). Reading unwraps with any held KEK; **crypto-shred deletes this\n * whole list**, making the segment's at-rest bytes permanently unrecoverable. Absent ⇒ the segment is\n * cleartext. See [DECISIONS #19].\n */\n readonly wrappedDeks?: readonly WrappedDek[];\n /**\n * Optional **external** key reference (reserved) — e.g. a KMS key ARN for a future KMS keystore adapter that\n * keeps wrapped material in the KMS rather than in-band {@link wrappedDeks}. Unused by the in-process BYOK\n * keystore. Clearable on crypto-shred.\n */\n readonly keyId?: string;\n /**\n * Dirty-row hint written by `findCompactable`. Discovery still recomputes the live dirty count by scanning\n * Warm each cycle (the count that decides candidacy), but it now **reads** this hint to gate a change-guarded\n * CAS — the hint is only rewritten when the count actually moved, so an all-idle fleet issues no per-segment\n * registry writes. It does not yet drive candidacy — turning the Warm scan itself into O(dirty) is a\n * deferred cheap-enumeration fix.\n */\n readonly dirtyChunkCount: number;\n readonly status: RegistryStatus;\n /**\n * Daemon health (Phase D, gap #2): epoch-ms of the last **successfully committed** compaction, and the\n * count of **consecutive** compaction failures (reset to 0 by a successful commit). `lastCompactedAt`\n * powers a dead-man's-switch / staleness alarm; `consecutiveFailures` drives **poison-segment quarantine** —\n * discovery skips a segment past a failure threshold so one corrupt Warm row can't freeze the compaction of a\n * segment **that has a committed generation** forever (with no alarm) while its Warm backlog grows unbounded.\n * (A segment whose *very first* compaction keeps failing has no registry row to count against yet —\n * bootstrap faults are surfaced as `error` results but not yet quarantined; gap #2.) Both\n * **optional** (absent on rows written before Phase D, and on a segment never compacted) — read them as\n * `lastCompactedAt ?? undefined`, `consecutiveFailures ?? 0`.\n */\n readonly lastCompactedAt?: number;\n readonly consecutiveFailures?: number;\n /**\n * Compaction lease (Phase 4d): the opaque id of the worker currently compacting this segment, and the\n * epoch-ms at which its lease expires. `status === 'compacting'` with `leaseExpiresAt` in the future means\n * a live daemon owns it; once `leaseExpiresAt` is past, another worker may **steal** the lease (the prior\n * holder crashed). Both absent in the steady (`active`) state. The lease is an efficiency guard only — the\n * 2-phase commit is correct without it (OCC-fenced swap + write-once generations + version-fenced purge).\n */\n readonly leaseOwner?: string;\n readonly leaseExpiresAt?: number;\n /** Governance policy (Phase 6); stored + round-tripped now, semantics later. */\n readonly retention?: GovernanceMeta;\n readonly residency?: GovernanceMeta;\n /** Epoch-ms of creation / last mutation (from the driver's injected clock). */\n readonly createdAt: number;\n readonly updatedAt: number;\n /** Opaque OCC token — compare-by-equality, never reused (ABA-safe), exactly like {@link WarmRow.token}. */\n readonly token: Token;\n}\n\n/** The caller-settable fields at {@link IRegistryDriver.create} (audit + token are driver-managed). */\nexport interface NewRegistryRecord {\n readonly currentGen: number;\n readonly wrappedDeks?: readonly WrappedDek[];\n readonly keyId?: string;\n /** Defaults to 0. */\n readonly dirtyChunkCount?: number;\n /** Defaults to `'active'`. */\n readonly status?: RegistryStatus;\n readonly retention?: GovernanceMeta;\n readonly residency?: GovernanceMeta;\n}\n\n/** Fields a {@link IRegistryDriver.compareAndSwap} may mutate (identity + audit + token are off-limits). */\nexport type RegistryPatch = Partial<\n Pick<\n RegistryRecord,\n | 'currentGen'\n | 'wrappedDeks'\n | 'keyId'\n | 'dirtyChunkCount'\n | 'status'\n | 'leaseOwner'\n | 'leaseExpiresAt'\n | 'lastCompactedAt'\n | 'consecutiveFailures'\n | 'retention'\n | 'residency'\n >\n>;\n\n/** Capabilities a registry driver advertises; validated fail-fast at wiring time. */\nexport interface RegCaps {\n /** REQUIRED — `currentGen` feeds read correctness + compaction CAS, so reads must be strongly consistent. */\n readonly strongRead: true;\n}\n\n/**\n * Per-segment registry — the authoritative source of `currentGen`, the discovery index, and (Phase 4e) the\n * wrapped-DEK holder. One row per segment under OCC: a\n * never-reused, equality-compared {@link Token} (ABA-safe across delete→recreate, like the Warm tier).\n */\nexport interface IRegistryDriver {\n capabilities(): RegCaps;\n /** The segment's record, or `null` if it doesn't exist (or was deleted). */\n get(ref: SegmentRef): Promise<RegistryRecord | null>;\n /** Create the row; throws {@link WriteConflictError} if it already exists (use CAS to mutate). */\n create(ref: SegmentRef, record: NewRegistryRecord): Promise<{ token: Token }>;\n /** Server-side compare-and-set: apply `patch` iff the stored token equals `expected`, else `WriteConflictError`. */\n compareAndSwap(ref: SegmentRef, expected: Token, patch: RegistryPatch): Promise<{ token: Token }>;\n /** Discovery: every live record, optionally scoped to one namespace. Order is unspecified. */\n list(namespace?: string): AsyncIterable<RegistryRecord>;\n /** Remove the row (tombstoned for ABA-safety — a later `create` still gets a fresh, greater token). */\n delete(ref: SegmentRef): Promise<void>;\n}\n","/**\n * Boundary validation for segment / namespace names (finding S2).\n * Names become object keys, partition keys, and file paths — so they're validated before they\n * ever reach storage: strict charset, bounded length, no path traversal.\n */\nimport { ValidationError } from './errors';\nimport type { ChunkRef, SegmentRef } from './ports';\n\nconst CHUNK_KEY_MAX = 0xffff;\n\n// The locked name grammar: 1 leading alphanumeric + up to 255 more (max 256 chars).\nconst NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;\n\nfunction validatePart(value: string, field: string): void {\n if (typeof value !== 'string' || !NAME.test(value) || value.includes('..')) {\n throw new ValidationError(\n `${field} must match ${String(NAME)} and contain no \"..\": got ${JSON.stringify(value)}`,\n );\n }\n}\n\nexport function validateSegmentRef(ref: SegmentRef): void {\n validatePart(ref.segment, 'segment');\n if (ref.namespace !== undefined) validatePart(ref.namespace, 'namespace');\n}\n\n/** Validate a chunk ref: the segment/namespace grammar plus `chunkKey` ∈ `[0, 65535]` (a u16). */\nexport function validateChunkRef(ref: ChunkRef): void {\n validateSegmentRef(ref);\n if (!Number.isInteger(ref.chunkKey) || ref.chunkKey < 0 || ref.chunkKey > CHUNK_KEY_MAX) {\n throw new ValidationError(\n `chunkKey must be an integer in [0, ${CHUNK_KEY_MAX}]; got ${ref.chunkKey}`,\n );\n }\n}\n","/**\n * Shared key-grammar fragments used by every driver's logical-ref → physical-key mapping (Phase 4c).\n *\n * Extracted once the registry drivers became the 4th/5th consumer of the same `_default` namespace sentinel\n * (it lived copy-pasted in `s3/keys`, `dynamodb/keys`, `localfs/paths`). Pure string logic, no SDK, no I/O —\n * lives in the SDK-free `_shared` bundle so any driver may import it.\n */\n\n/**\n * The physical stand-in for an **absent** namespace. The name grammar forbids a leading underscore\n * so `_default` can never collide with a real\n * namespace — `segment(\"s\")` and `segment(\"s\", { namespace: \"_default\" })` would be a grammar error, not an\n * aliasing hazard.\n */\nexport const DEFAULT_NAMESPACE = '_default';\n\n/** Map an optional namespace to its physical part: the namespace itself, or {@link DEFAULT_NAMESPACE}. */\nexport function namespacePart(namespace: string | undefined): string {\n return namespace ?? DEFAULT_NAMESPACE;\n}\n","/**\n * Identifier + key validation for {@link PostgresWarmDriver} (Phase 7).\n *\n * Pure, SDK-free string logic — unit-testable without a live Postgres. Unlike the object-store drivers (which\n * build a single string key), the Postgres driver stores the logical ref across **parameterized columns**\n * (`namespace`, `segment`, `chunk_key`, `key_prefix`), so ref/prefix values are never concatenated into SQL —\n * `pg`'s `$n` placeholders bind them as data (no injection surface). The one value that CANNOT be a bind\n * parameter is the **table name** (an identifier, not a value), so it is validated against a strict grammar\n * and quoted before interpolation — that is the whole reason this module exists.\n */\nimport { ValidationError } from '@/core/errors';\n\n/** A SQL identifier segment: leading letter/underscore, then letters/digits/underscores (ASCII, ≤63 = PG max). */\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;\n\n/**\n * Validate a table name — optionally schema-qualified (`schema.table`) — and return it **safely quoted** for\n * interpolation (each part wrapped in double quotes). A table name is an identifier, so it can't be a bind\n * parameter; validating against {@link IDENT} (which excludes quotes, whitespace, `;`, `-`, etc.) and quoting\n * closes the only SQL-injection vector the driver has. Rejects anything else, fail-fast.\n */\nexport function validateAndQuoteTable(table: string): string {\n const parts = table.split('.');\n if (parts.length > 2 || parts.some((p) => !IDENT.test(p))) {\n throw new ValidationError(\n `invalid table name ${JSON.stringify(table)} — expected an identifier or \"schema.table\" ` +\n `(letters, digits, underscore; ≤63 chars; leading letter/underscore)`,\n );\n }\n return parts.map((p) => `\"${p}\"`).join('.');\n}\n\n/**\n * Validate a caller-supplied `keyPrefix` (lets several logical stores share one table). It's bound as a `$n`\n * value, not concatenated, so this is a light sanity guard (no control characters), not an anti-injection\n * boundary. Empty/undefined means no prefix (stored as the empty string).\n */\nexport function normalizeKeyPrefix(prefix: string | undefined): string {\n if (prefix === undefined || prefix === '') return '';\n for (const ch of prefix) {\n if (ch.charCodeAt(0) < 0x20) {\n throw new ValidationError('keyPrefix must not contain control characters');\n }\n }\n return prefix;\n}\n","/**\n * Pure helpers for classifying PostgreSQL (`pg`) errors (Phase 7; transient class mirrors S3/GCS/Azure).\n *\n * SDK-free + side-effect-free — they read only structural shapes off the thrown value (`err.code`, a\n * SQLSTATE string; or a Node socket `code`), so the translation is unit-testable without a live Postgres.\n * Note the driver signals a write-once / OCC conflict itself (a conditional statement affecting **0 rows**),\n * so there is no \"conflict\" classifier here — only transient-vs-not. Everything not transient propagates\n * unchanged so a real bug is never silently retried.\n */\n\n/**\n * A Node system/socket error `code` (e.g. `ECONNRESET`, `EPIPE`, `EAI_AGAIN`): starts with `E`, only\n * uppercase letters + underscore, no digits. Checked BEFORE {@link sqlState} because some socket codes are\n * exactly 5 chars (`EPIPE`) and would otherwise collide with the SQLSTATE shape — no real Postgres SQLSTATE\n * class begins with a letter `E`, so this disambiguates cleanly.\n */\nfunction networkCode(err: unknown): string | undefined {\n const code = (err as { code?: unknown } | null)?.code;\n return typeof code === 'string' && /^E[A-Z_]+$/.test(code) ? code : undefined;\n}\n\n/**\n * `pg` surfaces its most common transient faults — a backend/socket that drops mid-query, or a pool\n * connect-timeout — as a plain `Error` with **no `.code`**, only a message (`pg/lib/client.js`: \"Connection\n * terminated unexpectedly\", \"…is not queryable\"; pg-pool's \"timeout exceeded when trying to connect\"). Without\n * this, such a fault would fall through as non-transient and the retry decorator would not ride it out — the\n * exact class of fault the resilience layer exists to absorb. Only consulted when there's no SQLSTATE/socket\n * code (a deterministic server error always carries a code, so this can never mask one).\n */\nconst CONNECTION_LOST =\n /connection terminated|not queryable|timeout exceeded when trying to connect/i;\nfunction isConnectionLostMessage(err: unknown): boolean {\n return err instanceof Error && CONNECTION_LOST.test(err.message);\n}\n\n/** The `pg` error's SQLSTATE (a 5-char `[0-9A-Z]` code like `40001`), if present and not a socket code. */\nfunction sqlState(err: unknown): string | undefined {\n if (networkCode(err) !== undefined) return undefined;\n const code = (err as { code?: unknown } | null)?.code;\n return typeof code === 'string' && /^[0-9A-Z]{5}$/.test(code) ? code : undefined;\n}\n\n/**\n * A transient Postgres fault that is safe to retry: a serialization failure / deadlock (SQLSTATE class 40),\n * an operator-intervention / cannot-connect-now (57P03 / 57P01 / 57P02), too-many-connections or\n * out-of-memory (53xxx), a connection-exception (class 08), or a dropped/timed-out socket. Deterministic,\n * caller-meaningful outcomes (constraint violations, syntax errors, etc.) are NOT transient — they must\n * surface, never be blind-retried.\n */\nexport function isTransient(err: unknown): boolean {\n const state = sqlState(err);\n if (state !== undefined) {\n const cls = state.slice(0, 2);\n if (cls === '40' || cls === '08' || cls === '53') return true; // serialization/deadlock, connection, resource\n if (state === '57P03' || state === '57P01' || state === '57P02') return true; // cannot_connect_now / shutdowns\n return false;\n }\n const net = networkCode(err);\n if (\n net === 'ECONNRESET' ||\n net === 'ECONNABORTED' ||\n net === 'ETIMEDOUT' ||\n net === 'ESOCKETTIMEDOUT' ||\n net === 'ECONNREFUSED' ||\n net === 'EHOSTUNREACH' ||\n net === 'ENETUNREACH' ||\n net === 'EPIPE' ||\n net === 'EAI_AGAIN' ||\n net === 'ENOTFOUND'\n ) {\n return true;\n }\n // pg's code-less connection-lost errors (see CONNECTION_LOST) — the tail case, only if nothing above matched.\n return isConnectionLostMessage(err);\n}\n","/**\n * `PostgresWarmDriver` — an {@link IWarmDriver} over PostgreSQL (Phase 7).\n *\n * \"No DynamoDB — use the Postgres you already run.\" Uses the official `pg` (node-postgres), an **optional\n * peer dependency** — only consumers of `cloud-roaring/postgres` install it. A `pg.Pool` is **injected**\n * (dependency injection): the driver owns no connection/credential logic, so it's thin, reuses the caller's\n * pool, and is testable against a Postgres container.\n *\n * Each chunk is one row in a single table (`PRIMARY KEY (key_prefix, namespace, segment, chunk_key)`), with\n * an opaque OCC **token** (a random UUID minted per write) and the delta `payload` (bytea). Optimistic\n * concurrency is real, cross-process, and server-side:\n * - **create-if-absent** = `INSERT … ON CONFLICT DO NOTHING`; 0 rows affected ⇒ the row already exists ⇒\n * {@link WriteConflictError}.\n * - **token-fenced update / delete** = `UPDATE … / DELETE … WHERE … AND token = :expected`; 0 rows affected\n * ⇒ the stored token moved (or the row is gone) ⇒ {@link WriteConflictError}.\n *\n * Tokens are not reused across delete→recreate (ABA-safe, D3): a delete removes the row and a recreate mints\n * a fresh random UUID, so a token from before the delete won't match. (This is a *probabilistic* guarantee —\n * a random 122-bit UUIDv4, collision odds negligible — vs the DynamoDB driver's *structural* monotonic-counter\n * guarantee; the hard-delete/no-tombstone model can't offer the latter, and conformance D3 pins the behavior.)\n * Reads are strongly consistent (single primary), so the optional `WarmReadOptions` consistency hint is a\n * no-op, like the in-memory / LocalFs drivers. Drivers may use `node:crypto`; only `core/` is determinism-bound.\n */\nimport { randomUUID } from 'node:crypto';\nimport type { Pool } from 'pg';\nimport {\n IntegrityError,\n TransientError,\n ValidationError,\n WriteConflictError,\n isWriteConflictError,\n} from '@/core/errors';\nimport { NO_ROW } from '@/core/ports';\nimport type { ChunkRef, IWarmDriver, NoRow, SegmentRef, Token, WarmRow } from '@/core/ports';\nimport { validateChunkRef, validateSegmentRef } from '@/core/validate';\nimport { namespacePart } from '../_shared/keys';\nimport { normalizeKeyPrefix, validateAndQuoteTable } from './keys';\nimport { isTransient } from './postgres-errors';\n\nconst DEFAULT_TABLE = 'cloud_roaring_warm';\n/** Default listChunks keyset-pagination batch — bounds peak memory to ~this many rows regardless of width. */\nconst DEFAULT_LIST_BATCH = 1000;\n\nexport interface PostgresWarmDriverOptions {\n /**\n * A constructed `pg.Pool` (or a pool-compatible client). The driver never opens/closes connections — the\n * caller owns the pool's lifecycle. It **must target the primary**: reads are treated as strongly\n * consistent (the OCC read-modify-write needs read-your-writes), so a pool pointed at a read replica /\n * hot standby could serve stale rows and silently break OCC.\n */\n readonly pool: Pool;\n /** Warm table name — identifier or `schema.table` (default `cloud_roaring_warm`). Must already exist. */\n readonly table?: string;\n /** Optional key-prefix column value so several logical stores can share one table (bound as data). */\n readonly keyPrefix?: string;\n /** Advanced: `listChunks` keyset-pagination page size (default 1000). Tunes peak memory on wide segments. */\n readonly listPageSize?: number;\n}\n\n/** One raw warm row as selected. */\ninterface RawRow {\n chunk_key?: number;\n token?: unknown;\n payload?: unknown;\n}\n\n/**\n * The idempotent DDL for the warm table (identifier-validated + quoted). The driver does **not** create\n * schema (it stays thin + needs no DDL privileges at runtime); run this once at deploy time, e.g.\n * `await pool.query(postgresWarmTableDDL())`.\n */\nexport function postgresWarmTableDDL(table: string = DEFAULT_TABLE): string {\n const t = validateAndQuoteTable(table);\n return (\n `CREATE TABLE IF NOT EXISTS ${t} (\\n` +\n ` key_prefix text NOT NULL,\\n` +\n ` namespace text NOT NULL,\\n` +\n ` segment text NOT NULL,\\n` +\n ` chunk_key integer NOT NULL,\\n` +\n ` token text NOT NULL,\\n` +\n ` payload bytea NOT NULL,\\n` +\n ` PRIMARY KEY (key_prefix, namespace, segment, chunk_key)\\n` +\n `);`\n );\n}\n\nexport class PostgresWarmDriver implements IWarmDriver {\n private readonly pool: Pool;\n private readonly table: string; // validated + quoted for interpolation\n private readonly keyPrefix: string;\n private readonly listBatch: number;\n\n constructor(options: PostgresWarmDriverOptions) {\n this.pool = options.pool;\n this.table = validateAndQuoteTable(options.table ?? DEFAULT_TABLE);\n this.keyPrefix = normalizeKeyPrefix(options.keyPrefix);\n const batch = options.listPageSize ?? DEFAULT_LIST_BATCH;\n if (!Number.isSafeInteger(batch) || batch < 1) {\n throw new ValidationError(`listPageSize must be a positive safe integer; got ${batch}`);\n }\n this.listBatch = batch;\n }\n\n // Reads are always strongly consistent (single primary), so the optional `WarmReadOptions` hint would be a\n // no-op — the structurally-optional param is simply omitted (still satisfies IWarmDriver), as in LocalFs.\n async get(ref: ChunkRef): Promise<WarmRow | null> {\n validateChunkRef(ref);\n try {\n const res = await this.pool.query<RawRow>(\n `SELECT token, payload FROM ${this.table} ` +\n `WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key = $4`,\n [this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey],\n );\n const row = res.rows[0];\n return row === undefined ? null : this.rowFrom(row, ref.chunkKey);\n } catch (err) {\n throw this.mapError(err);\n }\n }\n\n async putConditional(\n ref: ChunkRef,\n bytes: Uint8Array,\n expected: Token | NoRow,\n ): Promise<{ token: Token }> {\n validateChunkRef(ref);\n const token = randomUUID();\n // Copy the payload into a Buffer for `bytea` binding — severs any caller-owned/reused input buffer.\n const payload = Buffer.from(bytes);\n const ns = namespacePart(ref.namespace);\n try {\n if (expected === NO_ROW) {\n const res = await this.pool.query(\n `INSERT INTO ${this.table} (key_prefix, namespace, segment, chunk_key, token, payload) ` +\n `VALUES ($1, $2, $3, $4, $5, $6) ` +\n `ON CONFLICT (key_prefix, namespace, segment, chunk_key) DO NOTHING`,\n [this.keyPrefix, ns, ref.segment, ref.chunkKey, token, payload],\n );\n // A single-row PK write affects exactly 1 row on success; anything else (0 = conflict, or a `null`\n // rowCount) is NOT a confirmed insert — treat as a conflict, never a silent false-success.\n if (res.rowCount !== 1) {\n throw new WriteConflictError(`chunk ${ref.chunkKey} already exists (create-if-absent)`);\n }\n } else {\n const res = await this.pool.query(\n `UPDATE ${this.table} SET token = $5, payload = $6 ` +\n `WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key = $4 ` +\n `AND token = $7`,\n [this.keyPrefix, ns, ref.segment, ref.chunkKey, token, payload, expected],\n );\n if (res.rowCount !== 1)\n throw new WriteConflictError(`OCC conflict on chunk ${ref.chunkKey}`);\n }\n return { token };\n } catch (err) {\n if (isWriteConflictError(err)) throw err; // our own deterministic conflict — never a transient\n throw this.mapError(err);\n }\n }\n\n async deleteConditional(ref: ChunkRef, expected: Token): Promise<void> {\n validateChunkRef(ref);\n try {\n const res = await this.pool.query(\n `DELETE FROM ${this.table} ` +\n `WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key = $4 AND token = $5`,\n [this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey, expected],\n );\n if (res.rowCount !== 1) {\n throw new WriteConflictError(`fenced-delete conflict on chunk ${ref.chunkKey}`);\n }\n } catch (err) {\n if (isWriteConflictError(err)) throw err;\n throw this.mapError(err);\n }\n }\n\n async *listChunks(ref: SegmentRef): AsyncIterable<{ chunkKey: number } & WarmRow> {\n validateSegmentRef(ref);\n const ns = namespacePart(ref.namespace);\n // Keyset pagination on chunk_key (ascending) bounds peak memory to one page WITHIN a single enumeration,\n // regardless of how wide the segment is. (It does NOT resume across a transient fault — the retry decorator\n // re-enumerates a streaming method from the start and buffers, see drivers/retry/retrying-drivers.ts.)\n let after = -1;\n for (;;) {\n let rows: RawRow[];\n try {\n const res = await this.pool.query<RawRow>(\n `SELECT chunk_key, token, payload FROM ${this.table} ` +\n `WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key > $4 ` +\n `ORDER BY chunk_key ASC LIMIT $5`,\n [this.keyPrefix, ns, ref.segment, after, this.listBatch],\n );\n rows = res.rows;\n } catch (err) {\n throw this.mapError(err);\n }\n for (const row of rows) {\n const chunkKey = row.chunk_key;\n if (typeof chunkKey !== 'number') {\n throw new IntegrityError('warm row is missing its chunk_key');\n }\n yield { chunkKey, ...this.rowFrom(row, chunkKey) };\n after = chunkKey;\n }\n if (rows.length < this.listBatch) return;\n }\n }\n\n /**\n * Build a {@link WarmRow} from a raw row. `token` must be a non-empty string and `payload` a Buffer — a\n * missing/typo'd column means a corrupt or foreign row, which we reject (untrusted-data posture) rather\n * than paper over. The returned bytes are a fresh copy (driver-owned, read-only per the contract).\n */\n private rowFrom(row: RawRow, chunkKey: number): WarmRow {\n if (typeof row.token !== 'string' || row.token === '') {\n throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its token`);\n }\n if (!(row.payload instanceof Uint8Array)) {\n throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its payload`);\n }\n return { token: row.token, bytes: new Uint8Array(row.payload) };\n }\n\n /**\n * Reclassify a transient Postgres fault (serialization/deadlock, connection, resource, dropped socket) as\n * a retryable {@link TransientError}; everything else propagates unchanged. Applied at every query site so\n * callers + the retry decorator only ever see typed errors. A deterministic OCC conflict is signalled by\n * the driver itself (0 rows affected) — never reclassified here.\n */\n private mapError(err: unknown): unknown {\n if (isTransient(err)) {\n return new TransientError(\n `transient Postgres fault: ${(err as { code?: unknown } | null)?.code ?? 'unknown'}`,\n { cause: err },\n );\n }\n return err;\n }\n}\n"]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Pool } from 'pg';
|
|
2
|
+
import { a as IWarmDriver, b as ChunkRef, c as WarmRow, T as Token, N as NoRow, S as SegmentRef } from '../ports-D3BrJ6ax.cjs';
|
|
3
|
+
|
|
4
|
+
interface PostgresWarmDriverOptions {
|
|
5
|
+
/**
|
|
6
|
+
* A constructed `pg.Pool` (or a pool-compatible client). The driver never opens/closes connections — the
|
|
7
|
+
* caller owns the pool's lifecycle. It **must target the primary**: reads are treated as strongly
|
|
8
|
+
* consistent (the OCC read-modify-write needs read-your-writes), so a pool pointed at a read replica /
|
|
9
|
+
* hot standby could serve stale rows and silently break OCC.
|
|
10
|
+
*/
|
|
11
|
+
readonly pool: Pool;
|
|
12
|
+
/** Warm table name — identifier or `schema.table` (default `cloud_roaring_warm`). Must already exist. */
|
|
13
|
+
readonly table?: string;
|
|
14
|
+
/** Optional key-prefix column value so several logical stores can share one table (bound as data). */
|
|
15
|
+
readonly keyPrefix?: string;
|
|
16
|
+
/** Advanced: `listChunks` keyset-pagination page size (default 1000). Tunes peak memory on wide segments. */
|
|
17
|
+
readonly listPageSize?: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The idempotent DDL for the warm table (identifier-validated + quoted). The driver does **not** create
|
|
21
|
+
* schema (it stays thin + needs no DDL privileges at runtime); run this once at deploy time, e.g.
|
|
22
|
+
* `await pool.query(postgresWarmTableDDL())`.
|
|
23
|
+
*/
|
|
24
|
+
declare function postgresWarmTableDDL(table?: string): string;
|
|
25
|
+
declare class PostgresWarmDriver implements IWarmDriver {
|
|
26
|
+
private readonly pool;
|
|
27
|
+
private readonly table;
|
|
28
|
+
private readonly keyPrefix;
|
|
29
|
+
private readonly listBatch;
|
|
30
|
+
constructor(options: PostgresWarmDriverOptions);
|
|
31
|
+
get(ref: ChunkRef): Promise<WarmRow | null>;
|
|
32
|
+
putConditional(ref: ChunkRef, bytes: Uint8Array, expected: Token | NoRow): Promise<{
|
|
33
|
+
token: Token;
|
|
34
|
+
}>;
|
|
35
|
+
deleteConditional(ref: ChunkRef, expected: Token): Promise<void>;
|
|
36
|
+
listChunks(ref: SegmentRef): AsyncIterable<{
|
|
37
|
+
chunkKey: number;
|
|
38
|
+
} & WarmRow>;
|
|
39
|
+
/**
|
|
40
|
+
* Build a {@link WarmRow} from a raw row. `token` must be a non-empty string and `payload` a Buffer — a
|
|
41
|
+
* missing/typo'd column means a corrupt or foreign row, which we reject (untrusted-data posture) rather
|
|
42
|
+
* than paper over. The returned bytes are a fresh copy (driver-owned, read-only per the contract).
|
|
43
|
+
*/
|
|
44
|
+
private rowFrom;
|
|
45
|
+
/**
|
|
46
|
+
* Reclassify a transient Postgres fault (serialization/deadlock, connection, resource, dropped socket) as
|
|
47
|
+
* a retryable {@link TransientError}; everything else propagates unchanged. Applied at every query site so
|
|
48
|
+
* callers + the retry decorator only ever see typed errors. A deterministic OCC conflict is signalled by
|
|
49
|
+
* the driver itself (0 rows affected) — never reclassified here.
|
|
50
|
+
*/
|
|
51
|
+
private mapError;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export { PostgresWarmDriver, type PostgresWarmDriverOptions, postgresWarmTableDDL };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Pool } from 'pg';
|
|
2
|
+
import { a as IWarmDriver, b as ChunkRef, c as WarmRow, T as Token, N as NoRow, S as SegmentRef } from '../ports-D3BrJ6ax.js';
|
|
3
|
+
|
|
4
|
+
interface PostgresWarmDriverOptions {
|
|
5
|
+
/**
|
|
6
|
+
* A constructed `pg.Pool` (or a pool-compatible client). The driver never opens/closes connections — the
|
|
7
|
+
* caller owns the pool's lifecycle. It **must target the primary**: reads are treated as strongly
|
|
8
|
+
* consistent (the OCC read-modify-write needs read-your-writes), so a pool pointed at a read replica /
|
|
9
|
+
* hot standby could serve stale rows and silently break OCC.
|
|
10
|
+
*/
|
|
11
|
+
readonly pool: Pool;
|
|
12
|
+
/** Warm table name — identifier or `schema.table` (default `cloud_roaring_warm`). Must already exist. */
|
|
13
|
+
readonly table?: string;
|
|
14
|
+
/** Optional key-prefix column value so several logical stores can share one table (bound as data). */
|
|
15
|
+
readonly keyPrefix?: string;
|
|
16
|
+
/** Advanced: `listChunks` keyset-pagination page size (default 1000). Tunes peak memory on wide segments. */
|
|
17
|
+
readonly listPageSize?: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The idempotent DDL for the warm table (identifier-validated + quoted). The driver does **not** create
|
|
21
|
+
* schema (it stays thin + needs no DDL privileges at runtime); run this once at deploy time, e.g.
|
|
22
|
+
* `await pool.query(postgresWarmTableDDL())`.
|
|
23
|
+
*/
|
|
24
|
+
declare function postgresWarmTableDDL(table?: string): string;
|
|
25
|
+
declare class PostgresWarmDriver implements IWarmDriver {
|
|
26
|
+
private readonly pool;
|
|
27
|
+
private readonly table;
|
|
28
|
+
private readonly keyPrefix;
|
|
29
|
+
private readonly listBatch;
|
|
30
|
+
constructor(options: PostgresWarmDriverOptions);
|
|
31
|
+
get(ref: ChunkRef): Promise<WarmRow | null>;
|
|
32
|
+
putConditional(ref: ChunkRef, bytes: Uint8Array, expected: Token | NoRow): Promise<{
|
|
33
|
+
token: Token;
|
|
34
|
+
}>;
|
|
35
|
+
deleteConditional(ref: ChunkRef, expected: Token): Promise<void>;
|
|
36
|
+
listChunks(ref: SegmentRef): AsyncIterable<{
|
|
37
|
+
chunkKey: number;
|
|
38
|
+
} & WarmRow>;
|
|
39
|
+
/**
|
|
40
|
+
* Build a {@link WarmRow} from a raw row. `token` must be a non-empty string and `payload` a Buffer — a
|
|
41
|
+
* missing/typo'd column means a corrupt or foreign row, which we reject (untrusted-data posture) rather
|
|
42
|
+
* than paper over. The returned bytes are a fresh copy (driver-owned, read-only per the contract).
|
|
43
|
+
*/
|
|
44
|
+
private rowFrom;
|
|
45
|
+
/**
|
|
46
|
+
* Reclassify a transient Postgres fault (serialization/deadlock, connection, resource, dropped socket) as
|
|
47
|
+
* a retryable {@link TransientError}; everything else propagates unchanged. Applied at every query site so
|
|
48
|
+
* callers + the retry decorator only ever see typed errors. A deterministic OCC conflict is signalled by
|
|
49
|
+
* the driver itself (0 rows affected) — never reclassified here.
|
|
50
|
+
*/
|
|
51
|
+
private mapError;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export { PostgresWarmDriver, type PostgresWarmDriverOptions, postgresWarmTableDDL };
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { NO_ROW } from '../chunk-AS6ODRLT.js';
|
|
2
|
+
import { ValidationError, validateChunkRef, namespacePart, WriteConflictError, isWriteConflictError, validateSegmentRef, IntegrityError, TransientError } from '../chunk-NUIDEEFZ.js';
|
|
3
|
+
import { randomUUID } from 'crypto';
|
|
4
|
+
|
|
5
|
+
// src/drivers/postgres/keys.ts
|
|
6
|
+
var IDENT = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
|
|
7
|
+
function validateAndQuoteTable(table) {
|
|
8
|
+
const parts = table.split(".");
|
|
9
|
+
if (parts.length > 2 || parts.some((p) => !IDENT.test(p))) {
|
|
10
|
+
throw new ValidationError(
|
|
11
|
+
`invalid table name ${JSON.stringify(table)} \u2014 expected an identifier or "schema.table" (letters, digits, underscore; \u226463 chars; leading letter/underscore)`
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
return parts.map((p) => `"${p}"`).join(".");
|
|
15
|
+
}
|
|
16
|
+
function normalizeKeyPrefix(prefix) {
|
|
17
|
+
if (prefix === void 0 || prefix === "") return "";
|
|
18
|
+
for (const ch of prefix) {
|
|
19
|
+
if (ch.charCodeAt(0) < 32) {
|
|
20
|
+
throw new ValidationError("keyPrefix must not contain control characters");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return prefix;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/drivers/postgres/postgres-errors.ts
|
|
27
|
+
function networkCode(err) {
|
|
28
|
+
const code = err?.code;
|
|
29
|
+
return typeof code === "string" && /^E[A-Z_]+$/.test(code) ? code : void 0;
|
|
30
|
+
}
|
|
31
|
+
var CONNECTION_LOST = /connection terminated|not queryable|timeout exceeded when trying to connect/i;
|
|
32
|
+
function isConnectionLostMessage(err) {
|
|
33
|
+
return err instanceof Error && CONNECTION_LOST.test(err.message);
|
|
34
|
+
}
|
|
35
|
+
function sqlState(err) {
|
|
36
|
+
if (networkCode(err) !== void 0) return void 0;
|
|
37
|
+
const code = err?.code;
|
|
38
|
+
return typeof code === "string" && /^[0-9A-Z]{5}$/.test(code) ? code : void 0;
|
|
39
|
+
}
|
|
40
|
+
function isTransient(err) {
|
|
41
|
+
const state = sqlState(err);
|
|
42
|
+
if (state !== void 0) {
|
|
43
|
+
const cls = state.slice(0, 2);
|
|
44
|
+
if (cls === "40" || cls === "08" || cls === "53") return true;
|
|
45
|
+
if (state === "57P03" || state === "57P01" || state === "57P02") return true;
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
const net = networkCode(err);
|
|
49
|
+
if (net === "ECONNRESET" || net === "ECONNABORTED" || net === "ETIMEDOUT" || net === "ESOCKETTIMEDOUT" || net === "ECONNREFUSED" || net === "EHOSTUNREACH" || net === "ENETUNREACH" || net === "EPIPE" || net === "EAI_AGAIN" || net === "ENOTFOUND") {
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
return isConnectionLostMessage(err);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/drivers/postgres/warm.ts
|
|
56
|
+
var DEFAULT_TABLE = "cloud_roaring_warm";
|
|
57
|
+
var DEFAULT_LIST_BATCH = 1e3;
|
|
58
|
+
function postgresWarmTableDDL(table = DEFAULT_TABLE) {
|
|
59
|
+
const t = validateAndQuoteTable(table);
|
|
60
|
+
return `CREATE TABLE IF NOT EXISTS ${t} (
|
|
61
|
+
key_prefix text NOT NULL,
|
|
62
|
+
namespace text NOT NULL,
|
|
63
|
+
segment text NOT NULL,
|
|
64
|
+
chunk_key integer NOT NULL,
|
|
65
|
+
token text NOT NULL,
|
|
66
|
+
payload bytea NOT NULL,
|
|
67
|
+
PRIMARY KEY (key_prefix, namespace, segment, chunk_key)
|
|
68
|
+
);`;
|
|
69
|
+
}
|
|
70
|
+
var PostgresWarmDriver = class {
|
|
71
|
+
pool;
|
|
72
|
+
table;
|
|
73
|
+
// validated + quoted for interpolation
|
|
74
|
+
keyPrefix;
|
|
75
|
+
listBatch;
|
|
76
|
+
constructor(options) {
|
|
77
|
+
this.pool = options.pool;
|
|
78
|
+
this.table = validateAndQuoteTable(options.table ?? DEFAULT_TABLE);
|
|
79
|
+
this.keyPrefix = normalizeKeyPrefix(options.keyPrefix);
|
|
80
|
+
const batch = options.listPageSize ?? DEFAULT_LIST_BATCH;
|
|
81
|
+
if (!Number.isSafeInteger(batch) || batch < 1) {
|
|
82
|
+
throw new ValidationError(`listPageSize must be a positive safe integer; got ${batch}`);
|
|
83
|
+
}
|
|
84
|
+
this.listBatch = batch;
|
|
85
|
+
}
|
|
86
|
+
// Reads are always strongly consistent (single primary), so the optional `WarmReadOptions` hint would be a
|
|
87
|
+
// no-op — the structurally-optional param is simply omitted (still satisfies IWarmDriver), as in LocalFs.
|
|
88
|
+
async get(ref) {
|
|
89
|
+
validateChunkRef(ref);
|
|
90
|
+
try {
|
|
91
|
+
const res = await this.pool.query(
|
|
92
|
+
`SELECT token, payload FROM ${this.table} WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key = $4`,
|
|
93
|
+
[this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey]
|
|
94
|
+
);
|
|
95
|
+
const row = res.rows[0];
|
|
96
|
+
return row === void 0 ? null : this.rowFrom(row, ref.chunkKey);
|
|
97
|
+
} catch (err) {
|
|
98
|
+
throw this.mapError(err);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async putConditional(ref, bytes, expected) {
|
|
102
|
+
validateChunkRef(ref);
|
|
103
|
+
const token = randomUUID();
|
|
104
|
+
const payload = Buffer.from(bytes);
|
|
105
|
+
const ns = namespacePart(ref.namespace);
|
|
106
|
+
try {
|
|
107
|
+
if (expected === NO_ROW) {
|
|
108
|
+
const res = await this.pool.query(
|
|
109
|
+
`INSERT INTO ${this.table} (key_prefix, namespace, segment, chunk_key, token, payload) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (key_prefix, namespace, segment, chunk_key) DO NOTHING`,
|
|
110
|
+
[this.keyPrefix, ns, ref.segment, ref.chunkKey, token, payload]
|
|
111
|
+
);
|
|
112
|
+
if (res.rowCount !== 1) {
|
|
113
|
+
throw new WriteConflictError(`chunk ${ref.chunkKey} already exists (create-if-absent)`);
|
|
114
|
+
}
|
|
115
|
+
} else {
|
|
116
|
+
const res = await this.pool.query(
|
|
117
|
+
`UPDATE ${this.table} SET token = $5, payload = $6 WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key = $4 AND token = $7`,
|
|
118
|
+
[this.keyPrefix, ns, ref.segment, ref.chunkKey, token, payload, expected]
|
|
119
|
+
);
|
|
120
|
+
if (res.rowCount !== 1)
|
|
121
|
+
throw new WriteConflictError(`OCC conflict on chunk ${ref.chunkKey}`);
|
|
122
|
+
}
|
|
123
|
+
return { token };
|
|
124
|
+
} catch (err) {
|
|
125
|
+
if (isWriteConflictError(err)) throw err;
|
|
126
|
+
throw this.mapError(err);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async deleteConditional(ref, expected) {
|
|
130
|
+
validateChunkRef(ref);
|
|
131
|
+
try {
|
|
132
|
+
const res = await this.pool.query(
|
|
133
|
+
`DELETE FROM ${this.table} WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key = $4 AND token = $5`,
|
|
134
|
+
[this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey, expected]
|
|
135
|
+
);
|
|
136
|
+
if (res.rowCount !== 1) {
|
|
137
|
+
throw new WriteConflictError(`fenced-delete conflict on chunk ${ref.chunkKey}`);
|
|
138
|
+
}
|
|
139
|
+
} catch (err) {
|
|
140
|
+
if (isWriteConflictError(err)) throw err;
|
|
141
|
+
throw this.mapError(err);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async *listChunks(ref) {
|
|
145
|
+
validateSegmentRef(ref);
|
|
146
|
+
const ns = namespacePart(ref.namespace);
|
|
147
|
+
let after = -1;
|
|
148
|
+
for (; ; ) {
|
|
149
|
+
let rows;
|
|
150
|
+
try {
|
|
151
|
+
const res = await this.pool.query(
|
|
152
|
+
`SELECT chunk_key, token, payload FROM ${this.table} WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key > $4 ORDER BY chunk_key ASC LIMIT $5`,
|
|
153
|
+
[this.keyPrefix, ns, ref.segment, after, this.listBatch]
|
|
154
|
+
);
|
|
155
|
+
rows = res.rows;
|
|
156
|
+
} catch (err) {
|
|
157
|
+
throw this.mapError(err);
|
|
158
|
+
}
|
|
159
|
+
for (const row of rows) {
|
|
160
|
+
const chunkKey = row.chunk_key;
|
|
161
|
+
if (typeof chunkKey !== "number") {
|
|
162
|
+
throw new IntegrityError("warm row is missing its chunk_key");
|
|
163
|
+
}
|
|
164
|
+
yield { chunkKey, ...this.rowFrom(row, chunkKey) };
|
|
165
|
+
after = chunkKey;
|
|
166
|
+
}
|
|
167
|
+
if (rows.length < this.listBatch) return;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Build a {@link WarmRow} from a raw row. `token` must be a non-empty string and `payload` a Buffer — a
|
|
172
|
+
* missing/typo'd column means a corrupt or foreign row, which we reject (untrusted-data posture) rather
|
|
173
|
+
* than paper over. The returned bytes are a fresh copy (driver-owned, read-only per the contract).
|
|
174
|
+
*/
|
|
175
|
+
rowFrom(row, chunkKey) {
|
|
176
|
+
if (typeof row.token !== "string" || row.token === "") {
|
|
177
|
+
throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its token`);
|
|
178
|
+
}
|
|
179
|
+
if (!(row.payload instanceof Uint8Array)) {
|
|
180
|
+
throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its payload`);
|
|
181
|
+
}
|
|
182
|
+
return { token: row.token, bytes: new Uint8Array(row.payload) };
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Reclassify a transient Postgres fault (serialization/deadlock, connection, resource, dropped socket) as
|
|
186
|
+
* a retryable {@link TransientError}; everything else propagates unchanged. Applied at every query site so
|
|
187
|
+
* callers + the retry decorator only ever see typed errors. A deterministic OCC conflict is signalled by
|
|
188
|
+
* the driver itself (0 rows affected) — never reclassified here.
|
|
189
|
+
*/
|
|
190
|
+
mapError(err) {
|
|
191
|
+
if (isTransient(err)) {
|
|
192
|
+
return new TransientError(
|
|
193
|
+
`transient Postgres fault: ${err?.code ?? "unknown"}`,
|
|
194
|
+
{ cause: err }
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return err;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
export { PostgresWarmDriver, postgresWarmTableDDL };
|
|
202
|
+
//# sourceMappingURL=index.js.map
|
|
203
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/drivers/postgres/keys.ts","../../src/drivers/postgres/postgres-errors.ts","../../src/drivers/postgres/warm.ts"],"names":[],"mappings":";;;;;AAaA,IAAM,KAAA,GAAQ,+BAAA;AAQP,SAAS,sBAAsB,KAAA,EAAuB;AAC3D,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,KAAA,CAAM,GAAG,CAAA;AAC7B,EAAA,IAAI,KAAA,CAAM,MAAA,GAAS,CAAA,IAAK,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA,KAAM,CAAC,KAAA,CAAM,IAAA,CAAK,CAAC,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CAAA,CAAA;AAAA,QAClF,EAAE,OAAO,GAAA;AAAI,OACf;AAAA,IACF;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACF","file":"index.js","sourcesContent":["/**\n * Identifier + key validation for {@link PostgresWarmDriver} (Phase 7).\n *\n * Pure, SDK-free string logic — unit-testable without a live Postgres. Unlike the object-store drivers (which\n * build a single string key), the Postgres driver stores the logical ref across **parameterized columns**\n * (`namespace`, `segment`, `chunk_key`, `key_prefix`), so ref/prefix values are never concatenated into SQL —\n * `pg`'s `$n` placeholders bind them as data (no injection surface). The one value that CANNOT be a bind\n * parameter is the **table name** (an identifier, not a value), so it is validated against a strict grammar\n * and quoted before interpolation — that is the whole reason this module exists.\n */\nimport { ValidationError } from '@/core/errors';\n\n/** A SQL identifier segment: leading letter/underscore, then letters/digits/underscores (ASCII, ≤63 = PG max). */\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;\n\n/**\n * Validate a table name — optionally schema-qualified (`schema.table`) — and return it **safely quoted** for\n * interpolation (each part wrapped in double quotes). A table name is an identifier, so it can't be a bind\n * parameter; validating against {@link IDENT} (which excludes quotes, whitespace, `;`, `-`, etc.) and quoting\n * closes the only SQL-injection vector the driver has. Rejects anything else, fail-fast.\n */\nexport function validateAndQuoteTable(table: string): string {\n const parts = table.split('.');\n if (parts.length > 2 || parts.some((p) => !IDENT.test(p))) {\n throw new ValidationError(\n `invalid table name ${JSON.stringify(table)} — expected an identifier or \"schema.table\" ` +\n `(letters, digits, underscore; ≤63 chars; leading letter/underscore)`,\n );\n }\n return parts.map((p) => `\"${p}\"`).join('.');\n}\n\n/**\n * Validate a caller-supplied `keyPrefix` (lets several logical stores share one table). It's bound as a `$n`\n * value, not concatenated, so this is a light sanity guard (no control characters), not an anti-injection\n * boundary. Empty/undefined means no prefix (stored as the empty string).\n */\nexport function normalizeKeyPrefix(prefix: string | undefined): string {\n if (prefix === undefined || prefix === '') return '';\n for (const ch of prefix) {\n if (ch.charCodeAt(0) < 0x20) {\n throw new ValidationError('keyPrefix must not contain control characters');\n }\n }\n return prefix;\n}\n","/**\n * Pure helpers for classifying PostgreSQL (`pg`) errors (Phase 7; transient class mirrors S3/GCS/Azure).\n *\n * SDK-free + side-effect-free — they read only structural shapes off the thrown value (`err.code`, a\n * SQLSTATE string; or a Node socket `code`), so the translation is unit-testable without a live Postgres.\n * Note the driver signals a write-once / OCC conflict itself (a conditional statement affecting **0 rows**),\n * so there is no \"conflict\" classifier here — only transient-vs-not. Everything not transient propagates\n * unchanged so a real bug is never silently retried.\n */\n\n/**\n * A Node system/socket error `code` (e.g. `ECONNRESET`, `EPIPE`, `EAI_AGAIN`): starts with `E`, only\n * uppercase letters + underscore, no digits. Checked BEFORE {@link sqlState} because some socket codes are\n * exactly 5 chars (`EPIPE`) and would otherwise collide with the SQLSTATE shape — no real Postgres SQLSTATE\n * class begins with a letter `E`, so this disambiguates cleanly.\n */\nfunction networkCode(err: unknown): string | undefined {\n const code = (err as { code?: unknown } | null)?.code;\n return typeof code === 'string' && /^E[A-Z_]+$/.test(code) ? code : undefined;\n}\n\n/**\n * `pg` surfaces its most common transient faults — a backend/socket that drops mid-query, or a pool\n * connect-timeout — as a plain `Error` with **no `.code`**, only a message (`pg/lib/client.js`: \"Connection\n * terminated unexpectedly\", \"…is not queryable\"; pg-pool's \"timeout exceeded when trying to connect\"). Without\n * this, such a fault would fall through as non-transient and the retry decorator would not ride it out — the\n * exact class of fault the resilience layer exists to absorb. Only consulted when there's no SQLSTATE/socket\n * code (a deterministic server error always carries a code, so this can never mask one).\n */\nconst CONNECTION_LOST =\n /connection terminated|not queryable|timeout exceeded when trying to connect/i;\nfunction isConnectionLostMessage(err: unknown): boolean {\n return err instanceof Error && CONNECTION_LOST.test(err.message);\n}\n\n/** The `pg` error's SQLSTATE (a 5-char `[0-9A-Z]` code like `40001`), if present and not a socket code. */\nfunction sqlState(err: unknown): string | undefined {\n if (networkCode(err) !== undefined) return undefined;\n const code = (err as { code?: unknown } | null)?.code;\n return typeof code === 'string' && /^[0-9A-Z]{5}$/.test(code) ? code : undefined;\n}\n\n/**\n * A transient Postgres fault that is safe to retry: a serialization failure / deadlock (SQLSTATE class 40),\n * an operator-intervention / cannot-connect-now (57P03 / 57P01 / 57P02), too-many-connections or\n * out-of-memory (53xxx), a connection-exception (class 08), or a dropped/timed-out socket. Deterministic,\n * caller-meaningful outcomes (constraint violations, syntax errors, etc.) are NOT transient — they must\n * surface, never be blind-retried.\n */\nexport function isTransient(err: unknown): boolean {\n const state = sqlState(err);\n if (state !== undefined) {\n const cls = state.slice(0, 2);\n if (cls === '40' || cls === '08' || cls === '53') return true; // serialization/deadlock, connection, resource\n if (state === '57P03' || state === '57P01' || state === '57P02') return true; // cannot_connect_now / shutdowns\n return false;\n }\n const net = networkCode(err);\n if (\n net === 'ECONNRESET' ||\n net === 'ECONNABORTED' ||\n net === 'ETIMEDOUT' ||\n net === 'ESOCKETTIMEDOUT' ||\n net === 'ECONNREFUSED' ||\n net === 'EHOSTUNREACH' ||\n net === 'ENETUNREACH' ||\n net === 'EPIPE' ||\n net === 'EAI_AGAIN' ||\n net === 'ENOTFOUND'\n ) {\n return true;\n }\n // pg's code-less connection-lost errors (see CONNECTION_LOST) — the tail case, only if nothing above matched.\n return isConnectionLostMessage(err);\n}\n","/**\n * `PostgresWarmDriver` — an {@link IWarmDriver} over PostgreSQL (Phase 7).\n *\n * \"No DynamoDB — use the Postgres you already run.\" Uses the official `pg` (node-postgres), an **optional\n * peer dependency** — only consumers of `cloud-roaring/postgres` install it. A `pg.Pool` is **injected**\n * (dependency injection): the driver owns no connection/credential logic, so it's thin, reuses the caller's\n * pool, and is testable against a Postgres container.\n *\n * Each chunk is one row in a single table (`PRIMARY KEY (key_prefix, namespace, segment, chunk_key)`), with\n * an opaque OCC **token** (a random UUID minted per write) and the delta `payload` (bytea). Optimistic\n * concurrency is real, cross-process, and server-side:\n * - **create-if-absent** = `INSERT … ON CONFLICT DO NOTHING`; 0 rows affected ⇒ the row already exists ⇒\n * {@link WriteConflictError}.\n * - **token-fenced update / delete** = `UPDATE … / DELETE … WHERE … AND token = :expected`; 0 rows affected\n * ⇒ the stored token moved (or the row is gone) ⇒ {@link WriteConflictError}.\n *\n * Tokens are not reused across delete→recreate (ABA-safe, D3): a delete removes the row and a recreate mints\n * a fresh random UUID, so a token from before the delete won't match. (This is a *probabilistic* guarantee —\n * a random 122-bit UUIDv4, collision odds negligible — vs the DynamoDB driver's *structural* monotonic-counter\n * guarantee; the hard-delete/no-tombstone model can't offer the latter, and conformance D3 pins the behavior.)\n * Reads are strongly consistent (single primary), so the optional `WarmReadOptions` consistency hint is a\n * no-op, like the in-memory / LocalFs drivers. Drivers may use `node:crypto`; only `core/` is determinism-bound.\n */\nimport { randomUUID } from 'node:crypto';\nimport type { Pool } from 'pg';\nimport {\n IntegrityError,\n TransientError,\n ValidationError,\n WriteConflictError,\n isWriteConflictError,\n} from '@/core/errors';\nimport { NO_ROW } from '@/core/ports';\nimport type { ChunkRef, IWarmDriver, NoRow, SegmentRef, Token, WarmRow } from '@/core/ports';\nimport { validateChunkRef, validateSegmentRef } from '@/core/validate';\nimport { namespacePart } from '../_shared/keys';\nimport { normalizeKeyPrefix, validateAndQuoteTable } from './keys';\nimport { isTransient } from './postgres-errors';\n\nconst DEFAULT_TABLE = 'cloud_roaring_warm';\n/** Default listChunks keyset-pagination batch — bounds peak memory to ~this many rows regardless of width. */\nconst DEFAULT_LIST_BATCH = 1000;\n\nexport interface PostgresWarmDriverOptions {\n /**\n * A constructed `pg.Pool` (or a pool-compatible client). The driver never opens/closes connections — the\n * caller owns the pool's lifecycle. It **must target the primary**: reads are treated as strongly\n * consistent (the OCC read-modify-write needs read-your-writes), so a pool pointed at a read replica /\n * hot standby could serve stale rows and silently break OCC.\n */\n readonly pool: Pool;\n /** Warm table name — identifier or `schema.table` (default `cloud_roaring_warm`). Must already exist. */\n readonly table?: string;\n /** Optional key-prefix column value so several logical stores can share one table (bound as data). */\n readonly keyPrefix?: string;\n /** Advanced: `listChunks` keyset-pagination page size (default 1000). Tunes peak memory on wide segments. */\n readonly listPageSize?: number;\n}\n\n/** One raw warm row as selected. */\ninterface RawRow {\n chunk_key?: number;\n token?: unknown;\n payload?: unknown;\n}\n\n/**\n * The idempotent DDL for the warm table (identifier-validated + quoted). The driver does **not** create\n * schema (it stays thin + needs no DDL privileges at runtime); run this once at deploy time, e.g.\n * `await pool.query(postgresWarmTableDDL())`.\n */\nexport function postgresWarmTableDDL(table: string = DEFAULT_TABLE): string {\n const t = validateAndQuoteTable(table);\n return (\n `CREATE TABLE IF NOT EXISTS ${t} (\\n` +\n ` key_prefix text NOT NULL,\\n` +\n ` namespace text NOT NULL,\\n` +\n ` segment text NOT NULL,\\n` +\n ` chunk_key integer NOT NULL,\\n` +\n ` token text NOT NULL,\\n` +\n ` payload bytea NOT NULL,\\n` +\n ` PRIMARY KEY (key_prefix, namespace, segment, chunk_key)\\n` +\n `);`\n );\n}\n\nexport class PostgresWarmDriver implements IWarmDriver {\n private readonly pool: Pool;\n private readonly table: string; // validated + quoted for interpolation\n private readonly keyPrefix: string;\n private readonly listBatch: number;\n\n constructor(options: PostgresWarmDriverOptions) {\n this.pool = options.pool;\n this.table = validateAndQuoteTable(options.table ?? DEFAULT_TABLE);\n this.keyPrefix = normalizeKeyPrefix(options.keyPrefix);\n const batch = options.listPageSize ?? DEFAULT_LIST_BATCH;\n if (!Number.isSafeInteger(batch) || batch < 1) {\n throw new ValidationError(`listPageSize must be a positive safe integer; got ${batch}`);\n }\n this.listBatch = batch;\n }\n\n // Reads are always strongly consistent (single primary), so the optional `WarmReadOptions` hint would be a\n // no-op — the structurally-optional param is simply omitted (still satisfies IWarmDriver), as in LocalFs.\n async get(ref: ChunkRef): Promise<WarmRow | null> {\n validateChunkRef(ref);\n try {\n const res = await this.pool.query<RawRow>(\n `SELECT token, payload FROM ${this.table} ` +\n `WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key = $4`,\n [this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey],\n );\n const row = res.rows[0];\n return row === undefined ? null : this.rowFrom(row, ref.chunkKey);\n } catch (err) {\n throw this.mapError(err);\n }\n }\n\n async putConditional(\n ref: ChunkRef,\n bytes: Uint8Array,\n expected: Token | NoRow,\n ): Promise<{ token: Token }> {\n validateChunkRef(ref);\n const token = randomUUID();\n // Copy the payload into a Buffer for `bytea` binding — severs any caller-owned/reused input buffer.\n const payload = Buffer.from(bytes);\n const ns = namespacePart(ref.namespace);\n try {\n if (expected === NO_ROW) {\n const res = await this.pool.query(\n `INSERT INTO ${this.table} (key_prefix, namespace, segment, chunk_key, token, payload) ` +\n `VALUES ($1, $2, $3, $4, $5, $6) ` +\n `ON CONFLICT (key_prefix, namespace, segment, chunk_key) DO NOTHING`,\n [this.keyPrefix, ns, ref.segment, ref.chunkKey, token, payload],\n );\n // A single-row PK write affects exactly 1 row on success; anything else (0 = conflict, or a `null`\n // rowCount) is NOT a confirmed insert — treat as a conflict, never a silent false-success.\n if (res.rowCount !== 1) {\n throw new WriteConflictError(`chunk ${ref.chunkKey} already exists (create-if-absent)`);\n }\n } else {\n const res = await this.pool.query(\n `UPDATE ${this.table} SET token = $5, payload = $6 ` +\n `WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key = $4 ` +\n `AND token = $7`,\n [this.keyPrefix, ns, ref.segment, ref.chunkKey, token, payload, expected],\n );\n if (res.rowCount !== 1)\n throw new WriteConflictError(`OCC conflict on chunk ${ref.chunkKey}`);\n }\n return { token };\n } catch (err) {\n if (isWriteConflictError(err)) throw err; // our own deterministic conflict — never a transient\n throw this.mapError(err);\n }\n }\n\n async deleteConditional(ref: ChunkRef, expected: Token): Promise<void> {\n validateChunkRef(ref);\n try {\n const res = await this.pool.query(\n `DELETE FROM ${this.table} ` +\n `WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key = $4 AND token = $5`,\n [this.keyPrefix, namespacePart(ref.namespace), ref.segment, ref.chunkKey, expected],\n );\n if (res.rowCount !== 1) {\n throw new WriteConflictError(`fenced-delete conflict on chunk ${ref.chunkKey}`);\n }\n } catch (err) {\n if (isWriteConflictError(err)) throw err;\n throw this.mapError(err);\n }\n }\n\n async *listChunks(ref: SegmentRef): AsyncIterable<{ chunkKey: number } & WarmRow> {\n validateSegmentRef(ref);\n const ns = namespacePart(ref.namespace);\n // Keyset pagination on chunk_key (ascending) bounds peak memory to one page WITHIN a single enumeration,\n // regardless of how wide the segment is. (It does NOT resume across a transient fault — the retry decorator\n // re-enumerates a streaming method from the start and buffers, see drivers/retry/retrying-drivers.ts.)\n let after = -1;\n for (;;) {\n let rows: RawRow[];\n try {\n const res = await this.pool.query<RawRow>(\n `SELECT chunk_key, token, payload FROM ${this.table} ` +\n `WHERE key_prefix = $1 AND namespace = $2 AND segment = $3 AND chunk_key > $4 ` +\n `ORDER BY chunk_key ASC LIMIT $5`,\n [this.keyPrefix, ns, ref.segment, after, this.listBatch],\n );\n rows = res.rows;\n } catch (err) {\n throw this.mapError(err);\n }\n for (const row of rows) {\n const chunkKey = row.chunk_key;\n if (typeof chunkKey !== 'number') {\n throw new IntegrityError('warm row is missing its chunk_key');\n }\n yield { chunkKey, ...this.rowFrom(row, chunkKey) };\n after = chunkKey;\n }\n if (rows.length < this.listBatch) return;\n }\n }\n\n /**\n * Build a {@link WarmRow} from a raw row. `token` must be a non-empty string and `payload` a Buffer — a\n * missing/typo'd column means a corrupt or foreign row, which we reject (untrusted-data posture) rather\n * than paper over. The returned bytes are a fresh copy (driver-owned, read-only per the contract).\n */\n private rowFrom(row: RawRow, chunkKey: number): WarmRow {\n if (typeof row.token !== 'string' || row.token === '') {\n throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its token`);\n }\n if (!(row.payload instanceof Uint8Array)) {\n throw new IntegrityError(`warm row for chunk ${chunkKey} is missing its payload`);\n }\n return { token: row.token, bytes: new Uint8Array(row.payload) };\n }\n\n /**\n * Reclassify a transient Postgres fault (serialization/deadlock, connection, resource, dropped socket) as\n * a retryable {@link TransientError}; everything else propagates unchanged. Applied at every query site so\n * callers + the retry decorator only ever see typed errors. A deterministic OCC conflict is signalled by\n * the driver itself (0 rows affected) — never reclassified here.\n */\n private mapError(err: unknown): unknown {\n if (isTransient(err)) {\n return new TransientError(\n `transient Postgres fault: ${(err as { code?: unknown } | null)?.code ?? 'unknown'}`,\n { cause: err },\n );\n }\n return err;\n }\n}\n"]}
|