@duraxis/storage-disk 0.0.0-stage → 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,669 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_crypto = require("node:crypto");
3
+ let node_os = require("node:os");
4
+ let node_path = require("node:path");
5
+ let node_fs_promises = require("node:fs/promises");
6
+ let _duraxis_storage = require("@duraxis/storage");
7
+ // src/disk-format.ts
8
+ var OBJECT_MAGIC = Buffer.from("DXOBJ001", "ascii");
9
+ var MAX_HEADER_BYTES = 16384;
10
+ var encoder = new TextEncoder();
11
+ var decoder = new TextDecoder("utf-8", { fatal: true });
12
+ function sha256(data) {
13
+ return (0, node_crypto.createHash)("sha256").update(data).digest("hex");
14
+ }
15
+ function corruption(message, cause) {
16
+ return new _duraxis_storage.StorageError(message, "CORRUPTION", cause == null ? void 0 : { cause });
17
+ }
18
+ function parseRecord(bytes, label) {
19
+ try {
20
+ const value = JSON.parse(decoder.decode(bytes));
21
+ if (!value || typeof value != "object" || Array.isArray(value)) throw new Error("not an object");
22
+ return value;
23
+ } catch (cause) {
24
+ throw corruption(`Invalid ${label}`, cause);
25
+ }
26
+ }
27
+ function validDigest(value) {
28
+ return typeof value == "string" && /^[0-9a-f]{64}$/.test(value);
29
+ }
30
+ function validateMetadata(value) {
31
+ if (typeof value.version != "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.version) || !Number.isSafeInteger(value.createdAt) || value.createdAt < 0 || !Number.isSafeInteger(value.size) || value.size < 0 || !validDigest(value.digest)) throw corruption("Invalid physical object metadata");
32
+ }
33
+ function encodePhysicalObject(key, metadata, data) {
34
+ const headerPayload = {
35
+ format: 1,
36
+ key,
37
+ version: metadata.version,
38
+ createdAt: metadata.createdAt,
39
+ size: metadata.size,
40
+ digest: metadata.digest
41
+ };
42
+ const canonical = JSON.stringify(headerPayload);
43
+ const header = encoder.encode(JSON.stringify({
44
+ ...headerPayload,
45
+ checksum: sha256(canonical)
46
+ }));
47
+ if (header.byteLength > MAX_HEADER_BYTES) throw new _duraxis_storage.StorageError("Object metadata is too large", "RESOURCE_LIMIT");
48
+ const result = new Uint8Array(OBJECT_MAGIC.length + 4 + header.length + data.length);
49
+ result.set(OBJECT_MAGIC, 0);
50
+ new DataView(result.buffer).setUint32(OBJECT_MAGIC.length, header.length, false);
51
+ result.set(header, OBJECT_MAGIC.length + 4);
52
+ result.set(data, OBJECT_MAGIC.length + 4 + header.length);
53
+ return result;
54
+ }
55
+ function decodePhysicalObject(bytes, expectedKey, expected) {
56
+ if (bytes.byteLength < OBJECT_MAGIC.length + 4 || !Buffer.from(bytes.subarray(0, OBJECT_MAGIC.length)).equals(OBJECT_MAGIC)) throw corruption("Invalid physical object magic");
57
+ const headerLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(OBJECT_MAGIC.length, false);
58
+ if (headerLength == 0 || headerLength > MAX_HEADER_BYTES || OBJECT_MAGIC.length + 4 + headerLength > bytes.byteLength) throw corruption("Invalid physical object header length");
59
+ const header = parseRecord(bytes.subarray(OBJECT_MAGIC.length + 4, OBJECT_MAGIC.length + 4 + headerLength), "physical object header");
60
+ if (Object.keys(header).sort().join(",") != "checksum,createdAt,digest,format,key,size,version" || header.format != 1 || typeof header.key != "string" || typeof header.checksum != "string") throw corruption("Invalid physical object header");
61
+ validateMetadata(header);
62
+ if (sha256(JSON.stringify({
63
+ format: 1,
64
+ key: header.key,
65
+ version: header.version,
66
+ createdAt: header.createdAt,
67
+ size: header.size,
68
+ digest: header.digest
69
+ })) != header.checksum) throw corruption("Physical metadata integrity check failed");
70
+ if (header.key != expectedKey || header.version != expected.version || header.createdAt != expected.createdAt || header.size != expected.size || header.digest != expected.digest) throw corruption("Physical object does not match journal metadata");
71
+ const data = bytes.subarray(OBJECT_MAGIC.length + 4 + headerLength);
72
+ if (data.byteLength != expected.size || sha256(data) != expected.digest) throw corruption("Physical object payload integrity check failed");
73
+ return new Uint8Array(data);
74
+ }
75
+ function encodeJournalFrame(payload) {
76
+ const canonical = JSON.stringify(payload);
77
+ const body = encoder.encode(JSON.stringify({
78
+ ...payload,
79
+ checksum: sha256(canonical)
80
+ }));
81
+ if (body.byteLength > 65536) throw new _duraxis_storage.StorageError("Journal frame is too large", "RESOURCE_LIMIT");
82
+ const result = new Uint8Array(4 + body.byteLength);
83
+ new DataView(result.buffer).setUint32(0, body.byteLength, false);
84
+ result.set(body, 4);
85
+ return result;
86
+ }
87
+ function decodeFrame(bytes, expectedSequence) {
88
+ const record = parseRecord(bytes, "storage journal frame");
89
+ if (record.format != 1 || record.sequence != expectedSequence || record.op != "put" && record.op != "delete" || typeof record.key != "string" || typeof record.checksum != "string") throw corruption("Invalid storage journal frame");
90
+ let payload;
91
+ if (record.op == "put") {
92
+ if (Object.keys(record).sort().join(",") != "checksum,createdAt,digest,format,key,op,sequence,size,version") throw corruption("Invalid put journal frame layout");
93
+ validateMetadata(record);
94
+ payload = {
95
+ format: 1,
96
+ sequence: expectedSequence,
97
+ op: "put",
98
+ key: record.key,
99
+ version: record.version,
100
+ createdAt: record.createdAt,
101
+ size: record.size,
102
+ digest: record.digest
103
+ };
104
+ } else {
105
+ if (Object.keys(record).sort().join(",") != "checksum,format,key,op,sequence") throw corruption("Invalid delete journal frame layout");
106
+ payload = {
107
+ format: 1,
108
+ sequence: expectedSequence,
109
+ op: "delete",
110
+ key: record.key
111
+ };
112
+ }
113
+ if (sha256(JSON.stringify(payload)) != record.checksum) throw corruption("Storage journal integrity check failed");
114
+ return payload;
115
+ }
116
+ function decodeJournal(bytes) {
117
+ const frames = [];
118
+ let offset = 0;
119
+ let sequence = 1;
120
+ while (offset < bytes.byteLength) {
121
+ if (bytes.byteLength - offset < 4) return {
122
+ frames,
123
+ validBytes: offset,
124
+ incompleteTail: true
125
+ };
126
+ const length = new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(0, false);
127
+ if (length == 0 || length > 65536) throw corruption("Invalid storage journal frame length");
128
+ if (bytes.byteLength - offset - 4 < length) return {
129
+ frames,
130
+ validBytes: offset,
131
+ incompleteTail: true
132
+ };
133
+ frames.push(decodeFrame(bytes.subarray(offset + 4, offset + 4 + length), sequence++));
134
+ offset += 4 + length;
135
+ }
136
+ return {
137
+ frames,
138
+ validBytes: offset,
139
+ incompleteTail: false
140
+ };
141
+ }
142
+ // src/async-disk-storage.driver.ts
143
+ var LOCK_FILE = ".duraxis-owner.lock";
144
+ var JOURNAL_FILE = "journal.log";
145
+ var PREVIOUS_JOURNAL = "journal.previous";
146
+ var NEXT_JOURNAL = "journal.next";
147
+ var OBJECTS_DIRECTORY = "objects";
148
+ var OWNERSHIP_CONFIRMATION = "I_HAVE_VERIFIED_EXCLUSIVE_ACCESS";
149
+ function nodeErrorCode(error) {
150
+ return error && typeof error == "object" && "code" in error ? String(error.code) : void 0;
151
+ }
152
+ async function exists(path) {
153
+ try {
154
+ await (0, node_fs_promises.stat)(path);
155
+ return true;
156
+ } catch (error) {
157
+ if (nodeErrorCode(error) == "ENOENT") return false;
158
+ throw error;
159
+ }
160
+ }
161
+ async function writeAll(handle, bytes, position = 0) {
162
+ let offset = 0;
163
+ while (offset < bytes.byteLength) {
164
+ const result = await handle.write(bytes, offset, bytes.byteLength - offset, position + offset);
165
+ if (result.bytesWritten <= 0) throw new _duraxis_storage.StorageError("Disk write made no progress", "UNAVAILABLE");
166
+ offset += result.bytesWritten;
167
+ }
168
+ }
169
+ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
170
+ root;
171
+ registryKey;
172
+ options;
173
+ static activeDirectories = /* @__PURE__ */ new Set();
174
+ entries = /* @__PURE__ */ new Map();
175
+ ownerId = (0, node_crypto.randomUUID)();
176
+ metrics = {
177
+ reads: 0,
178
+ writes: 0,
179
+ deletes: 0,
180
+ lists: 0,
181
+ bytesRead: 0,
182
+ bytesWritten: 0,
183
+ synchronizationWaitMs: 0
184
+ };
185
+ operationTail = Promise.resolve();
186
+ journal;
187
+ lockHandle;
188
+ journalBytes = 0;
189
+ sequence = 0;
190
+ directorySync = true;
191
+ closed = false;
192
+ closing = false;
193
+ poisoned = false;
194
+ constructor(root, registryKey, options) {
195
+ this.root = root;
196
+ this.registryKey = registryKey;
197
+ this.options = options;
198
+ }
199
+ static async open(options) {
200
+ if (!options || typeof options.directory != "string" || options.directory.trim() == "") throw new TypeError("A storage directory is required");
201
+ const maxKeyBytes = options.maxKeyBytes ?? 4096;
202
+ const maxObjectBytes = options.maxObjectBytes ?? 268435456;
203
+ const maxJournalBytes = options.maxJournalBytes ?? 1073741824;
204
+ if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes < 64 || maxKeyBytes > 65536) throw new RangeError("Invalid maximum storage key size");
205
+ if (!Number.isSafeInteger(maxObjectBytes) || maxObjectBytes < 0 || maxObjectBytes > 1073741824) throw new RangeError("Invalid maximum object size");
206
+ if (!Number.isSafeInteger(maxJournalBytes) || maxJournalBytes < 1048576) throw new RangeError("Invalid maximum journal size");
207
+ const requested = (0, node_path.resolve)(options.directory);
208
+ await (0, node_fs_promises.mkdir)(requested, { recursive: true });
209
+ const root = await (0, node_fs_promises.realpath)(requested);
210
+ const registryKey = process.platform == "win32" ? root.toLocaleLowerCase("en-US") : root;
211
+ if (this.activeDirectories.has(registryKey)) throw new _duraxis_storage.StorageError("Storage directory is already owned by this process", "OWNERSHIP_CONFLICT");
212
+ this.activeDirectories.add(registryKey);
213
+ const driver = new AsyncDiskStorageDriver(root, registryKey, {
214
+ ...options,
215
+ directory: root,
216
+ maxKeyBytes,
217
+ maxObjectBytes,
218
+ maxJournalBytes
219
+ });
220
+ try {
221
+ await driver.initialize();
222
+ return driver;
223
+ } catch (error) {
224
+ this.activeDirectories.delete(registryKey);
225
+ await driver.cleanupFailedOpen();
226
+ throw error;
227
+ }
228
+ }
229
+ static async recoverAbandonedOwnership(options) {
230
+ if (options.confirmation != OWNERSHIP_CONFIRMATION) throw new _duraxis_storage.StorageError("Explicit exclusive-access confirmation is required", "ACCESS_DENIED");
231
+ const root = await (0, node_fs_promises.realpath)((0, node_path.resolve)(options.directory));
232
+ const registryKey = process.platform == "win32" ? root.toLocaleLowerCase("en-US") : root;
233
+ if (this.activeDirectories.has(registryKey)) throw new _duraxis_storage.StorageError("Cannot recover ownership held by this process", "OWNERSHIP_CONFLICT");
234
+ try {
235
+ await (0, node_fs_promises.unlink)((0, node_path.join)(root, LOCK_FILE));
236
+ } catch (error) {
237
+ if (nodeErrorCode(error) != "ENOENT") throw error;
238
+ }
239
+ try {
240
+ await this.syncDirectoryStatic(root);
241
+ } catch (error) {
242
+ if (![
243
+ "EINVAL",
244
+ "ENOTSUP",
245
+ "EBADF",
246
+ "EISDIR",
247
+ "EPERM"
248
+ ].includes(nodeErrorCode(error) ?? "")) throw error;
249
+ }
250
+ }
251
+ get durability() {
252
+ return {
253
+ fileDataSync: true,
254
+ directoryEntrySync: this.directorySync,
255
+ ownership: "exclusive-directory",
256
+ processCrashRecovery: true,
257
+ powerLossGuarantee: this.directorySync ? "file-and-directory-sync" : "file-sync-only"
258
+ };
259
+ }
260
+ getMetrics() {
261
+ return { ...this.metrics };
262
+ }
263
+ async initialize() {
264
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(this.root, OBJECTS_DIRECTORY), { recursive: true });
265
+ const lockPath = (0, node_path.join)(this.root, LOCK_FILE);
266
+ try {
267
+ this.lockHandle = await (0, node_fs_promises.open)(lockPath, "wx", 384);
268
+ } catch (error) {
269
+ if (nodeErrorCode(error) == "EEXIST") throw new _duraxis_storage.StorageError("Storage directory has an owner lock; close the owner or perform explicit abandoned-lock recovery", "OWNERSHIP_CONFLICT", { cause: error });
270
+ throw error;
271
+ }
272
+ const lockPayload = {
273
+ format: 1,
274
+ ownerId: this.ownerId,
275
+ pid: process.pid,
276
+ hostname: (0, node_os.hostname)(),
277
+ createdAt: Date.now()
278
+ };
279
+ const canonical = JSON.stringify(lockPayload);
280
+ await writeAll(this.lockHandle, new TextEncoder().encode(JSON.stringify({
281
+ ...lockPayload,
282
+ checksum: sha256(canonical)
283
+ })));
284
+ await this.lockHandle.sync();
285
+ await this.syncDirectory(this.root);
286
+ await this.recoverJournalRotation();
287
+ const journalPath = (0, node_path.join)(this.root, JOURNAL_FILE);
288
+ if (!await exists(journalPath)) {
289
+ const created = await (0, node_fs_promises.open)(journalPath, "wx", 384);
290
+ await created.sync();
291
+ await created.close();
292
+ await this.syncDirectory(this.root);
293
+ }
294
+ const bytes = await (0, node_fs_promises.readFile)(journalPath);
295
+ if (bytes.byteLength > this.options.maxJournalBytes) throw new _duraxis_storage.StorageError("Storage journal exceeds configured limit", "RESOURCE_LIMIT");
296
+ const decoded = decodeJournal(bytes);
297
+ for (const frame of decoded.frames) {
298
+ this.validateKey(frame.key);
299
+ this.sequence = frame.sequence;
300
+ if (frame.op == "put") this.entries.set(frame.key, {
301
+ version: frame.version,
302
+ createdAt: frame.createdAt,
303
+ size: frame.size,
304
+ digest: frame.digest
305
+ });
306
+ else this.entries.delete(frame.key);
307
+ }
308
+ if (decoded.incompleteTail) {
309
+ await (0, node_fs_promises.truncate)(journalPath, decoded.validBytes);
310
+ const repaired = await (0, node_fs_promises.open)(journalPath, "r+");
311
+ await repaired.sync();
312
+ await repaired.close();
313
+ }
314
+ this.journalBytes = decoded.validBytes;
315
+ this.journal = await (0, node_fs_promises.open)(journalPath, "r+");
316
+ await this.assertCurrentObjectsExist();
317
+ await this.cleanupPhysicalObjects();
318
+ }
319
+ validateKey(key) {
320
+ (0, _duraxis_storage.assertStorageKey)(key);
321
+ if (Buffer.byteLength(key, "utf8") > this.options.maxKeyBytes) throw new _duraxis_storage.StorageError("Storage key exceeds configured byte limit", "INVALID_KEY");
322
+ }
323
+ assertUsable() {
324
+ if (this.closed || this.closing) throw new _duraxis_storage.StorageError("Storage driver is closed", "CLOSED");
325
+ if (this.poisoned) throw new _duraxis_storage.StorageError("Storage outcome is unknown; close and reopen before continuing", "OUTCOME_UNKNOWN");
326
+ }
327
+ async exclusive(operation) {
328
+ this.assertUsable();
329
+ const before = performance.now();
330
+ const previous = this.operationTail;
331
+ let release;
332
+ this.operationTail = new Promise((resolve) => {
333
+ release = resolve;
334
+ });
335
+ await previous;
336
+ this.metrics.synchronizationWaitMs += performance.now() - before;
337
+ try {
338
+ this.assertUsable();
339
+ return await operation();
340
+ } finally {
341
+ release();
342
+ }
343
+ }
344
+ get(key) {
345
+ return this.exclusive(async () => {
346
+ this.validateKey(key);
347
+ this.metrics.reads++;
348
+ const metadata = this.entries.get(key);
349
+ if (!metadata) return null;
350
+ const path = this.objectPath(key, metadata.version);
351
+ let info;
352
+ try {
353
+ info = await (0, node_fs_promises.stat)(path);
354
+ } catch (error) {
355
+ if (nodeErrorCode(error) == "ENOENT") throw new _duraxis_storage.StorageError(`Missing physical object for key ${key}`, "CORRUPTION", { cause: error });
356
+ throw error;
357
+ }
358
+ if (info.size > this.options.maxObjectBytes + 32768) throw new _duraxis_storage.StorageError("Physical object exceeds configured size", "CORRUPTION");
359
+ const physical = await (0, node_fs_promises.readFile)(path);
360
+ this.metrics.bytesRead += physical.byteLength;
361
+ return {
362
+ data: decodePhysicalObject(physical, key, metadata),
363
+ version: metadata.version
364
+ };
365
+ });
366
+ }
367
+ put(key, data, options) {
368
+ return this.exclusive(async () => {
369
+ this.validateKey(key);
370
+ if (!(data instanceof Uint8Array)) throw new TypeError("Storage data must be a Uint8Array");
371
+ if (data.byteLength > this.options.maxObjectBytes) throw new _duraxis_storage.StorageError("Storage object exceeds configured byte limit", "RESOURCE_LIMIT");
372
+ const current = this.entries.get(key);
373
+ if (options.condition.type == "if-absent" ? current != null : current == null || current.version != options.condition.version) return {
374
+ success: false,
375
+ reason: "conflict"
376
+ };
377
+ this.metrics.writes++;
378
+ const metadata = {
379
+ version: (0, node_crypto.randomUUID)(),
380
+ createdAt: Date.now(),
381
+ size: data.byteLength,
382
+ digest: sha256(data)
383
+ };
384
+ const physical = encodePhysicalObject(key, metadata, data);
385
+ const finalPath = this.objectPath(key, metadata.version);
386
+ const parent = (0, node_path.dirname)(finalPath);
387
+ await (0, node_fs_promises.mkdir)(parent, { recursive: true });
388
+ const temporary = (0, node_path.join)(parent, `.${metadata.version}.${(0, node_crypto.randomUUID)()}.tmp`);
389
+ let published = false;
390
+ try {
391
+ const handle = await (0, node_fs_promises.open)(temporary, "wx", 384);
392
+ try {
393
+ await writeAll(handle, physical);
394
+ await handle.sync();
395
+ } finally {
396
+ await handle.close();
397
+ }
398
+ await this.fault("after-object-sync", {
399
+ operation: "put",
400
+ key
401
+ });
402
+ await (0, node_fs_promises.rename)(temporary, finalPath);
403
+ published = true;
404
+ await this.fault("after-object-publish", {
405
+ operation: "put",
406
+ key
407
+ });
408
+ await this.syncDirectory(parent);
409
+ await this.fault("after-object-directory-sync", {
410
+ operation: "put",
411
+ key
412
+ });
413
+ const frame = {
414
+ format: 1,
415
+ sequence: this.sequence + 1,
416
+ op: "put",
417
+ key,
418
+ version: metadata.version,
419
+ createdAt: metadata.createdAt,
420
+ size: metadata.size,
421
+ digest: metadata.digest
422
+ };
423
+ await this.append(frame);
424
+ this.entries.set(key, metadata);
425
+ this.sequence = frame.sequence;
426
+ this.metrics.bytesWritten += physical.byteLength;
427
+ if (current) await this.removeObsolete(this.objectPath(key, current.version));
428
+ return {
429
+ success: true,
430
+ version: metadata.version
431
+ };
432
+ } catch (error) {
433
+ if (!published) await this.removeObsolete(temporary);
434
+ throw error;
435
+ }
436
+ });
437
+ }
438
+ delete(key, options) {
439
+ return this.exclusive(async () => {
440
+ this.validateKey(key);
441
+ const current = this.entries.get(key);
442
+ if (options.condition.type == "if-absent") return current ? {
443
+ success: false,
444
+ reason: "conflict"
445
+ } : { success: true };
446
+ if (!current || current.version != options.condition.version) return {
447
+ success: false,
448
+ reason: "conflict"
449
+ };
450
+ this.metrics.deletes++;
451
+ const frame = {
452
+ format: 1,
453
+ sequence: this.sequence + 1,
454
+ op: "delete",
455
+ key
456
+ };
457
+ await this.append(frame);
458
+ this.entries.delete(key);
459
+ this.sequence = frame.sequence;
460
+ await this.removeObsolete(this.objectPath(key, current.version));
461
+ return { success: true };
462
+ });
463
+ }
464
+ list(prefix) {
465
+ return this.exclusive(async () => {
466
+ if (typeof prefix != "string" || prefix.includes("\0") || Buffer.byteLength(prefix, "utf8") > this.options.maxKeyBytes) throw new _duraxis_storage.StorageError("Invalid storage prefix", "INVALID_KEY");
467
+ this.metrics.lists++;
468
+ return [...this.entries].filter(([key]) => key.startsWith(prefix)).map(([key, value]) => ({
469
+ key,
470
+ version: value.version,
471
+ createdAt: value.createdAt
472
+ })).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
473
+ });
474
+ }
475
+ async append(frame) {
476
+ const encoded = encodeJournalFrame(frame);
477
+ if (this.journalBytes + encoded.byteLength > this.options.maxJournalBytes) throw new _duraxis_storage.StorageError("Storage journal limit reached; compact before writing", "RESOURCE_LIMIT");
478
+ try {
479
+ await writeAll(this.journal, encoded, this.journalBytes);
480
+ await this.fault("after-journal-write", {
481
+ operation: frame.op,
482
+ key: frame.key
483
+ });
484
+ await this.journal.sync();
485
+ await this.fault("after-journal-sync", {
486
+ operation: frame.op,
487
+ key: frame.key
488
+ });
489
+ this.journalBytes += encoded.byteLength;
490
+ this.metrics.bytesWritten += encoded.byteLength;
491
+ } catch (cause) {
492
+ this.poisoned = true;
493
+ throw new _duraxis_storage.StorageError("Storage publication outcome is unknown", "OUTCOME_UNKNOWN", { cause });
494
+ }
495
+ }
496
+ compact() {
497
+ return this.exclusive(async () => {
498
+ try {
499
+ const nextPath = (0, node_path.join)(this.root, NEXT_JOURNAL);
500
+ const previousPath = (0, node_path.join)(this.root, PREVIOUS_JOURNAL);
501
+ const currentPath = (0, node_path.join)(this.root, JOURNAL_FILE);
502
+ await this.removeObsolete(nextPath);
503
+ await this.removeObsolete(previousPath);
504
+ const next = await (0, node_fs_promises.open)(nextPath, "wx", 384);
505
+ let offset = 0;
506
+ let sequence = 0;
507
+ try {
508
+ for (const [key, metadata] of [...this.entries].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
509
+ const bytes = encodeJournalFrame({
510
+ format: 1,
511
+ sequence: ++sequence,
512
+ op: "put",
513
+ key,
514
+ version: metadata.version,
515
+ createdAt: metadata.createdAt,
516
+ size: metadata.size,
517
+ digest: metadata.digest
518
+ });
519
+ await writeAll(next, bytes, offset);
520
+ offset += bytes.byteLength;
521
+ }
522
+ await next.sync();
523
+ } finally {
524
+ await next.close();
525
+ }
526
+ await this.journal.close();
527
+ await (0, node_fs_promises.rename)(currentPath, previousPath);
528
+ await (0, node_fs_promises.rename)(nextPath, currentPath);
529
+ await this.syncDirectory(this.root);
530
+ await this.fault("after-journal-rotation", { operation: "compact" });
531
+ this.journal = await (0, node_fs_promises.open)(currentPath, "r+");
532
+ this.journalBytes = offset;
533
+ this.sequence = sequence;
534
+ await this.removeObsolete(previousPath);
535
+ } catch (cause) {
536
+ this.poisoned = true;
537
+ throw new _duraxis_storage.StorageError("Journal compaction outcome is unknown", "OUTCOME_UNKNOWN", { cause });
538
+ }
539
+ });
540
+ }
541
+ async close() {
542
+ if (this.closed || this.closing) return;
543
+ this.closing = true;
544
+ await this.operationTail;
545
+ let failure;
546
+ try {
547
+ if (this.journal) await this.journal.close();
548
+ if (this.lockHandle) await this.lockHandle.close();
549
+ const lockPath = (0, node_path.join)(this.root, LOCK_FILE);
550
+ const lock = JSON.parse(await (0, node_fs_promises.readFile)(lockPath, "utf8"));
551
+ const canonical = JSON.stringify({
552
+ format: lock.format,
553
+ ownerId: lock.ownerId,
554
+ pid: lock.pid,
555
+ hostname: lock.hostname,
556
+ createdAt: lock.createdAt
557
+ });
558
+ if (Object.keys(lock).sort().join(",") != "checksum,createdAt,format,hostname,ownerId,pid" || lock.format != 1 || lock.ownerId != this.ownerId || lock.checksum != sha256(canonical)) throw new _duraxis_storage.StorageError("Storage ownership changed unexpectedly", "OWNERSHIP_CONFLICT");
559
+ await (0, node_fs_promises.unlink)(lockPath);
560
+ await this.syncDirectory(this.root);
561
+ } catch (error) {
562
+ failure = error;
563
+ } finally {
564
+ this.closed = true;
565
+ this.closing = false;
566
+ AsyncDiskStorageDriver.activeDirectories.delete(this.registryKey);
567
+ }
568
+ if (failure) throw failure;
569
+ }
570
+ objectPath(key, version) {
571
+ const hash = sha256(new TextEncoder().encode(key));
572
+ return (0, node_path.join)(this.root, OBJECTS_DIRECTORY, hash.slice(0, 2), hash, `${version}.obj`);
573
+ }
574
+ async assertCurrentObjectsExist() {
575
+ for (const [key, metadata] of this.entries) try {
576
+ await (0, node_fs_promises.stat)(this.objectPath(key, metadata.version));
577
+ } catch (error) {
578
+ if (nodeErrorCode(error) == "ENOENT") throw new _duraxis_storage.StorageError(`Journal references a missing object: ${key}`, "CORRUPTION", { cause: error });
579
+ throw error;
580
+ }
581
+ }
582
+ async cleanupPhysicalObjects() {
583
+ const referenced = new Set([...this.entries].map(([key, metadata]) => this.objectPath(key, metadata.version)));
584
+ const walk = async (directory) => {
585
+ let items;
586
+ try {
587
+ items = await (0, node_fs_promises.readdir)(directory, { withFileTypes: true });
588
+ } catch (error) {
589
+ if (nodeErrorCode(error) == "ENOENT") return;
590
+ throw error;
591
+ }
592
+ for (const item of items) {
593
+ const path = (0, node_path.join)(directory, item.name);
594
+ if (item.isDirectory()) await walk(path);
595
+ else if (item.isFile() && (item.name.endsWith(".tmp") || item.name.endsWith(".obj") && !referenced.has(path))) await this.removeObsolete(path);
596
+ }
597
+ };
598
+ await walk((0, node_path.join)(this.root, OBJECTS_DIRECTORY));
599
+ }
600
+ async recoverJournalRotation() {
601
+ const current = (0, node_path.join)(this.root, JOURNAL_FILE);
602
+ const previous = (0, node_path.join)(this.root, PREVIOUS_JOURNAL);
603
+ const next = (0, node_path.join)(this.root, NEXT_JOURNAL);
604
+ const hasCurrent = await exists(current);
605
+ const hasPrevious = await exists(previous);
606
+ const hasNext = await exists(next);
607
+ if (!hasCurrent) {
608
+ if (hasNext) await (0, node_fs_promises.rename)(next, current);
609
+ else if (hasPrevious) await (0, node_fs_promises.rename)(previous, current);
610
+ } else if (hasPrevious) try {
611
+ decodeJournal(await (0, node_fs_promises.readFile)(current));
612
+ await this.removeObsolete(previous);
613
+ } catch {
614
+ await this.removeObsolete(current);
615
+ await (0, node_fs_promises.rename)(previous, current);
616
+ }
617
+ if (await exists(current) && await exists(next)) await this.removeObsolete(next);
618
+ if (await exists(current) && await exists(previous)) await this.removeObsolete(previous);
619
+ await this.syncDirectory(this.root);
620
+ }
621
+ async fault(point, context) {
622
+ await this.options.faultInjector?.(point, context);
623
+ }
624
+ async removeObsolete(path) {
625
+ try {
626
+ await (0, node_fs_promises.rm)(path, { force: true });
627
+ } catch {}
628
+ }
629
+ async syncDirectory(directory) {
630
+ if (!this.directorySync) return;
631
+ try {
632
+ await AsyncDiskStorageDriver.syncDirectoryStatic(directory);
633
+ } catch (error) {
634
+ if ([
635
+ "EINVAL",
636
+ "ENOTSUP",
637
+ "EBADF",
638
+ "EISDIR",
639
+ "EPERM"
640
+ ].includes(nodeErrorCode(error) ?? "")) this.directorySync = false;
641
+ else throw error;
642
+ }
643
+ }
644
+ static async syncDirectoryStatic(directory) {
645
+ const handle = await (0, node_fs_promises.open)(directory, "r");
646
+ try {
647
+ await handle.sync();
648
+ } finally {
649
+ await handle.close();
650
+ }
651
+ }
652
+ async cleanupFailedOpen() {
653
+ try {
654
+ if (this.journal) await this.journal.close();
655
+ } catch {}
656
+ try {
657
+ if (this.lockHandle) await this.lockHandle.close();
658
+ } catch {}
659
+ try {
660
+ const lockPath = (0, node_path.join)(this.root, LOCK_FILE);
661
+ if (await exists(lockPath)) {
662
+ if (JSON.parse(await (0, node_fs_promises.readFile)(lockPath, "utf8")).ownerId == this.ownerId) await (0, node_fs_promises.unlink)(lockPath);
663
+ }
664
+ } catch {}
665
+ }
666
+ };
667
+ exports.AsyncDiskStorageDriver = AsyncDiskStorageDriver;
668
+
669
+ //# sourceMappingURL=index.cjs.map