@duraxis/storage-disk 0.1.0 → 0.1.3

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 CHANGED
@@ -1,9 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let node_crypto = require("node:crypto");
3
- let node_os = require("node:os");
4
3
  let node_path = require("node:path");
5
4
  let node_fs_promises = require("node:fs/promises");
6
5
  let _duraxis_storage = require("@duraxis/storage");
6
+ let node_os = require("node:os");
7
7
  // src/disk-format.ts
8
8
  var OBJECT_MAGIC = Buffer.from("DXOBJ001", "ascii");
9
9
  var MAX_HEADER_BYTES = 16384;
@@ -15,7 +15,7 @@ function sha256(data) {
15
15
  function corruption(message, cause) {
16
16
  return new _duraxis_storage.StorageError(message, "CORRUPTION", cause == null ? void 0 : { cause });
17
17
  }
18
- function parseRecord(bytes, label) {
18
+ function parseRecord$1(bytes, label) {
19
19
  try {
20
20
  const value = JSON.parse(decoder.decode(bytes));
21
21
  if (!value || typeof value != "object" || Array.isArray(value)) throw new Error("not an object");
@@ -56,7 +56,7 @@ function decodePhysicalObject(bytes, expectedKey, expected) {
56
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
57
  const headerLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(OBJECT_MAGIC.length, false);
58
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");
59
+ const header = parseRecord$1(bytes.subarray(OBJECT_MAGIC.length + 4, OBJECT_MAGIC.length + 4 + headerLength), "physical object header");
60
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
61
  validateMetadata(header);
62
62
  if (sha256(JSON.stringify({
@@ -85,7 +85,7 @@ function encodeJournalFrame(payload) {
85
85
  return result;
86
86
  }
87
87
  function decodeFrame(bytes, expectedSequence) {
88
- const record = parseRecord(bytes, "storage journal frame");
88
+ const record = parseRecord$1(bytes, "storage journal frame");
89
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
90
  let payload;
91
91
  if (record.op == "put") {
@@ -139,13 +139,417 @@ function decodeJournal(bytes) {
139
139
  incompleteTail: false
140
140
  };
141
141
  }
142
- // src/async-disk-storage.driver.ts
142
+ // src/ownership.ts
143
143
  var LOCK_FILE = ".duraxis-owner.lock";
144
+ var RECOVERY_GUARD_FILE = ".duraxis-owner.recovery";
145
+ var OWNERSHIP_CONFIRMATION = "I_HAVE_VERIFIED_EXCLUSIVE_ACCESS";
146
+ var OWNER_FIELDS = "applicationId,checksum,createdAt,format,hostname,ownerId,pid,processIdentity";
147
+ var GUARD_FIELDS = "checksum,createdAt,format,guardId,hostname,pid";
148
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
149
+ var APPLICATION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._:/-]{0,126}[A-Za-z0-9])?$/;
150
+ var PROCESS_IDENTITY_PATTERN = /^(?:linux:(?:pid:\[\d+\]|unavailable)|[a-z0-9]+:unverified)$/;
151
+ var MAX_METADATA_BYTES = 4096;
152
+ var LINUX_LOCAL_FILESYSTEMS = /* @__PURE__ */ new Set([
153
+ 61267,
154
+ 16914836,
155
+ 801189825,
156
+ 1481003842,
157
+ 2035054128,
158
+ 2240043254,
159
+ 2435016766
160
+ ]);
161
+ function errorCode(error) {
162
+ return error && typeof error == "object" && "code" in error ? String(error.code) : void 0;
163
+ }
164
+ function ownershipConflict(message, cause) {
165
+ return new _duraxis_storage.StorageError(message, "OWNERSHIP_CONFLICT", cause == null ? void 0 : { cause });
166
+ }
167
+ function canonicalOwner(payload) {
168
+ return JSON.stringify(payload);
169
+ }
170
+ function canonicalGuard(payload) {
171
+ return JSON.stringify(payload);
172
+ }
173
+ function validHostname(value) {
174
+ return typeof value == "string" && value.length > 0 && value.length <= 255 && !/[\0-\x1f\x7f]/.test(value);
175
+ }
176
+ function sameIdentity(left, right) {
177
+ return left.dev == right.dev && left.ino == right.ino;
178
+ }
179
+ async function writeAll$1(handle, bytes) {
180
+ let offset = 0;
181
+ while (offset < bytes.byteLength) {
182
+ const result = await handle.write(bytes, offset, bytes.byteLength - offset, offset);
183
+ if (result.bytesWritten <= 0) throw new _duraxis_storage.StorageError("Ownership metadata write made no progress", "UNAVAILABLE");
184
+ offset += result.bytesWritten;
185
+ }
186
+ }
187
+ async function syncDirectory(directory) {
188
+ let handle;
189
+ try {
190
+ handle = await (0, node_fs_promises.open)(directory, "r");
191
+ await handle.sync();
192
+ } catch (error) {
193
+ if (![
194
+ "EINVAL",
195
+ "ENOTSUP",
196
+ "EBADF",
197
+ "EISDIR",
198
+ "EPERM"
199
+ ].includes(errorCode(error) ?? "")) throw error;
200
+ } finally {
201
+ await handle?.close();
202
+ }
203
+ }
204
+ async function observe(path) {
205
+ let handle;
206
+ try {
207
+ handle = await (0, node_fs_promises.open)(path, "r");
208
+ } catch (error) {
209
+ if (errorCode(error) == "ENOENT") return null;
210
+ throw error;
211
+ }
212
+ try {
213
+ const identity = await handle.stat();
214
+ const bytes = await handle.readFile();
215
+ return {
216
+ path,
217
+ handle,
218
+ identity,
219
+ bytes
220
+ };
221
+ } catch (error) {
222
+ await handle.close().catch(() => void 0);
223
+ throw error;
224
+ }
225
+ }
226
+ async function assertObservedUnchanged(observed) {
227
+ let currentIdentity;
228
+ let currentBytes;
229
+ try {
230
+ [currentIdentity, currentBytes] = await Promise.all([(0, node_fs_promises.stat)(observed.path), (0, node_fs_promises.readFile)(observed.path)]);
231
+ } catch (cause) {
232
+ throw ownershipConflict("Ownership metadata changed during inspection", cause);
233
+ }
234
+ if (!sameIdentity(observed.identity, currentIdentity) || !observed.bytes.equals(currentBytes)) throw ownershipConflict("Ownership metadata changed during inspection");
235
+ }
236
+ async function removeObserved(observed) {
237
+ try {
238
+ await assertObservedUnchanged(observed);
239
+ } finally {
240
+ await observed.handle.close();
241
+ }
242
+ try {
243
+ await (0, node_fs_promises.unlink)(observed.path);
244
+ } catch (cause) {
245
+ throw ownershipConflict("Failed to remove the observed ownership lock", cause);
246
+ }
247
+ }
248
+ async function removeCreatedFile(path, handle, identity) {
249
+ await handle.close().catch(() => void 0);
250
+ try {
251
+ if (!sameIdentity(identity, await (0, node_fs_promises.stat)(path))) throw ownershipConflict("Created ownership file was replaced unexpectedly");
252
+ await (0, node_fs_promises.unlink)(path);
253
+ } catch (error) {
254
+ if (errorCode(error) != "ENOENT") throw error;
255
+ }
256
+ }
257
+ function parseRecord(bytes, label) {
258
+ if (bytes.byteLength == 0 || bytes.byteLength > MAX_METADATA_BYTES) throw ownershipConflict(`Invalid ${label}`);
259
+ try {
260
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
261
+ if (!value || typeof value != "object" || Array.isArray(value)) throw new Error("not an object");
262
+ return value;
263
+ } catch (cause) {
264
+ throw ownershipConflict(`Invalid ${label}`, cause);
265
+ }
266
+ }
267
+ function parseOwner(bytes) {
268
+ const record = parseRecord(bytes, "owner lock metadata");
269
+ if (record.format != 2) throw ownershipConflict("Owner lock format is incompatible with automatic recovery; use explicit manual recovery");
270
+ if (Object.keys(record).sort().join(",") != OWNER_FIELDS || !UUID_PATTERN.test(String(record.ownerId)) || !Number.isSafeInteger(record.pid) || record.pid <= 0 || !validHostname(record.hostname) || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0 || record.applicationId !== null && (typeof record.applicationId != "string" || !APPLICATION_ID_PATTERN.test(record.applicationId)) || typeof record.processIdentity != "string" || !PROCESS_IDENTITY_PATTERN.test(record.processIdentity) || typeof record.checksum != "string" || !/^[0-9a-f]{64}$/.test(record.checksum)) throw ownershipConflict("Invalid owner lock metadata");
271
+ const payload = {
272
+ format: 2,
273
+ ownerId: record.ownerId,
274
+ pid: record.pid,
275
+ hostname: record.hostname,
276
+ createdAt: record.createdAt,
277
+ applicationId: record.applicationId,
278
+ processIdentity: record.processIdentity
279
+ };
280
+ if (sha256(canonicalOwner(payload)) != record.checksum) throw ownershipConflict("Owner lock metadata checksum is invalid");
281
+ return {
282
+ ...payload,
283
+ checksum: record.checksum
284
+ };
285
+ }
286
+ function parseGuard(bytes) {
287
+ const record = parseRecord(bytes, "ownership recovery guard");
288
+ if (Object.keys(record).sort().join(",") != GUARD_FIELDS || record.format != 1 || !UUID_PATTERN.test(String(record.guardId)) || !Number.isSafeInteger(record.pid) || record.pid <= 0 || !validHostname(record.hostname) || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0 || typeof record.checksum != "string" || !/^[0-9a-f]{64}$/.test(record.checksum)) throw ownershipConflict("Invalid ownership recovery guard");
289
+ const payload = {
290
+ format: 1,
291
+ guardId: record.guardId,
292
+ pid: record.pid,
293
+ hostname: record.hostname,
294
+ createdAt: record.createdAt
295
+ };
296
+ if (sha256(canonicalGuard(payload)) != record.checksum) throw ownershipConflict("Ownership recovery guard checksum is invalid");
297
+ return {
298
+ ...payload,
299
+ checksum: record.checksum
300
+ };
301
+ }
302
+ async function acquireGuard(root) {
303
+ const path = (0, node_path.join)(root, RECOVERY_GUARD_FILE);
304
+ let handle;
305
+ try {
306
+ handle = await (0, node_fs_promises.open)(path, "wx", 384);
307
+ } catch (cause) {
308
+ if (errorCode(cause) == "EEXIST") throw ownershipConflict("Another ownership operation is active or left an uncertain recovery guard", cause);
309
+ throw cause;
310
+ }
311
+ let identity;
312
+ try {
313
+ identity = await handle.stat();
314
+ } catch (cause) {
315
+ await handle.close().catch(() => void 0);
316
+ throw cause;
317
+ }
318
+ const payload = {
319
+ format: 1,
320
+ guardId: (0, node_crypto.randomUUID)(),
321
+ pid: process.pid,
322
+ hostname: (0, node_os.hostname)(),
323
+ createdAt: Date.now()
324
+ };
325
+ const bytes = Buffer.from(JSON.stringify({
326
+ ...payload,
327
+ checksum: sha256(canonicalGuard(payload))
328
+ }));
329
+ try {
330
+ await writeAll$1(handle, bytes);
331
+ await handle.sync();
332
+ await syncDirectory(root);
333
+ return {
334
+ path,
335
+ handle,
336
+ identity,
337
+ bytes,
338
+ guardId: payload.guardId
339
+ };
340
+ } catch (cause) {
341
+ try {
342
+ await removeCreatedFile(path, handle, identity);
343
+ } catch (cleanupCause) {
344
+ throw new AggregateError([cause, cleanupCause], "Ownership guard creation and cleanup both failed");
345
+ }
346
+ throw cause;
347
+ }
348
+ }
349
+ async function releaseGuard(root, guard) {
350
+ try {
351
+ const currentIdentity = await (0, node_fs_promises.stat)(guard.path);
352
+ const currentBytes = await (0, node_fs_promises.readFile)(guard.path);
353
+ const record = parseGuard(currentBytes);
354
+ if (!sameIdentity(guard.identity, currentIdentity) || !guard.bytes.equals(currentBytes) || record.guardId != guard.guardId) throw ownershipConflict("Ownership recovery guard changed unexpectedly");
355
+ } finally {
356
+ await guard.handle.close();
357
+ }
358
+ await (0, node_fs_promises.unlink)(guard.path);
359
+ await syncDirectory(root);
360
+ }
361
+ async function withGuard(root, operation) {
362
+ const guard = await acquireGuard(root);
363
+ let result;
364
+ let operationFailure;
365
+ try {
366
+ result = await operation();
367
+ } catch (error) {
368
+ operationFailure = error;
369
+ }
370
+ try {
371
+ await releaseGuard(root, guard);
372
+ } catch (guardFailure) {
373
+ if (operationFailure != null) throw new AggregateError([operationFailure, guardFailure], "Ownership operation and recovery-guard release both failed");
374
+ throw guardFailure;
375
+ }
376
+ if (operationFailure != null) throw operationFailure;
377
+ return result;
378
+ }
379
+ async function automaticProcessIdentity(root) {
380
+ if (process.platform != "linux") throw ownershipConflict("Automatic dead-process recovery is supported only on validated Linux environments");
381
+ let namespace;
382
+ try {
383
+ namespace = await (0, node_fs_promises.readlink)("/proc/self/ns/pid");
384
+ } catch (cause) {
385
+ throw ownershipConflict("The Linux PID namespace cannot be established", cause);
386
+ }
387
+ if (!/^pid:\[\d+\]$/.test(namespace)) throw ownershipConflict("The Linux PID namespace identity is invalid");
388
+ let filesystemType;
389
+ try {
390
+ filesystemType = (await (0, node_fs_promises.statfs)(root)).type >>> 0;
391
+ } catch (cause) {
392
+ throw ownershipConflict("The storage filesystem type cannot be established", cause);
393
+ }
394
+ if (!LINUX_LOCAL_FILESYSTEMS.has(filesystemType)) throw ownershipConflict(`Automatic recovery is not supported on filesystem type 0x${filesystemType.toString(16)}`);
395
+ return `linux:${namespace}`;
396
+ }
397
+ async function processIdentityForLock(root, mode) {
398
+ if (mode == "dead-process") return await automaticProcessIdentity(root);
399
+ if (process.platform == "linux") try {
400
+ return `linux:${await (0, node_fs_promises.readlink)("/proc/self/ns/pid")}`;
401
+ } catch {
402
+ return "linux:unavailable";
403
+ }
404
+ return `${process.platform}:unverified`;
405
+ }
406
+ function assertRecoverableOwner(owner, recovery, processIdentity) {
407
+ if (owner.hostname != (0, node_os.hostname)()) throw ownershipConflict("Owner lock belongs to a different host");
408
+ if (owner.processIdentity != processIdentity) throw ownershipConflict("Owner lock belongs to a different or unsupported process namespace");
409
+ if (owner.applicationId != (recovery.applicationId ?? null)) throw ownershipConflict("Owner lock belongs to a different application identity");
410
+ try {
411
+ process.kill(owner.pid, 0);
412
+ } catch (cause) {
413
+ if (errorCode(cause) == "ESRCH") return;
414
+ if (errorCode(cause) == "EPERM") throw ownershipConflict("Owner process existence is inconclusive", cause);
415
+ throw ownershipConflict("Owner process existence could not be determined", cause);
416
+ }
417
+ throw ownershipConflict("Owner process may still be running; PID reuse is treated as an ownership conflict");
418
+ }
419
+ async function createOwnerFile(root, ownerId, recovery, processIdentity) {
420
+ const path = (0, node_path.join)(root, LOCK_FILE);
421
+ let handle;
422
+ try {
423
+ handle = await (0, node_fs_promises.open)(path, "wx", 384);
424
+ } catch (error) {
425
+ if (errorCode(error) == "EEXIST") return null;
426
+ throw error;
427
+ }
428
+ let identity;
429
+ try {
430
+ identity = await handle.stat();
431
+ } catch (cause) {
432
+ await handle.close().catch(() => void 0);
433
+ throw cause;
434
+ }
435
+ const payload = {
436
+ format: 2,
437
+ ownerId,
438
+ pid: process.pid,
439
+ hostname: (0, node_os.hostname)(),
440
+ createdAt: Date.now(),
441
+ applicationId: recovery.applicationId ?? null,
442
+ processIdentity
443
+ };
444
+ const bytes = Buffer.from(JSON.stringify({
445
+ ...payload,
446
+ checksum: sha256(canonicalOwner(payload))
447
+ }));
448
+ try {
449
+ await writeAll$1(handle, bytes);
450
+ await handle.sync();
451
+ await syncDirectory(root);
452
+ return {
453
+ handle,
454
+ identity
455
+ };
456
+ } catch (cause) {
457
+ try {
458
+ await removeCreatedFile(path, handle, identity);
459
+ } catch (cleanupCause) {
460
+ throw new AggregateError([cause, cleanupCause], "Owner lock creation and cleanup both failed");
461
+ }
462
+ throw cause;
463
+ }
464
+ }
465
+ function normalizeOwnershipRecovery(options) {
466
+ if (options == null) return { mode: "manual" };
467
+ if (options.mode != "manual" && options.mode != "dead-process") throw new TypeError("ownershipRecovery.mode must be \"manual\" or \"dead-process\"");
468
+ if (options.applicationId != null && (typeof options.applicationId != "string" || !APPLICATION_ID_PATTERN.test(options.applicationId))) throw new TypeError("ownershipRecovery.applicationId must be 1-128 safe identifier characters");
469
+ return {
470
+ mode: options.mode,
471
+ ...options.applicationId == null ? {} : { applicationId: options.applicationId }
472
+ };
473
+ }
474
+ var DirectoryOwnership = class {
475
+ root;
476
+ recovery;
477
+ #ownerId = (0, node_crypto.randomUUID)();
478
+ #lockHandle;
479
+ #owned = false;
480
+ constructor(root, recovery) {
481
+ this.root = root;
482
+ this.recovery = recovery;
483
+ }
484
+ get isOwned() {
485
+ return this.#owned;
486
+ }
487
+ async acquire() {
488
+ const processIdentity = await processIdentityForLock(this.root, this.recovery.mode);
489
+ await withGuard(this.root, async () => {
490
+ let created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);
491
+ if (!created) {
492
+ if (this.recovery.mode == "manual") throw ownershipConflict("Storage directory has an owner lock; close the owner or perform explicit abandoned-lock recovery");
493
+ const observed = await observe((0, node_path.join)(this.root, LOCK_FILE));
494
+ if (observed) {
495
+ let owner;
496
+ try {
497
+ owner = parseOwner(observed.bytes);
498
+ assertRecoverableOwner(owner, this.recovery, processIdentity);
499
+ await removeObserved(observed);
500
+ } catch (error) {
501
+ await observed.handle.close().catch(() => void 0);
502
+ throw error;
503
+ }
504
+ await syncDirectory(this.root);
505
+ }
506
+ created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);
507
+ if (!created) throw ownershipConflict("Another process acquired storage ownership during recovery");
508
+ }
509
+ this.#lockHandle = created.handle;
510
+ this.#owned = true;
511
+ });
512
+ }
513
+ async release() {
514
+ if (!this.#owned) return;
515
+ await withGuard(this.root, async () => {
516
+ const observed = await observe((0, node_path.join)(this.root, LOCK_FILE));
517
+ if (!observed) {
518
+ this.#owned = false;
519
+ await this.#lockHandle?.close().catch(() => void 0);
520
+ this.#lockHandle = void 0;
521
+ throw ownershipConflict("Current owner lock is missing");
522
+ }
523
+ try {
524
+ if (parseOwner(observed.bytes).ownerId != this.#ownerId) throw ownershipConflict("Storage ownership changed unexpectedly");
525
+ await this.#lockHandle?.close();
526
+ this.#lockHandle = void 0;
527
+ await removeObserved(observed);
528
+ this.#owned = false;
529
+ await syncDirectory(this.root);
530
+ } catch (error) {
531
+ await observed.handle.close().catch(() => void 0);
532
+ throw error;
533
+ }
534
+ });
535
+ }
536
+ };
537
+ async function manuallyRecoverOwnership(root) {
538
+ await withGuard(root, async () => {
539
+ const observed = await observe((0, node_path.join)(root, LOCK_FILE));
540
+ if (!observed) return;
541
+ await removeObserved(observed);
542
+ await syncDirectory(root);
543
+ });
544
+ }
545
+ function validateManualRecoveryConfirmation(confirmation) {
546
+ if (confirmation != OWNERSHIP_CONFIRMATION) throw new _duraxis_storage.StorageError("Explicit exclusive-access confirmation is required", "ACCESS_DENIED");
547
+ }
548
+ // src/async-disk-storage.driver.ts
144
549
  var JOURNAL_FILE = "journal.log";
145
550
  var PREVIOUS_JOURNAL = "journal.previous";
146
551
  var NEXT_JOURNAL = "journal.next";
147
552
  var OBJECTS_DIRECTORY = "objects";
148
- var OWNERSHIP_CONFIRMATION = "I_HAVE_VERIFIED_EXCLUSIVE_ACCESS";
149
553
  function nodeErrorCode(error) {
150
554
  return error && typeof error == "object" && "code" in error ? String(error.code) : void 0;
151
555
  }
@@ -166,13 +570,28 @@ async function writeAll(handle, bytes, position = 0) {
166
570
  offset += result.bytesWritten;
167
571
  }
168
572
  }
573
+ async function syncAndClose(handle, context) {
574
+ let syncFailure;
575
+ try {
576
+ await handle.sync();
577
+ } catch (error) {
578
+ syncFailure = error;
579
+ }
580
+ try {
581
+ await handle.close();
582
+ } catch (closeFailure) {
583
+ if (syncFailure != null) throw new AggregateError([syncFailure, closeFailure], `${context} sync and close both failed`);
584
+ throw closeFailure;
585
+ }
586
+ if (syncFailure != null) throw syncFailure;
587
+ }
169
588
  var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
170
589
  root;
171
590
  registryKey;
172
591
  options;
173
592
  static activeDirectories = /* @__PURE__ */ new Set();
174
593
  entries = /* @__PURE__ */ new Map();
175
- ownerId = (0, node_crypto.randomUUID)();
594
+ ownership;
176
595
  metrics = {
177
596
  reads: 0,
178
597
  writes: 0,
@@ -184,23 +603,26 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
184
603
  };
185
604
  operationTail = Promise.resolve();
186
605
  journal;
187
- lockHandle;
188
606
  journalBytes = 0;
189
607
  sequence = 0;
190
608
  directorySync = true;
191
609
  closed = false;
192
610
  closing = false;
611
+ resourcesClosed = false;
612
+ closePromise;
193
613
  poisoned = false;
194
614
  constructor(root, registryKey, options) {
195
615
  this.root = root;
196
616
  this.registryKey = registryKey;
197
617
  this.options = options;
618
+ this.ownership = new DirectoryOwnership(root, options.ownershipRecovery);
198
619
  }
199
620
  static async open(options) {
200
621
  if (!options || typeof options.directory != "string" || options.directory.trim() == "") throw new TypeError("A storage directory is required");
201
622
  const maxKeyBytes = options.maxKeyBytes ?? 4096;
202
623
  const maxObjectBytes = options.maxObjectBytes ?? 268435456;
203
624
  const maxJournalBytes = options.maxJournalBytes ?? 1073741824;
625
+ const ownershipRecovery = normalizeOwnershipRecovery(options.ownershipRecovery);
204
626
  if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes < 64 || maxKeyBytes > 65536) throw new RangeError("Invalid maximum storage key size");
205
627
  if (!Number.isSafeInteger(maxObjectBytes) || maxObjectBytes < 0 || maxObjectBytes > 1073741824) throw new RangeError("Invalid maximum object size");
206
628
  if (!Number.isSafeInteger(maxJournalBytes) || maxJournalBytes < 1048576) throw new RangeError("Invalid maximum journal size");
@@ -215,38 +637,29 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
215
637
  directory: root,
216
638
  maxKeyBytes,
217
639
  maxObjectBytes,
218
- maxJournalBytes
640
+ maxJournalBytes,
641
+ ownershipRecovery
219
642
  });
220
643
  try {
221
644
  await driver.initialize();
222
645
  return driver;
223
- } catch (error) {
224
- this.activeDirectories.delete(registryKey);
225
- await driver.cleanupFailedOpen();
226
- throw error;
646
+ } catch (cause) {
647
+ try {
648
+ await driver.cleanupFailedOpen();
649
+ } catch (cleanupCause) {
650
+ if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);
651
+ throw new AggregateError([cause, cleanupCause], "Storage initialization and ownership cleanup both failed");
652
+ }
653
+ if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);
654
+ throw cause;
227
655
  }
228
656
  }
229
657
  static async recoverAbandonedOwnership(options) {
230
- if (options.confirmation != OWNERSHIP_CONFIRMATION) throw new _duraxis_storage.StorageError("Explicit exclusive-access confirmation is required", "ACCESS_DENIED");
658
+ validateManualRecoveryConfirmation(options.confirmation);
231
659
  const root = await (0, node_fs_promises.realpath)((0, node_path.resolve)(options.directory));
232
660
  const registryKey = process.platform == "win32" ? root.toLocaleLowerCase("en-US") : root;
233
661
  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
- }
662
+ await manuallyRecoverOwnership(root);
250
663
  }
251
664
  get durability() {
252
665
  return {
@@ -261,34 +674,12 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
261
674
  return { ...this.metrics };
262
675
  }
263
676
  async initialize() {
677
+ await this.ownership.acquire();
264
678
  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
679
  await this.recoverJournalRotation();
287
680
  const journalPath = (0, node_path.join)(this.root, JOURNAL_FILE);
288
681
  if (!await exists(journalPath)) {
289
- const created = await (0, node_fs_promises.open)(journalPath, "wx", 384);
290
- await created.sync();
291
- await created.close();
682
+ await syncAndClose(await (0, node_fs_promises.open)(journalPath, "wx", 384), "New storage journal");
292
683
  await this.syncDirectory(this.root);
293
684
  }
294
685
  const bytes = await (0, node_fs_promises.readFile)(journalPath);
@@ -307,9 +698,7 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
307
698
  }
308
699
  if (decoded.incompleteTail) {
309
700
  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();
701
+ await syncAndClose(await (0, node_fs_promises.open)(journalPath, "r+"), "Repaired storage journal");
313
702
  }
314
703
  this.journalBytes = decoded.validBytes;
315
704
  this.journal = await (0, node_fs_promises.open)(journalPath, "r+");
@@ -538,34 +927,40 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
538
927
  }
539
928
  });
540
929
  }
541
- async close() {
542
- if (this.closed || this.closing) return;
930
+ close() {
931
+ if (!this.ownership.isOwned && this.closed) return Promise.resolve();
932
+ if (this.closePromise) return this.closePromise;
543
933
  this.closing = true;
934
+ const attempt = this.closeAttempt();
935
+ this.closePromise = attempt;
936
+ const clearAttempt = () => {
937
+ if (this.closePromise == attempt) this.closePromise = void 0;
938
+ };
939
+ attempt.then(clearAttempt, clearAttempt);
940
+ return attempt;
941
+ }
942
+ async closeAttempt() {
943
+ const failures = [];
544
944
  await this.operationTail;
545
- let failure;
546
945
  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;
946
+ if (!this.resourcesClosed) try {
947
+ if (this.journal) await this.journal.close();
948
+ this.resourcesClosed = true;
949
+ } catch (error) {
950
+ failures.push(error);
951
+ }
952
+ if (failures.length == 0) try {
953
+ await this.ownership.release();
954
+ } catch (error) {
955
+ failures.push(error);
956
+ }
563
957
  } finally {
564
958
  this.closed = true;
565
959
  this.closing = false;
566
- AsyncDiskStorageDriver.activeDirectories.delete(this.registryKey);
960
+ if (!this.ownership.isOwned) AsyncDiskStorageDriver.activeDirectories.delete(this.registryKey);
567
961
  }
568
- if (failure) throw failure;
962
+ if (failures.length == 1) throw failures[0];
963
+ if (failures.length > 1) throw new AggregateError(failures, "Storage shutdown encountered multiple failures");
569
964
  }
570
965
  objectPath(key, version) {
571
966
  const hash = sha256(new TextEncoder().encode(key));
@@ -650,18 +1045,19 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
650
1045
  }
651
1046
  }
652
1047
  async cleanupFailedOpen() {
1048
+ const failures = [];
653
1049
  try {
654
1050
  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 {}
1051
+ } catch (error) {
1052
+ failures.push(error);
1053
+ }
1054
+ if (failures.length == 0) try {
1055
+ await this.ownership.release();
1056
+ } catch (error) {
1057
+ failures.push(error);
1058
+ }
1059
+ if (failures.length == 1) throw failures[0];
1060
+ if (failures.length > 1) throw new AggregateError(failures, "Failed storage initialization cleanup");
665
1061
  }
666
1062
  };
667
1063
  exports.AsyncDiskStorageDriver = AsyncDiskStorageDriver;