@duraxis/storage-disk 0.0.0-stage → 0.1.1

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,1064 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { mkdir, open, readFile, readdir, readlink, realpath, rename, rm, stat, statfs, truncate, unlink } from "node:fs/promises";
4
+ import { StorageError, assertStorageKey } from "@duraxis/storage";
5
+ import { hostname } from "node:os";
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$1(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$1(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$1(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/ownership.ts
142
+ var LOCK_FILE = ".duraxis-owner.lock";
143
+ var RECOVERY_GUARD_FILE = ".duraxis-owner.recovery";
144
+ var OWNERSHIP_CONFIRMATION = "I_HAVE_VERIFIED_EXCLUSIVE_ACCESS";
145
+ var OWNER_FIELDS = "applicationId,checksum,createdAt,format,hostname,ownerId,pid,processIdentity";
146
+ var GUARD_FIELDS = "checksum,createdAt,format,guardId,hostname,pid";
147
+ 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}$/;
148
+ var APPLICATION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._:/-]{0,126}[A-Za-z0-9])?$/;
149
+ var PROCESS_IDENTITY_PATTERN = /^(?:linux:(?:pid:\[\d+\]|unavailable)|[a-z0-9]+:unverified)$/;
150
+ var MAX_METADATA_BYTES = 4096;
151
+ var LINUX_LOCAL_FILESYSTEMS = /* @__PURE__ */ new Set([
152
+ 61267,
153
+ 16914836,
154
+ 801189825,
155
+ 1481003842,
156
+ 2035054128,
157
+ 2240043254,
158
+ 2435016766
159
+ ]);
160
+ function errorCode(error) {
161
+ return error && typeof error == "object" && "code" in error ? String(error.code) : void 0;
162
+ }
163
+ function ownershipConflict(message, cause) {
164
+ return new StorageError(message, "OWNERSHIP_CONFLICT", cause == null ? void 0 : { cause });
165
+ }
166
+ function canonicalOwner(payload) {
167
+ return JSON.stringify(payload);
168
+ }
169
+ function canonicalGuard(payload) {
170
+ return JSON.stringify(payload);
171
+ }
172
+ function validHostname(value) {
173
+ return typeof value == "string" && value.length > 0 && value.length <= 255 && !/[\0-\x1f\x7f]/.test(value);
174
+ }
175
+ function sameIdentity(left, right) {
176
+ return left.dev == right.dev && left.ino == right.ino;
177
+ }
178
+ async function writeAll$1(handle, bytes) {
179
+ let offset = 0;
180
+ while (offset < bytes.byteLength) {
181
+ const result = await handle.write(bytes, offset, bytes.byteLength - offset, offset);
182
+ if (result.bytesWritten <= 0) throw new StorageError("Ownership metadata write made no progress", "UNAVAILABLE");
183
+ offset += result.bytesWritten;
184
+ }
185
+ }
186
+ async function syncDirectory(directory) {
187
+ let handle;
188
+ try {
189
+ handle = await open(directory, "r");
190
+ await handle.sync();
191
+ } catch (error) {
192
+ if (![
193
+ "EINVAL",
194
+ "ENOTSUP",
195
+ "EBADF",
196
+ "EISDIR",
197
+ "EPERM"
198
+ ].includes(errorCode(error) ?? "")) throw error;
199
+ } finally {
200
+ await handle?.close();
201
+ }
202
+ }
203
+ async function observe(path) {
204
+ let handle;
205
+ try {
206
+ handle = await open(path, "r");
207
+ } catch (error) {
208
+ if (errorCode(error) == "ENOENT") return null;
209
+ throw error;
210
+ }
211
+ try {
212
+ const identity = await handle.stat();
213
+ const bytes = await handle.readFile();
214
+ return {
215
+ path,
216
+ handle,
217
+ identity,
218
+ bytes
219
+ };
220
+ } catch (error) {
221
+ await handle.close().catch(() => void 0);
222
+ throw error;
223
+ }
224
+ }
225
+ async function assertObservedUnchanged(observed) {
226
+ let currentIdentity;
227
+ let currentBytes;
228
+ try {
229
+ [currentIdentity, currentBytes] = await Promise.all([stat(observed.path), readFile(observed.path)]);
230
+ } catch (cause) {
231
+ throw ownershipConflict("Ownership metadata changed during inspection", cause);
232
+ }
233
+ if (!sameIdentity(observed.identity, currentIdentity) || !observed.bytes.equals(currentBytes)) throw ownershipConflict("Ownership metadata changed during inspection");
234
+ }
235
+ async function removeObserved(observed) {
236
+ try {
237
+ await assertObservedUnchanged(observed);
238
+ } finally {
239
+ await observed.handle.close();
240
+ }
241
+ try {
242
+ await unlink(observed.path);
243
+ } catch (cause) {
244
+ throw ownershipConflict("Failed to remove the observed ownership lock", cause);
245
+ }
246
+ }
247
+ async function removeCreatedFile(path, handle, identity) {
248
+ await handle.close().catch(() => void 0);
249
+ try {
250
+ if (!sameIdentity(identity, await stat(path))) throw ownershipConflict("Created ownership file was replaced unexpectedly");
251
+ await unlink(path);
252
+ } catch (error) {
253
+ if (errorCode(error) != "ENOENT") throw error;
254
+ }
255
+ }
256
+ function parseRecord(bytes, label) {
257
+ if (bytes.byteLength == 0 || bytes.byteLength > MAX_METADATA_BYTES) throw ownershipConflict(`Invalid ${label}`);
258
+ try {
259
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
260
+ if (!value || typeof value != "object" || Array.isArray(value)) throw new Error("not an object");
261
+ return value;
262
+ } catch (cause) {
263
+ throw ownershipConflict(`Invalid ${label}`, cause);
264
+ }
265
+ }
266
+ function parseOwner(bytes) {
267
+ const record = parseRecord(bytes, "owner lock metadata");
268
+ if (record.format != 2) throw ownershipConflict("Owner lock format is incompatible with automatic recovery; use explicit manual recovery");
269
+ 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");
270
+ const payload = {
271
+ format: 2,
272
+ ownerId: record.ownerId,
273
+ pid: record.pid,
274
+ hostname: record.hostname,
275
+ createdAt: record.createdAt,
276
+ applicationId: record.applicationId,
277
+ processIdentity: record.processIdentity
278
+ };
279
+ if (sha256(canonicalOwner(payload)) != record.checksum) throw ownershipConflict("Owner lock metadata checksum is invalid");
280
+ return {
281
+ ...payload,
282
+ checksum: record.checksum
283
+ };
284
+ }
285
+ function parseGuard(bytes) {
286
+ const record = parseRecord(bytes, "ownership recovery guard");
287
+ 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");
288
+ const payload = {
289
+ format: 1,
290
+ guardId: record.guardId,
291
+ pid: record.pid,
292
+ hostname: record.hostname,
293
+ createdAt: record.createdAt
294
+ };
295
+ if (sha256(canonicalGuard(payload)) != record.checksum) throw ownershipConflict("Ownership recovery guard checksum is invalid");
296
+ return {
297
+ ...payload,
298
+ checksum: record.checksum
299
+ };
300
+ }
301
+ async function acquireGuard(root) {
302
+ const path = join(root, RECOVERY_GUARD_FILE);
303
+ let handle;
304
+ try {
305
+ handle = await open(path, "wx", 384);
306
+ } catch (cause) {
307
+ if (errorCode(cause) == "EEXIST") throw ownershipConflict("Another ownership operation is active or left an uncertain recovery guard", cause);
308
+ throw cause;
309
+ }
310
+ let identity;
311
+ try {
312
+ identity = await handle.stat();
313
+ } catch (cause) {
314
+ await handle.close().catch(() => void 0);
315
+ throw cause;
316
+ }
317
+ const payload = {
318
+ format: 1,
319
+ guardId: randomUUID(),
320
+ pid: process.pid,
321
+ hostname: hostname(),
322
+ createdAt: Date.now()
323
+ };
324
+ const bytes = Buffer.from(JSON.stringify({
325
+ ...payload,
326
+ checksum: sha256(canonicalGuard(payload))
327
+ }));
328
+ try {
329
+ await writeAll$1(handle, bytes);
330
+ await handle.sync();
331
+ await syncDirectory(root);
332
+ return {
333
+ path,
334
+ handle,
335
+ identity,
336
+ bytes,
337
+ guardId: payload.guardId
338
+ };
339
+ } catch (cause) {
340
+ try {
341
+ await removeCreatedFile(path, handle, identity);
342
+ } catch (cleanupCause) {
343
+ throw new AggregateError([cause, cleanupCause], "Ownership guard creation and cleanup both failed");
344
+ }
345
+ throw cause;
346
+ }
347
+ }
348
+ async function releaseGuard(root, guard) {
349
+ try {
350
+ const currentIdentity = await stat(guard.path);
351
+ const currentBytes = await readFile(guard.path);
352
+ const record = parseGuard(currentBytes);
353
+ if (!sameIdentity(guard.identity, currentIdentity) || !guard.bytes.equals(currentBytes) || record.guardId != guard.guardId) throw ownershipConflict("Ownership recovery guard changed unexpectedly");
354
+ } finally {
355
+ await guard.handle.close();
356
+ }
357
+ await unlink(guard.path);
358
+ await syncDirectory(root);
359
+ }
360
+ async function withGuard(root, operation) {
361
+ const guard = await acquireGuard(root);
362
+ let result;
363
+ let operationFailure;
364
+ try {
365
+ result = await operation();
366
+ } catch (error) {
367
+ operationFailure = error;
368
+ }
369
+ try {
370
+ await releaseGuard(root, guard);
371
+ } catch (guardFailure) {
372
+ if (operationFailure != null) throw new AggregateError([operationFailure, guardFailure], "Ownership operation and recovery-guard release both failed");
373
+ throw guardFailure;
374
+ }
375
+ if (operationFailure != null) throw operationFailure;
376
+ return result;
377
+ }
378
+ async function automaticProcessIdentity(root) {
379
+ if (process.platform != "linux") throw ownershipConflict("Automatic dead-process recovery is supported only on validated Linux environments");
380
+ let namespace;
381
+ try {
382
+ namespace = await readlink("/proc/self/ns/pid");
383
+ } catch (cause) {
384
+ throw ownershipConflict("The Linux PID namespace cannot be established", cause);
385
+ }
386
+ if (!/^pid:\[\d+\]$/.test(namespace)) throw ownershipConflict("The Linux PID namespace identity is invalid");
387
+ let filesystemType;
388
+ try {
389
+ filesystemType = (await statfs(root)).type >>> 0;
390
+ } catch (cause) {
391
+ throw ownershipConflict("The storage filesystem type cannot be established", cause);
392
+ }
393
+ if (!LINUX_LOCAL_FILESYSTEMS.has(filesystemType)) throw ownershipConflict(`Automatic recovery is not supported on filesystem type 0x${filesystemType.toString(16)}`);
394
+ return `linux:${namespace}`;
395
+ }
396
+ async function processIdentityForLock(root, mode) {
397
+ if (mode == "dead-process") return await automaticProcessIdentity(root);
398
+ if (process.platform == "linux") try {
399
+ return `linux:${await readlink("/proc/self/ns/pid")}`;
400
+ } catch {
401
+ return "linux:unavailable";
402
+ }
403
+ return `${process.platform}:unverified`;
404
+ }
405
+ function assertRecoverableOwner(owner, recovery, processIdentity) {
406
+ if (owner.hostname != hostname()) throw ownershipConflict("Owner lock belongs to a different host");
407
+ if (owner.processIdentity != processIdentity) throw ownershipConflict("Owner lock belongs to a different or unsupported process namespace");
408
+ if (owner.applicationId != (recovery.applicationId ?? null)) throw ownershipConflict("Owner lock belongs to a different application identity");
409
+ try {
410
+ process.kill(owner.pid, 0);
411
+ } catch (cause) {
412
+ if (errorCode(cause) == "ESRCH") return;
413
+ if (errorCode(cause) == "EPERM") throw ownershipConflict("Owner process existence is inconclusive", cause);
414
+ throw ownershipConflict("Owner process existence could not be determined", cause);
415
+ }
416
+ throw ownershipConflict("Owner process may still be running; PID reuse is treated as an ownership conflict");
417
+ }
418
+ async function createOwnerFile(root, ownerId, recovery, processIdentity) {
419
+ const path = join(root, LOCK_FILE);
420
+ let handle;
421
+ try {
422
+ handle = await open(path, "wx", 384);
423
+ } catch (error) {
424
+ if (errorCode(error) == "EEXIST") return null;
425
+ throw error;
426
+ }
427
+ let identity;
428
+ try {
429
+ identity = await handle.stat();
430
+ } catch (cause) {
431
+ await handle.close().catch(() => void 0);
432
+ throw cause;
433
+ }
434
+ const payload = {
435
+ format: 2,
436
+ ownerId,
437
+ pid: process.pid,
438
+ hostname: hostname(),
439
+ createdAt: Date.now(),
440
+ applicationId: recovery.applicationId ?? null,
441
+ processIdentity
442
+ };
443
+ const bytes = Buffer.from(JSON.stringify({
444
+ ...payload,
445
+ checksum: sha256(canonicalOwner(payload))
446
+ }));
447
+ try {
448
+ await writeAll$1(handle, bytes);
449
+ await handle.sync();
450
+ await syncDirectory(root);
451
+ return {
452
+ handle,
453
+ identity
454
+ };
455
+ } catch (cause) {
456
+ try {
457
+ await removeCreatedFile(path, handle, identity);
458
+ } catch (cleanupCause) {
459
+ throw new AggregateError([cause, cleanupCause], "Owner lock creation and cleanup both failed");
460
+ }
461
+ throw cause;
462
+ }
463
+ }
464
+ function normalizeOwnershipRecovery(options) {
465
+ if (options == null) return { mode: "manual" };
466
+ if (options.mode != "manual" && options.mode != "dead-process") throw new TypeError("ownershipRecovery.mode must be \"manual\" or \"dead-process\"");
467
+ 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");
468
+ return {
469
+ mode: options.mode,
470
+ ...options.applicationId == null ? {} : { applicationId: options.applicationId }
471
+ };
472
+ }
473
+ var DirectoryOwnership = class {
474
+ root;
475
+ recovery;
476
+ #ownerId = randomUUID();
477
+ #lockHandle;
478
+ #owned = false;
479
+ constructor(root, recovery) {
480
+ this.root = root;
481
+ this.recovery = recovery;
482
+ }
483
+ get isOwned() {
484
+ return this.#owned;
485
+ }
486
+ async acquire() {
487
+ const processIdentity = await processIdentityForLock(this.root, this.recovery.mode);
488
+ await withGuard(this.root, async () => {
489
+ let created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);
490
+ if (!created) {
491
+ if (this.recovery.mode == "manual") throw ownershipConflict("Storage directory has an owner lock; close the owner or perform explicit abandoned-lock recovery");
492
+ const observed = await observe(join(this.root, LOCK_FILE));
493
+ if (observed) {
494
+ let owner;
495
+ try {
496
+ owner = parseOwner(observed.bytes);
497
+ assertRecoverableOwner(owner, this.recovery, processIdentity);
498
+ await removeObserved(observed);
499
+ } catch (error) {
500
+ await observed.handle.close().catch(() => void 0);
501
+ throw error;
502
+ }
503
+ await syncDirectory(this.root);
504
+ }
505
+ created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);
506
+ if (!created) throw ownershipConflict("Another process acquired storage ownership during recovery");
507
+ }
508
+ this.#lockHandle = created.handle;
509
+ this.#owned = true;
510
+ });
511
+ }
512
+ async release() {
513
+ if (!this.#owned) return;
514
+ await withGuard(this.root, async () => {
515
+ const observed = await observe(join(this.root, LOCK_FILE));
516
+ if (!observed) {
517
+ this.#owned = false;
518
+ await this.#lockHandle?.close().catch(() => void 0);
519
+ this.#lockHandle = void 0;
520
+ throw ownershipConflict("Current owner lock is missing");
521
+ }
522
+ try {
523
+ if (parseOwner(observed.bytes).ownerId != this.#ownerId) throw ownershipConflict("Storage ownership changed unexpectedly");
524
+ await this.#lockHandle?.close();
525
+ this.#lockHandle = void 0;
526
+ await removeObserved(observed);
527
+ this.#owned = false;
528
+ await syncDirectory(this.root);
529
+ } catch (error) {
530
+ await observed.handle.close().catch(() => void 0);
531
+ throw error;
532
+ }
533
+ });
534
+ }
535
+ };
536
+ async function manuallyRecoverOwnership(root) {
537
+ await withGuard(root, async () => {
538
+ const observed = await observe(join(root, LOCK_FILE));
539
+ if (!observed) return;
540
+ await removeObserved(observed);
541
+ await syncDirectory(root);
542
+ });
543
+ }
544
+ function validateManualRecoveryConfirmation(confirmation) {
545
+ if (confirmation != OWNERSHIP_CONFIRMATION) throw new StorageError("Explicit exclusive-access confirmation is required", "ACCESS_DENIED");
546
+ }
547
+ // src/async-disk-storage.driver.ts
548
+ var JOURNAL_FILE = "journal.log";
549
+ var PREVIOUS_JOURNAL = "journal.previous";
550
+ var NEXT_JOURNAL = "journal.next";
551
+ var OBJECTS_DIRECTORY = "objects";
552
+ function nodeErrorCode(error) {
553
+ return error && typeof error == "object" && "code" in error ? String(error.code) : void 0;
554
+ }
555
+ async function exists(path) {
556
+ try {
557
+ await stat(path);
558
+ return true;
559
+ } catch (error) {
560
+ if (nodeErrorCode(error) == "ENOENT") return false;
561
+ throw error;
562
+ }
563
+ }
564
+ async function writeAll(handle, bytes, position = 0) {
565
+ let offset = 0;
566
+ while (offset < bytes.byteLength) {
567
+ const result = await handle.write(bytes, offset, bytes.byteLength - offset, position + offset);
568
+ if (result.bytesWritten <= 0) throw new StorageError("Disk write made no progress", "UNAVAILABLE");
569
+ offset += result.bytesWritten;
570
+ }
571
+ }
572
+ async function syncAndClose(handle, context) {
573
+ let syncFailure;
574
+ try {
575
+ await handle.sync();
576
+ } catch (error) {
577
+ syncFailure = error;
578
+ }
579
+ try {
580
+ await handle.close();
581
+ } catch (closeFailure) {
582
+ if (syncFailure != null) throw new AggregateError([syncFailure, closeFailure], `${context} sync and close both failed`);
583
+ throw closeFailure;
584
+ }
585
+ if (syncFailure != null) throw syncFailure;
586
+ }
587
+ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
588
+ root;
589
+ registryKey;
590
+ options;
591
+ static activeDirectories = /* @__PURE__ */ new Set();
592
+ entries = /* @__PURE__ */ new Map();
593
+ ownership;
594
+ metrics = {
595
+ reads: 0,
596
+ writes: 0,
597
+ deletes: 0,
598
+ lists: 0,
599
+ bytesRead: 0,
600
+ bytesWritten: 0,
601
+ synchronizationWaitMs: 0
602
+ };
603
+ operationTail = Promise.resolve();
604
+ journal;
605
+ journalBytes = 0;
606
+ sequence = 0;
607
+ directorySync = true;
608
+ closed = false;
609
+ closing = false;
610
+ resourcesClosed = false;
611
+ closePromise;
612
+ poisoned = false;
613
+ constructor(root, registryKey, options) {
614
+ this.root = root;
615
+ this.registryKey = registryKey;
616
+ this.options = options;
617
+ this.ownership = new DirectoryOwnership(root, options.ownershipRecovery);
618
+ }
619
+ static async open(options) {
620
+ if (!options || typeof options.directory != "string" || options.directory.trim() == "") throw new TypeError("A storage directory is required");
621
+ const maxKeyBytes = options.maxKeyBytes ?? 4096;
622
+ const maxObjectBytes = options.maxObjectBytes ?? 268435456;
623
+ const maxJournalBytes = options.maxJournalBytes ?? 1073741824;
624
+ const ownershipRecovery = normalizeOwnershipRecovery(options.ownershipRecovery);
625
+ if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes < 64 || maxKeyBytes > 65536) throw new RangeError("Invalid maximum storage key size");
626
+ if (!Number.isSafeInteger(maxObjectBytes) || maxObjectBytes < 0 || maxObjectBytes > 1073741824) throw new RangeError("Invalid maximum object size");
627
+ if (!Number.isSafeInteger(maxJournalBytes) || maxJournalBytes < 1048576) throw new RangeError("Invalid maximum journal size");
628
+ const requested = resolve(options.directory);
629
+ await mkdir(requested, { recursive: true });
630
+ const root = await realpath(requested);
631
+ const registryKey = process.platform == "win32" ? root.toLocaleLowerCase("en-US") : root;
632
+ if (this.activeDirectories.has(registryKey)) throw new StorageError("Storage directory is already owned by this process", "OWNERSHIP_CONFLICT");
633
+ this.activeDirectories.add(registryKey);
634
+ const driver = new AsyncDiskStorageDriver(root, registryKey, {
635
+ ...options,
636
+ directory: root,
637
+ maxKeyBytes,
638
+ maxObjectBytes,
639
+ maxJournalBytes,
640
+ ownershipRecovery
641
+ });
642
+ try {
643
+ await driver.initialize();
644
+ return driver;
645
+ } catch (cause) {
646
+ try {
647
+ await driver.cleanupFailedOpen();
648
+ } catch (cleanupCause) {
649
+ if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);
650
+ throw new AggregateError([cause, cleanupCause], "Storage initialization and ownership cleanup both failed");
651
+ }
652
+ if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);
653
+ throw cause;
654
+ }
655
+ }
656
+ static async recoverAbandonedOwnership(options) {
657
+ validateManualRecoveryConfirmation(options.confirmation);
658
+ const root = await realpath(resolve(options.directory));
659
+ const registryKey = process.platform == "win32" ? root.toLocaleLowerCase("en-US") : root;
660
+ if (this.activeDirectories.has(registryKey)) throw new StorageError("Cannot recover ownership held by this process", "OWNERSHIP_CONFLICT");
661
+ await manuallyRecoverOwnership(root);
662
+ }
663
+ get durability() {
664
+ return {
665
+ fileDataSync: true,
666
+ directoryEntrySync: this.directorySync,
667
+ ownership: "exclusive-directory",
668
+ processCrashRecovery: true,
669
+ powerLossGuarantee: this.directorySync ? "file-and-directory-sync" : "file-sync-only"
670
+ };
671
+ }
672
+ getMetrics() {
673
+ return { ...this.metrics };
674
+ }
675
+ async initialize() {
676
+ await this.ownership.acquire();
677
+ await mkdir(join(this.root, OBJECTS_DIRECTORY), { recursive: true });
678
+ await this.recoverJournalRotation();
679
+ const journalPath = join(this.root, JOURNAL_FILE);
680
+ if (!await exists(journalPath)) {
681
+ await syncAndClose(await open(journalPath, "wx", 384), "New storage journal");
682
+ await this.syncDirectory(this.root);
683
+ }
684
+ const bytes = await readFile(journalPath);
685
+ if (bytes.byteLength > this.options.maxJournalBytes) throw new StorageError("Storage journal exceeds configured limit", "RESOURCE_LIMIT");
686
+ const decoded = decodeJournal(bytes);
687
+ for (const frame of decoded.frames) {
688
+ this.validateKey(frame.key);
689
+ this.sequence = frame.sequence;
690
+ if (frame.op == "put") this.entries.set(frame.key, {
691
+ version: frame.version,
692
+ createdAt: frame.createdAt,
693
+ size: frame.size,
694
+ digest: frame.digest
695
+ });
696
+ else this.entries.delete(frame.key);
697
+ }
698
+ if (decoded.incompleteTail) {
699
+ await truncate(journalPath, decoded.validBytes);
700
+ await syncAndClose(await open(journalPath, "r+"), "Repaired storage journal");
701
+ }
702
+ this.journalBytes = decoded.validBytes;
703
+ this.journal = await open(journalPath, "r+");
704
+ await this.assertCurrentObjectsExist();
705
+ await this.cleanupPhysicalObjects();
706
+ }
707
+ validateKey(key) {
708
+ assertStorageKey(key);
709
+ if (Buffer.byteLength(key, "utf8") > this.options.maxKeyBytes) throw new StorageError("Storage key exceeds configured byte limit", "INVALID_KEY");
710
+ }
711
+ assertUsable() {
712
+ if (this.closed || this.closing) throw new StorageError("Storage driver is closed", "CLOSED");
713
+ if (this.poisoned) throw new StorageError("Storage outcome is unknown; close and reopen before continuing", "OUTCOME_UNKNOWN");
714
+ }
715
+ async exclusive(operation) {
716
+ this.assertUsable();
717
+ const before = performance.now();
718
+ const previous = this.operationTail;
719
+ let release;
720
+ this.operationTail = new Promise((resolve) => {
721
+ release = resolve;
722
+ });
723
+ await previous;
724
+ this.metrics.synchronizationWaitMs += performance.now() - before;
725
+ try {
726
+ this.assertUsable();
727
+ return await operation();
728
+ } finally {
729
+ release();
730
+ }
731
+ }
732
+ get(key) {
733
+ return this.exclusive(async () => {
734
+ this.validateKey(key);
735
+ this.metrics.reads++;
736
+ const metadata = this.entries.get(key);
737
+ if (!metadata) return null;
738
+ const path = this.objectPath(key, metadata.version);
739
+ let info;
740
+ try {
741
+ info = await stat(path);
742
+ } catch (error) {
743
+ if (nodeErrorCode(error) == "ENOENT") throw new StorageError(`Missing physical object for key ${key}`, "CORRUPTION", { cause: error });
744
+ throw error;
745
+ }
746
+ if (info.size > this.options.maxObjectBytes + 32768) throw new StorageError("Physical object exceeds configured size", "CORRUPTION");
747
+ const physical = await readFile(path);
748
+ this.metrics.bytesRead += physical.byteLength;
749
+ return {
750
+ data: decodePhysicalObject(physical, key, metadata),
751
+ version: metadata.version
752
+ };
753
+ });
754
+ }
755
+ put(key, data, options) {
756
+ return this.exclusive(async () => {
757
+ this.validateKey(key);
758
+ if (!(data instanceof Uint8Array)) throw new TypeError("Storage data must be a Uint8Array");
759
+ if (data.byteLength > this.options.maxObjectBytes) throw new StorageError("Storage object exceeds configured byte limit", "RESOURCE_LIMIT");
760
+ const current = this.entries.get(key);
761
+ if (options.condition.type == "if-absent" ? current != null : current == null || current.version != options.condition.version) return {
762
+ success: false,
763
+ reason: "conflict"
764
+ };
765
+ this.metrics.writes++;
766
+ const metadata = {
767
+ version: randomUUID(),
768
+ createdAt: Date.now(),
769
+ size: data.byteLength,
770
+ digest: sha256(data)
771
+ };
772
+ const physical = encodePhysicalObject(key, metadata, data);
773
+ const finalPath = this.objectPath(key, metadata.version);
774
+ const parent = dirname(finalPath);
775
+ await mkdir(parent, { recursive: true });
776
+ const temporary = join(parent, `.${metadata.version}.${randomUUID()}.tmp`);
777
+ let published = false;
778
+ try {
779
+ const handle = await open(temporary, "wx", 384);
780
+ try {
781
+ await writeAll(handle, physical);
782
+ await handle.sync();
783
+ } finally {
784
+ await handle.close();
785
+ }
786
+ await this.fault("after-object-sync", {
787
+ operation: "put",
788
+ key
789
+ });
790
+ await rename(temporary, finalPath);
791
+ published = true;
792
+ await this.fault("after-object-publish", {
793
+ operation: "put",
794
+ key
795
+ });
796
+ await this.syncDirectory(parent);
797
+ await this.fault("after-object-directory-sync", {
798
+ operation: "put",
799
+ key
800
+ });
801
+ const frame = {
802
+ format: 1,
803
+ sequence: this.sequence + 1,
804
+ op: "put",
805
+ key,
806
+ version: metadata.version,
807
+ createdAt: metadata.createdAt,
808
+ size: metadata.size,
809
+ digest: metadata.digest
810
+ };
811
+ await this.append(frame);
812
+ this.entries.set(key, metadata);
813
+ this.sequence = frame.sequence;
814
+ this.metrics.bytesWritten += physical.byteLength;
815
+ if (current) await this.removeObsolete(this.objectPath(key, current.version));
816
+ return {
817
+ success: true,
818
+ version: metadata.version
819
+ };
820
+ } catch (error) {
821
+ if (!published) await this.removeObsolete(temporary);
822
+ throw error;
823
+ }
824
+ });
825
+ }
826
+ delete(key, options) {
827
+ return this.exclusive(async () => {
828
+ this.validateKey(key);
829
+ const current = this.entries.get(key);
830
+ if (options.condition.type == "if-absent") return current ? {
831
+ success: false,
832
+ reason: "conflict"
833
+ } : { success: true };
834
+ if (!current || current.version != options.condition.version) return {
835
+ success: false,
836
+ reason: "conflict"
837
+ };
838
+ this.metrics.deletes++;
839
+ const frame = {
840
+ format: 1,
841
+ sequence: this.sequence + 1,
842
+ op: "delete",
843
+ key
844
+ };
845
+ await this.append(frame);
846
+ this.entries.delete(key);
847
+ this.sequence = frame.sequence;
848
+ await this.removeObsolete(this.objectPath(key, current.version));
849
+ return { success: true };
850
+ });
851
+ }
852
+ list(prefix) {
853
+ return this.exclusive(async () => {
854
+ if (typeof prefix != "string" || prefix.includes("\0") || Buffer.byteLength(prefix, "utf8") > this.options.maxKeyBytes) throw new StorageError("Invalid storage prefix", "INVALID_KEY");
855
+ this.metrics.lists++;
856
+ return [...this.entries].filter(([key]) => key.startsWith(prefix)).map(([key, value]) => ({
857
+ key,
858
+ version: value.version,
859
+ createdAt: value.createdAt
860
+ })).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
861
+ });
862
+ }
863
+ async append(frame) {
864
+ const encoded = encodeJournalFrame(frame);
865
+ if (this.journalBytes + encoded.byteLength > this.options.maxJournalBytes) throw new StorageError("Storage journal limit reached; compact before writing", "RESOURCE_LIMIT");
866
+ try {
867
+ await writeAll(this.journal, encoded, this.journalBytes);
868
+ await this.fault("after-journal-write", {
869
+ operation: frame.op,
870
+ key: frame.key
871
+ });
872
+ await this.journal.sync();
873
+ await this.fault("after-journal-sync", {
874
+ operation: frame.op,
875
+ key: frame.key
876
+ });
877
+ this.journalBytes += encoded.byteLength;
878
+ this.metrics.bytesWritten += encoded.byteLength;
879
+ } catch (cause) {
880
+ this.poisoned = true;
881
+ throw new StorageError("Storage publication outcome is unknown", "OUTCOME_UNKNOWN", { cause });
882
+ }
883
+ }
884
+ compact() {
885
+ return this.exclusive(async () => {
886
+ try {
887
+ const nextPath = join(this.root, NEXT_JOURNAL);
888
+ const previousPath = join(this.root, PREVIOUS_JOURNAL);
889
+ const currentPath = join(this.root, JOURNAL_FILE);
890
+ await this.removeObsolete(nextPath);
891
+ await this.removeObsolete(previousPath);
892
+ const next = await open(nextPath, "wx", 384);
893
+ let offset = 0;
894
+ let sequence = 0;
895
+ try {
896
+ for (const [key, metadata] of [...this.entries].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
897
+ const bytes = encodeJournalFrame({
898
+ format: 1,
899
+ sequence: ++sequence,
900
+ op: "put",
901
+ key,
902
+ version: metadata.version,
903
+ createdAt: metadata.createdAt,
904
+ size: metadata.size,
905
+ digest: metadata.digest
906
+ });
907
+ await writeAll(next, bytes, offset);
908
+ offset += bytes.byteLength;
909
+ }
910
+ await next.sync();
911
+ } finally {
912
+ await next.close();
913
+ }
914
+ await this.journal.close();
915
+ await rename(currentPath, previousPath);
916
+ await rename(nextPath, currentPath);
917
+ await this.syncDirectory(this.root);
918
+ await this.fault("after-journal-rotation", { operation: "compact" });
919
+ this.journal = await open(currentPath, "r+");
920
+ this.journalBytes = offset;
921
+ this.sequence = sequence;
922
+ await this.removeObsolete(previousPath);
923
+ } catch (cause) {
924
+ this.poisoned = true;
925
+ throw new StorageError("Journal compaction outcome is unknown", "OUTCOME_UNKNOWN", { cause });
926
+ }
927
+ });
928
+ }
929
+ close() {
930
+ if (!this.ownership.isOwned && this.closed) return Promise.resolve();
931
+ if (this.closePromise) return this.closePromise;
932
+ this.closing = true;
933
+ const attempt = this.closeAttempt();
934
+ this.closePromise = attempt;
935
+ const clearAttempt = () => {
936
+ if (this.closePromise == attempt) this.closePromise = void 0;
937
+ };
938
+ attempt.then(clearAttempt, clearAttempt);
939
+ return attempt;
940
+ }
941
+ async closeAttempt() {
942
+ const failures = [];
943
+ await this.operationTail;
944
+ try {
945
+ if (!this.resourcesClosed) try {
946
+ if (this.journal) await this.journal.close();
947
+ this.resourcesClosed = true;
948
+ } catch (error) {
949
+ failures.push(error);
950
+ }
951
+ if (failures.length == 0) try {
952
+ await this.ownership.release();
953
+ } catch (error) {
954
+ failures.push(error);
955
+ }
956
+ } finally {
957
+ this.closed = true;
958
+ this.closing = false;
959
+ if (!this.ownership.isOwned) AsyncDiskStorageDriver.activeDirectories.delete(this.registryKey);
960
+ }
961
+ if (failures.length == 1) throw failures[0];
962
+ if (failures.length > 1) throw new AggregateError(failures, "Storage shutdown encountered multiple failures");
963
+ }
964
+ objectPath(key, version) {
965
+ const hash = sha256(new TextEncoder().encode(key));
966
+ return join(this.root, OBJECTS_DIRECTORY, hash.slice(0, 2), hash, `${version}.obj`);
967
+ }
968
+ async assertCurrentObjectsExist() {
969
+ for (const [key, metadata] of this.entries) try {
970
+ await stat(this.objectPath(key, metadata.version));
971
+ } catch (error) {
972
+ if (nodeErrorCode(error) == "ENOENT") throw new StorageError(`Journal references a missing object: ${key}`, "CORRUPTION", { cause: error });
973
+ throw error;
974
+ }
975
+ }
976
+ async cleanupPhysicalObjects() {
977
+ const referenced = new Set([...this.entries].map(([key, metadata]) => this.objectPath(key, metadata.version)));
978
+ const walk = async (directory) => {
979
+ let items;
980
+ try {
981
+ items = await readdir(directory, { withFileTypes: true });
982
+ } catch (error) {
983
+ if (nodeErrorCode(error) == "ENOENT") return;
984
+ throw error;
985
+ }
986
+ for (const item of items) {
987
+ const path = join(directory, item.name);
988
+ if (item.isDirectory()) await walk(path);
989
+ else if (item.isFile() && (item.name.endsWith(".tmp") || item.name.endsWith(".obj") && !referenced.has(path))) await this.removeObsolete(path);
990
+ }
991
+ };
992
+ await walk(join(this.root, OBJECTS_DIRECTORY));
993
+ }
994
+ async recoverJournalRotation() {
995
+ const current = join(this.root, JOURNAL_FILE);
996
+ const previous = join(this.root, PREVIOUS_JOURNAL);
997
+ const next = join(this.root, NEXT_JOURNAL);
998
+ const hasCurrent = await exists(current);
999
+ const hasPrevious = await exists(previous);
1000
+ const hasNext = await exists(next);
1001
+ if (!hasCurrent) {
1002
+ if (hasNext) await rename(next, current);
1003
+ else if (hasPrevious) await rename(previous, current);
1004
+ } else if (hasPrevious) try {
1005
+ decodeJournal(await readFile(current));
1006
+ await this.removeObsolete(previous);
1007
+ } catch {
1008
+ await this.removeObsolete(current);
1009
+ await rename(previous, current);
1010
+ }
1011
+ if (await exists(current) && await exists(next)) await this.removeObsolete(next);
1012
+ if (await exists(current) && await exists(previous)) await this.removeObsolete(previous);
1013
+ await this.syncDirectory(this.root);
1014
+ }
1015
+ async fault(point, context) {
1016
+ await this.options.faultInjector?.(point, context);
1017
+ }
1018
+ async removeObsolete(path) {
1019
+ try {
1020
+ await rm(path, { force: true });
1021
+ } catch {}
1022
+ }
1023
+ async syncDirectory(directory) {
1024
+ if (!this.directorySync) return;
1025
+ try {
1026
+ await AsyncDiskStorageDriver.syncDirectoryStatic(directory);
1027
+ } catch (error) {
1028
+ if ([
1029
+ "EINVAL",
1030
+ "ENOTSUP",
1031
+ "EBADF",
1032
+ "EISDIR",
1033
+ "EPERM"
1034
+ ].includes(nodeErrorCode(error) ?? "")) this.directorySync = false;
1035
+ else throw error;
1036
+ }
1037
+ }
1038
+ static async syncDirectoryStatic(directory) {
1039
+ const handle = await open(directory, "r");
1040
+ try {
1041
+ await handle.sync();
1042
+ } finally {
1043
+ await handle.close();
1044
+ }
1045
+ }
1046
+ async cleanupFailedOpen() {
1047
+ const failures = [];
1048
+ try {
1049
+ if (this.journal) await this.journal.close();
1050
+ } catch (error) {
1051
+ failures.push(error);
1052
+ }
1053
+ if (failures.length == 0) try {
1054
+ await this.ownership.release();
1055
+ } catch (error) {
1056
+ failures.push(error);
1057
+ }
1058
+ if (failures.length == 1) throw failures[0];
1059
+ if (failures.length > 1) throw new AggregateError(failures, "Failed storage initialization cleanup");
1060
+ }
1061
+ };
1062
+ export { AsyncDiskStorageDriver };
1063
+
1064
+ //# sourceMappingURL=index.js.map