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