@duraxis/storage-s3 0.0.0-stage → 0.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # @duraxis/storage-s3
2
+
3
+ ## 0.1.0
4
+
5
+ Initial S3 driver with conditional writes, isolated namespaces and managed AWS SDK lifecycle.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 João Paulo Dias
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,289 @@
1
- # Temporary Holding Version
1
+ # @duraxis/storage-s3
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Amazon S3 storage for Duraxis, with an internally managed AWS SDK v3 client. Applications only
4
+ import Duraxis APIs. Requires Node.js 22.12+ and a pre-existing general-purpose S3 bucket.
5
+ No network requests occur in the constructor.
6
+
7
+ ## Installation and standalone usage
8
+
9
+ ```bash
10
+ pnpm add @duraxis/core @duraxis/storage-s3
11
+ ```
12
+
13
+ ```ts
14
+ import { DuraxisDatabase } from "@duraxis/core";
15
+ import { S3StorageDriver } from "@duraxis/storage-s3";
16
+
17
+ const storage = new S3StorageDriver({
18
+ bucket: "my-duraxis-bucket",
19
+ prefix: "databases/orders",
20
+ client: { region: "sa-east-1" },
21
+ });
22
+ const database = new DuraxisDatabase({ storage });
23
+ try {
24
+ await database.transaction((tx) => {
25
+ tx.put("greeting", new TextEncoder().encode("hello"));
26
+ });
27
+ await database.transaction(async (tx) => {
28
+ console.log(new TextDecoder().decode((await tx.get("greeting"))!));
29
+ });
30
+ } finally {
31
+ await database.close({ closeStorage: true });
32
+ }
33
+ ```
34
+
35
+ The AWS SDK is a regular runtime dependency of this package. Do not install or construct an AWS
36
+ SDK client separately. For ORM usage, also install `@duraxis/orm` and pass the same database to
37
+ `DuraxisORM` as with the other drivers.
38
+
39
+ ## NestJS
40
+
41
+ Install `@duraxis/nestjs`, `@duraxis/orm`, `@duraxis/core` and `@duraxis/storage-s3` alongside the
42
+ normal NestJS dependencies:
43
+
44
+ ```ts
45
+ import { Module } from "@nestjs/common";
46
+ import { DuraxisModule } from "@duraxis/nestjs";
47
+ import { S3StorageDriver } from "@duraxis/storage-s3";
48
+
49
+ @Module({
50
+ imports: [
51
+ DuraxisModule.forRootAsync({
52
+ useFactory: async () => ({
53
+ driver: new S3StorageDriver({
54
+ client: { region: "sa-east-1" },
55
+ bucket: "my-duraxis-bucket",
56
+ prefix: "databases/orders",
57
+ }),
58
+ closeStorage: true,
59
+ autoLoadEntities: true,
60
+ schema: { mode: "validate" },
61
+ }),
62
+ }),
63
+ ],
64
+ })
65
+ export class AppModule {}
66
+ ```
67
+
68
+ Provision the schema before using `validate`; an explicitly chosen `create` mode can initialize
69
+ a new namespace. Feature modules continue using `DuraxisModule.forFeature([Entity])`, ordinary
70
+ `providers: [Service]` and `@Transactional()`.
71
+
72
+ Nest treats a supplied driver instance as externally owned. Set **`closeStorage: true`** to close
73
+ it on shutdown. Alternatively, return `driver: () => new S3StorageDriver(options)`; Nest owns
74
+ factory-created drivers by default. No Nest ownership or transaction lifecycle rules are changed.
75
+
76
+ ## Configuration and credentials
77
+
78
+ ```ts
79
+ import type { S3StorageDriverOptions } from "@duraxis/storage-s3";
80
+
81
+ const options: S3StorageDriverOptions = {
82
+ bucket: "my-duraxis-bucket",
83
+ prefix: "database-a", // normalized to "database-a/"
84
+ client: {
85
+ region: "sa-east-1",
86
+ endpoint: "http://127.0.0.1:9000", // optional compatible endpoint
87
+ forcePathStyle: true, // commonly required by local compatible services
88
+ maxAttempts: 3, // read attempts only, from 1 to 10
89
+ credentials: {
90
+ // optional; normally omit this entire property
91
+ accessKeyId: process.env.S3_ACCESS_KEY_ID!,
92
+ secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
93
+ sessionToken: process.env.S3_SESSION_TOKEN,
94
+ },
95
+ },
96
+ };
97
+ ```
98
+
99
+ Omitting credentials uses the internal SDK's default credential provider chain, including
100
+ environment credentials, shared configuration, workload identity, ECS and EC2 IAM roles.
101
+ Omitting `region` uses the SDK's region resolution. Prefer IAM roles with short-lived credentials
102
+ in production. Explicit credential objects are static snapshots; rotate them by replacing the
103
+ driver, or use the default role/provider chain for automatic refresh. Never hard-code secrets.
104
+
105
+ Endpoints must be HTTP(S) URLs without embedded credentials, query strings or fragments. Bucket
106
+ names must satisfy general-purpose bucket naming constraints. Directory buckets, access-point
107
+ ARNs and S3 on Outposts are outside this driver's supported configuration.
108
+
109
+ The prefix is a database namespace, not a filesystem path. A nonempty prefix gets a trailing slash;
110
+ it is prepended consistently and removed from logical `list()` results. Keys remain case-sensitive,
111
+ are not path-normalized, and must be well-formed UTF-8 with a nonempty nonblank logical value.
112
+ The complete physical key is limited to S3's 1,024-byte limit. An empty prefix dedicates the
113
+ bucket to this driver's format. Do not share the same prefix with other object formats or writers.
114
+
115
+ ## Storage format, versions and conditions
116
+
117
+ The local `StorageDriver` contract has conditional create, replacement and deletion, opaque
118
+ generation versions, isolated byte arrays, deterministic listing and shared `StorageError` codes.
119
+ The S3 implementation preserves these contracts without changing core, ORM, Nest or other drivers.
120
+
121
+ Each physical object contains a versioned 72-byte envelope: an 8-byte format marker, a fresh
122
+ 32-byte random nonce, a SHA-256 payload digest, and then the unchanged logical payload. S3 user
123
+ metadata identifies format `1` and state `live` or `deleted`. A tombstone has an empty logical
124
+ payload. The driver verifies and removes the envelope on GET. Empty logical objects are supported.
125
+
126
+ The **opaque quoted ETag** returned by S3 is the storage version. It is reused as an `If-Match`
127
+ value; it is not interpreted as a cryptographic checksum. S3 `VersionId` is never used as a
128
+ conditional token. GET, successful PUT and LIST agree on the current live object's ETag.
129
+ Versions must be reused exactly as issued; wildcard and multi-value conditional expressions
130
+ are not accepted. Missing or malformed service ETags fail explicitly.
131
+
132
+ The nonce changes the physical body for every write, including identical-value replacements,
133
+ deletions and recreations. This prevents ordinary same-content/ABA version reuse under S3's
134
+ ETag semantics, subject to the probabilistic uniqueness of random nonces and service tokens.
135
+ Payload integrity uses SHA-256 independently of ETag. This is not protection against an actor
136
+ authorized to rewrite both data and metadata. Copying/restoring old physical objects, external
137
+ unconditional writes or an endpoint that reuses ETags across distinct bodies invalidate the
138
+ concurrency assumptions. Bucket versioning is optional and does not replace these conditions.
139
+
140
+ | Operation | Physical behavior |
141
+ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
142
+ | GET | `GetObject`, consume/close body, decode envelope; `NoSuchKey` or a valid tombstone becomes `null`. |
143
+ | PUT `if-absent` | `PutObject` with `If-None-Match: *`. An existing live object conflicts. A tombstone can be replaced using `If-Match` against its observed ETag. |
144
+ | PUT `if-version` | HEAD checks live state and version; `PutObject` still uses the caller's `If-Match` token atomically. |
145
+ | DELETE `if-version` | HEAD checks live state and version; a conditional `PutObject` replaces it with a new tombstone using `If-Match`. |
146
+ | DELETE `if-absent` | A read-only absence assertion using HEAD; success if logically absent, conflict if live. No object is removed. |
147
+ | LIST | `ListObjectsV2` pages plus HEAD per physical entry; filters tombstones and returns sorted logical keys, current ETags and last-modified milliseconds. |
148
+
149
+ All physical mutations are conditional writes. Metadata preflights never authorize an
150
+ unconditional overwrite: if another writer wins after HEAD, the final `If-Match` fails. Two
151
+ independent drivers racing against one version cannot both publish a replacement, deletion or
152
+ recreation. The implementation never uses a GET followed by an unconditional PUT/DELETE.
153
+
154
+ **Why tombstones?** An idempotent S3 deletion API is not the same contract as Duraxis's deletion
155
+ CAS, where a missing object conflicts and exactly one competing mutation may succeed. The
156
+ implementation uses conditional PUT's existence precondition to avoid depending on missing-key
157
+ DeleteObject behavior. `if-absent` deletion is simply an atomic read-only assertion: a later
158
+ concurrent create may succeed, which is consistent with the assertion's earlier observation.
159
+
160
+ Deleting replaces the body with a small persistent tombstone; it does not issue `DeleteObject`.
161
+ These objects intentionally remain to preserve logical state. Do not expire tombstones or restore
162
+ historical object generations while the database is active. In versioned buckets, old object
163
+ versions also retain previous payloads and incur storage costs. Removing historical versions or
164
+ tombstones requires a separately planned, externally exclusive maintenance procedure; no automatic
165
+ physical tombstone compactor is provided.
166
+
167
+ ListObjectsV2 includes ETag and LastModified, but no Duraxis state metadata or S3 VersionId.
168
+ HEAD is needed to exclude tombstones and read a coherent current ETag/state/timestamp tuple.
169
+ Up to 16 HEAD requests run concurrently per page, and all settle before shutdown or a listing
170
+ error is returned. No object bodies are downloaded during listing. LastModified is the current
171
+ generation's creation time, not the original logical key's first-ever creation time. Listing is
172
+ not a multi-object snapshot under concurrent writes; external exclusive maintenance remains
173
+ necessary for destructive GC. Generic HEAD 404s are confirmed with a narrow listing so missing
174
+ buckets and permission failures are not silently treated as missing objects.
175
+
176
+ ## Transactions, uncertain outcomes and errors
177
+
178
+ The existing core writes immutable objects/index nodes and a commit-history record before
179
+ publishing the manifest with a conditional write. The manifest ETag is its optimistic publication
180
+ token. Losing that CAS raises the existing `TransactionConflictError`; the driver never retries
181
+ the transaction callback. These guarantees rely on a service that correctly implements strongly
182
+ consistent reads/listing and atomic `If-Match` / `If-None-Match` conditional writes.
183
+
184
+ The SDK has **one attempt for every request**. The driver explicitly retries safe reads only,
185
+ with bounded jitter, for selected transient failures (default three attempts). The public
186
+ `client.maxAttempts` controls these read attempts, never mutation retries. Access denial, invalid
187
+ requests and known unsupported operations are not automatically retried. Explicit 412 responses
188
+ and 409 `ConditionalRequestConflict` responses become conflicts; unrelated 409 errors remain errors.
189
+
190
+ A lost response, timeout, cancellation or server failure during a mutation may have happened
191
+ after S3 committed it. The driver throws `StorageError` with `OUTCOME_UNKNOWN` instead of claiming
192
+ failure or retrying into a false conflict. The core wraps manifest publication exceptions in
193
+ `CommitOutcomeUnknownError` and supplies the transaction ID for `database.getCommitStatus(id)`.
194
+ Commit history can establish `committed` even after later commits. An absent history entry means
195
+ `unknown`, not proof that an operation failed. Confirm status before deciding on an application retry.
196
+
197
+ Other failures map to `INVALID_KEY`, `ACCESS_DENIED`, `UNAVAILABLE`, `TIMEOUT`, `RESOURCE_LIMIT`,
198
+ `CORRUPTION`, `CLOSED` or `UNKNOWN` as appropriate. GET returns `null` only for confirmed key absence
199
+ or a valid tombstone. The driver does not log credentials or include configuration, object keys,
200
+ signed URLs or raw SDK messages in its public error messages. Original causes are retained for
201
+ diagnosis; apply your normal redaction policy before logging nested causes.
202
+
203
+ The implementation preserves the core's snapshot/optimistic transaction model. It does not add
204
+ distributed transactions, transparent conflict retries or a blanket full-ACID certification.
205
+
206
+ ## Lifecycle, GC and metrics
207
+
208
+ One AWS client belongs to each driver. `close()` is idempotent, rejects new operations with
209
+ `CLOSED`, waits for active operations (including streams, pagination and retry waits), and then
210
+ destroys the client's resources. It does not force-cancel a hung request or impose a shutdown
211
+ deadline. Close after completing database/ORM work; close the database with `closeStorage: true`
212
+ or close the externally managed driver yourself.
213
+
214
+ GC uses listing timestamps and versions. A changed object's old ETag cannot authorize replacing
215
+ the newer generation with a tombstone. The existing core defaults GC to dry run; destructive GC
216
+ requires `exclusiveMaintenance: true` and an actual external guarantee that all application
217
+ instances, uploads and readers have stopped. The flag is an assertion, not an S3 distributed lock.
218
+ No destructive GC is enabled by this driver. S3 lifecycle policies must not expire live database
219
+ objects or commit-history records independently of Duraxis reachability.
220
+
221
+ `getMetrics()` returns a snapshot. `reads`, `writes`, `deletes` and `lists` count validated logical
222
+ driver calls, including conflicts. Bytes count successfully returned logical data and acknowledged
223
+ logical writes, excluding envelopes, tombstones and uncertain writes. `synchronizationWaitMs` is
224
+ zero because the driver has no local mutation lock. Counts are **not HTTP request counts**: HEAD
225
+ preflights, pagination, conflict checks and read retries add requests.
226
+
227
+ ## Permissions and operational costs
228
+
229
+ Allow `s3:GetObject` and `s3:PutObject` for the dedicated object prefix, and `s3:ListBucket` on the
230
+ bucket with an appropriate prefix restriction. HEAD uses GetObject permission. No bucket creation,
231
+ ACL, version-listing or DeleteObject permission is needed by the driver. Default bucket SSE-KMS
232
+ encryption also needs the appropriate KMS permissions (including decrypt and data-key generation).
233
+ The optional integration-test cleanup additionally needs `s3:DeleteObject` in its random test prefix.
234
+
235
+ Typical request costs are one PUT for a new key, one HEAD plus one PUT for a replacement/deletion,
236
+ and a failed PUT, HEAD and conditional PUT for recreation over a tombstone. Missing HEAD may add
237
+ a narrow LIST. Listing adds one HEAD per physical object, including retained tombstones. Duraxis
238
+ transactions can write many immutable/index objects; measure latency and request charges for your
239
+ workload. Full objects are buffered in memory, with 72 bytes of physical envelope overhead; this
240
+ driver uses single PUT, not multipart uploads (maximum physical object size 5 GiB). Versioning,
241
+ noncurrent generations, tombstones, KMS and data transfer can add costs.
242
+
243
+ MinIO and other compatible endpoints must be independently verified for all required conditions,
244
+ metadata, pagination and consistency. Passing a fake transport or MinIO test does not establish
245
+ Amazon S3 compatibility. Production bucket policies should prevent other writers from bypassing
246
+ the driver's conditional-write protocol. A correct configuration cannot compensate for a service
247
+ that ignores conditional headers.
248
+
249
+ ## Tests
250
+
251
+ ```bash
252
+ pnpm build
253
+ pnpm exec vitest run --project @duraxis/storage-s3
254
+ ```
255
+
256
+ Default tests make no AWS requests and need no credentials. They reuse the storage conformance
257
+ suite, a fake SDK transport, the actual SDK against a loopback HTTP server, real core/ORM/Nest
258
+ modules, racing manifest publishers, unknown commit outcomes, retained recovery history and GC
259
+ version checks. Loopback tests verify serialized conditional headers and mutation retry behavior.
260
+
261
+ Live tests are disabled by default. To opt in for a dedicated test bucket:
262
+
263
+ ```bash
264
+ DURAXIS_S3_INTEGRATION=1 \
265
+ DURAXIS_S3_TEST_BUCKET=my-dedicated-test-bucket \
266
+ DURAXIS_S3_TEST_REGION=sa-east-1 \
267
+ pnpm exec vitest run --project @duraxis/storage-s3 src/__test__/s3-integration.spec.ts
268
+ ```
269
+
270
+ For a compatible endpoint, additionally set `DURAXIS_S3_TEST_ENDPOINT=http://127.0.0.1:9000` and
271
+ `DURAXIS_S3_TEST_PATH_STYLE=1`. Configure standard AWS credential environment variables or a role;
272
+ no SDK client code is needed. Live conformance tests include 100-way write/CAS races and incur
273
+ requests. Each run creates a random `duraxis-integration/<UUID>/` namespace. Cleanup conditionally
274
+ deletes only that run's current objects. Versioned buckets retain historical versions/delete markers;
275
+ use a dedicated bucket and arrange their cleanup separately. Interrupted tests can leave isolated
276
+ test objects. Never point live tests at an active application's namespace.
277
+
278
+ ## Local architecture reviewed
279
+
280
+ The implementation follows `storage`'s exact interface and errors, `storage-memory`/`storage-disk`
281
+ byte isolation and CAS conventions, and `storage-testkit`'s complete conformance suite. Core's
282
+ `CommitCoordinator` publishes through manifest CAS; `RecoveryManager` follows transaction IDs and
283
+ history; `GarbageCollector` relies on current versions/timestamps and conditional deletion. Nest's
284
+ `DuraxisNestConnection` owns factory-created drivers and optionally closes external ones. None of
285
+ these production implementations are changed.
286
+
287
+ The package follows the local ESM/CommonJS Vite build, strict TypeScript declarations, pnpm
288
+ workspace, Vitest project, package-validation and Changesets conventions. Public declarations only
289
+ reference Duraxis types. The repository has no Turborepo build configuration to extend.
package/dist/index.cjs ADDED
@@ -0,0 +1,361 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_timers_promises = require("node:timers/promises");
3
+ let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
4
+ let _duraxis_storage = require("@duraxis/storage");
5
+ let node_crypto = require("node:crypto");
6
+ // src/s3-storage.options.ts
7
+ function validateOptions(options) {
8
+ const bucket = options?.bucket;
9
+ if (typeof bucket != "string" || bucket.length < 3 || bucket.length > 63 || !bucket.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label)) || /^\d+\.\d+\.\d+\.\d+$/.test(bucket) || /^(xn--|sthree-|amzn-s3-demo-)/.test(bucket) || /(\.mrap|--x-s3|--ol-s3|--table-s3)$/.test(bucket)) throw new TypeError("Invalid S3 general-purpose bucket name");
10
+ const prefix = options.prefix ?? "";
11
+ if (typeof prefix != "string" || prefix.includes("\0") || prefix.length > 0 && prefix.trim().length == 0 || Buffer.from(prefix).toString("utf8") != prefix) throw new TypeError("Invalid S3 namespace prefix");
12
+ const normalized = prefix && !prefix.endsWith("/") ? `${prefix}/` : prefix;
13
+ if (Buffer.byteLength(normalized) > 1023) throw new RangeError("S3 namespace prefix is too long");
14
+ const client = options.client;
15
+ if (client != null && typeof client != "object") throw new TypeError("Invalid S3 client options");
16
+ if (client?.region != null && (typeof client.region != "string" || !/^[a-z0-9-]+$/.test(client.region))) throw new TypeError("Invalid S3 region");
17
+ if (client?.endpoint != null) {
18
+ let endpoint;
19
+ try {
20
+ endpoint = new URL(client.endpoint);
21
+ } catch {
22
+ throw new TypeError("Invalid S3 endpoint");
23
+ }
24
+ if (!["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) throw new TypeError("Invalid S3 endpoint");
25
+ }
26
+ if (client?.forcePathStyle != null && typeof client.forcePathStyle != "boolean") throw new TypeError("Invalid S3 path style option");
27
+ if (client?.maxAttempts != null && (!Number.isSafeInteger(client.maxAttempts) || client.maxAttempts < 1 || client.maxAttempts > 10)) throw new RangeError("S3 read attempts must be between 1 and 10");
28
+ if (client?.credentials != null) {
29
+ for (const value of [client.credentials.accessKeyId, client.credentials.secretAccessKey]) if (typeof value != "string" || value.trim().length == 0) throw new TypeError("Invalid explicit S3 credentials");
30
+ if (client.credentials.sessionToken != null && (typeof client.credentials.sessionToken != "string" || !client.credentials.sessionToken.trim())) throw new TypeError("Invalid explicit S3 session token");
31
+ }
32
+ return normalized;
33
+ }
34
+ // src/s3-object.codec.ts
35
+ var MAGIC = Buffer.from("DRXS3v1\0");
36
+ var HEADER_BYTES = 72;
37
+ function encodeObject(data) {
38
+ const physical = new Uint8Array(HEADER_BYTES + data.byteLength);
39
+ physical.set(MAGIC);
40
+ physical.set((0, node_crypto.randomBytes)(32), 8);
41
+ physical.set((0, node_crypto.createHash)("sha256").update(data).digest(), 40);
42
+ physical.set(data, HEADER_BYTES);
43
+ return physical;
44
+ }
45
+ function decodeObject(physical) {
46
+ if (physical.byteLength < HEADER_BYTES || !MAGIC.equals(physical.subarray(0, 8))) throw new _duraxis_storage.StorageError("Invalid S3 storage object envelope", "CORRUPTION");
47
+ const data = physical.slice(HEADER_BYTES);
48
+ const digest = (0, node_crypto.createHash)("sha256").update(data).digest();
49
+ if (!(0, node_crypto.timingSafeEqual)(digest, physical.subarray(40, HEADER_BYTES))) throw new _duraxis_storage.StorageError("S3 storage object integrity check failed", "CORRUPTION");
50
+ return data;
51
+ }
52
+ function isVersion(version) {
53
+ return typeof version == "string" && /^"[\x21\x23-\x7e]{1,256}"$/.test(version);
54
+ }
55
+ function requireVersion(version) {
56
+ if (!isVersion(version)) throw new _duraxis_storage.StorageError("Missing or invalid S3 ETag", "CORRUPTION");
57
+ return version;
58
+ }
59
+ function objectState(metadata) {
60
+ if (metadata?.["duraxis-format"] != "1" || !["live", "deleted"].includes(metadata["duraxis-state"])) throw new _duraxis_storage.StorageError("Unrecognized S3 object metadata in Duraxis namespace", "CORRUPTION");
61
+ return metadata["duraxis-state"] == "live" ? "live" : "deleted";
62
+ }
63
+ // src/s3-error.mapper.ts
64
+ function field(error, property) {
65
+ return typeof error == "object" && error != null ? Reflect.get(error, property) : void 0;
66
+ }
67
+ function errorName(error) {
68
+ return field(error, "name");
69
+ }
70
+ function statusCode(error) {
71
+ return field(field(error, "$metadata"), "httpStatusCode");
72
+ }
73
+ function isMissingKey(error) {
74
+ return errorName(error) == "NoSuchKey" && statusCode(error) == 404;
75
+ }
76
+ function isConditionalConflict(error) {
77
+ return statusCode(error) == 412 || statusCode(error) == 409 && errorName(error) == "ConditionalRequestConflict" || isMissingKey(error);
78
+ }
79
+ function isRetryableRead(error) {
80
+ if (error instanceof _duraxis_storage.StorageError) return false;
81
+ const status = statusCode(error);
82
+ return typeof status == "number" && [
83
+ 408,
84
+ 429,
85
+ 500,
86
+ 502,
87
+ 503,
88
+ 504
89
+ ].includes(status) || [
90
+ "TimeoutError",
91
+ "RequestTimeout",
92
+ "RequestTimeoutException",
93
+ "SlowDown"
94
+ ].includes(String(errorName(error))) || [
95
+ "ECONNRESET",
96
+ "ECONNREFUSED",
97
+ "EPIPE",
98
+ "ETIMEDOUT",
99
+ "EAI_AGAIN",
100
+ "ENETUNREACH",
101
+ "ERR_STREAM_PREMATURE_CLOSE",
102
+ "UND_ERR_SOCKET"
103
+ ].includes(String(field(error, "code")));
104
+ }
105
+ function mapS3Error(error, mutation = false) {
106
+ if (error instanceof _duraxis_storage.StorageError) return error;
107
+ const status = statusCode(error);
108
+ const name = errorName(error);
109
+ let code;
110
+ if (status == 401 || status == 403 || name == "CredentialsProviderError" || name == "AccessDenied") code = "ACCESS_DENIED";
111
+ else if (status == 429 || name == "SlowDown" || name == "EntityTooLarge") code = "RESOURCE_LIMIT";
112
+ else if (name == "NoSuchBucket") code = "UNAVAILABLE";
113
+ else if (mutation && (status == null || status == 408 || typeof status == "number" && status >= 500 || [
114
+ "TimeoutError",
115
+ "RequestTimeout",
116
+ "RequestTimeoutException",
117
+ "AbortError"
118
+ ].includes(String(name)))) code = "OUTCOME_UNKNOWN";
119
+ else if (status == 408 || [
120
+ "TimeoutError",
121
+ "RequestTimeout",
122
+ "RequestTimeoutException",
123
+ "AbortError"
124
+ ].includes(String(name)) || field(error, "code") == "ETIMEDOUT") code = "TIMEOUT";
125
+ else if (isRetryableRead(error)) code = "UNAVAILABLE";
126
+ else code = "UNKNOWN";
127
+ return new _duraxis_storage.StorageError(`S3 storage operation failed (${code})`, code, { cause: error });
128
+ }
129
+ // src/s3-storage.driver.ts
130
+ var CONFLICT = {
131
+ success: false,
132
+ reason: "conflict"
133
+ };
134
+ var S3StorageDriver = class {
135
+ #client;
136
+ #bucket;
137
+ #prefix;
138
+ #readAttempts;
139
+ #metrics = {
140
+ reads: 0,
141
+ writes: 0,
142
+ deletes: 0,
143
+ lists: 0,
144
+ bytesRead: 0,
145
+ bytesWritten: 0,
146
+ synchronizationWaitMs: 0
147
+ };
148
+ #closing = false;
149
+ #active = 0;
150
+ #drain;
151
+ #closePromise;
152
+ constructor(options) {
153
+ this.#prefix = validateOptions(options);
154
+ this.#bucket = options.bucket;
155
+ this.#readAttempts = options.client?.maxAttempts ?? 3;
156
+ this.#client = new _aws_sdk_client_s3.S3Client({
157
+ ...options.client,
158
+ ...options.client?.credentials ? { credentials: { ...options.client.credentials } } : {},
159
+ maxAttempts: 1
160
+ });
161
+ }
162
+ getMetrics() {
163
+ return { ...this.#metrics };
164
+ }
165
+ get(key) {
166
+ return this.operate(async () => {
167
+ const physicalKey = this.key(key);
168
+ this.#metrics.reads++;
169
+ const result = await this.read(async () => {
170
+ let response;
171
+ try {
172
+ response = await this.#client.send(new _aws_sdk_client_s3.GetObjectCommand({
173
+ Bucket: this.#bucket,
174
+ Key: physicalKey
175
+ }));
176
+ } catch (error) {
177
+ if (isMissingKey(error)) return null;
178
+ throw error;
179
+ }
180
+ try {
181
+ const state = objectState(response.Metadata);
182
+ const version = requireVersion(response.ETag);
183
+ if (!response.Body) throw new _duraxis_storage.StorageError("Missing S3 response body", "CORRUPTION");
184
+ if (response.ContentLength != null && response.ContentLength > 5 * 1024 ** 3) throw new _duraxis_storage.StorageError("S3 object exceeds single-object limit", "RESOURCE_LIMIT");
185
+ const data = decodeObject(await response.Body.transformToByteArray());
186
+ return state == "deleted" ? null : {
187
+ data,
188
+ version
189
+ };
190
+ } finally {
191
+ if (response.Body && "destroy" in response.Body && typeof response.Body.destroy == "function") response.Body.destroy();
192
+ }
193
+ });
194
+ if (result) this.#metrics.bytesRead += result.data.byteLength;
195
+ return result;
196
+ });
197
+ }
198
+ put(key, data, options) {
199
+ return this.operate(async () => {
200
+ const physicalKey = this.key(key);
201
+ if (!(data instanceof Uint8Array)) throw new TypeError("Storage data must be a Uint8Array");
202
+ if (data.byteLength > 5 * 1024 ** 3 - 72) throw new _duraxis_storage.StorageError("S3 object is too large", "RESOURCE_LIMIT");
203
+ this.validateCondition(options?.condition);
204
+ this.#metrics.writes++;
205
+ if (options.condition.type == "if-version" && !isVersion(options.condition.version)) return CONFLICT;
206
+ const logicalBytes = data.byteLength;
207
+ const body = encodeObject(data);
208
+ if (options.condition.type == "if-version" && !await this.matchesLiveVersion(physicalKey, options.condition.version)) return CONFLICT;
209
+ const initial = await this.write(physicalKey, body, "live", options.condition.type == "if-absent" ? void 0 : options.condition.version);
210
+ let result = initial;
211
+ if (!initial.success && options.condition.type == "if-absent") {
212
+ const current = await this.head(physicalKey);
213
+ if (current && objectState(current.Metadata) == "deleted") result = await this.write(physicalKey, body, "live", requireVersion(current.ETag));
214
+ }
215
+ if (result.success) this.#metrics.bytesWritten += logicalBytes;
216
+ return result;
217
+ });
218
+ }
219
+ delete(key, options) {
220
+ return this.operate(async () => {
221
+ const physicalKey = this.key(key);
222
+ this.validateCondition(options?.condition);
223
+ this.#metrics.deletes++;
224
+ if (options.condition.type == "if-absent") {
225
+ const current = await this.head(physicalKey);
226
+ return !current || objectState(current.Metadata) == "deleted" ? { success: true } : CONFLICT;
227
+ }
228
+ if (!isVersion(options.condition.version)) return CONFLICT;
229
+ if (!await this.matchesLiveVersion(physicalKey, options.condition.version)) return CONFLICT;
230
+ const result = await this.write(physicalKey, encodeObject(/* @__PURE__ */ new Uint8Array()), "deleted", options.condition.version);
231
+ return result.success ? { success: true } : result;
232
+ });
233
+ }
234
+ list(prefix) {
235
+ return this.operate(async () => {
236
+ if (typeof prefix != "string" || prefix.includes("\0") || Buffer.from(prefix).toString() != prefix) throw new _duraxis_storage.StorageError("Invalid storage prefix", "INVALID_KEY");
237
+ const physicalPrefix = this.#prefix + prefix;
238
+ if (Buffer.byteLength(physicalPrefix) > 1024) throw new _duraxis_storage.StorageError("Storage prefix is too long", "INVALID_KEY");
239
+ this.#metrics.lists++;
240
+ const objects = /* @__PURE__ */ new Map();
241
+ const tokens = /* @__PURE__ */ new Set();
242
+ let token;
243
+ do {
244
+ const page = await this.read(async () => await this.#client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
245
+ Bucket: this.#bucket,
246
+ Prefix: physicalPrefix,
247
+ ContinuationToken: token
248
+ })));
249
+ const contents = page.Contents ?? [];
250
+ for (let offset = 0; offset < contents.length; offset += 16) {
251
+ const results = await Promise.allSettled(contents.slice(offset, offset + 16).map(async (item) => {
252
+ if (!item.Key?.startsWith(physicalPrefix)) throw new _duraxis_storage.StorageError("Invalid S3 listing key", "CORRUPTION");
253
+ const key = item.Key.slice(this.#prefix.length);
254
+ this.key(key);
255
+ const head = await this.head(item.Key);
256
+ if (!head || objectState(head.Metadata) == "deleted") return;
257
+ const createdAt = head.LastModified?.getTime();
258
+ if (createdAt == null || !Number.isSafeInteger(createdAt) || createdAt < 0) throw new _duraxis_storage.StorageError("Missing or invalid S3 object timestamp", "CORRUPTION");
259
+ objects.set(key, {
260
+ key,
261
+ version: requireVersion(head.ETag),
262
+ createdAt
263
+ });
264
+ }));
265
+ for (const result of results) if (result.status == "rejected") throw result.reason;
266
+ }
267
+ token = page.IsTruncated ? page.NextContinuationToken : void 0;
268
+ if (page.IsTruncated && (!token || tokens.has(token))) throw new _duraxis_storage.StorageError("Invalid S3 pagination token", "CORRUPTION");
269
+ if (token) tokens.add(token);
270
+ } while (token);
271
+ return [...objects.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
272
+ });
273
+ }
274
+ close() {
275
+ if (!this.#closePromise) {
276
+ this.#closing = true;
277
+ this.#closePromise = (async () => {
278
+ if (this.#active > 0) await new Promise((resolve) => {
279
+ this.#drain = resolve;
280
+ });
281
+ this.#client.destroy();
282
+ })();
283
+ }
284
+ return this.#closePromise;
285
+ }
286
+ async operate(callback) {
287
+ if (this.#closing) throw new _duraxis_storage.StorageError("S3 storage driver is closed", "CLOSED");
288
+ this.#active++;
289
+ try {
290
+ return await callback();
291
+ } finally {
292
+ if (--this.#active == 0) this.#drain?.();
293
+ }
294
+ }
295
+ key(key) {
296
+ (0, _duraxis_storage.assertStorageKey)(key);
297
+ const physical = this.#prefix + key;
298
+ if (Buffer.from(key).toString() != key || Buffer.byteLength(physical) > 1024) throw new _duraxis_storage.StorageError("S3 storage key is invalid or too long", "INVALID_KEY");
299
+ return physical;
300
+ }
301
+ validateCondition(condition) {
302
+ if (!condition || !["if-absent", "if-version"].includes(condition.type)) throw new TypeError("A supported storage condition is required");
303
+ }
304
+ async read(callback) {
305
+ for (let attempt = 1;; attempt++) try {
306
+ return await callback();
307
+ } catch (error) {
308
+ if (attempt >= this.#readAttempts || !isRetryableRead(error)) throw mapS3Error(error);
309
+ await (0, node_timers_promises.setTimeout)(Math.floor(Math.random() * Math.min(1e3, 50 * 2 ** (attempt - 1))));
310
+ }
311
+ }
312
+ async head(key) {
313
+ return await this.read(async () => {
314
+ try {
315
+ return await this.#client.send(new _aws_sdk_client_s3.HeadObjectCommand({
316
+ Bucket: this.#bucket,
317
+ Key: key
318
+ }));
319
+ } catch (error) {
320
+ if (isMissingKey(error)) return null;
321
+ if (statusCode(error) != 404 || errorName(error) != "NotFound") throw error;
322
+ if (!(await this.#client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
323
+ Bucket: this.#bucket,
324
+ Prefix: key,
325
+ MaxKeys: 1
326
+ }))).Contents?.some((item) => item.Key == key)) return null;
327
+ throw new _duraxis_storage.StorageError("S3 object changed during metadata lookup", "UNAVAILABLE", { cause: error });
328
+ }
329
+ });
330
+ }
331
+ async matchesLiveVersion(key, version) {
332
+ const current = await this.head(key);
333
+ return current != null && objectState(current.Metadata) == "live" && requireVersion(current.ETag) == version;
334
+ }
335
+ async write(key, body, state, version) {
336
+ try {
337
+ const result = await this.#client.send(new _aws_sdk_client_s3.PutObjectCommand({
338
+ Bucket: this.#bucket,
339
+ Key: key,
340
+ Body: body,
341
+ ContentType: "application/octet-stream",
342
+ Metadata: {
343
+ "duraxis-format": "1",
344
+ "duraxis-state": state
345
+ },
346
+ ...version == null ? { IfNoneMatch: "*" } : { IfMatch: version }
347
+ }));
348
+ if (!isVersion(result.ETag)) throw new _duraxis_storage.StorageError("S3 write outcome lacks a usable ETag", "OUTCOME_UNKNOWN");
349
+ return {
350
+ success: true,
351
+ version: result.ETag
352
+ };
353
+ } catch (error) {
354
+ if (isConditionalConflict(error) && (!isMissingKey(error) || version != null)) return CONFLICT;
355
+ throw mapS3Error(error, true);
356
+ }
357
+ }
358
+ };
359
+ exports.S3StorageDriver = S3StorageDriver;
360
+
361
+ //# sourceMappingURL=index.cjs.map