@duraxis/storage-disk 0.2.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @duraxis/storage-disk changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 6377fde: Add framework-independent configuration and owned database/ORM factories, bounded decorated-entity discovery, and shared NestJS/CLI schema resolution. Initialize projects with one source-root configuration and direct AST-guided AppModule integration. Support static inspection/mutation, centralized named connections, registry-free generators and source/compiled deployments without runtime CLI dependencies. Use shared typed configuration across runtime and CLI, standard Nest feature modules, and authenticated encrypted cursors. Document storage, migration, discovery and lifecycle contracts.
8
+ - Updated dependencies [6377fde]
9
+ - @duraxis/storage@0.2.1
10
+
3
11
  ## 0.2.0
4
12
 
5
13
  ### Minor Changes
package/README.md CHANGED
@@ -53,7 +53,7 @@ process identity.
53
53
 
54
54
  ## Recovery modes
55
55
 
56
- The default remains conservative and backward-compatible:
56
+ The default remains conservative:
57
57
 
58
58
  ```ts
59
59
  await AsyncDiskStorageDriver.open({
@@ -173,3 +173,7 @@ failure model and storage stack of each deployment.
173
173
  ## Production resource and lifecycle limits
174
174
 
175
175
  See the [production hardening guide](../../docs/PRODUCTION-HARDENING.md) for bounded defaults, cancellation, verified maintenance, tenant trust boundaries, encrypted cursors, upgrade instructions and remaining pilot limitations. Core rejects storage adapters without bounded-read capability; destructive shared-storage garbage collection is unsupported.
176
+
177
+ ## Shared application configuration
178
+
179
+ Storage drivers remain independently usable. The [shared configuration guide](../../docs/CLI-SETUP.md) shows minimal memory, asynchronous disk, S3 and custom-driver configurations for standalone and NestJS applications. Configuration factories preserve existing conditional-operation, bounded-read, ownership and resource-limit guarantees.
package/dist/index.cjs CHANGED
@@ -940,7 +940,7 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
940
940
  this.metrics.lists++;
941
941
  const result = [];
942
942
  for (const [key, value] of this.entries) if (key.startsWith(prefix)) {
943
- if (result.length >= 1e5) throw new _duraxis_storage.StorageError("Legacy listing limit exceeded; use iterate()", "RESOURCE_LIMIT");
943
+ if (result.length >= 1e5) throw new _duraxis_storage.StorageError("Listing limit exceeded; use iterate()", "RESOURCE_LIMIT");
944
944
  result.push({
945
945
  key,
946
946
  version: value.version,
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["createHash","StorageError","parseRecord","StorageError","writeAll","open","stat","readFile","unlink","join","randomUUID","hostname","readlink","statfs","stat","StorageError","resolve","mkdir","realpath","join","open","truncate","readFile","randomUUID","dirname","rename","opendir","basename","rm"],"sources":["../src/disk-format.ts","../src/ownership.ts","../src/async-disk-storage.driver.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { StorageError } from \"@duraxis/storage\";\n\nconst OBJECT_MAGIC = Buffer.from(\"DXOBJ001\", \"ascii\");\nconst MAX_HEADER_BYTES = 16 * 1024;\nexport const MAX_JOURNAL_FRAME_BYTES = 64 * 1024;\n\nexport interface StoredMetadata {\n readonly version: string;\n readonly createdAt: number;\n readonly size: number;\n readonly digest: string;\n}\n\nexport type JournalPayload =\n | ({\n readonly format: 1;\n readonly sequence: number;\n readonly op: \"put\";\n readonly key: string;\n } & StoredMetadata)\n | { readonly format: 1; readonly sequence: number; readonly op: \"delete\"; readonly key: string };\n\nexport interface DecodedJournal {\n readonly frames: readonly JournalPayload[];\n readonly validBytes: number;\n readonly incompleteTail: boolean;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nexport function sha256(data: Uint8Array | string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\nfunction corruption(message: string, cause?: unknown): StorageError {\n return new StorageError(message, \"CORRUPTION\", cause == null ? undefined : { cause });\n}\n\nfunction parseRecord(bytes: Uint8Array, label: string): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(decoder.decode(bytes));\n if (!value || typeof value != \"object\" || Array.isArray(value))\n throw new Error(\"not an object\");\n return value as Record<string, unknown>;\n } catch (cause) {\n throw corruption(`Invalid ${label}`, cause);\n }\n}\n\nfunction validDigest(value: unknown): value is string {\n return typeof value == \"string\" && /^[0-9a-f]{64}$/.test(value);\n}\n\nfunction validateMetadata(\n value: Record<string, unknown>,\n): asserts value is Record<string, unknown> & StoredMetadata {\n if (\n typeof value.version != \"string\" ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(\n value.version,\n ) ||\n !Number.isSafeInteger(value.createdAt) ||\n (value.createdAt as number) < 0 ||\n !Number.isSafeInteger(value.size) ||\n (value.size as number) < 0 ||\n !validDigest(value.digest)\n )\n throw corruption(\"Invalid physical object metadata\");\n}\n\nexport function encodePhysicalObject(\n key: string,\n metadata: StoredMetadata,\n data: Uint8Array,\n): Uint8Array {\n const headerPayload = {\n format: 1 as const,\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n };\n const canonical = JSON.stringify(headerPayload);\n const header = encoder.encode(JSON.stringify({ ...headerPayload, checksum: sha256(canonical) }));\n if (header.byteLength > MAX_HEADER_BYTES)\n throw new StorageError(\"Object metadata is too large\", \"RESOURCE_LIMIT\");\n const result = new Uint8Array(OBJECT_MAGIC.length + 4 + header.length + data.length);\n result.set(OBJECT_MAGIC, 0);\n new DataView(result.buffer).setUint32(OBJECT_MAGIC.length, header.length, false);\n result.set(header, OBJECT_MAGIC.length + 4);\n result.set(data, OBJECT_MAGIC.length + 4 + header.length);\n return result;\n}\n\nexport function decodePhysicalObject(\n bytes: Uint8Array,\n expectedKey: string,\n expected: StoredMetadata,\n): Uint8Array {\n if (\n bytes.byteLength < OBJECT_MAGIC.length + 4 ||\n !Buffer.from(bytes.subarray(0, OBJECT_MAGIC.length)).equals(OBJECT_MAGIC)\n )\n throw corruption(\"Invalid physical object magic\");\n const headerLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(\n OBJECT_MAGIC.length,\n false,\n );\n if (\n headerLength == 0 ||\n headerLength > MAX_HEADER_BYTES ||\n OBJECT_MAGIC.length + 4 + headerLength > bytes.byteLength\n )\n throw corruption(\"Invalid physical object header length\");\n const header = parseRecord(\n bytes.subarray(OBJECT_MAGIC.length + 4, OBJECT_MAGIC.length + 4 + headerLength),\n \"physical object header\",\n );\n const fields = Object.keys(header).sort().join(\",\");\n if (\n fields != \"checksum,createdAt,digest,format,key,size,version\" ||\n header.format != 1 ||\n typeof header.key != \"string\" ||\n typeof header.checksum != \"string\"\n )\n throw corruption(\"Invalid physical object header\");\n validateMetadata(header);\n const canonical = JSON.stringify({\n format: 1,\n key: header.key,\n version: header.version,\n createdAt: header.createdAt,\n size: header.size,\n digest: header.digest,\n });\n if (sha256(canonical) != header.checksum)\n throw corruption(\"Physical metadata integrity check failed\");\n if (\n header.key != expectedKey ||\n header.version != expected.version ||\n header.createdAt != expected.createdAt ||\n header.size != expected.size ||\n header.digest != expected.digest\n )\n throw corruption(\"Physical object does not match journal metadata\");\n const data = bytes.subarray(OBJECT_MAGIC.length + 4 + headerLength);\n if (data.byteLength != expected.size || sha256(data) != expected.digest)\n throw corruption(\"Physical object payload integrity check failed\");\n return new Uint8Array(data);\n}\n\nexport function encodeJournalFrame(payload: JournalPayload): Uint8Array {\n const canonical = JSON.stringify(payload);\n const body = encoder.encode(JSON.stringify({ ...payload, checksum: sha256(canonical) }));\n if (body.byteLength > MAX_JOURNAL_FRAME_BYTES)\n throw new StorageError(\"Journal frame is too large\", \"RESOURCE_LIMIT\");\n const result = new Uint8Array(4 + body.byteLength);\n new DataView(result.buffer).setUint32(0, body.byteLength, false);\n result.set(body, 4);\n return result;\n}\n\nfunction decodeFrame(bytes: Uint8Array, expectedSequence: number): JournalPayload {\n const record = parseRecord(bytes, \"storage journal frame\");\n if (\n record.format != 1 ||\n record.sequence != expectedSequence ||\n (record.op != \"put\" && record.op != \"delete\") ||\n typeof record.key != \"string\" ||\n typeof record.checksum != \"string\"\n )\n throw corruption(\"Invalid storage journal frame\");\n let payload: JournalPayload;\n if (record.op == \"put\") {\n if (\n Object.keys(record).sort().join(\",\") !=\n \"checksum,createdAt,digest,format,key,op,sequence,size,version\"\n )\n throw corruption(\"Invalid put journal frame layout\");\n validateMetadata(record);\n payload = {\n format: 1,\n sequence: expectedSequence,\n op: \"put\",\n key: record.key,\n version: record.version,\n createdAt: record.createdAt,\n size: record.size,\n digest: record.digest,\n };\n } else {\n if (Object.keys(record).sort().join(\",\") != \"checksum,format,key,op,sequence\")\n throw corruption(\"Invalid delete journal frame layout\");\n payload = { format: 1, sequence: expectedSequence, op: \"delete\", key: record.key };\n }\n if (sha256(JSON.stringify(payload)) != record.checksum)\n throw corruption(\"Storage journal integrity check failed\");\n return payload;\n}\n\nexport function decodeJournal(bytes: Uint8Array): DecodedJournal {\n const frames: JournalPayload[] = [];\n let offset = 0;\n let sequence = 1;\n while (offset < bytes.byteLength) {\n if (bytes.byteLength - offset < 4) return { frames, validBytes: offset, incompleteTail: true };\n const length = new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(0, false);\n if (length == 0 || length > MAX_JOURNAL_FRAME_BYTES)\n throw corruption(\"Invalid storage journal frame length\");\n if (bytes.byteLength - offset - 4 < length)\n return { frames, validBytes: offset, incompleteTail: true };\n frames.push(decodeFrame(bytes.subarray(offset + 4, offset + 4 + length), sequence++));\n offset += 4 + length;\n }\n return { frames, validBytes: offset, incompleteTail: false };\n}\n\nexport async function replayJournal(\n handle: {\n stat(): Promise<{ readonly size: number }>;\n read(\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): Promise<{ readonly bytesRead: number }>;\n },\n maxBytes: number,\n consume: (payload: JournalPayload) => void,\n): Promise<Omit<DecodedJournal, \"frames\">> {\n const info = await handle.stat();\n\n if (info.size > maxBytes)\n throw new StorageError(\"Storage journal exceeds configured limit\", \"RESOURCE_LIMIT\");\n\n let offset = 0;\n let sequence = 1;\n\n const read = async (buffer: Uint8Array, position: number) => {\n let received = 0;\n\n while (received < buffer.byteLength) {\n const result = await handle.read(\n buffer,\n received,\n buffer.byteLength - received,\n position + received,\n );\n\n if (!result.bytesRead) break;\n\n received += result.bytesRead;\n }\n\n return received;\n };\n\n while (offset < info.size) {\n const header = new Uint8Array(4);\n\n if ((await read(header, offset)) != 4) return { validBytes: offset, incompleteTail: true };\n\n const length = new DataView(header.buffer).getUint32(0, false);\n\n if (!length || length > MAX_JOURNAL_FRAME_BYTES)\n throw corruption(\"Invalid storage journal frame length\");\n\n const payload = new Uint8Array(length);\n\n if ((await read(payload, offset + 4)) != length)\n return { validBytes: offset, incompleteTail: true };\n\n consume(decodeFrame(payload, sequence++));\n\n offset += 4 + length;\n }\n\n return { validBytes: offset, incompleteTail: false };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { open, readFile, readlink, stat, statfs, unlink, type FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { join } from \"node:path\";\nimport { StorageError } from \"@duraxis/storage\";\nimport { sha256 } from \"./disk-format.js\";\n\nconst LOCK_FILE = \".duraxis-owner.lock\";\nconst RECOVERY_GUARD_FILE = \".duraxis-owner.recovery\";\nconst OWNERSHIP_CONFIRMATION = \"I_HAVE_VERIFIED_EXCLUSIVE_ACCESS\";\nconst OWNER_FIELDS = \"applicationId,checksum,createdAt,format,hostname,ownerId,pid,processIdentity\";\nconst GUARD_FIELDS = \"checksum,createdAt,format,guardId,hostname,pid\";\nconst 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}$/;\nconst APPLICATION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._:/-]{0,126}[A-Za-z0-9])?$/;\nconst PROCESS_IDENTITY_PATTERN = /^(?:linux:(?:pid:\\[\\d+\\]|unavailable)|[a-z0-9]+:unverified)$/;\nconst MAX_METADATA_BYTES = 4096;\n\nconst LINUX_LOCAL_FILESYSTEMS = new Set([\n 0x0000ef53, // ext2/3/4\n 0x01021994, // tmpfs\n 0x2fc12fc1, // zfs\n 0x58465342, // xfs\n 0x794c7630, // overlayfs\n 0x858458f6, // ramfs\n 0x9123683e, // btrfs\n]);\n\nexport interface OwnershipRecoveryOptions {\n readonly mode: \"manual\" | \"dead-process\";\n readonly applicationId?: string;\n}\n\nexport interface RecoverOwnershipOptions {\n readonly directory: string;\n readonly confirmation: typeof OWNERSHIP_CONFIRMATION;\n}\n\nexport interface NormalizedOwnershipRecovery {\n readonly mode: \"manual\" | \"dead-process\";\n readonly applicationId?: string;\n}\n\ninterface OwnerPayload {\n readonly format: 2;\n readonly ownerId: string;\n readonly pid: number;\n readonly hostname: string;\n readonly createdAt: number;\n readonly applicationId: string | null;\n readonly processIdentity: string;\n}\n\ninterface OwnerRecord extends OwnerPayload {\n readonly checksum: string;\n}\n\ninterface GuardPayload {\n readonly format: 1;\n readonly guardId: string;\n readonly pid: number;\n readonly hostname: string;\n readonly createdAt: number;\n}\n\ninterface GuardRecord extends GuardPayload {\n readonly checksum: string;\n}\n\ninterface ObservedFile {\n readonly path: string;\n readonly handle: FileHandle;\n readonly identity: Stats;\n readonly bytes: Buffer;\n}\n\ninterface CoordinationGuard {\n readonly path: string;\n readonly handle: FileHandle;\n readonly identity: Stats;\n readonly bytes: Buffer;\n readonly guardId: string;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return error && typeof error == \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n}\n\nfunction ownershipConflict(message: string, cause?: unknown): StorageError {\n return new StorageError(message, \"OWNERSHIP_CONFLICT\", cause == null ? undefined : { cause });\n}\n\nfunction canonicalOwner(payload: OwnerPayload): string {\n return JSON.stringify(payload);\n}\n\nfunction canonicalGuard(payload: GuardPayload): string {\n return JSON.stringify(payload);\n}\n\nfunction validHostname(value: unknown): value is string {\n return (\n typeof value == \"string\" &&\n value.length > 0 &&\n value.length <= 255 &&\n !/[\\0-\\x1f\\x7f]/.test(value)\n );\n}\n\nfunction sameIdentity(left: Stats, right: Stats): boolean {\n return left.dev == right.dev && left.ino == right.ino;\n}\n\nasync function writeAll(handle: FileHandle, bytes: Uint8Array): Promise<void> {\n let offset = 0;\n\n while (offset < bytes.byteLength) {\n const result = await handle.write(bytes, offset, bytes.byteLength - offset, offset);\n\n if (result.bytesWritten <= 0)\n throw new StorageError(\"Ownership metadata write made no progress\", \"UNAVAILABLE\");\n\n offset += result.bytesWritten;\n }\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n let handle: FileHandle | undefined;\n\n try {\n handle = await open(directory, \"r\");\n await handle.sync();\n } catch (error) {\n if (![\"EINVAL\", \"ENOTSUP\", \"EBADF\", \"EISDIR\", \"EPERM\"].includes(errorCode(error) ?? \"\"))\n throw error;\n } finally {\n await handle?.close();\n }\n}\n\nasync function observe(path: string): Promise<ObservedFile | null> {\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"r\");\n } catch (error) {\n if (errorCode(error) == \"ENOENT\") return null;\n throw error;\n }\n\n try {\n const identity = await handle.stat();\n const bytes = await handle.readFile();\n\n return { path, handle, identity, bytes };\n } catch (error) {\n await handle.close().catch(() => undefined);\n throw error;\n }\n}\n\nasync function assertObservedUnchanged(observed: ObservedFile): Promise<void> {\n let currentIdentity: Stats;\n let currentBytes: Buffer;\n\n try {\n [currentIdentity, currentBytes] = await Promise.all([\n stat(observed.path),\n readFile(observed.path),\n ]);\n } catch (cause) {\n throw ownershipConflict(\"Ownership metadata changed during inspection\", cause);\n }\n\n if (!sameIdentity(observed.identity, currentIdentity) || !observed.bytes.equals(currentBytes))\n throw ownershipConflict(\"Ownership metadata changed during inspection\");\n}\n\nasync function removeObserved(observed: ObservedFile): Promise<void> {\n try {\n await assertObservedUnchanged(observed);\n } finally {\n await observed.handle.close();\n }\n\n try {\n await unlink(observed.path);\n } catch (cause) {\n throw ownershipConflict(\"Failed to remove the observed ownership lock\", cause);\n }\n}\n\nasync function removeCreatedFile(path: string, handle: FileHandle, identity: Stats): Promise<void> {\n await handle.close().catch(() => undefined);\n\n try {\n const current = await stat(path);\n\n if (!sameIdentity(identity, current))\n throw ownershipConflict(\"Created ownership file was replaced unexpectedly\");\n\n await unlink(path);\n } catch (error) {\n if (errorCode(error) != \"ENOENT\") throw error;\n }\n}\n\nfunction parseRecord(bytes: Uint8Array, label: string): Record<string, unknown> {\n if (bytes.byteLength == 0 || bytes.byteLength > MAX_METADATA_BYTES)\n throw ownershipConflict(`Invalid ${label}`);\n\n try {\n const value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (!value || typeof value != \"object\" || Array.isArray(value))\n throw new Error(\"not an object\");\n\n return value as Record<string, unknown>;\n } catch (cause) {\n throw ownershipConflict(`Invalid ${label}`, cause);\n }\n}\n\nfunction parseOwner(bytes: Uint8Array): OwnerRecord {\n const record = parseRecord(bytes, \"owner lock metadata\");\n\n if (record.format != 2)\n throw ownershipConflict(\n \"Owner lock format is incompatible with automatic recovery; use explicit manual recovery\",\n );\n\n if (\n Object.keys(record).sort().join(\",\") != OWNER_FIELDS ||\n !UUID_PATTERN.test(String(record.ownerId)) ||\n !Number.isSafeInteger(record.pid) ||\n (record.pid as number) <= 0 ||\n !validHostname(record.hostname) ||\n !Number.isSafeInteger(record.createdAt) ||\n (record.createdAt as number) < 0 ||\n (record.applicationId !== null &&\n (typeof record.applicationId != \"string\" ||\n !APPLICATION_ID_PATTERN.test(record.applicationId))) ||\n typeof record.processIdentity != \"string\" ||\n !PROCESS_IDENTITY_PATTERN.test(record.processIdentity) ||\n typeof record.checksum != \"string\" ||\n !/^[0-9a-f]{64}$/.test(record.checksum)\n )\n throw ownershipConflict(\"Invalid owner lock metadata\");\n\n const payload: OwnerPayload = {\n format: 2,\n ownerId: record.ownerId as string,\n pid: record.pid as number,\n hostname: record.hostname,\n createdAt: record.createdAt as number,\n applicationId: record.applicationId as string | null,\n processIdentity: record.processIdentity,\n };\n\n if (sha256(canonicalOwner(payload)) != record.checksum)\n throw ownershipConflict(\"Owner lock metadata checksum is invalid\");\n\n return { ...payload, checksum: record.checksum };\n}\n\nfunction parseGuard(bytes: Uint8Array): GuardRecord {\n const record = parseRecord(bytes, \"ownership recovery guard\");\n\n if (\n Object.keys(record).sort().join(\",\") != GUARD_FIELDS ||\n record.format != 1 ||\n !UUID_PATTERN.test(String(record.guardId)) ||\n !Number.isSafeInteger(record.pid) ||\n (record.pid as number) <= 0 ||\n !validHostname(record.hostname) ||\n !Number.isSafeInteger(record.createdAt) ||\n (record.createdAt as number) < 0 ||\n typeof record.checksum != \"string\" ||\n !/^[0-9a-f]{64}$/.test(record.checksum)\n )\n throw ownershipConflict(\"Invalid ownership recovery guard\");\n\n const payload: GuardPayload = {\n format: 1,\n guardId: record.guardId as string,\n pid: record.pid as number,\n hostname: record.hostname,\n createdAt: record.createdAt as number,\n };\n\n if (sha256(canonicalGuard(payload)) != record.checksum)\n throw ownershipConflict(\"Ownership recovery guard checksum is invalid\");\n\n return { ...payload, checksum: record.checksum };\n}\n\nasync function acquireGuard(root: string): Promise<CoordinationGuard> {\n const path = join(root, RECOVERY_GUARD_FILE);\n\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"wx\", 0o600);\n } catch (cause) {\n if (errorCode(cause) == \"EEXIST\")\n throw ownershipConflict(\n \"Another ownership operation is active or left an uncertain recovery guard\",\n cause,\n );\n\n throw cause;\n }\n let identity: Stats;\n try {\n identity = await handle.stat();\n } catch (cause) {\n await handle.close().catch(() => undefined);\n\n throw cause;\n }\n\n const payload: GuardPayload = {\n format: 1,\n guardId: randomUUID(),\n pid: process.pid,\n hostname: hostname(),\n createdAt: Date.now(),\n };\n\n const bytes = Buffer.from(\n JSON.stringify({ ...payload, checksum: sha256(canonicalGuard(payload)) }),\n );\n\n try {\n await writeAll(handle, bytes);\n await handle.sync();\n await syncDirectory(root);\n\n return { path, handle, identity, bytes, guardId: payload.guardId };\n } catch (cause) {\n try {\n await removeCreatedFile(path, handle, identity);\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Ownership guard creation and cleanup both failed\",\n );\n }\n throw cause;\n }\n}\n\nasync function releaseGuard(root: string, guard: CoordinationGuard): Promise<void> {\n try {\n const currentIdentity = await stat(guard.path);\n const currentBytes = await readFile(guard.path);\n const record = parseGuard(currentBytes);\n\n if (\n !sameIdentity(guard.identity, currentIdentity) ||\n !guard.bytes.equals(currentBytes) ||\n record.guardId != guard.guardId\n )\n throw ownershipConflict(\"Ownership recovery guard changed unexpectedly\");\n } finally {\n await guard.handle.close();\n }\n\n await unlink(guard.path);\n await syncDirectory(root);\n}\n\nasync function withGuard<T>(root: string, operation: () => Promise<T>): Promise<T> {\n const guard = await acquireGuard(root);\n let result: T | undefined;\n let operationFailure: unknown;\n\n try {\n result = await operation();\n } catch (error) {\n operationFailure = error;\n }\n\n try {\n await releaseGuard(root, guard);\n } catch (guardFailure) {\n if (operationFailure != null)\n throw new AggregateError(\n [operationFailure, guardFailure],\n \"Ownership operation and recovery-guard release both failed\",\n );\n\n throw guardFailure;\n }\n\n if (operationFailure != null) throw operationFailure;\n\n return result as T;\n}\n\nasync function automaticProcessIdentity(root: string): Promise<string> {\n if (process.platform != \"linux\")\n throw ownershipConflict(\n \"Automatic dead-process recovery is supported only on validated Linux environments\",\n );\n\n let namespace: string;\n\n try {\n namespace = await readlink(\"/proc/self/ns/pid\");\n } catch (cause) {\n throw ownershipConflict(\"The Linux PID namespace cannot be established\", cause);\n }\n\n if (!/^pid:\\[\\d+\\]$/.test(namespace))\n throw ownershipConflict(\"The Linux PID namespace identity is invalid\");\n\n let filesystemType: number;\n\n try {\n filesystemType = (await statfs(root)).type >>> 0;\n } catch (cause) {\n throw ownershipConflict(\"The storage filesystem type cannot be established\", cause);\n }\n\n if (!LINUX_LOCAL_FILESYSTEMS.has(filesystemType))\n throw ownershipConflict(\n `Automatic recovery is not supported on filesystem type 0x${filesystemType.toString(16)}`,\n );\n\n return `linux:${namespace}`;\n}\n\nasync function processIdentityForLock(root: string, mode: \"manual\" | \"dead-process\") {\n if (mode == \"dead-process\") return await automaticProcessIdentity(root);\n\n if (process.platform == \"linux\") {\n try {\n return `linux:${await readlink(\"/proc/self/ns/pid\")}`;\n } catch {\n return \"linux:unavailable\";\n }\n }\n return `${process.platform}:unverified`;\n}\n\nfunction assertRecoverableOwner(\n owner: OwnerRecord,\n recovery: NormalizedOwnershipRecovery,\n processIdentity: string,\n): void {\n if (owner.hostname != hostname())\n throw ownershipConflict(\"Owner lock belongs to a different host\");\n\n if (owner.processIdentity != processIdentity)\n throw ownershipConflict(\"Owner lock belongs to a different or unsupported process namespace\");\n\n if (owner.applicationId != (recovery.applicationId ?? null))\n throw ownershipConflict(\"Owner lock belongs to a different application identity\");\n\n try {\n process.kill(owner.pid, 0);\n } catch (cause) {\n if (errorCode(cause) == \"ESRCH\") return;\n\n if (errorCode(cause) == \"EPERM\")\n throw ownershipConflict(\"Owner process existence is inconclusive\", cause);\n\n throw ownershipConflict(\"Owner process existence could not be determined\", cause);\n }\n\n throw ownershipConflict(\n \"Owner process may still be running; PID reuse is treated as an ownership conflict\",\n );\n}\n\nasync function createOwnerFile(\n root: string,\n ownerId: string,\n recovery: NormalizedOwnershipRecovery,\n processIdentity: string,\n): Promise<{ handle: FileHandle; identity: Stats } | null> {\n const path = join(root, LOCK_FILE);\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"wx\", 0o600);\n } catch (error) {\n if (errorCode(error) == \"EEXIST\") return null;\n throw error;\n }\n\n let identity: Stats;\n\n try {\n identity = await handle.stat();\n } catch (cause) {\n await handle.close().catch(() => undefined);\n throw cause;\n }\n\n const payload: OwnerPayload = {\n format: 2,\n ownerId,\n pid: process.pid,\n hostname: hostname(),\n createdAt: Date.now(),\n applicationId: recovery.applicationId ?? null,\n processIdentity,\n };\n\n const bytes = Buffer.from(\n JSON.stringify({ ...payload, checksum: sha256(canonicalOwner(payload)) }),\n );\n\n try {\n await writeAll(handle, bytes);\n await handle.sync();\n await syncDirectory(root);\n return { handle, identity };\n } catch (cause) {\n try {\n await removeCreatedFile(path, handle, identity);\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Owner lock creation and cleanup both failed\",\n );\n }\n\n throw cause;\n }\n}\n\nexport function normalizeOwnershipRecovery(\n options: OwnershipRecoveryOptions | undefined,\n): NormalizedOwnershipRecovery {\n if (options == null) return { mode: \"manual\" };\n\n if (options.mode != \"manual\" && options.mode != \"dead-process\")\n throw new TypeError('ownershipRecovery.mode must be \"manual\" or \"dead-process\"');\n\n if (\n options.applicationId != null &&\n (typeof options.applicationId != \"string\" ||\n !APPLICATION_ID_PATTERN.test(options.applicationId))\n )\n throw new TypeError(\"ownershipRecovery.applicationId must be 1-128 safe identifier characters\");\n\n return {\n mode: options.mode,\n ...(options.applicationId == null ? {} : { applicationId: options.applicationId }),\n };\n}\n\nexport class DirectoryOwnership {\n readonly #ownerId = randomUUID();\n #lockHandle?: FileHandle;\n #owned = false;\n\n public constructor(\n private readonly root: string,\n private readonly recovery: NormalizedOwnershipRecovery,\n ) {}\n\n public get isOwned(): boolean {\n return this.#owned;\n }\n\n public async acquire(): Promise<void> {\n const processIdentity = await processIdentityForLock(this.root, this.recovery.mode);\n\n await withGuard(this.root, async () => {\n let created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);\n if (!created) {\n if (this.recovery.mode == \"manual\")\n throw ownershipConflict(\n \"Storage directory has an owner lock; close the owner or perform explicit abandoned-lock recovery\",\n );\n\n const observed = await observe(join(this.root, LOCK_FILE));\n\n if (observed) {\n let owner: OwnerRecord;\n\n try {\n owner = parseOwner(observed.bytes);\n assertRecoverableOwner(owner, this.recovery, processIdentity);\n await removeObserved(observed);\n } catch (error) {\n await observed.handle.close().catch(() => undefined);\n throw error;\n }\n\n await syncDirectory(this.root);\n }\n\n created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);\n\n if (!created)\n throw ownershipConflict(\"Another process acquired storage ownership during recovery\");\n }\n this.#lockHandle = created.handle;\n this.#owned = true;\n });\n }\n\n public async verify(): Promise<void> {\n if (!this.#owned) throw ownershipConflict(\"Storage directory is not owned\");\n\n await withGuard(this.root, async () => {\n const observed = await observe(join(this.root, LOCK_FILE));\n\n if (!observed) throw ownershipConflict(\"Storage owner lock is missing\");\n\n try {\n if (parseOwner(observed.bytes).ownerId != this.#ownerId)\n throw ownershipConflict(\"Storage ownership changed\");\n\n await assertObservedUnchanged(observed);\n } finally {\n await observed.handle.close();\n }\n });\n }\n\n public async release(): Promise<void> {\n if (!this.#owned) return;\n\n await withGuard(this.root, async () => {\n const observed = await observe(join(this.root, LOCK_FILE));\n if (!observed) {\n this.#owned = false;\n await this.#lockHandle?.close().catch(() => undefined);\n\n this.#lockHandle = undefined;\n throw ownershipConflict(\"Current owner lock is missing\");\n }\n\n try {\n const owner = parseOwner(observed.bytes);\n\n if (owner.ownerId != this.#ownerId)\n throw ownershipConflict(\"Storage ownership changed unexpectedly\");\n\n await this.#lockHandle?.close();\n this.#lockHandle = undefined;\n\n await removeObserved(observed);\n this.#owned = false;\n\n await syncDirectory(this.root);\n } catch (error) {\n await observed.handle.close().catch(() => undefined);\n throw error;\n }\n });\n }\n}\n\nexport async function manuallyRecoverOwnership(root: string): Promise<void> {\n await withGuard(root, async () => {\n const observed = await observe(join(root, LOCK_FILE));\n if (!observed) return;\n await removeObserved(observed);\n await syncDirectory(root);\n });\n}\n\nexport function validateManualRecoveryConfirmation(\n confirmation: RecoverOwnershipOptions[\"confirmation\"],\n): void {\n if (confirmation != OWNERSHIP_CONFIRMATION)\n throw new StorageError(\"Explicit exclusive-access confirmation is required\", \"ACCESS_DENIED\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport {\n mkdir,\n open,\n readFile,\n opendir,\n realpath,\n rename,\n rm,\n stat,\n truncate,\n type FileHandle,\n} from \"node:fs/promises\";\nimport {\n assertStorageKey,\n assertWriteCondition,\n StorageError,\n type DeleteOptions,\n type DeleteResult,\n type StorageDriver,\n type StorageDriverMetrics,\n type StorageObject,\n type StorageObjectInfo,\n type WriteOptions,\n type WriteResult,\n} from \"@duraxis/storage\";\nimport {\n replayJournal,\n decodePhysicalObject,\n encodeJournalFrame,\n encodePhysicalObject,\n sha256,\n type JournalPayload,\n type StoredMetadata,\n} from \"./disk-format.js\";\nimport {\n DirectoryOwnership,\n manuallyRecoverOwnership,\n normalizeOwnershipRecovery,\n validateManualRecoveryConfirmation,\n type NormalizedOwnershipRecovery,\n type OwnershipRecoveryOptions,\n type RecoverOwnershipOptions,\n} from \"./ownership.js\";\n\nconst JOURNAL_FILE = \"journal.log\";\nconst PREVIOUS_JOURNAL = \"journal.previous\";\nconst NEXT_JOURNAL = \"journal.next\";\nconst OBJECTS_DIRECTORY = \"objects\";\n\nconst MAX_KEY_BYTES = 4096;\nconst MAX_OBJECT_BYTES = 256 * 1024 * 1024;\nconst MAX_JOURNAL_BYTES = 1024 * 1024 * 1024;\n\nexport type { OwnershipRecoveryOptions, RecoverOwnershipOptions } from \"./ownership.js\";\n\nexport type DiskFaultPoint =\n | \"after-object-sync\"\n | \"after-object-publish\"\n | \"after-object-directory-sync\"\n | \"after-journal-write\"\n | \"after-journal-sync\"\n | \"after-journal-rotation\";\n\nexport interface DiskFaultContext {\n readonly operation: \"put\" | \"delete\" | \"compact\";\n readonly key?: string;\n}\n\nexport interface AsyncDiskStorageOptions {\n readonly directory: string;\n readonly ownershipRecovery?: OwnershipRecoveryOptions;\n readonly maxKeyBytes?: number;\n readonly maxObjectBytes?: number;\n readonly maxJournalBytes?: number;\n readonly maxMetadataBytes?: number;\n readonly maxQueuedOperations?: number;\n readonly nodeCacheHint?: number;\n readonly faultInjector?: (\n point: DiskFaultPoint,\n context: DiskFaultContext,\n ) => void | Promise<void>;\n}\n\nexport interface DiskDurabilityCapabilities {\n readonly fileDataSync: true;\n readonly directoryEntrySync: boolean;\n readonly ownership: \"exclusive-directory\";\n readonly processCrashRecovery: true;\n readonly powerLossGuarantee: \"file-and-directory-sync\" | \"file-sync-only\";\n}\n\ninterface MutableMetrics {\n reads: number;\n writes: number;\n deletes: number;\n lists: number;\n bytesRead: number;\n bytesWritten: number;\n synchronizationWaitMs: number;\n}\n\nfunction nodeErrorCode(error: unknown): string | undefined {\n return error && typeof error == \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\") return false;\n throw error;\n }\n}\n\nasync function writeAll(handle: FileHandle, bytes: Uint8Array, position = 0): Promise<void> {\n let offset = 0;\n\n while (offset < bytes.byteLength) {\n const result = await handle.write(bytes, offset, bytes.byteLength - offset, position + offset);\n\n if (result.bytesWritten <= 0)\n throw new StorageError(\"Disk write made no progress\", \"UNAVAILABLE\");\n\n offset += result.bytesWritten;\n }\n}\n\nasync function syncAndClose(handle: FileHandle, context: string): Promise<void> {\n let syncFailure: unknown;\n\n try {\n await handle.sync();\n } catch (error) {\n syncFailure = error;\n }\n\n try {\n await handle.close();\n } catch (closeFailure) {\n if (syncFailure != null)\n throw new AggregateError(\n [syncFailure, closeFailure],\n `${context} sync and close both failed`,\n );\n\n throw closeFailure;\n }\n\n if (syncFailure != null) throw syncFailure;\n}\n\nexport class AsyncDiskStorageDriver implements StorageDriver {\n public readonly capabilities = Object.freeze({ boundedReads: true });\n private static readonly activeDirectories = new Set<string>();\n\n private readonly entries = new Map<string, StoredMetadata>();\n private readonly ownership: DirectoryOwnership;\n private readonly metrics: MutableMetrics = {\n reads: 0,\n writes: 0,\n deletes: 0,\n lists: 0,\n bytesRead: 0,\n bytesWritten: 0,\n synchronizationWaitMs: 0,\n };\n\n private metadataBytes = 0;\n private queuedOperations = 0;\n\n private operationTail: Promise<void> = Promise.resolve();\n private journal!: FileHandle;\n private journalBytes = 0;\n private sequence = 0;\n private directorySync = true;\n private closed = false;\n private closing = false;\n private resourcesClosed = false;\n private closePromise?: Promise<void>;\n private poisoned = false;\n\n private constructor(\n private readonly root: string,\n private readonly registryKey: string,\n private readonly options: Required<\n Pick<AsyncDiskStorageOptions, \"maxKeyBytes\" | \"maxObjectBytes\" | \"maxJournalBytes\">\n > &\n AsyncDiskStorageOptions & { readonly ownershipRecovery: NormalizedOwnershipRecovery },\n ) {\n this.ownership = new DirectoryOwnership(root, options.ownershipRecovery);\n }\n\n public static async open(options: AsyncDiskStorageOptions): Promise<AsyncDiskStorageDriver> {\n if (!options || typeof options.directory != \"string\" || options.directory.trim() == \"\")\n throw new TypeError(\"A storage directory is required\");\n\n const maxKeyBytes = options.maxKeyBytes ?? MAX_KEY_BYTES;\n const maxObjectBytes = options.maxObjectBytes ?? MAX_OBJECT_BYTES;\n const maxJournalBytes = options.maxJournalBytes ?? MAX_JOURNAL_BYTES;\n\n const ownershipRecovery = normalizeOwnershipRecovery(options.ownershipRecovery);\n\n if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes < 64 || maxKeyBytes > 64 * 1024)\n throw new RangeError(\"Invalid maximum storage key size\");\n\n if (\n !Number.isSafeInteger(maxObjectBytes) ||\n maxObjectBytes < 0 ||\n maxObjectBytes > MAX_JOURNAL_BYTES\n )\n throw new RangeError(\"Invalid maximum object size\");\n\n if (!Number.isSafeInteger(maxJournalBytes) || maxJournalBytes < 1024 * 1024)\n throw new RangeError(\"Invalid maximum journal size\");\n\n for (const value of [options.maxMetadataBytes, options.maxQueuedOperations])\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1))\n throw new RangeError(\"Invalid storage resource limit\");\n\n const requested = resolve(options.directory);\n\n await mkdir(requested, { recursive: true });\n\n const root = await realpath(requested);\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\n \"Storage directory is already owned by this process\",\n \"OWNERSHIP_CONFLICT\",\n );\n\n this.activeDirectories.add(registryKey);\n\n const driver = new AsyncDiskStorageDriver(root, registryKey, {\n ...options,\n directory: root,\n maxKeyBytes,\n maxObjectBytes,\n maxJournalBytes,\n ownershipRecovery,\n });\n\n try {\n await driver.initialize();\n return driver;\n } catch (cause) {\n try {\n await driver.cleanupFailedOpen();\n } catch (cleanupCause) {\n if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);\n throw new AggregateError(\n [cause, cleanupCause],\n \"Storage initialization and ownership cleanup both failed\",\n );\n }\n if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);\n throw cause;\n }\n }\n\n public static async recoverAbandonedOwnership(options: RecoverOwnershipOptions): Promise<void> {\n validateManualRecoveryConfirmation(options.confirmation);\n\n const root = await realpath(resolve(options.directory));\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\"Cannot recover ownership held by this process\", \"OWNERSHIP_CONFLICT\");\n\n await manuallyRecoverOwnership(root);\n }\n\n public get durability(): DiskDurabilityCapabilities {\n return {\n fileDataSync: true,\n directoryEntrySync: this.directorySync,\n ownership: \"exclusive-directory\",\n processCrashRecovery: true,\n powerLossGuarantee: this.directorySync ? \"file-and-directory-sync\" : \"file-sync-only\",\n };\n }\n\n public getMetrics(): Readonly<StorageDriverMetrics> {\n return { ...this.metrics };\n }\n\n private async initialize(): Promise<void> {\n await this.ownership.acquire();\n await mkdir(join(this.root, OBJECTS_DIRECTORY), { recursive: true });\n await this.recoverJournalRotation();\n\n const journalPath = join(this.root, JOURNAL_FILE);\n\n if (!(await exists(journalPath))) {\n const created = await open(journalPath, \"wx\", 0o600);\n await syncAndClose(created, \"New storage journal\");\n await this.syncDirectory(this.root);\n }\n\n const input = await open(journalPath, \"r\");\n let decoded: Awaited<ReturnType<typeof replayJournal>>;\n\n try {\n decoded = await replayJournal(input, this.options.maxJournalBytes, (frame) => {\n this.validateKey(frame.key);\n this.sequence = frame.sequence;\n\n if (frame.op == \"put\")\n this.setEntry(frame.key, {\n version: frame.version,\n createdAt: frame.createdAt,\n size: frame.size,\n digest: frame.digest,\n });\n else this.deleteEntry(frame.key);\n });\n } finally {\n await input.close();\n }\n\n if (decoded.incompleteTail) {\n await truncate(journalPath, decoded.validBytes);\n const repaired = await open(journalPath, \"r+\");\n await syncAndClose(repaired, \"Repaired storage journal\");\n }\n\n this.journalBytes = decoded.validBytes;\n this.journal = await open(journalPath, \"r+\");\n\n await this.assertCurrentObjectsExist();\n await this.cleanupPhysicalObjects();\n }\n\n private setEntry(key: string, value: StoredMetadata): void {\n const size = this.entries.has(key) ? 0 : key.length * 2 + 256;\n\n if (this.metadataBytes + size > (this.options.maxMetadataBytes ?? 64 * 1024 * 1024))\n throw new StorageError(\"Resident storage metadata limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.metadataBytes += size;\n this.entries.set(key, value);\n }\n\n private deleteEntry(key: string): void {\n if (this.entries.delete(key)) this.metadataBytes -= key.length * 2 + 256;\n }\n\n private validateKey(key: string): void {\n assertStorageKey(key);\n\n if (Buffer.byteLength(key, \"utf8\") > this.options.maxKeyBytes)\n throw new StorageError(\"Storage key exceeds configured byte limit\", \"INVALID_KEY\");\n }\n\n private assertUsable(): void {\n if (this.closed || this.closing) throw new StorageError(\"Storage driver is closed\", \"CLOSED\");\n\n if (this.poisoned)\n throw new StorageError(\n \"Storage outcome is unknown; close and reopen before continuing\",\n \"OUTCOME_UNKNOWN\",\n );\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n this.assertUsable();\n\n if (this.queuedOperations >= (this.options.maxQueuedOperations ?? 256))\n throw new StorageError(\"Storage operation admission limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.queuedOperations++;\n\n const before = performance.now();\n const previous = this.operationTail;\n\n let release!: () => void;\n\n this.operationTail = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await previous;\n this.metrics.synchronizationWaitMs += performance.now() - before;\n\n try {\n this.assertUsable();\n return await operation();\n } finally {\n this.queuedOperations--;\n release();\n }\n }\n\n public get(\n key: string,\n options: { readonly signal?: AbortSignal; readonly maxBytes?: number } = {},\n ): Promise<StorageObject | null> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n options.signal?.throwIfAborted();\n this.metrics.reads++;\n\n const metadata = this.entries.get(key);\n\n if (!metadata) return null;\n\n if (metadata.size > (options.maxBytes ?? this.options.maxObjectBytes))\n throw new StorageError(\"Storage read exceeds byte limit\", \"RESOURCE_LIMIT\");\n\n const path = this.objectPath(key, metadata.version);\n\n let info;\n\n try {\n info = await stat(path);\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\")\n throw new StorageError(`Missing physical object for key ${key}`, \"CORRUPTION\", {\n cause: error,\n });\n throw error;\n }\n\n if (info.size > this.options.maxObjectBytes + 32 * 1024)\n throw new StorageError(\"Physical object exceeds configured size\", \"CORRUPTION\");\n\n const physical = await readFile(path, { signal: options.signal });\n\n this.metrics.bytesRead += physical.byteLength;\n\n return { data: decodePhysicalObject(physical, key, metadata), version: metadata.version };\n });\n }\n\n public put(key: string, data: Uint8Array, options: WriteOptions): Promise<WriteResult> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n if (!(data instanceof Uint8Array)) throw new TypeError(\"Storage data must be a Uint8Array\");\n\n if (data.byteLength > this.options.maxObjectBytes)\n throw new StorageError(\"Storage object exceeds configured byte limit\", \"RESOURCE_LIMIT\");\n\n assertWriteCondition(options?.condition);\n\n const current = this.entries.get(key);\n\n if (\n options.condition.type == \"if-absent\"\n ? current != null\n : current == null || current.version != options.condition.version\n )\n return { success: false, reason: \"conflict\" };\n\n if (\n !this.entries.has(key) &&\n this.metadataBytes + key.length * 2 + 256 >\n (this.options.maxMetadataBytes ?? 64 * 1024 * 1024)\n )\n throw new StorageError(\"Resident storage metadata limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.metrics.writes++;\n\n const metadata: StoredMetadata = {\n version: randomUUID(),\n createdAt: Date.now(),\n size: data.byteLength,\n digest: sha256(data),\n };\n\n const physical = encodePhysicalObject(key, metadata, data);\n const finalPath = this.objectPath(key, metadata.version);\n const parent = dirname(finalPath);\n\n await mkdir(parent, { recursive: true });\n\n const temporary = join(parent, `.${metadata.version}.${randomUUID()}.tmp`);\n\n let published = false;\n\n try {\n const handle = await open(temporary, \"wx\", 0o600);\n\n try {\n await writeAll(handle, physical);\n await handle.sync();\n } finally {\n await handle.close();\n }\n\n await this.fault(\"after-object-sync\", { operation: \"put\", key });\n await rename(temporary, finalPath);\n\n published = true;\n\n await this.fault(\"after-object-publish\", { operation: \"put\", key });\n await this.syncDirectory(parent);\n await this.fault(\"after-object-directory-sync\", { operation: \"put\", key });\n\n const frame: JournalPayload = {\n format: 1,\n sequence: this.sequence + 1,\n op: \"put\",\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n };\n\n await this.append(frame);\n\n this.setEntry(key, metadata);\n this.sequence = frame.sequence;\n this.metrics.bytesWritten += physical.byteLength;\n\n if (current) await this.removeObsolete(this.objectPath(key, current.version));\n\n return { success: true, version: metadata.version };\n } catch (error) {\n if (!published) await this.removeObsolete(temporary);\n throw error;\n }\n });\n }\n\n public delete(key: string, options: DeleteOptions): Promise<DeleteResult> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n assertWriteCondition(options?.condition);\n\n const current = this.entries.get(key);\n\n if (options.condition.type == \"if-absent\")\n return current ? { success: false, reason: \"conflict\" } : { success: true };\n\n if (!current || current.version != options.condition.version)\n return { success: false, reason: \"conflict\" };\n\n this.metrics.deletes++;\n\n const frame: JournalPayload = {\n format: 1,\n sequence: this.sequence + 1,\n op: \"delete\",\n key,\n };\n\n await this.append(frame);\n\n this.deleteEntry(key);\n this.sequence = frame.sequence;\n\n await this.removeObsolete(this.objectPath(key, current.version));\n\n return { success: true };\n });\n }\n\n public verifyExclusiveOwnership(): Promise<void> {\n return this.exclusive(() => this.ownership.verify());\n }\n public async *iterate(\n prefix: string,\n options: { readonly pageSize?: number; readonly signal?: AbortSignal } = {},\n ): AsyncIterable<StorageObjectInfo> {\n if (typeof prefix != \"string\" || prefix.includes(\"\\0\"))\n throw new StorageError(\"Invalid storage prefix\", \"INVALID_KEY\");\n\n const size = options.pageSize ?? 256;\n\n if (!Number.isSafeInteger(size) || size < 1 || size > 1000)\n throw new RangeError(\"Invalid listing page size\");\n\n const iterator = this.entries.entries();\n\n let done = false;\n\n while (!done) {\n options.signal?.throwIfAborted();\n\n const page = await this.exclusive(async () => {\n const entries: StorageObjectInfo[] = [];\n\n let visited = 0;\n\n while (visited++ < size) {\n const next = iterator.next();\n\n if (next.done) {\n done = true;\n break;\n }\n\n const [key, value] = next.value;\n\n if (key.startsWith(prefix))\n entries.push({ key, version: value.version, createdAt: value.createdAt });\n }\n\n return entries;\n });\n\n for (const entry of page) {\n options.signal?.throwIfAborted();\n yield entry;\n }\n }\n }\n\n public list(prefix: string): Promise<readonly StorageObjectInfo[]> {\n return this.exclusive(async () => {\n if (\n typeof prefix != \"string\" ||\n prefix.includes(\"\\0\") ||\n Buffer.byteLength(prefix, \"utf8\") > this.options.maxKeyBytes\n )\n throw new StorageError(\"Invalid storage prefix\", \"INVALID_KEY\");\n\n this.metrics.lists++;\n\n const result: StorageObjectInfo[] = [];\n\n for (const [key, value] of this.entries)\n if (key.startsWith(prefix)) {\n if (result.length >= 100_000)\n throw new StorageError(\n \"Legacy listing limit exceeded; use iterate()\",\n \"RESOURCE_LIMIT\",\n );\n result.push({ key, version: value.version, createdAt: value.createdAt });\n }\n\n return result.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n });\n }\n\n private async append(frame: JournalPayload): Promise<void> {\n const encoded = encodeJournalFrame(frame);\n\n if (this.journalBytes + encoded.byteLength > this.options.maxJournalBytes)\n throw new StorageError(\n \"Storage journal limit reached; compact before writing\",\n \"RESOURCE_LIMIT\",\n );\n\n try {\n await writeAll(this.journal, encoded, this.journalBytes);\n await this.fault(\"after-journal-write\", { operation: frame.op, key: frame.key });\n await this.journal.sync();\n await this.fault(\"after-journal-sync\", { operation: frame.op, key: frame.key });\n\n this.journalBytes += encoded.byteLength;\n this.metrics.bytesWritten += encoded.byteLength;\n } catch (cause) {\n this.poisoned = true;\n throw new StorageError(\"Storage publication outcome is unknown\", \"OUTCOME_UNKNOWN\", {\n cause,\n });\n }\n }\n\n public compact(): Promise<void> {\n return this.exclusive(async () => {\n try {\n const nextPath = join(this.root, NEXT_JOURNAL);\n const previousPath = join(this.root, PREVIOUS_JOURNAL);\n const currentPath = join(this.root, JOURNAL_FILE);\n\n await this.removeObsolete(nextPath);\n await this.removeObsolete(previousPath);\n\n const next = await open(nextPath, \"wx\", 0o600);\n\n let offset = 0;\n let sequence = 0;\n\n try {\n for (const [key, metadata] of this.entries) {\n const bytes = encodeJournalFrame({\n format: 1,\n sequence: ++sequence,\n op: \"put\",\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n });\n\n if (offset + bytes.byteLength > this.options.maxJournalBytes)\n throw new StorageError(\n \"Compacted journal exceeds configured limit\",\n \"RESOURCE_LIMIT\",\n );\n\n await writeAll(next, bytes, offset);\n offset += bytes.byteLength;\n }\n\n await next.sync();\n } finally {\n await next.close();\n }\n\n await this.journal.close();\n\n await rename(currentPath, previousPath);\n await rename(nextPath, currentPath);\n\n await this.syncDirectory(this.root);\n await this.fault(\"after-journal-rotation\", { operation: \"compact\" });\n\n this.journal = await open(currentPath, \"r+\");\n this.journalBytes = offset;\n this.sequence = sequence;\n\n await this.removeObsolete(previousPath);\n } catch (cause) {\n this.poisoned = true;\n throw new StorageError(\"Journal compaction outcome is unknown\", \"OUTCOME_UNKNOWN\", {\n cause,\n });\n }\n });\n }\n\n public close(): Promise<void> {\n if (!this.ownership.isOwned && this.closed) return Promise.resolve();\n if (this.closePromise) return this.closePromise;\n\n this.closing = true;\n const attempt = this.closeAttempt();\n this.closePromise = attempt;\n\n const clearAttempt = () => {\n if (this.closePromise == attempt) this.closePromise = undefined;\n };\n\n void attempt.then(clearAttempt, clearAttempt);\n\n return attempt;\n }\n\n private async closeAttempt(): Promise<void> {\n const failures: unknown[] = [];\n await this.operationTail;\n\n try {\n if (!this.resourcesClosed) {\n try {\n if (this.journal) await this.journal.close();\n this.resourcesClosed = true;\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length == 0) {\n try {\n await this.ownership.release();\n } catch (error) {\n failures.push(error);\n }\n }\n } finally {\n this.closed = true;\n this.closing = false;\n\n if (!this.ownership.isOwned)\n AsyncDiskStorageDriver.activeDirectories.delete(this.registryKey);\n }\n\n if (failures.length == 1) throw failures[0];\n\n if (failures.length > 1)\n throw new AggregateError(failures, \"Storage shutdown encountered multiple failures\");\n }\n\n private objectPath(key: string, version: string): string {\n const hash = sha256(new TextEncoder().encode(key));\n return join(this.root, OBJECTS_DIRECTORY, hash.slice(0, 2), hash, `${version}.obj`);\n }\n\n private async assertCurrentObjectsExist(): Promise<void> {\n for (const [key, metadata] of this.entries)\n try {\n await stat(this.objectPath(key, metadata.version));\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\")\n throw new StorageError(`Journal references a missing object: ${key}`, \"CORRUPTION\", {\n cause: error,\n });\n\n throw error;\n }\n }\n\n private async cleanupPhysicalObjects(): Promise<void> {\n const referenced = new Map<string, string>();\n\n for (const [key, metadata] of this.entries)\n referenced.set(sha256(new TextEncoder().encode(key)), metadata.version);\n\n const walk = async (directory: string): Promise<void> => {\n let items;\n\n try {\n items = await opendir(directory);\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\") return;\n throw error;\n }\n\n for await (const item of items) {\n const path = join(directory, item.name);\n\n if (item.isDirectory()) await walk(path);\n else if (\n item.isFile() &&\n (item.name.endsWith(\".tmp\") ||\n (item.name.endsWith(\".obj\") &&\n referenced.get(basename(dirname(path))) + \".obj\" != item.name))\n )\n await this.removeObsolete(path);\n }\n };\n\n await walk(join(this.root, OBJECTS_DIRECTORY));\n }\n\n private async recoverJournalRotation(): Promise<void> {\n const current = join(this.root, JOURNAL_FILE);\n const previous = join(this.root, PREVIOUS_JOURNAL);\n const next = join(this.root, NEXT_JOURNAL);\n\n const hasCurrent = await exists(current);\n const hasPrevious = await exists(previous);\n const hasNext = await exists(next);\n\n if (!hasCurrent) {\n if (hasNext) await rename(next, current);\n else if (hasPrevious) await rename(previous, current);\n } else if (hasPrevious) {\n try {\n const input = await open(current, \"r\");\n\n try {\n await replayJournal(input, this.options.maxJournalBytes, () => {});\n } finally {\n await input.close();\n }\n\n await this.removeObsolete(previous);\n } catch (cause) {\n throw new StorageError(\n \"Cannot establish journal rotation outcome; refusing to restore stale journal\",\n \"CORRUPTION\",\n { cause },\n );\n }\n }\n\n if ((await exists(current)) && (await exists(next))) await this.removeObsolete(next);\n if ((await exists(current)) && (await exists(previous))) await this.removeObsolete(previous);\n\n await this.syncDirectory(this.root);\n }\n\n private async fault(point: DiskFaultPoint, context: DiskFaultContext): Promise<void> {\n await this.options.faultInjector?.(point, context);\n }\n\n private async removeObsolete(path: string): Promise<void> {\n try {\n await rm(path, { force: true });\n } catch {\n /* Cleanup is retried during the next open. */\n }\n }\n\n private async syncDirectory(directory: string): Promise<void> {\n if (!this.directorySync) return;\n\n try {\n await AsyncDiskStorageDriver.syncDirectoryStatic(directory);\n } catch (error) {\n if ([\"EINVAL\", \"ENOTSUP\", \"EBADF\", \"EISDIR\", \"EPERM\"].includes(nodeErrorCode(error) ?? \"\"))\n this.directorySync = false;\n else throw error;\n }\n }\n\n private static async syncDirectoryStatic(directory: string): Promise<void> {\n const handle = await open(directory, \"r\");\n\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n }\n\n private async cleanupFailedOpen(): Promise<void> {\n const failures: unknown[] = [];\n\n try {\n if (this.journal) await this.journal.close();\n } catch (error) {\n failures.push(error);\n }\n\n if (failures.length == 0) {\n try {\n await this.ownership.release();\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length == 1) throw failures[0];\n\n if (failures.length > 1)\n throw new AggregateError(failures, \"Failed storage initialization cleanup\");\n }\n}\n"],"mappings":";;;;;;;AAGA,IAAM,eAAe,OAAO,KAAK,YAAY,OAAO;AACpD,IAAM,mBAAmB;AAyBzB,IAAM,UAAU,IAAI,YAAY;AAChC,IAAM,UAAU,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC;AAExD,SAAgB,OAAO,MAAmC;CACxD,QAAA,GAAOA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK;AACvD;AAEA,SAAS,WAAW,SAAiB,OAA+B;CAClE,OAAO,IAAIC,iBAAAA,aAAa,SAAS,cAAc,SAAS,OAAO,KAAA,IAAY,EAAE,MAAM,CAAC;AACtF;AAEA,SAASC,cAAY,OAAmB,OAAwC;CAC9E,IAAI;EACF,MAAM,QAAiB,KAAK,MAAM,QAAQ,OAAO,KAAK,CAAC;EACvD,IAAI,CAAC,SAAS,OAAO,SAAS,YAAY,MAAM,QAAQ,KAAK,GAC3D,MAAM,IAAI,MAAM,eAAe;EACjC,OAAO;CACT,SAAS,OAAO;EACd,MAAM,WAAW,WAAW,SAAS,KAAK;CAC5C;AACF;AAEA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,SAAS,YAAY,iBAAiB,KAAK,KAAK;AAChE;AAEA,SAAS,iBACP,OAC2D;CAC3D,IACE,OAAO,MAAM,WAAW,YACxB,CAAC,4EAA4E,KAC3E,MAAM,OACR,KACA,CAAC,OAAO,cAAc,MAAM,SAAS,KACpC,MAAM,YAAuB,KAC9B,CAAC,OAAO,cAAc,MAAM,IAAI,KAC/B,MAAM,OAAkB,KACzB,CAAC,YAAY,MAAM,MAAM,GAEzB,MAAM,WAAW,kCAAkC;AACvD;AAEA,SAAgB,qBACd,KACA,UACA,MACY;CACZ,MAAM,gBAAgB;EACpB,QAAQ;EACR;EACA,SAAS,SAAS;EA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,QAAQ,gBAAgB,OAAO,OAAO;CACnD;CAEA,MAAc,eAAe,MAA6B;EACxD,IAAI;GACF,OAAA,GAAMa,iBAAAA,GAAAA,CAAG,MAAM,EAAE,OAAO,KAAK,CAAC;EAChC,QAAQ,CAER;CACF;CAEA,MAAc,cAAc,WAAkC;EAC5D,IAAI,CAAC,KAAK,eAAe;EAEzB,IAAI;GACF,MAAM,uBAAuB,oBAAoB,SAAS;EAC5D,SAAS,OAAO;GACd,IAAI;IAAC;IAAU;IAAW;IAAS;IAAU;GAAO,CAAC,CAAC,SAAS,cAAc,KAAK,KAAK,EAAE,GACvF,KAAK,gBAAgB;QAClB,MAAM;EACb;CACF;CAEA,aAAqB,oBAAoB,WAAkC;EACzE,MAAM,SAAS,OAAA,GAAMR,iBAAAA,KAAAA,CAAK,WAAW,GAAG;EAExC,IAAI;GACF,MAAM,OAAO,KAAK;EACpB,UAAU;GACR,MAAM,OAAO,MAAM;EACrB;CACF;CAEA,MAAc,oBAAmC;EAC/C,MAAM,WAAsB,CAAC;EAE7B,IAAI;GACF,IAAI,KAAK,SAAS,MAAM,KAAK,QAAQ,MAAM;EAC7C,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAEA,IAAI,SAAS,UAAU,GACrB,IAAI;GACF,MAAM,KAAK,UAAU,QAAQ;EAC/B,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAGF,IAAI,SAAS,UAAU,GAAG,MAAM,SAAS;EAEzC,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,eAAe,UAAU,uCAAuC;CAC9E;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["createHash","StorageError","parseRecord","StorageError","writeAll","open","stat","readFile","unlink","join","randomUUID","hostname","readlink","statfs","stat","StorageError","resolve","mkdir","realpath","join","open","truncate","readFile","randomUUID","dirname","rename","opendir","basename","rm"],"sources":["../src/disk-format.ts","../src/ownership.ts","../src/async-disk-storage.driver.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { StorageError } from \"@duraxis/storage\";\n\nconst OBJECT_MAGIC = Buffer.from(\"DXOBJ001\", \"ascii\");\nconst MAX_HEADER_BYTES = 16 * 1024;\nexport const MAX_JOURNAL_FRAME_BYTES = 64 * 1024;\n\nexport interface StoredMetadata {\n readonly version: string;\n readonly createdAt: number;\n readonly size: number;\n readonly digest: string;\n}\n\nexport type JournalPayload =\n | ({\n readonly format: 1;\n readonly sequence: number;\n readonly op: \"put\";\n readonly key: string;\n } & StoredMetadata)\n | { readonly format: 1; readonly sequence: number; readonly op: \"delete\"; readonly key: string };\n\nexport interface DecodedJournal {\n readonly frames: readonly JournalPayload[];\n readonly validBytes: number;\n readonly incompleteTail: boolean;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nexport function sha256(data: Uint8Array | string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\nfunction corruption(message: string, cause?: unknown): StorageError {\n return new StorageError(message, \"CORRUPTION\", cause == null ? undefined : { cause });\n}\n\nfunction parseRecord(bytes: Uint8Array, label: string): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(decoder.decode(bytes));\n if (!value || typeof value != \"object\" || Array.isArray(value))\n throw new Error(\"not an object\");\n return value as Record<string, unknown>;\n } catch (cause) {\n throw corruption(`Invalid ${label}`, cause);\n }\n}\n\nfunction validDigest(value: unknown): value is string {\n return typeof value == \"string\" && /^[0-9a-f]{64}$/.test(value);\n}\n\nfunction validateMetadata(\n value: Record<string, unknown>,\n): asserts value is Record<string, unknown> & StoredMetadata {\n if (\n typeof value.version != \"string\" ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(\n value.version,\n ) ||\n !Number.isSafeInteger(value.createdAt) ||\n (value.createdAt as number) < 0 ||\n !Number.isSafeInteger(value.size) ||\n (value.size as number) < 0 ||\n !validDigest(value.digest)\n )\n throw corruption(\"Invalid physical object metadata\");\n}\n\nexport function encodePhysicalObject(\n key: string,\n metadata: StoredMetadata,\n data: Uint8Array,\n): Uint8Array {\n const headerPayload = {\n format: 1 as const,\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n };\n const canonical = JSON.stringify(headerPayload);\n const header = encoder.encode(JSON.stringify({ ...headerPayload, checksum: sha256(canonical) }));\n if (header.byteLength > MAX_HEADER_BYTES)\n throw new StorageError(\"Object metadata is too large\", \"RESOURCE_LIMIT\");\n const result = new Uint8Array(OBJECT_MAGIC.length + 4 + header.length + data.length);\n result.set(OBJECT_MAGIC, 0);\n new DataView(result.buffer).setUint32(OBJECT_MAGIC.length, header.length, false);\n result.set(header, OBJECT_MAGIC.length + 4);\n result.set(data, OBJECT_MAGIC.length + 4 + header.length);\n return result;\n}\n\nexport function decodePhysicalObject(\n bytes: Uint8Array,\n expectedKey: string,\n expected: StoredMetadata,\n): Uint8Array {\n if (\n bytes.byteLength < OBJECT_MAGIC.length + 4 ||\n !Buffer.from(bytes.subarray(0, OBJECT_MAGIC.length)).equals(OBJECT_MAGIC)\n )\n throw corruption(\"Invalid physical object magic\");\n const headerLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(\n OBJECT_MAGIC.length,\n false,\n );\n if (\n headerLength == 0 ||\n headerLength > MAX_HEADER_BYTES ||\n OBJECT_MAGIC.length + 4 + headerLength > bytes.byteLength\n )\n throw corruption(\"Invalid physical object header length\");\n const header = parseRecord(\n bytes.subarray(OBJECT_MAGIC.length + 4, OBJECT_MAGIC.length + 4 + headerLength),\n \"physical object header\",\n );\n const fields = Object.keys(header).sort().join(\",\");\n if (\n fields != \"checksum,createdAt,digest,format,key,size,version\" ||\n header.format != 1 ||\n typeof header.key != \"string\" ||\n typeof header.checksum != \"string\"\n )\n throw corruption(\"Invalid physical object header\");\n validateMetadata(header);\n const canonical = JSON.stringify({\n format: 1,\n key: header.key,\n version: header.version,\n createdAt: header.createdAt,\n size: header.size,\n digest: header.digest,\n });\n if (sha256(canonical) != header.checksum)\n throw corruption(\"Physical metadata integrity check failed\");\n if (\n header.key != expectedKey ||\n header.version != expected.version ||\n header.createdAt != expected.createdAt ||\n header.size != expected.size ||\n header.digest != expected.digest\n )\n throw corruption(\"Physical object does not match journal metadata\");\n const data = bytes.subarray(OBJECT_MAGIC.length + 4 + headerLength);\n if (data.byteLength != expected.size || sha256(data) != expected.digest)\n throw corruption(\"Physical object payload integrity check failed\");\n return new Uint8Array(data);\n}\n\nexport function encodeJournalFrame(payload: JournalPayload): Uint8Array {\n const canonical = JSON.stringify(payload);\n const body = encoder.encode(JSON.stringify({ ...payload, checksum: sha256(canonical) }));\n if (body.byteLength > MAX_JOURNAL_FRAME_BYTES)\n throw new StorageError(\"Journal frame is too large\", \"RESOURCE_LIMIT\");\n const result = new Uint8Array(4 + body.byteLength);\n new DataView(result.buffer).setUint32(0, body.byteLength, false);\n result.set(body, 4);\n return result;\n}\n\nfunction decodeFrame(bytes: Uint8Array, expectedSequence: number): JournalPayload {\n const record = parseRecord(bytes, \"storage journal frame\");\n if (\n record.format != 1 ||\n record.sequence != expectedSequence ||\n (record.op != \"put\" && record.op != \"delete\") ||\n typeof record.key != \"string\" ||\n typeof record.checksum != \"string\"\n )\n throw corruption(\"Invalid storage journal frame\");\n let payload: JournalPayload;\n if (record.op == \"put\") {\n if (\n Object.keys(record).sort().join(\",\") !=\n \"checksum,createdAt,digest,format,key,op,sequence,size,version\"\n )\n throw corruption(\"Invalid put journal frame layout\");\n validateMetadata(record);\n payload = {\n format: 1,\n sequence: expectedSequence,\n op: \"put\",\n key: record.key,\n version: record.version,\n createdAt: record.createdAt,\n size: record.size,\n digest: record.digest,\n };\n } else {\n if (Object.keys(record).sort().join(\",\") != \"checksum,format,key,op,sequence\")\n throw corruption(\"Invalid delete journal frame layout\");\n payload = { format: 1, sequence: expectedSequence, op: \"delete\", key: record.key };\n }\n if (sha256(JSON.stringify(payload)) != record.checksum)\n throw corruption(\"Storage journal integrity check failed\");\n return payload;\n}\n\nexport function decodeJournal(bytes: Uint8Array): DecodedJournal {\n const frames: JournalPayload[] = [];\n let offset = 0;\n let sequence = 1;\n while (offset < bytes.byteLength) {\n if (bytes.byteLength - offset < 4) return { frames, validBytes: offset, incompleteTail: true };\n const length = new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(0, false);\n if (length == 0 || length > MAX_JOURNAL_FRAME_BYTES)\n throw corruption(\"Invalid storage journal frame length\");\n if (bytes.byteLength - offset - 4 < length)\n return { frames, validBytes: offset, incompleteTail: true };\n frames.push(decodeFrame(bytes.subarray(offset + 4, offset + 4 + length), sequence++));\n offset += 4 + length;\n }\n return { frames, validBytes: offset, incompleteTail: false };\n}\n\nexport async function replayJournal(\n handle: {\n stat(): Promise<{ readonly size: number }>;\n read(\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): Promise<{ readonly bytesRead: number }>;\n },\n maxBytes: number,\n consume: (payload: JournalPayload) => void,\n): Promise<Omit<DecodedJournal, \"frames\">> {\n const info = await handle.stat();\n\n if (info.size > maxBytes)\n throw new StorageError(\"Storage journal exceeds configured limit\", \"RESOURCE_LIMIT\");\n\n let offset = 0;\n let sequence = 1;\n\n const read = async (buffer: Uint8Array, position: number) => {\n let received = 0;\n\n while (received < buffer.byteLength) {\n const result = await handle.read(\n buffer,\n received,\n buffer.byteLength - received,\n position + received,\n );\n\n if (!result.bytesRead) break;\n\n received += result.bytesRead;\n }\n\n return received;\n };\n\n while (offset < info.size) {\n const header = new Uint8Array(4);\n\n if ((await read(header, offset)) != 4) return { validBytes: offset, incompleteTail: true };\n\n const length = new DataView(header.buffer).getUint32(0, false);\n\n if (!length || length > MAX_JOURNAL_FRAME_BYTES)\n throw corruption(\"Invalid storage journal frame length\");\n\n const payload = new Uint8Array(length);\n\n if ((await read(payload, offset + 4)) != length)\n return { validBytes: offset, incompleteTail: true };\n\n consume(decodeFrame(payload, sequence++));\n\n offset += 4 + length;\n }\n\n return { validBytes: offset, incompleteTail: false };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { open, readFile, readlink, stat, statfs, unlink, type FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { join } from \"node:path\";\nimport { StorageError } from \"@duraxis/storage\";\nimport { sha256 } from \"./disk-format.js\";\n\nconst LOCK_FILE = \".duraxis-owner.lock\";\nconst RECOVERY_GUARD_FILE = \".duraxis-owner.recovery\";\nconst OWNERSHIP_CONFIRMATION = \"I_HAVE_VERIFIED_EXCLUSIVE_ACCESS\";\nconst OWNER_FIELDS = \"applicationId,checksum,createdAt,format,hostname,ownerId,pid,processIdentity\";\nconst GUARD_FIELDS = \"checksum,createdAt,format,guardId,hostname,pid\";\nconst 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}$/;\nconst APPLICATION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._:/-]{0,126}[A-Za-z0-9])?$/;\nconst PROCESS_IDENTITY_PATTERN = /^(?:linux:(?:pid:\\[\\d+\\]|unavailable)|[a-z0-9]+:unverified)$/;\nconst MAX_METADATA_BYTES = 4096;\n\nconst LINUX_LOCAL_FILESYSTEMS = new Set([\n 0x0000ef53, // ext2/3/4\n 0x01021994, // tmpfs\n 0x2fc12fc1, // zfs\n 0x58465342, // xfs\n 0x794c7630, // overlayfs\n 0x858458f6, // ramfs\n 0x9123683e, // btrfs\n]);\n\nexport interface OwnershipRecoveryOptions {\n readonly mode: \"manual\" | \"dead-process\";\n readonly applicationId?: string;\n}\n\nexport interface RecoverOwnershipOptions {\n readonly directory: string;\n readonly confirmation: typeof OWNERSHIP_CONFIRMATION;\n}\n\nexport interface NormalizedOwnershipRecovery {\n readonly mode: \"manual\" | \"dead-process\";\n readonly applicationId?: string;\n}\n\ninterface OwnerPayload {\n readonly format: 2;\n readonly ownerId: string;\n readonly pid: number;\n readonly hostname: string;\n readonly createdAt: number;\n readonly applicationId: string | null;\n readonly processIdentity: string;\n}\n\ninterface OwnerRecord extends OwnerPayload {\n readonly checksum: string;\n}\n\ninterface GuardPayload {\n readonly format: 1;\n readonly guardId: string;\n readonly pid: number;\n readonly hostname: string;\n readonly createdAt: number;\n}\n\ninterface GuardRecord extends GuardPayload {\n readonly checksum: string;\n}\n\ninterface ObservedFile {\n readonly path: string;\n readonly handle: FileHandle;\n readonly identity: Stats;\n readonly bytes: Buffer;\n}\n\ninterface CoordinationGuard {\n readonly path: string;\n readonly handle: FileHandle;\n readonly identity: Stats;\n readonly bytes: Buffer;\n readonly guardId: string;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return error && typeof error == \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n}\n\nfunction ownershipConflict(message: string, cause?: unknown): StorageError {\n return new StorageError(message, \"OWNERSHIP_CONFLICT\", cause == null ? undefined : { cause });\n}\n\nfunction canonicalOwner(payload: OwnerPayload): string {\n return JSON.stringify(payload);\n}\n\nfunction canonicalGuard(payload: GuardPayload): string {\n return JSON.stringify(payload);\n}\n\nfunction validHostname(value: unknown): value is string {\n return (\n typeof value == \"string\" &&\n value.length > 0 &&\n value.length <= 255 &&\n !/[\\0-\\x1f\\x7f]/.test(value)\n );\n}\n\nfunction sameIdentity(left: Stats, right: Stats): boolean {\n return left.dev == right.dev && left.ino == right.ino;\n}\n\nasync function writeAll(handle: FileHandle, bytes: Uint8Array): Promise<void> {\n let offset = 0;\n\n while (offset < bytes.byteLength) {\n const result = await handle.write(bytes, offset, bytes.byteLength - offset, offset);\n\n if (result.bytesWritten <= 0)\n throw new StorageError(\"Ownership metadata write made no progress\", \"UNAVAILABLE\");\n\n offset += result.bytesWritten;\n }\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n let handle: FileHandle | undefined;\n\n try {\n handle = await open(directory, \"r\");\n await handle.sync();\n } catch (error) {\n if (![\"EINVAL\", \"ENOTSUP\", \"EBADF\", \"EISDIR\", \"EPERM\"].includes(errorCode(error) ?? \"\"))\n throw error;\n } finally {\n await handle?.close();\n }\n}\n\nasync function observe(path: string): Promise<ObservedFile | null> {\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"r\");\n } catch (error) {\n if (errorCode(error) == \"ENOENT\") return null;\n throw error;\n }\n\n try {\n const identity = await handle.stat();\n const bytes = await handle.readFile();\n\n return { path, handle, identity, bytes };\n } catch (error) {\n await handle.close().catch(() => undefined);\n throw error;\n }\n}\n\nasync function assertObservedUnchanged(observed: ObservedFile): Promise<void> {\n let currentIdentity: Stats;\n let currentBytes: Buffer;\n\n try {\n [currentIdentity, currentBytes] = await Promise.all([\n stat(observed.path),\n readFile(observed.path),\n ]);\n } catch (cause) {\n throw ownershipConflict(\"Ownership metadata changed during inspection\", cause);\n }\n\n if (!sameIdentity(observed.identity, currentIdentity) || !observed.bytes.equals(currentBytes))\n throw ownershipConflict(\"Ownership metadata changed during inspection\");\n}\n\nasync function removeObserved(observed: ObservedFile): Promise<void> {\n try {\n await assertObservedUnchanged(observed);\n } finally {\n await observed.handle.close();\n }\n\n try {\n await unlink(observed.path);\n } catch (cause) {\n throw ownershipConflict(\"Failed to remove the observed ownership lock\", cause);\n }\n}\n\nasync function removeCreatedFile(path: string, handle: FileHandle, identity: Stats): Promise<void> {\n await handle.close().catch(() => undefined);\n\n try {\n const current = await stat(path);\n\n if (!sameIdentity(identity, current))\n throw ownershipConflict(\"Created ownership file was replaced unexpectedly\");\n\n await unlink(path);\n } catch (error) {\n if (errorCode(error) != \"ENOENT\") throw error;\n }\n}\n\nfunction parseRecord(bytes: Uint8Array, label: string): Record<string, unknown> {\n if (bytes.byteLength == 0 || bytes.byteLength > MAX_METADATA_BYTES)\n throw ownershipConflict(`Invalid ${label}`);\n\n try {\n const value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (!value || typeof value != \"object\" || Array.isArray(value))\n throw new Error(\"not an object\");\n\n return value as Record<string, unknown>;\n } catch (cause) {\n throw ownershipConflict(`Invalid ${label}`, cause);\n }\n}\n\nfunction parseOwner(bytes: Uint8Array): OwnerRecord {\n const record = parseRecord(bytes, \"owner lock metadata\");\n\n if (record.format != 2)\n throw ownershipConflict(\n \"Owner lock format is incompatible with automatic recovery; use explicit manual recovery\",\n );\n\n if (\n Object.keys(record).sort().join(\",\") != OWNER_FIELDS ||\n !UUID_PATTERN.test(String(record.ownerId)) ||\n !Number.isSafeInteger(record.pid) ||\n (record.pid as number) <= 0 ||\n !validHostname(record.hostname) ||\n !Number.isSafeInteger(record.createdAt) ||\n (record.createdAt as number) < 0 ||\n (record.applicationId !== null &&\n (typeof record.applicationId != \"string\" ||\n !APPLICATION_ID_PATTERN.test(record.applicationId))) ||\n typeof record.processIdentity != \"string\" ||\n !PROCESS_IDENTITY_PATTERN.test(record.processIdentity) ||\n typeof record.checksum != \"string\" ||\n !/^[0-9a-f]{64}$/.test(record.checksum)\n )\n throw ownershipConflict(\"Invalid owner lock metadata\");\n\n const payload: OwnerPayload = {\n format: 2,\n ownerId: record.ownerId as string,\n pid: record.pid as number,\n hostname: record.hostname,\n createdAt: record.createdAt as number,\n applicationId: record.applicationId as string | null,\n processIdentity: record.processIdentity,\n };\n\n if (sha256(canonicalOwner(payload)) != record.checksum)\n throw ownershipConflict(\"Owner lock metadata checksum is invalid\");\n\n return { ...payload, checksum: record.checksum };\n}\n\nfunction parseGuard(bytes: Uint8Array): GuardRecord {\n const record = parseRecord(bytes, \"ownership recovery guard\");\n\n if (\n Object.keys(record).sort().join(\",\") != GUARD_FIELDS ||\n record.format != 1 ||\n !UUID_PATTERN.test(String(record.guardId)) ||\n !Number.isSafeInteger(record.pid) ||\n (record.pid as number) <= 0 ||\n !validHostname(record.hostname) ||\n !Number.isSafeInteger(record.createdAt) ||\n (record.createdAt as number) < 0 ||\n typeof record.checksum != \"string\" ||\n !/^[0-9a-f]{64}$/.test(record.checksum)\n )\n throw ownershipConflict(\"Invalid ownership recovery guard\");\n\n const payload: GuardPayload = {\n format: 1,\n guardId: record.guardId as string,\n pid: record.pid as number,\n hostname: record.hostname,\n createdAt: record.createdAt as number,\n };\n\n if (sha256(canonicalGuard(payload)) != record.checksum)\n throw ownershipConflict(\"Ownership recovery guard checksum is invalid\");\n\n return { ...payload, checksum: record.checksum };\n}\n\nasync function acquireGuard(root: string): Promise<CoordinationGuard> {\n const path = join(root, RECOVERY_GUARD_FILE);\n\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"wx\", 0o600);\n } catch (cause) {\n if (errorCode(cause) == \"EEXIST\")\n throw ownershipConflict(\n \"Another ownership operation is active or left an uncertain recovery guard\",\n cause,\n );\n\n throw cause;\n }\n let identity: Stats;\n try {\n identity = await handle.stat();\n } catch (cause) {\n await handle.close().catch(() => undefined);\n\n throw cause;\n }\n\n const payload: GuardPayload = {\n format: 1,\n guardId: randomUUID(),\n pid: process.pid,\n hostname: hostname(),\n createdAt: Date.now(),\n };\n\n const bytes = Buffer.from(\n JSON.stringify({ ...payload, checksum: sha256(canonicalGuard(payload)) }),\n );\n\n try {\n await writeAll(handle, bytes);\n await handle.sync();\n await syncDirectory(root);\n\n return { path, handle, identity, bytes, guardId: payload.guardId };\n } catch (cause) {\n try {\n await removeCreatedFile(path, handle, identity);\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Ownership guard creation and cleanup both failed\",\n );\n }\n throw cause;\n }\n}\n\nasync function releaseGuard(root: string, guard: CoordinationGuard): Promise<void> {\n try {\n const currentIdentity = await stat(guard.path);\n const currentBytes = await readFile(guard.path);\n const record = parseGuard(currentBytes);\n\n if (\n !sameIdentity(guard.identity, currentIdentity) ||\n !guard.bytes.equals(currentBytes) ||\n record.guardId != guard.guardId\n )\n throw ownershipConflict(\"Ownership recovery guard changed unexpectedly\");\n } finally {\n await guard.handle.close();\n }\n\n await unlink(guard.path);\n await syncDirectory(root);\n}\n\nasync function withGuard<T>(root: string, operation: () => Promise<T>): Promise<T> {\n const guard = await acquireGuard(root);\n let result: T | undefined;\n let operationFailure: unknown;\n\n try {\n result = await operation();\n } catch (error) {\n operationFailure = error;\n }\n\n try {\n await releaseGuard(root, guard);\n } catch (guardFailure) {\n if (operationFailure != null)\n throw new AggregateError(\n [operationFailure, guardFailure],\n \"Ownership operation and recovery-guard release both failed\",\n );\n\n throw guardFailure;\n }\n\n if (operationFailure != null) throw operationFailure;\n\n return result as T;\n}\n\nasync function automaticProcessIdentity(root: string): Promise<string> {\n if (process.platform != \"linux\")\n throw ownershipConflict(\n \"Automatic dead-process recovery is supported only on validated Linux environments\",\n );\n\n let namespace: string;\n\n try {\n namespace = await readlink(\"/proc/self/ns/pid\");\n } catch (cause) {\n throw ownershipConflict(\"The Linux PID namespace cannot be established\", cause);\n }\n\n if (!/^pid:\\[\\d+\\]$/.test(namespace))\n throw ownershipConflict(\"The Linux PID namespace identity is invalid\");\n\n let filesystemType: number;\n\n try {\n filesystemType = (await statfs(root)).type >>> 0;\n } catch (cause) {\n throw ownershipConflict(\"The storage filesystem type cannot be established\", cause);\n }\n\n if (!LINUX_LOCAL_FILESYSTEMS.has(filesystemType))\n throw ownershipConflict(\n `Automatic recovery is not supported on filesystem type 0x${filesystemType.toString(16)}`,\n );\n\n return `linux:${namespace}`;\n}\n\nasync function processIdentityForLock(root: string, mode: \"manual\" | \"dead-process\") {\n if (mode == \"dead-process\") return await automaticProcessIdentity(root);\n\n if (process.platform == \"linux\") {\n try {\n return `linux:${await readlink(\"/proc/self/ns/pid\")}`;\n } catch {\n return \"linux:unavailable\";\n }\n }\n return `${process.platform}:unverified`;\n}\n\nfunction assertRecoverableOwner(\n owner: OwnerRecord,\n recovery: NormalizedOwnershipRecovery,\n processIdentity: string,\n): void {\n if (owner.hostname != hostname())\n throw ownershipConflict(\"Owner lock belongs to a different host\");\n\n if (owner.processIdentity != processIdentity)\n throw ownershipConflict(\"Owner lock belongs to a different or unsupported process namespace\");\n\n if (owner.applicationId != (recovery.applicationId ?? null))\n throw ownershipConflict(\"Owner lock belongs to a different application identity\");\n\n try {\n process.kill(owner.pid, 0);\n } catch (cause) {\n if (errorCode(cause) == \"ESRCH\") return;\n\n if (errorCode(cause) == \"EPERM\")\n throw ownershipConflict(\"Owner process existence is inconclusive\", cause);\n\n throw ownershipConflict(\"Owner process existence could not be determined\", cause);\n }\n\n throw ownershipConflict(\n \"Owner process may still be running; PID reuse is treated as an ownership conflict\",\n );\n}\n\nasync function createOwnerFile(\n root: string,\n ownerId: string,\n recovery: NormalizedOwnershipRecovery,\n processIdentity: string,\n): Promise<{ handle: FileHandle; identity: Stats } | null> {\n const path = join(root, LOCK_FILE);\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"wx\", 0o600);\n } catch (error) {\n if (errorCode(error) == \"EEXIST\") return null;\n throw error;\n }\n\n let identity: Stats;\n\n try {\n identity = await handle.stat();\n } catch (cause) {\n await handle.close().catch(() => undefined);\n throw cause;\n }\n\n const payload: OwnerPayload = {\n format: 2,\n ownerId,\n pid: process.pid,\n hostname: hostname(),\n createdAt: Date.now(),\n applicationId: recovery.applicationId ?? null,\n processIdentity,\n };\n\n const bytes = Buffer.from(\n JSON.stringify({ ...payload, checksum: sha256(canonicalOwner(payload)) }),\n );\n\n try {\n await writeAll(handle, bytes);\n await handle.sync();\n await syncDirectory(root);\n return { handle, identity };\n } catch (cause) {\n try {\n await removeCreatedFile(path, handle, identity);\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Owner lock creation and cleanup both failed\",\n );\n }\n\n throw cause;\n }\n}\n\nexport function normalizeOwnershipRecovery(\n options: OwnershipRecoveryOptions | undefined,\n): NormalizedOwnershipRecovery {\n if (options == null) return { mode: \"manual\" };\n\n if (options.mode != \"manual\" && options.mode != \"dead-process\")\n throw new TypeError('ownershipRecovery.mode must be \"manual\" or \"dead-process\"');\n\n if (\n options.applicationId != null &&\n (typeof options.applicationId != \"string\" ||\n !APPLICATION_ID_PATTERN.test(options.applicationId))\n )\n throw new TypeError(\"ownershipRecovery.applicationId must be 1-128 safe identifier characters\");\n\n return {\n mode: options.mode,\n ...(options.applicationId == null ? {} : { applicationId: options.applicationId }),\n };\n}\n\nexport class DirectoryOwnership {\n readonly #ownerId = randomUUID();\n #lockHandle?: FileHandle;\n #owned = false;\n\n public constructor(\n private readonly root: string,\n private readonly recovery: NormalizedOwnershipRecovery,\n ) {}\n\n public get isOwned(): boolean {\n return this.#owned;\n }\n\n public async acquire(): Promise<void> {\n const processIdentity = await processIdentityForLock(this.root, this.recovery.mode);\n\n await withGuard(this.root, async () => {\n let created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);\n if (!created) {\n if (this.recovery.mode == \"manual\")\n throw ownershipConflict(\n \"Storage directory has an owner lock; close the owner or perform explicit abandoned-lock recovery\",\n );\n\n const observed = await observe(join(this.root, LOCK_FILE));\n\n if (observed) {\n let owner: OwnerRecord;\n\n try {\n owner = parseOwner(observed.bytes);\n assertRecoverableOwner(owner, this.recovery, processIdentity);\n await removeObserved(observed);\n } catch (error) {\n await observed.handle.close().catch(() => undefined);\n throw error;\n }\n\n await syncDirectory(this.root);\n }\n\n created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);\n\n if (!created)\n throw ownershipConflict(\"Another process acquired storage ownership during recovery\");\n }\n this.#lockHandle = created.handle;\n this.#owned = true;\n });\n }\n\n public async verify(): Promise<void> {\n if (!this.#owned) throw ownershipConflict(\"Storage directory is not owned\");\n\n await withGuard(this.root, async () => {\n const observed = await observe(join(this.root, LOCK_FILE));\n\n if (!observed) throw ownershipConflict(\"Storage owner lock is missing\");\n\n try {\n if (parseOwner(observed.bytes).ownerId != this.#ownerId)\n throw ownershipConflict(\"Storage ownership changed\");\n\n await assertObservedUnchanged(observed);\n } finally {\n await observed.handle.close();\n }\n });\n }\n\n public async release(): Promise<void> {\n if (!this.#owned) return;\n\n await withGuard(this.root, async () => {\n const observed = await observe(join(this.root, LOCK_FILE));\n if (!observed) {\n this.#owned = false;\n await this.#lockHandle?.close().catch(() => undefined);\n\n this.#lockHandle = undefined;\n throw ownershipConflict(\"Current owner lock is missing\");\n }\n\n try {\n const owner = parseOwner(observed.bytes);\n\n if (owner.ownerId != this.#ownerId)\n throw ownershipConflict(\"Storage ownership changed unexpectedly\");\n\n await this.#lockHandle?.close();\n this.#lockHandle = undefined;\n\n await removeObserved(observed);\n this.#owned = false;\n\n await syncDirectory(this.root);\n } catch (error) {\n await observed.handle.close().catch(() => undefined);\n throw error;\n }\n });\n }\n}\n\nexport async function manuallyRecoverOwnership(root: string): Promise<void> {\n await withGuard(root, async () => {\n const observed = await observe(join(root, LOCK_FILE));\n if (!observed) return;\n await removeObserved(observed);\n await syncDirectory(root);\n });\n}\n\nexport function validateManualRecoveryConfirmation(\n confirmation: RecoverOwnershipOptions[\"confirmation\"],\n): void {\n if (confirmation != OWNERSHIP_CONFIRMATION)\n throw new StorageError(\"Explicit exclusive-access confirmation is required\", \"ACCESS_DENIED\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport {\n mkdir,\n open,\n readFile,\n opendir,\n realpath,\n rename,\n rm,\n stat,\n truncate,\n type FileHandle,\n} from \"node:fs/promises\";\nimport {\n assertStorageKey,\n assertWriteCondition,\n StorageError,\n type DeleteOptions,\n type DeleteResult,\n type StorageDriver,\n type StorageDriverMetrics,\n type StorageObject,\n type StorageObjectInfo,\n type WriteOptions,\n type WriteResult,\n} from \"@duraxis/storage\";\nimport {\n replayJournal,\n decodePhysicalObject,\n encodeJournalFrame,\n encodePhysicalObject,\n sha256,\n type JournalPayload,\n type StoredMetadata,\n} from \"./disk-format.js\";\nimport {\n DirectoryOwnership,\n manuallyRecoverOwnership,\n normalizeOwnershipRecovery,\n validateManualRecoveryConfirmation,\n type NormalizedOwnershipRecovery,\n type OwnershipRecoveryOptions,\n type RecoverOwnershipOptions,\n} from \"./ownership.js\";\n\nconst JOURNAL_FILE = \"journal.log\";\nconst PREVIOUS_JOURNAL = \"journal.previous\";\nconst NEXT_JOURNAL = \"journal.next\";\nconst OBJECTS_DIRECTORY = \"objects\";\n\nconst MAX_KEY_BYTES = 4096;\nconst MAX_OBJECT_BYTES = 256 * 1024 * 1024;\nconst MAX_JOURNAL_BYTES = 1024 * 1024 * 1024;\n\nexport type { OwnershipRecoveryOptions, RecoverOwnershipOptions } from \"./ownership.js\";\n\nexport type DiskFaultPoint =\n | \"after-object-sync\"\n | \"after-object-publish\"\n | \"after-object-directory-sync\"\n | \"after-journal-write\"\n | \"after-journal-sync\"\n | \"after-journal-rotation\";\n\nexport interface DiskFaultContext {\n readonly operation: \"put\" | \"delete\" | \"compact\";\n readonly key?: string;\n}\n\nexport interface AsyncDiskStorageOptions {\n readonly directory: string;\n readonly ownershipRecovery?: OwnershipRecoveryOptions;\n readonly maxKeyBytes?: number;\n readonly maxObjectBytes?: number;\n readonly maxJournalBytes?: number;\n readonly maxMetadataBytes?: number;\n readonly maxQueuedOperations?: number;\n readonly nodeCacheHint?: number;\n readonly faultInjector?: (\n point: DiskFaultPoint,\n context: DiskFaultContext,\n ) => void | Promise<void>;\n}\n\nexport interface DiskDurabilityCapabilities {\n readonly fileDataSync: true;\n readonly directoryEntrySync: boolean;\n readonly ownership: \"exclusive-directory\";\n readonly processCrashRecovery: true;\n readonly powerLossGuarantee: \"file-and-directory-sync\" | \"file-sync-only\";\n}\n\ninterface MutableMetrics {\n reads: number;\n writes: number;\n deletes: number;\n lists: number;\n bytesRead: number;\n bytesWritten: number;\n synchronizationWaitMs: number;\n}\n\nfunction nodeErrorCode(error: unknown): string | undefined {\n return error && typeof error == \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\") return false;\n throw error;\n }\n}\n\nasync function writeAll(handle: FileHandle, bytes: Uint8Array, position = 0): Promise<void> {\n let offset = 0;\n\n while (offset < bytes.byteLength) {\n const result = await handle.write(bytes, offset, bytes.byteLength - offset, position + offset);\n\n if (result.bytesWritten <= 0)\n throw new StorageError(\"Disk write made no progress\", \"UNAVAILABLE\");\n\n offset += result.bytesWritten;\n }\n}\n\nasync function syncAndClose(handle: FileHandle, context: string): Promise<void> {\n let syncFailure: unknown;\n\n try {\n await handle.sync();\n } catch (error) {\n syncFailure = error;\n }\n\n try {\n await handle.close();\n } catch (closeFailure) {\n if (syncFailure != null)\n throw new AggregateError(\n [syncFailure, closeFailure],\n `${context} sync and close both failed`,\n );\n\n throw closeFailure;\n }\n\n if (syncFailure != null) throw syncFailure;\n}\n\nexport class AsyncDiskStorageDriver implements StorageDriver {\n public readonly capabilities = Object.freeze({ boundedReads: true });\n private static readonly activeDirectories = new Set<string>();\n\n private readonly entries = new Map<string, StoredMetadata>();\n private readonly ownership: DirectoryOwnership;\n private readonly metrics: MutableMetrics = {\n reads: 0,\n writes: 0,\n deletes: 0,\n lists: 0,\n bytesRead: 0,\n bytesWritten: 0,\n synchronizationWaitMs: 0,\n };\n\n private metadataBytes = 0;\n private queuedOperations = 0;\n\n private operationTail: Promise<void> = Promise.resolve();\n private journal!: FileHandle;\n private journalBytes = 0;\n private sequence = 0;\n private directorySync = true;\n private closed = false;\n private closing = false;\n private resourcesClosed = false;\n private closePromise?: Promise<void>;\n private poisoned = false;\n\n private constructor(\n private readonly root: string,\n private readonly registryKey: string,\n private readonly options: Required<\n Pick<AsyncDiskStorageOptions, \"maxKeyBytes\" | \"maxObjectBytes\" | \"maxJournalBytes\">\n > &\n AsyncDiskStorageOptions & { readonly ownershipRecovery: NormalizedOwnershipRecovery },\n ) {\n this.ownership = new DirectoryOwnership(root, options.ownershipRecovery);\n }\n\n public static async open(options: AsyncDiskStorageOptions): Promise<AsyncDiskStorageDriver> {\n if (!options || typeof options.directory != \"string\" || options.directory.trim() == \"\")\n throw new TypeError(\"A storage directory is required\");\n\n const maxKeyBytes = options.maxKeyBytes ?? MAX_KEY_BYTES;\n const maxObjectBytes = options.maxObjectBytes ?? MAX_OBJECT_BYTES;\n const maxJournalBytes = options.maxJournalBytes ?? MAX_JOURNAL_BYTES;\n\n const ownershipRecovery = normalizeOwnershipRecovery(options.ownershipRecovery);\n\n if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes < 64 || maxKeyBytes > 64 * 1024)\n throw new RangeError(\"Invalid maximum storage key size\");\n\n if (\n !Number.isSafeInteger(maxObjectBytes) ||\n maxObjectBytes < 0 ||\n maxObjectBytes > MAX_JOURNAL_BYTES\n )\n throw new RangeError(\"Invalid maximum object size\");\n\n if (!Number.isSafeInteger(maxJournalBytes) || maxJournalBytes < 1024 * 1024)\n throw new RangeError(\"Invalid maximum journal size\");\n\n for (const value of [options.maxMetadataBytes, options.maxQueuedOperations])\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1))\n throw new RangeError(\"Invalid storage resource limit\");\n\n const requested = resolve(options.directory);\n\n await mkdir(requested, { recursive: true });\n\n const root = await realpath(requested);\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\n \"Storage directory is already owned by this process\",\n \"OWNERSHIP_CONFLICT\",\n );\n\n this.activeDirectories.add(registryKey);\n\n const driver = new AsyncDiskStorageDriver(root, registryKey, {\n ...options,\n directory: root,\n maxKeyBytes,\n maxObjectBytes,\n maxJournalBytes,\n ownershipRecovery,\n });\n\n try {\n await driver.initialize();\n return driver;\n } catch (cause) {\n try {\n await driver.cleanupFailedOpen();\n } catch (cleanupCause) {\n if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);\n throw new AggregateError(\n [cause, cleanupCause],\n \"Storage initialization and ownership cleanup both failed\",\n );\n }\n if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);\n throw cause;\n }\n }\n\n public static async recoverAbandonedOwnership(options: RecoverOwnershipOptions): Promise<void> {\n validateManualRecoveryConfirmation(options.confirmation);\n\n const root = await realpath(resolve(options.directory));\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\"Cannot recover ownership held by this process\", \"OWNERSHIP_CONFLICT\");\n\n await manuallyRecoverOwnership(root);\n }\n\n public get durability(): DiskDurabilityCapabilities {\n return {\n fileDataSync: true,\n directoryEntrySync: this.directorySync,\n ownership: \"exclusive-directory\",\n processCrashRecovery: true,\n powerLossGuarantee: this.directorySync ? \"file-and-directory-sync\" : \"file-sync-only\",\n };\n }\n\n public getMetrics(): Readonly<StorageDriverMetrics> {\n return { ...this.metrics };\n }\n\n private async initialize(): Promise<void> {\n await this.ownership.acquire();\n await mkdir(join(this.root, OBJECTS_DIRECTORY), { recursive: true });\n await this.recoverJournalRotation();\n\n const journalPath = join(this.root, JOURNAL_FILE);\n\n if (!(await exists(journalPath))) {\n const created = await open(journalPath, \"wx\", 0o600);\n await syncAndClose(created, \"New storage journal\");\n await this.syncDirectory(this.root);\n }\n\n const input = await open(journalPath, \"r\");\n let decoded: Awaited<ReturnType<typeof replayJournal>>;\n\n try {\n decoded = await replayJournal(input, this.options.maxJournalBytes, (frame) => {\n this.validateKey(frame.key);\n this.sequence = frame.sequence;\n\n if (frame.op == \"put\")\n this.setEntry(frame.key, {\n version: frame.version,\n createdAt: frame.createdAt,\n size: frame.size,\n digest: frame.digest,\n });\n else this.deleteEntry(frame.key);\n });\n } finally {\n await input.close();\n }\n\n if (decoded.incompleteTail) {\n await truncate(journalPath, decoded.validBytes);\n const repaired = await open(journalPath, \"r+\");\n await syncAndClose(repaired, \"Repaired storage journal\");\n }\n\n this.journalBytes = decoded.validBytes;\n this.journal = await open(journalPath, \"r+\");\n\n await this.assertCurrentObjectsExist();\n await this.cleanupPhysicalObjects();\n }\n\n private setEntry(key: string, value: StoredMetadata): void {\n const size = this.entries.has(key) ? 0 : key.length * 2 + 256;\n\n if (this.metadataBytes + size > (this.options.maxMetadataBytes ?? 64 * 1024 * 1024))\n throw new StorageError(\"Resident storage metadata limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.metadataBytes += size;\n this.entries.set(key, value);\n }\n\n private deleteEntry(key: string): void {\n if (this.entries.delete(key)) this.metadataBytes -= key.length * 2 + 256;\n }\n\n private validateKey(key: string): void {\n assertStorageKey(key);\n\n if (Buffer.byteLength(key, \"utf8\") > this.options.maxKeyBytes)\n throw new StorageError(\"Storage key exceeds configured byte limit\", \"INVALID_KEY\");\n }\n\n private assertUsable(): void {\n if (this.closed || this.closing) throw new StorageError(\"Storage driver is closed\", \"CLOSED\");\n\n if (this.poisoned)\n throw new StorageError(\n \"Storage outcome is unknown; close and reopen before continuing\",\n \"OUTCOME_UNKNOWN\",\n );\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n this.assertUsable();\n\n if (this.queuedOperations >= (this.options.maxQueuedOperations ?? 256))\n throw new StorageError(\"Storage operation admission limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.queuedOperations++;\n\n const before = performance.now();\n const previous = this.operationTail;\n\n let release!: () => void;\n\n this.operationTail = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await previous;\n this.metrics.synchronizationWaitMs += performance.now() - before;\n\n try {\n this.assertUsable();\n return await operation();\n } finally {\n this.queuedOperations--;\n release();\n }\n }\n\n public get(\n key: string,\n options: { readonly signal?: AbortSignal; readonly maxBytes?: number } = {},\n ): Promise<StorageObject | null> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n options.signal?.throwIfAborted();\n this.metrics.reads++;\n\n const metadata = this.entries.get(key);\n\n if (!metadata) return null;\n\n if (metadata.size > (options.maxBytes ?? this.options.maxObjectBytes))\n throw new StorageError(\"Storage read exceeds byte limit\", \"RESOURCE_LIMIT\");\n\n const path = this.objectPath(key, metadata.version);\n\n let info;\n\n try {\n info = await stat(path);\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\")\n throw new StorageError(`Missing physical object for key ${key}`, \"CORRUPTION\", {\n cause: error,\n });\n throw error;\n }\n\n if (info.size > this.options.maxObjectBytes + 32 * 1024)\n throw new StorageError(\"Physical object exceeds configured size\", \"CORRUPTION\");\n\n const physical = await readFile(path, { signal: options.signal });\n\n this.metrics.bytesRead += physical.byteLength;\n\n return { data: decodePhysicalObject(physical, key, metadata), version: metadata.version };\n });\n }\n\n public put(key: string, data: Uint8Array, options: WriteOptions): Promise<WriteResult> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n if (!(data instanceof Uint8Array)) throw new TypeError(\"Storage data must be a Uint8Array\");\n\n if (data.byteLength > this.options.maxObjectBytes)\n throw new StorageError(\"Storage object exceeds configured byte limit\", \"RESOURCE_LIMIT\");\n\n assertWriteCondition(options?.condition);\n\n const current = this.entries.get(key);\n\n if (\n options.condition.type == \"if-absent\"\n ? current != null\n : current == null || current.version != options.condition.version\n )\n return { success: false, reason: \"conflict\" };\n\n if (\n !this.entries.has(key) &&\n this.metadataBytes + key.length * 2 + 256 >\n (this.options.maxMetadataBytes ?? 64 * 1024 * 1024)\n )\n throw new StorageError(\"Resident storage metadata limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.metrics.writes++;\n\n const metadata: StoredMetadata = {\n version: randomUUID(),\n createdAt: Date.now(),\n size: data.byteLength,\n digest: sha256(data),\n };\n\n const physical = encodePhysicalObject(key, metadata, data);\n const finalPath = this.objectPath(key, metadata.version);\n const parent = dirname(finalPath);\n\n await mkdir(parent, { recursive: true });\n\n const temporary = join(parent, `.${metadata.version}.${randomUUID()}.tmp`);\n\n let published = false;\n\n try {\n const handle = await open(temporary, \"wx\", 0o600);\n\n try {\n await writeAll(handle, physical);\n await handle.sync();\n } finally {\n await handle.close();\n }\n\n await this.fault(\"after-object-sync\", { operation: \"put\", key });\n await rename(temporary, finalPath);\n\n published = true;\n\n await this.fault(\"after-object-publish\", { operation: \"put\", key });\n await this.syncDirectory(parent);\n await this.fault(\"after-object-directory-sync\", { operation: \"put\", key });\n\n const frame: JournalPayload = {\n format: 1,\n sequence: this.sequence + 1,\n op: \"put\",\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n };\n\n await this.append(frame);\n\n this.setEntry(key, metadata);\n this.sequence = frame.sequence;\n this.metrics.bytesWritten += physical.byteLength;\n\n if (current) await this.removeObsolete(this.objectPath(key, current.version));\n\n return { success: true, version: metadata.version };\n } catch (error) {\n if (!published) await this.removeObsolete(temporary);\n throw error;\n }\n });\n }\n\n public delete(key: string, options: DeleteOptions): Promise<DeleteResult> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n assertWriteCondition(options?.condition);\n\n const current = this.entries.get(key);\n\n if (options.condition.type == \"if-absent\")\n return current ? { success: false, reason: \"conflict\" } : { success: true };\n\n if (!current || current.version != options.condition.version)\n return { success: false, reason: \"conflict\" };\n\n this.metrics.deletes++;\n\n const frame: JournalPayload = {\n format: 1,\n sequence: this.sequence + 1,\n op: \"delete\",\n key,\n };\n\n await this.append(frame);\n\n this.deleteEntry(key);\n this.sequence = frame.sequence;\n\n await this.removeObsolete(this.objectPath(key, current.version));\n\n return { success: true };\n });\n }\n\n public verifyExclusiveOwnership(): Promise<void> {\n return this.exclusive(() => this.ownership.verify());\n }\n public async *iterate(\n prefix: string,\n options: { readonly pageSize?: number; readonly signal?: AbortSignal } = {},\n ): AsyncIterable<StorageObjectInfo> {\n if (typeof prefix != \"string\" || prefix.includes(\"\\0\"))\n throw new StorageError(\"Invalid storage prefix\", \"INVALID_KEY\");\n\n const size = options.pageSize ?? 256;\n\n if (!Number.isSafeInteger(size) || size < 1 || size > 1000)\n throw new RangeError(\"Invalid listing page size\");\n\n const iterator = this.entries.entries();\n\n let done = false;\n\n while (!done) {\n options.signal?.throwIfAborted();\n\n const page = await this.exclusive(async () => {\n const entries: StorageObjectInfo[] = [];\n\n let visited = 0;\n\n while (visited++ < size) {\n const next = iterator.next();\n\n if (next.done) {\n done = true;\n break;\n }\n\n const [key, value] = next.value;\n\n if (key.startsWith(prefix))\n entries.push({ key, version: value.version, createdAt: value.createdAt });\n }\n\n return entries;\n });\n\n for (const entry of page) {\n options.signal?.throwIfAborted();\n yield entry;\n }\n }\n }\n\n public list(prefix: string): Promise<readonly StorageObjectInfo[]> {\n return this.exclusive(async () => {\n if (\n typeof prefix != \"string\" ||\n prefix.includes(\"\\0\") ||\n Buffer.byteLength(prefix, \"utf8\") > this.options.maxKeyBytes\n )\n throw new StorageError(\"Invalid storage prefix\", \"INVALID_KEY\");\n\n this.metrics.lists++;\n\n const result: StorageObjectInfo[] = [];\n\n for (const [key, value] of this.entries)\n if (key.startsWith(prefix)) {\n if (result.length >= 100_000)\n throw new StorageError(\"Listing limit exceeded; use iterate()\", \"RESOURCE_LIMIT\");\n result.push({ key, version: value.version, createdAt: value.createdAt });\n }\n\n return result.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n });\n }\n\n private async append(frame: JournalPayload): Promise<void> {\n const encoded = encodeJournalFrame(frame);\n\n if (this.journalBytes + encoded.byteLength > this.options.maxJournalBytes)\n throw new StorageError(\n \"Storage journal limit reached; compact before writing\",\n \"RESOURCE_LIMIT\",\n );\n\n try {\n await writeAll(this.journal, encoded, this.journalBytes);\n await this.fault(\"after-journal-write\", { operation: frame.op, key: frame.key });\n await this.journal.sync();\n await this.fault(\"after-journal-sync\", { operation: frame.op, key: frame.key });\n\n this.journalBytes += encoded.byteLength;\n this.metrics.bytesWritten += encoded.byteLength;\n } catch (cause) {\n this.poisoned = true;\n throw new StorageError(\"Storage publication outcome is unknown\", \"OUTCOME_UNKNOWN\", {\n cause,\n });\n }\n }\n\n public compact(): Promise<void> {\n return this.exclusive(async () => {\n try {\n const nextPath = join(this.root, NEXT_JOURNAL);\n const previousPath = join(this.root, PREVIOUS_JOURNAL);\n const currentPath = join(this.root, JOURNAL_FILE);\n\n await this.removeObsolete(nextPath);\n await this.removeObsolete(previousPath);\n\n const next = await open(nextPath, \"wx\", 0o600);\n\n let offset = 0;\n let sequence = 0;\n\n try {\n for (const [key, metadata] of this.entries) {\n const bytes = encodeJournalFrame({\n format: 1,\n sequence: ++sequence,\n op: \"put\",\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n });\n\n if (offset + bytes.byteLength > this.options.maxJournalBytes)\n throw new StorageError(\n \"Compacted journal exceeds configured limit\",\n \"RESOURCE_LIMIT\",\n );\n\n await writeAll(next, bytes, offset);\n offset += bytes.byteLength;\n }\n\n await next.sync();\n } finally {\n await next.close();\n }\n\n await this.journal.close();\n\n await rename(currentPath, previousPath);\n await rename(nextPath, currentPath);\n\n await this.syncDirectory(this.root);\n await this.fault(\"after-journal-rotation\", { operation: \"compact\" });\n\n this.journal = await open(currentPath, \"r+\");\n this.journalBytes = offset;\n this.sequence = sequence;\n\n await this.removeObsolete(previousPath);\n } catch (cause) {\n this.poisoned = true;\n throw new StorageError(\"Journal compaction outcome is unknown\", \"OUTCOME_UNKNOWN\", {\n cause,\n });\n }\n });\n }\n\n public close(): Promise<void> {\n if (!this.ownership.isOwned && this.closed) return Promise.resolve();\n if (this.closePromise) return this.closePromise;\n\n this.closing = true;\n const attempt = this.closeAttempt();\n this.closePromise = attempt;\n\n const clearAttempt = () => {\n if (this.closePromise == attempt) this.closePromise = undefined;\n };\n\n void attempt.then(clearAttempt, clearAttempt);\n\n return attempt;\n }\n\n private async closeAttempt(): Promise<void> {\n const failures: unknown[] = [];\n await this.operationTail;\n\n try {\n if (!this.resourcesClosed) {\n try {\n if (this.journal) await this.journal.close();\n this.resourcesClosed = true;\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length == 0) {\n try {\n await this.ownership.release();\n } catch (error) {\n failures.push(error);\n }\n }\n } finally {\n this.closed = true;\n this.closing = false;\n\n if (!this.ownership.isOwned)\n AsyncDiskStorageDriver.activeDirectories.delete(this.registryKey);\n }\n\n if (failures.length == 1) throw failures[0];\n\n if (failures.length > 1)\n throw new AggregateError(failures, \"Storage shutdown encountered multiple failures\");\n }\n\n private objectPath(key: string, version: string): string {\n const hash = sha256(new TextEncoder().encode(key));\n return join(this.root, OBJECTS_DIRECTORY, hash.slice(0, 2), hash, `${version}.obj`);\n }\n\n private async assertCurrentObjectsExist(): Promise<void> {\n for (const [key, metadata] of this.entries)\n try {\n await stat(this.objectPath(key, metadata.version));\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\")\n throw new StorageError(`Journal references a missing object: ${key}`, \"CORRUPTION\", {\n cause: error,\n });\n\n throw error;\n }\n }\n\n private async cleanupPhysicalObjects(): Promise<void> {\n const referenced = new Map<string, string>();\n\n for (const [key, metadata] of this.entries)\n referenced.set(sha256(new TextEncoder().encode(key)), metadata.version);\n\n const walk = async (directory: string): Promise<void> => {\n let items;\n\n try {\n items = await opendir(directory);\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\") return;\n throw error;\n }\n\n for await (const item of items) {\n const path = join(directory, item.name);\n\n if (item.isDirectory()) await walk(path);\n else if (\n item.isFile() &&\n (item.name.endsWith(\".tmp\") ||\n (item.name.endsWith(\".obj\") &&\n referenced.get(basename(dirname(path))) + \".obj\" != item.name))\n )\n await this.removeObsolete(path);\n }\n };\n\n await walk(join(this.root, OBJECTS_DIRECTORY));\n }\n\n private async recoverJournalRotation(): Promise<void> {\n const current = join(this.root, JOURNAL_FILE);\n const previous = join(this.root, PREVIOUS_JOURNAL);\n const next = join(this.root, NEXT_JOURNAL);\n\n const hasCurrent = await exists(current);\n const hasPrevious = await exists(previous);\n const hasNext = await exists(next);\n\n if (!hasCurrent) {\n if (hasNext) await rename(next, current);\n else if (hasPrevious) await rename(previous, current);\n } else if (hasPrevious) {\n try {\n const input = await open(current, \"r\");\n\n try {\n await replayJournal(input, this.options.maxJournalBytes, () => {});\n } finally {\n await input.close();\n }\n\n await this.removeObsolete(previous);\n } catch (cause) {\n throw new StorageError(\n \"Cannot establish journal rotation outcome; refusing to restore stale journal\",\n \"CORRUPTION\",\n { cause },\n );\n }\n }\n\n if ((await exists(current)) && (await exists(next))) await this.removeObsolete(next);\n if ((await exists(current)) && (await exists(previous))) await this.removeObsolete(previous);\n\n await this.syncDirectory(this.root);\n }\n\n private async fault(point: DiskFaultPoint, context: DiskFaultContext): Promise<void> {\n await this.options.faultInjector?.(point, context);\n }\n\n private async removeObsolete(path: string): Promise<void> {\n try {\n await rm(path, { force: true });\n } catch {\n /* Cleanup is retried during the next open. */\n }\n }\n\n private async syncDirectory(directory: string): Promise<void> {\n if (!this.directorySync) return;\n\n try {\n await AsyncDiskStorageDriver.syncDirectoryStatic(directory);\n } catch (error) {\n if ([\"EINVAL\", \"ENOTSUP\", \"EBADF\", \"EISDIR\", \"EPERM\"].includes(nodeErrorCode(error) ?? \"\"))\n this.directorySync = false;\n else throw error;\n }\n }\n\n private static async syncDirectoryStatic(directory: string): Promise<void> {\n const handle = await open(directory, \"r\");\n\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n }\n\n private async cleanupFailedOpen(): Promise<void> {\n const failures: unknown[] = [];\n\n try {\n if (this.journal) await this.journal.close();\n } catch (error) {\n failures.push(error);\n }\n\n if (failures.length == 0) {\n try {\n await this.ownership.release();\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length == 1) throw failures[0];\n\n if (failures.length > 1)\n throw new AggregateError(failures, \"Failed storage initialization cleanup\");\n }\n}\n"],"mappings":";;;;;;;AAGA,IAAM,eAAe,OAAO,KAAK,YAAY,OAAO;AACpD,IAAM,mBAAmB;AAyBzB,IAAM,UAAU,IAAI,YAAY;AAChC,IAAM,UAAU,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC;AAExD,SAAgB,OAAO,MAAmC;CACxD,QAAA,GAAOA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK;AACvD;AAEA,SAAS,WAAW,SAAiB,OAA+B;CAClE,OAAO,IAAIC,iBAAAA,aAAa,SAAS,cAAc,SAAS,OAAO,KAAA,IAAY,EA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AA,CAAK,WAAW,GAAG;EAExC,IAAI;GACF,MAAM,OAAO,KAAK;EACpB,UAAU;GACR,MAAM,OAAO,MAAM;EACrB;CACF;CAEA,MAAc,oBAAmC;EAC/C,MAAM,WAAsB,CAAC;EAE7B,IAAI;GACF,IAAI,KAAK,SAAS,MAAM,KAAK,QAAQ,MAAM;EAC7C,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAEA,IAAI,SAAS,UAAU,GACrB,IAAI;GACF,MAAM,KAAK,UAAU,QAAQ;EAC/B,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAGF,IAAI,SAAS,UAAU,GAAG,MAAM,SAAS;EAEzC,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,eAAe,UAAU,uCAAuC;CAC9E;AACF"}
package/dist/index.js CHANGED
@@ -939,7 +939,7 @@ var AsyncDiskStorageDriver = class AsyncDiskStorageDriver {
939
939
  this.metrics.lists++;
940
940
  const result = [];
941
941
  for (const [key, value] of this.entries) if (key.startsWith(prefix)) {
942
- if (result.length >= 1e5) throw new StorageError("Legacy listing limit exceeded; use iterate()", "RESOURCE_LIMIT");
942
+ if (result.length >= 1e5) throw new StorageError("Listing limit exceeded; use iterate()", "RESOURCE_LIMIT");
943
943
  result.push({
944
944
  key,
945
945
  version: value.version,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["parseRecord","writeAll"],"sources":["../src/disk-format.ts","../src/ownership.ts","../src/async-disk-storage.driver.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { StorageError } from \"@duraxis/storage\";\n\nconst OBJECT_MAGIC = Buffer.from(\"DXOBJ001\", \"ascii\");\nconst MAX_HEADER_BYTES = 16 * 1024;\nexport const MAX_JOURNAL_FRAME_BYTES = 64 * 1024;\n\nexport interface StoredMetadata {\n readonly version: string;\n readonly createdAt: number;\n readonly size: number;\n readonly digest: string;\n}\n\nexport type JournalPayload =\n | ({\n readonly format: 1;\n readonly sequence: number;\n readonly op: \"put\";\n readonly key: string;\n } & StoredMetadata)\n | { readonly format: 1; readonly sequence: number; readonly op: \"delete\"; readonly key: string };\n\nexport interface DecodedJournal {\n readonly frames: readonly JournalPayload[];\n readonly validBytes: number;\n readonly incompleteTail: boolean;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nexport function sha256(data: Uint8Array | string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\nfunction corruption(message: string, cause?: unknown): StorageError {\n return new StorageError(message, \"CORRUPTION\", cause == null ? undefined : { cause });\n}\n\nfunction parseRecord(bytes: Uint8Array, label: string): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(decoder.decode(bytes));\n if (!value || typeof value != \"object\" || Array.isArray(value))\n throw new Error(\"not an object\");\n return value as Record<string, unknown>;\n } catch (cause) {\n throw corruption(`Invalid ${label}`, cause);\n }\n}\n\nfunction validDigest(value: unknown): value is string {\n return typeof value == \"string\" && /^[0-9a-f]{64}$/.test(value);\n}\n\nfunction validateMetadata(\n value: Record<string, unknown>,\n): asserts value is Record<string, unknown> & StoredMetadata {\n if (\n typeof value.version != \"string\" ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(\n value.version,\n ) ||\n !Number.isSafeInteger(value.createdAt) ||\n (value.createdAt as number) < 0 ||\n !Number.isSafeInteger(value.size) ||\n (value.size as number) < 0 ||\n !validDigest(value.digest)\n )\n throw corruption(\"Invalid physical object metadata\");\n}\n\nexport function encodePhysicalObject(\n key: string,\n metadata: StoredMetadata,\n data: Uint8Array,\n): Uint8Array {\n const headerPayload = {\n format: 1 as const,\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n };\n const canonical = JSON.stringify(headerPayload);\n const header = encoder.encode(JSON.stringify({ ...headerPayload, checksum: sha256(canonical) }));\n if (header.byteLength > MAX_HEADER_BYTES)\n throw new StorageError(\"Object metadata is too large\", \"RESOURCE_LIMIT\");\n const result = new Uint8Array(OBJECT_MAGIC.length + 4 + header.length + data.length);\n result.set(OBJECT_MAGIC, 0);\n new DataView(result.buffer).setUint32(OBJECT_MAGIC.length, header.length, false);\n result.set(header, OBJECT_MAGIC.length + 4);\n result.set(data, OBJECT_MAGIC.length + 4 + header.length);\n return result;\n}\n\nexport function decodePhysicalObject(\n bytes: Uint8Array,\n expectedKey: string,\n expected: StoredMetadata,\n): Uint8Array {\n if (\n bytes.byteLength < OBJECT_MAGIC.length + 4 ||\n !Buffer.from(bytes.subarray(0, OBJECT_MAGIC.length)).equals(OBJECT_MAGIC)\n )\n throw corruption(\"Invalid physical object magic\");\n const headerLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(\n OBJECT_MAGIC.length,\n false,\n );\n if (\n headerLength == 0 ||\n headerLength > MAX_HEADER_BYTES ||\n OBJECT_MAGIC.length + 4 + headerLength > bytes.byteLength\n )\n throw corruption(\"Invalid physical object header length\");\n const header = parseRecord(\n bytes.subarray(OBJECT_MAGIC.length + 4, OBJECT_MAGIC.length + 4 + headerLength),\n \"physical object header\",\n );\n const fields = Object.keys(header).sort().join(\",\");\n if (\n fields != \"checksum,createdAt,digest,format,key,size,version\" ||\n header.format != 1 ||\n typeof header.key != \"string\" ||\n typeof header.checksum != \"string\"\n )\n throw corruption(\"Invalid physical object header\");\n validateMetadata(header);\n const canonical = JSON.stringify({\n format: 1,\n key: header.key,\n version: header.version,\n createdAt: header.createdAt,\n size: header.size,\n digest: header.digest,\n });\n if (sha256(canonical) != header.checksum)\n throw corruption(\"Physical metadata integrity check failed\");\n if (\n header.key != expectedKey ||\n header.version != expected.version ||\n header.createdAt != expected.createdAt ||\n header.size != expected.size ||\n header.digest != expected.digest\n )\n throw corruption(\"Physical object does not match journal metadata\");\n const data = bytes.subarray(OBJECT_MAGIC.length + 4 + headerLength);\n if (data.byteLength != expected.size || sha256(data) != expected.digest)\n throw corruption(\"Physical object payload integrity check failed\");\n return new Uint8Array(data);\n}\n\nexport function encodeJournalFrame(payload: JournalPayload): Uint8Array {\n const canonical = JSON.stringify(payload);\n const body = encoder.encode(JSON.stringify({ ...payload, checksum: sha256(canonical) }));\n if (body.byteLength > MAX_JOURNAL_FRAME_BYTES)\n throw new StorageError(\"Journal frame is too large\", \"RESOURCE_LIMIT\");\n const result = new Uint8Array(4 + body.byteLength);\n new DataView(result.buffer).setUint32(0, body.byteLength, false);\n result.set(body, 4);\n return result;\n}\n\nfunction decodeFrame(bytes: Uint8Array, expectedSequence: number): JournalPayload {\n const record = parseRecord(bytes, \"storage journal frame\");\n if (\n record.format != 1 ||\n record.sequence != expectedSequence ||\n (record.op != \"put\" && record.op != \"delete\") ||\n typeof record.key != \"string\" ||\n typeof record.checksum != \"string\"\n )\n throw corruption(\"Invalid storage journal frame\");\n let payload: JournalPayload;\n if (record.op == \"put\") {\n if (\n Object.keys(record).sort().join(\",\") !=\n \"checksum,createdAt,digest,format,key,op,sequence,size,version\"\n )\n throw corruption(\"Invalid put journal frame layout\");\n validateMetadata(record);\n payload = {\n format: 1,\n sequence: expectedSequence,\n op: \"put\",\n key: record.key,\n version: record.version,\n createdAt: record.createdAt,\n size: record.size,\n digest: record.digest,\n };\n } else {\n if (Object.keys(record).sort().join(\",\") != \"checksum,format,key,op,sequence\")\n throw corruption(\"Invalid delete journal frame layout\");\n payload = { format: 1, sequence: expectedSequence, op: \"delete\", key: record.key };\n }\n if (sha256(JSON.stringify(payload)) != record.checksum)\n throw corruption(\"Storage journal integrity check failed\");\n return payload;\n}\n\nexport function decodeJournal(bytes: Uint8Array): DecodedJournal {\n const frames: JournalPayload[] = [];\n let offset = 0;\n let sequence = 1;\n while (offset < bytes.byteLength) {\n if (bytes.byteLength - offset < 4) return { frames, validBytes: offset, incompleteTail: true };\n const length = new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(0, false);\n if (length == 0 || length > MAX_JOURNAL_FRAME_BYTES)\n throw corruption(\"Invalid storage journal frame length\");\n if (bytes.byteLength - offset - 4 < length)\n return { frames, validBytes: offset, incompleteTail: true };\n frames.push(decodeFrame(bytes.subarray(offset + 4, offset + 4 + length), sequence++));\n offset += 4 + length;\n }\n return { frames, validBytes: offset, incompleteTail: false };\n}\n\nexport async function replayJournal(\n handle: {\n stat(): Promise<{ readonly size: number }>;\n read(\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): Promise<{ readonly bytesRead: number }>;\n },\n maxBytes: number,\n consume: (payload: JournalPayload) => void,\n): Promise<Omit<DecodedJournal, \"frames\">> {\n const info = await handle.stat();\n\n if (info.size > maxBytes)\n throw new StorageError(\"Storage journal exceeds configured limit\", \"RESOURCE_LIMIT\");\n\n let offset = 0;\n let sequence = 1;\n\n const read = async (buffer: Uint8Array, position: number) => {\n let received = 0;\n\n while (received < buffer.byteLength) {\n const result = await handle.read(\n buffer,\n received,\n buffer.byteLength - received,\n position + received,\n );\n\n if (!result.bytesRead) break;\n\n received += result.bytesRead;\n }\n\n return received;\n };\n\n while (offset < info.size) {\n const header = new Uint8Array(4);\n\n if ((await read(header, offset)) != 4) return { validBytes: offset, incompleteTail: true };\n\n const length = new DataView(header.buffer).getUint32(0, false);\n\n if (!length || length > MAX_JOURNAL_FRAME_BYTES)\n throw corruption(\"Invalid storage journal frame length\");\n\n const payload = new Uint8Array(length);\n\n if ((await read(payload, offset + 4)) != length)\n return { validBytes: offset, incompleteTail: true };\n\n consume(decodeFrame(payload, sequence++));\n\n offset += 4 + length;\n }\n\n return { validBytes: offset, incompleteTail: false };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { open, readFile, readlink, stat, statfs, unlink, type FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { join } from \"node:path\";\nimport { StorageError } from \"@duraxis/storage\";\nimport { sha256 } from \"./disk-format.js\";\n\nconst LOCK_FILE = \".duraxis-owner.lock\";\nconst RECOVERY_GUARD_FILE = \".duraxis-owner.recovery\";\nconst OWNERSHIP_CONFIRMATION = \"I_HAVE_VERIFIED_EXCLUSIVE_ACCESS\";\nconst OWNER_FIELDS = \"applicationId,checksum,createdAt,format,hostname,ownerId,pid,processIdentity\";\nconst GUARD_FIELDS = \"checksum,createdAt,format,guardId,hostname,pid\";\nconst 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}$/;\nconst APPLICATION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._:/-]{0,126}[A-Za-z0-9])?$/;\nconst PROCESS_IDENTITY_PATTERN = /^(?:linux:(?:pid:\\[\\d+\\]|unavailable)|[a-z0-9]+:unverified)$/;\nconst MAX_METADATA_BYTES = 4096;\n\nconst LINUX_LOCAL_FILESYSTEMS = new Set([\n 0x0000ef53, // ext2/3/4\n 0x01021994, // tmpfs\n 0x2fc12fc1, // zfs\n 0x58465342, // xfs\n 0x794c7630, // overlayfs\n 0x858458f6, // ramfs\n 0x9123683e, // btrfs\n]);\n\nexport interface OwnershipRecoveryOptions {\n readonly mode: \"manual\" | \"dead-process\";\n readonly applicationId?: string;\n}\n\nexport interface RecoverOwnershipOptions {\n readonly directory: string;\n readonly confirmation: typeof OWNERSHIP_CONFIRMATION;\n}\n\nexport interface NormalizedOwnershipRecovery {\n readonly mode: \"manual\" | \"dead-process\";\n readonly applicationId?: string;\n}\n\ninterface OwnerPayload {\n readonly format: 2;\n readonly ownerId: string;\n readonly pid: number;\n readonly hostname: string;\n readonly createdAt: number;\n readonly applicationId: string | null;\n readonly processIdentity: string;\n}\n\ninterface OwnerRecord extends OwnerPayload {\n readonly checksum: string;\n}\n\ninterface GuardPayload {\n readonly format: 1;\n readonly guardId: string;\n readonly pid: number;\n readonly hostname: string;\n readonly createdAt: number;\n}\n\ninterface GuardRecord extends GuardPayload {\n readonly checksum: string;\n}\n\ninterface ObservedFile {\n readonly path: string;\n readonly handle: FileHandle;\n readonly identity: Stats;\n readonly bytes: Buffer;\n}\n\ninterface CoordinationGuard {\n readonly path: string;\n readonly handle: FileHandle;\n readonly identity: Stats;\n readonly bytes: Buffer;\n readonly guardId: string;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return error && typeof error == \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n}\n\nfunction ownershipConflict(message: string, cause?: unknown): StorageError {\n return new StorageError(message, \"OWNERSHIP_CONFLICT\", cause == null ? undefined : { cause });\n}\n\nfunction canonicalOwner(payload: OwnerPayload): string {\n return JSON.stringify(payload);\n}\n\nfunction canonicalGuard(payload: GuardPayload): string {\n return JSON.stringify(payload);\n}\n\nfunction validHostname(value: unknown): value is string {\n return (\n typeof value == \"string\" &&\n value.length > 0 &&\n value.length <= 255 &&\n !/[\\0-\\x1f\\x7f]/.test(value)\n );\n}\n\nfunction sameIdentity(left: Stats, right: Stats): boolean {\n return left.dev == right.dev && left.ino == right.ino;\n}\n\nasync function writeAll(handle: FileHandle, bytes: Uint8Array): Promise<void> {\n let offset = 0;\n\n while (offset < bytes.byteLength) {\n const result = await handle.write(bytes, offset, bytes.byteLength - offset, offset);\n\n if (result.bytesWritten <= 0)\n throw new StorageError(\"Ownership metadata write made no progress\", \"UNAVAILABLE\");\n\n offset += result.bytesWritten;\n }\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n let handle: FileHandle | undefined;\n\n try {\n handle = await open(directory, \"r\");\n await handle.sync();\n } catch (error) {\n if (![\"EINVAL\", \"ENOTSUP\", \"EBADF\", \"EISDIR\", \"EPERM\"].includes(errorCode(error) ?? \"\"))\n throw error;\n } finally {\n await handle?.close();\n }\n}\n\nasync function observe(path: string): Promise<ObservedFile | null> {\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"r\");\n } catch (error) {\n if (errorCode(error) == \"ENOENT\") return null;\n throw error;\n }\n\n try {\n const identity = await handle.stat();\n const bytes = await handle.readFile();\n\n return { path, handle, identity, bytes };\n } catch (error) {\n await handle.close().catch(() => undefined);\n throw error;\n }\n}\n\nasync function assertObservedUnchanged(observed: ObservedFile): Promise<void> {\n let currentIdentity: Stats;\n let currentBytes: Buffer;\n\n try {\n [currentIdentity, currentBytes] = await Promise.all([\n stat(observed.path),\n readFile(observed.path),\n ]);\n } catch (cause) {\n throw ownershipConflict(\"Ownership metadata changed during inspection\", cause);\n }\n\n if (!sameIdentity(observed.identity, currentIdentity) || !observed.bytes.equals(currentBytes))\n throw ownershipConflict(\"Ownership metadata changed during inspection\");\n}\n\nasync function removeObserved(observed: ObservedFile): Promise<void> {\n try {\n await assertObservedUnchanged(observed);\n } finally {\n await observed.handle.close();\n }\n\n try {\n await unlink(observed.path);\n } catch (cause) {\n throw ownershipConflict(\"Failed to remove the observed ownership lock\", cause);\n }\n}\n\nasync function removeCreatedFile(path: string, handle: FileHandle, identity: Stats): Promise<void> {\n await handle.close().catch(() => undefined);\n\n try {\n const current = await stat(path);\n\n if (!sameIdentity(identity, current))\n throw ownershipConflict(\"Created ownership file was replaced unexpectedly\");\n\n await unlink(path);\n } catch (error) {\n if (errorCode(error) != \"ENOENT\") throw error;\n }\n}\n\nfunction parseRecord(bytes: Uint8Array, label: string): Record<string, unknown> {\n if (bytes.byteLength == 0 || bytes.byteLength > MAX_METADATA_BYTES)\n throw ownershipConflict(`Invalid ${label}`);\n\n try {\n const value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (!value || typeof value != \"object\" || Array.isArray(value))\n throw new Error(\"not an object\");\n\n return value as Record<string, unknown>;\n } catch (cause) {\n throw ownershipConflict(`Invalid ${label}`, cause);\n }\n}\n\nfunction parseOwner(bytes: Uint8Array): OwnerRecord {\n const record = parseRecord(bytes, \"owner lock metadata\");\n\n if (record.format != 2)\n throw ownershipConflict(\n \"Owner lock format is incompatible with automatic recovery; use explicit manual recovery\",\n );\n\n if (\n Object.keys(record).sort().join(\",\") != OWNER_FIELDS ||\n !UUID_PATTERN.test(String(record.ownerId)) ||\n !Number.isSafeInteger(record.pid) ||\n (record.pid as number) <= 0 ||\n !validHostname(record.hostname) ||\n !Number.isSafeInteger(record.createdAt) ||\n (record.createdAt as number) < 0 ||\n (record.applicationId !== null &&\n (typeof record.applicationId != \"string\" ||\n !APPLICATION_ID_PATTERN.test(record.applicationId))) ||\n typeof record.processIdentity != \"string\" ||\n !PROCESS_IDENTITY_PATTERN.test(record.processIdentity) ||\n typeof record.checksum != \"string\" ||\n !/^[0-9a-f]{64}$/.test(record.checksum)\n )\n throw ownershipConflict(\"Invalid owner lock metadata\");\n\n const payload: OwnerPayload = {\n format: 2,\n ownerId: record.ownerId as string,\n pid: record.pid as number,\n hostname: record.hostname,\n createdAt: record.createdAt as number,\n applicationId: record.applicationId as string | null,\n processIdentity: record.processIdentity,\n };\n\n if (sha256(canonicalOwner(payload)) != record.checksum)\n throw ownershipConflict(\"Owner lock metadata checksum is invalid\");\n\n return { ...payload, checksum: record.checksum };\n}\n\nfunction parseGuard(bytes: Uint8Array): GuardRecord {\n const record = parseRecord(bytes, \"ownership recovery guard\");\n\n if (\n Object.keys(record).sort().join(\",\") != GUARD_FIELDS ||\n record.format != 1 ||\n !UUID_PATTERN.test(String(record.guardId)) ||\n !Number.isSafeInteger(record.pid) ||\n (record.pid as number) <= 0 ||\n !validHostname(record.hostname) ||\n !Number.isSafeInteger(record.createdAt) ||\n (record.createdAt as number) < 0 ||\n typeof record.checksum != \"string\" ||\n !/^[0-9a-f]{64}$/.test(record.checksum)\n )\n throw ownershipConflict(\"Invalid ownership recovery guard\");\n\n const payload: GuardPayload = {\n format: 1,\n guardId: record.guardId as string,\n pid: record.pid as number,\n hostname: record.hostname,\n createdAt: record.createdAt as number,\n };\n\n if (sha256(canonicalGuard(payload)) != record.checksum)\n throw ownershipConflict(\"Ownership recovery guard checksum is invalid\");\n\n return { ...payload, checksum: record.checksum };\n}\n\nasync function acquireGuard(root: string): Promise<CoordinationGuard> {\n const path = join(root, RECOVERY_GUARD_FILE);\n\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"wx\", 0o600);\n } catch (cause) {\n if (errorCode(cause) == \"EEXIST\")\n throw ownershipConflict(\n \"Another ownership operation is active or left an uncertain recovery guard\",\n cause,\n );\n\n throw cause;\n }\n let identity: Stats;\n try {\n identity = await handle.stat();\n } catch (cause) {\n await handle.close().catch(() => undefined);\n\n throw cause;\n }\n\n const payload: GuardPayload = {\n format: 1,\n guardId: randomUUID(),\n pid: process.pid,\n hostname: hostname(),\n createdAt: Date.now(),\n };\n\n const bytes = Buffer.from(\n JSON.stringify({ ...payload, checksum: sha256(canonicalGuard(payload)) }),\n );\n\n try {\n await writeAll(handle, bytes);\n await handle.sync();\n await syncDirectory(root);\n\n return { path, handle, identity, bytes, guardId: payload.guardId };\n } catch (cause) {\n try {\n await removeCreatedFile(path, handle, identity);\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Ownership guard creation and cleanup both failed\",\n );\n }\n throw cause;\n }\n}\n\nasync function releaseGuard(root: string, guard: CoordinationGuard): Promise<void> {\n try {\n const currentIdentity = await stat(guard.path);\n const currentBytes = await readFile(guard.path);\n const record = parseGuard(currentBytes);\n\n if (\n !sameIdentity(guard.identity, currentIdentity) ||\n !guard.bytes.equals(currentBytes) ||\n record.guardId != guard.guardId\n )\n throw ownershipConflict(\"Ownership recovery guard changed unexpectedly\");\n } finally {\n await guard.handle.close();\n }\n\n await unlink(guard.path);\n await syncDirectory(root);\n}\n\nasync function withGuard<T>(root: string, operation: () => Promise<T>): Promise<T> {\n const guard = await acquireGuard(root);\n let result: T | undefined;\n let operationFailure: unknown;\n\n try {\n result = await operation();\n } catch (error) {\n operationFailure = error;\n }\n\n try {\n await releaseGuard(root, guard);\n } catch (guardFailure) {\n if (operationFailure != null)\n throw new AggregateError(\n [operationFailure, guardFailure],\n \"Ownership operation and recovery-guard release both failed\",\n );\n\n throw guardFailure;\n }\n\n if (operationFailure != null) throw operationFailure;\n\n return result as T;\n}\n\nasync function automaticProcessIdentity(root: string): Promise<string> {\n if (process.platform != \"linux\")\n throw ownershipConflict(\n \"Automatic dead-process recovery is supported only on validated Linux environments\",\n );\n\n let namespace: string;\n\n try {\n namespace = await readlink(\"/proc/self/ns/pid\");\n } catch (cause) {\n throw ownershipConflict(\"The Linux PID namespace cannot be established\", cause);\n }\n\n if (!/^pid:\\[\\d+\\]$/.test(namespace))\n throw ownershipConflict(\"The Linux PID namespace identity is invalid\");\n\n let filesystemType: number;\n\n try {\n filesystemType = (await statfs(root)).type >>> 0;\n } catch (cause) {\n throw ownershipConflict(\"The storage filesystem type cannot be established\", cause);\n }\n\n if (!LINUX_LOCAL_FILESYSTEMS.has(filesystemType))\n throw ownershipConflict(\n `Automatic recovery is not supported on filesystem type 0x${filesystemType.toString(16)}`,\n );\n\n return `linux:${namespace}`;\n}\n\nasync function processIdentityForLock(root: string, mode: \"manual\" | \"dead-process\") {\n if (mode == \"dead-process\") return await automaticProcessIdentity(root);\n\n if (process.platform == \"linux\") {\n try {\n return `linux:${await readlink(\"/proc/self/ns/pid\")}`;\n } catch {\n return \"linux:unavailable\";\n }\n }\n return `${process.platform}:unverified`;\n}\n\nfunction assertRecoverableOwner(\n owner: OwnerRecord,\n recovery: NormalizedOwnershipRecovery,\n processIdentity: string,\n): void {\n if (owner.hostname != hostname())\n throw ownershipConflict(\"Owner lock belongs to a different host\");\n\n if (owner.processIdentity != processIdentity)\n throw ownershipConflict(\"Owner lock belongs to a different or unsupported process namespace\");\n\n if (owner.applicationId != (recovery.applicationId ?? null))\n throw ownershipConflict(\"Owner lock belongs to a different application identity\");\n\n try {\n process.kill(owner.pid, 0);\n } catch (cause) {\n if (errorCode(cause) == \"ESRCH\") return;\n\n if (errorCode(cause) == \"EPERM\")\n throw ownershipConflict(\"Owner process existence is inconclusive\", cause);\n\n throw ownershipConflict(\"Owner process existence could not be determined\", cause);\n }\n\n throw ownershipConflict(\n \"Owner process may still be running; PID reuse is treated as an ownership conflict\",\n );\n}\n\nasync function createOwnerFile(\n root: string,\n ownerId: string,\n recovery: NormalizedOwnershipRecovery,\n processIdentity: string,\n): Promise<{ handle: FileHandle; identity: Stats } | null> {\n const path = join(root, LOCK_FILE);\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"wx\", 0o600);\n } catch (error) {\n if (errorCode(error) == \"EEXIST\") return null;\n throw error;\n }\n\n let identity: Stats;\n\n try {\n identity = await handle.stat();\n } catch (cause) {\n await handle.close().catch(() => undefined);\n throw cause;\n }\n\n const payload: OwnerPayload = {\n format: 2,\n ownerId,\n pid: process.pid,\n hostname: hostname(),\n createdAt: Date.now(),\n applicationId: recovery.applicationId ?? null,\n processIdentity,\n };\n\n const bytes = Buffer.from(\n JSON.stringify({ ...payload, checksum: sha256(canonicalOwner(payload)) }),\n );\n\n try {\n await writeAll(handle, bytes);\n await handle.sync();\n await syncDirectory(root);\n return { handle, identity };\n } catch (cause) {\n try {\n await removeCreatedFile(path, handle, identity);\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Owner lock creation and cleanup both failed\",\n );\n }\n\n throw cause;\n }\n}\n\nexport function normalizeOwnershipRecovery(\n options: OwnershipRecoveryOptions | undefined,\n): NormalizedOwnershipRecovery {\n if (options == null) return { mode: \"manual\" };\n\n if (options.mode != \"manual\" && options.mode != \"dead-process\")\n throw new TypeError('ownershipRecovery.mode must be \"manual\" or \"dead-process\"');\n\n if (\n options.applicationId != null &&\n (typeof options.applicationId != \"string\" ||\n !APPLICATION_ID_PATTERN.test(options.applicationId))\n )\n throw new TypeError(\"ownershipRecovery.applicationId must be 1-128 safe identifier characters\");\n\n return {\n mode: options.mode,\n ...(options.applicationId == null ? {} : { applicationId: options.applicationId }),\n };\n}\n\nexport class DirectoryOwnership {\n readonly #ownerId = randomUUID();\n #lockHandle?: FileHandle;\n #owned = false;\n\n public constructor(\n private readonly root: string,\n private readonly recovery: NormalizedOwnershipRecovery,\n ) {}\n\n public get isOwned(): boolean {\n return this.#owned;\n }\n\n public async acquire(): Promise<void> {\n const processIdentity = await processIdentityForLock(this.root, this.recovery.mode);\n\n await withGuard(this.root, async () => {\n let created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);\n if (!created) {\n if (this.recovery.mode == \"manual\")\n throw ownershipConflict(\n \"Storage directory has an owner lock; close the owner or perform explicit abandoned-lock recovery\",\n );\n\n const observed = await observe(join(this.root, LOCK_FILE));\n\n if (observed) {\n let owner: OwnerRecord;\n\n try {\n owner = parseOwner(observed.bytes);\n assertRecoverableOwner(owner, this.recovery, processIdentity);\n await removeObserved(observed);\n } catch (error) {\n await observed.handle.close().catch(() => undefined);\n throw error;\n }\n\n await syncDirectory(this.root);\n }\n\n created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);\n\n if (!created)\n throw ownershipConflict(\"Another process acquired storage ownership during recovery\");\n }\n this.#lockHandle = created.handle;\n this.#owned = true;\n });\n }\n\n public async verify(): Promise<void> {\n if (!this.#owned) throw ownershipConflict(\"Storage directory is not owned\");\n\n await withGuard(this.root, async () => {\n const observed = await observe(join(this.root, LOCK_FILE));\n\n if (!observed) throw ownershipConflict(\"Storage owner lock is missing\");\n\n try {\n if (parseOwner(observed.bytes).ownerId != this.#ownerId)\n throw ownershipConflict(\"Storage ownership changed\");\n\n await assertObservedUnchanged(observed);\n } finally {\n await observed.handle.close();\n }\n });\n }\n\n public async release(): Promise<void> {\n if (!this.#owned) return;\n\n await withGuard(this.root, async () => {\n const observed = await observe(join(this.root, LOCK_FILE));\n if (!observed) {\n this.#owned = false;\n await this.#lockHandle?.close().catch(() => undefined);\n\n this.#lockHandle = undefined;\n throw ownershipConflict(\"Current owner lock is missing\");\n }\n\n try {\n const owner = parseOwner(observed.bytes);\n\n if (owner.ownerId != this.#ownerId)\n throw ownershipConflict(\"Storage ownership changed unexpectedly\");\n\n await this.#lockHandle?.close();\n this.#lockHandle = undefined;\n\n await removeObserved(observed);\n this.#owned = false;\n\n await syncDirectory(this.root);\n } catch (error) {\n await observed.handle.close().catch(() => undefined);\n throw error;\n }\n });\n }\n}\n\nexport async function manuallyRecoverOwnership(root: string): Promise<void> {\n await withGuard(root, async () => {\n const observed = await observe(join(root, LOCK_FILE));\n if (!observed) return;\n await removeObserved(observed);\n await syncDirectory(root);\n });\n}\n\nexport function validateManualRecoveryConfirmation(\n confirmation: RecoverOwnershipOptions[\"confirmation\"],\n): void {\n if (confirmation != OWNERSHIP_CONFIRMATION)\n throw new StorageError(\"Explicit exclusive-access confirmation is required\", \"ACCESS_DENIED\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport {\n mkdir,\n open,\n readFile,\n opendir,\n realpath,\n rename,\n rm,\n stat,\n truncate,\n type FileHandle,\n} from \"node:fs/promises\";\nimport {\n assertStorageKey,\n assertWriteCondition,\n StorageError,\n type DeleteOptions,\n type DeleteResult,\n type StorageDriver,\n type StorageDriverMetrics,\n type StorageObject,\n type StorageObjectInfo,\n type WriteOptions,\n type WriteResult,\n} from \"@duraxis/storage\";\nimport {\n replayJournal,\n decodePhysicalObject,\n encodeJournalFrame,\n encodePhysicalObject,\n sha256,\n type JournalPayload,\n type StoredMetadata,\n} from \"./disk-format.js\";\nimport {\n DirectoryOwnership,\n manuallyRecoverOwnership,\n normalizeOwnershipRecovery,\n validateManualRecoveryConfirmation,\n type NormalizedOwnershipRecovery,\n type OwnershipRecoveryOptions,\n type RecoverOwnershipOptions,\n} from \"./ownership.js\";\n\nconst JOURNAL_FILE = \"journal.log\";\nconst PREVIOUS_JOURNAL = \"journal.previous\";\nconst NEXT_JOURNAL = \"journal.next\";\nconst OBJECTS_DIRECTORY = \"objects\";\n\nconst MAX_KEY_BYTES = 4096;\nconst MAX_OBJECT_BYTES = 256 * 1024 * 1024;\nconst MAX_JOURNAL_BYTES = 1024 * 1024 * 1024;\n\nexport type { OwnershipRecoveryOptions, RecoverOwnershipOptions } from \"./ownership.js\";\n\nexport type DiskFaultPoint =\n | \"after-object-sync\"\n | \"after-object-publish\"\n | \"after-object-directory-sync\"\n | \"after-journal-write\"\n | \"after-journal-sync\"\n | \"after-journal-rotation\";\n\nexport interface DiskFaultContext {\n readonly operation: \"put\" | \"delete\" | \"compact\";\n readonly key?: string;\n}\n\nexport interface AsyncDiskStorageOptions {\n readonly directory: string;\n readonly ownershipRecovery?: OwnershipRecoveryOptions;\n readonly maxKeyBytes?: number;\n readonly maxObjectBytes?: number;\n readonly maxJournalBytes?: number;\n readonly maxMetadataBytes?: number;\n readonly maxQueuedOperations?: number;\n readonly nodeCacheHint?: number;\n readonly faultInjector?: (\n point: DiskFaultPoint,\n context: DiskFaultContext,\n ) => void | Promise<void>;\n}\n\nexport interface DiskDurabilityCapabilities {\n readonly fileDataSync: true;\n readonly directoryEntrySync: boolean;\n readonly ownership: \"exclusive-directory\";\n readonly processCrashRecovery: true;\n readonly powerLossGuarantee: \"file-and-directory-sync\" | \"file-sync-only\";\n}\n\ninterface MutableMetrics {\n reads: number;\n writes: number;\n deletes: number;\n lists: number;\n bytesRead: number;\n bytesWritten: number;\n synchronizationWaitMs: number;\n}\n\nfunction nodeErrorCode(error: unknown): string | undefined {\n return error && typeof error == \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\") return false;\n throw error;\n }\n}\n\nasync function writeAll(handle: FileHandle, bytes: Uint8Array, position = 0): Promise<void> {\n let offset = 0;\n\n while (offset < bytes.byteLength) {\n const result = await handle.write(bytes, offset, bytes.byteLength - offset, position + offset);\n\n if (result.bytesWritten <= 0)\n throw new StorageError(\"Disk write made no progress\", \"UNAVAILABLE\");\n\n offset += result.bytesWritten;\n }\n}\n\nasync function syncAndClose(handle: FileHandle, context: string): Promise<void> {\n let syncFailure: unknown;\n\n try {\n await handle.sync();\n } catch (error) {\n syncFailure = error;\n }\n\n try {\n await handle.close();\n } catch (closeFailure) {\n if (syncFailure != null)\n throw new AggregateError(\n [syncFailure, closeFailure],\n `${context} sync and close both failed`,\n );\n\n throw closeFailure;\n }\n\n if (syncFailure != null) throw syncFailure;\n}\n\nexport class AsyncDiskStorageDriver implements StorageDriver {\n public readonly capabilities = Object.freeze({ boundedReads: true });\n private static readonly activeDirectories = new Set<string>();\n\n private readonly entries = new Map<string, StoredMetadata>();\n private readonly ownership: DirectoryOwnership;\n private readonly metrics: MutableMetrics = {\n reads: 0,\n writes: 0,\n deletes: 0,\n lists: 0,\n bytesRead: 0,\n bytesWritten: 0,\n synchronizationWaitMs: 0,\n };\n\n private metadataBytes = 0;\n private queuedOperations = 0;\n\n private operationTail: Promise<void> = Promise.resolve();\n private journal!: FileHandle;\n private journalBytes = 0;\n private sequence = 0;\n private directorySync = true;\n private closed = false;\n private closing = false;\n private resourcesClosed = false;\n private closePromise?: Promise<void>;\n private poisoned = false;\n\n private constructor(\n private readonly root: string,\n private readonly registryKey: string,\n private readonly options: Required<\n Pick<AsyncDiskStorageOptions, \"maxKeyBytes\" | \"maxObjectBytes\" | \"maxJournalBytes\">\n > &\n AsyncDiskStorageOptions & { readonly ownershipRecovery: NormalizedOwnershipRecovery },\n ) {\n this.ownership = new DirectoryOwnership(root, options.ownershipRecovery);\n }\n\n public static async open(options: AsyncDiskStorageOptions): Promise<AsyncDiskStorageDriver> {\n if (!options || typeof options.directory != \"string\" || options.directory.trim() == \"\")\n throw new TypeError(\"A storage directory is required\");\n\n const maxKeyBytes = options.maxKeyBytes ?? MAX_KEY_BYTES;\n const maxObjectBytes = options.maxObjectBytes ?? MAX_OBJECT_BYTES;\n const maxJournalBytes = options.maxJournalBytes ?? MAX_JOURNAL_BYTES;\n\n const ownershipRecovery = normalizeOwnershipRecovery(options.ownershipRecovery);\n\n if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes < 64 || maxKeyBytes > 64 * 1024)\n throw new RangeError(\"Invalid maximum storage key size\");\n\n if (\n !Number.isSafeInteger(maxObjectBytes) ||\n maxObjectBytes < 0 ||\n maxObjectBytes > MAX_JOURNAL_BYTES\n )\n throw new RangeError(\"Invalid maximum object size\");\n\n if (!Number.isSafeInteger(maxJournalBytes) || maxJournalBytes < 1024 * 1024)\n throw new RangeError(\"Invalid maximum journal size\");\n\n for (const value of [options.maxMetadataBytes, options.maxQueuedOperations])\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1))\n throw new RangeError(\"Invalid storage resource limit\");\n\n const requested = resolve(options.directory);\n\n await mkdir(requested, { recursive: true });\n\n const root = await realpath(requested);\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\n \"Storage directory is already owned by this process\",\n \"OWNERSHIP_CONFLICT\",\n );\n\n this.activeDirectories.add(registryKey);\n\n const driver = new AsyncDiskStorageDriver(root, registryKey, {\n ...options,\n directory: root,\n maxKeyBytes,\n maxObjectBytes,\n maxJournalBytes,\n ownershipRecovery,\n });\n\n try {\n await driver.initialize();\n return driver;\n } catch (cause) {\n try {\n await driver.cleanupFailedOpen();\n } catch (cleanupCause) {\n if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);\n throw new AggregateError(\n [cause, cleanupCause],\n \"Storage initialization and ownership cleanup both failed\",\n );\n }\n if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);\n throw cause;\n }\n }\n\n public static async recoverAbandonedOwnership(options: RecoverOwnershipOptions): Promise<void> {\n validateManualRecoveryConfirmation(options.confirmation);\n\n const root = await realpath(resolve(options.directory));\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\"Cannot recover ownership held by this process\", \"OWNERSHIP_CONFLICT\");\n\n await manuallyRecoverOwnership(root);\n }\n\n public get durability(): DiskDurabilityCapabilities {\n return {\n fileDataSync: true,\n directoryEntrySync: this.directorySync,\n ownership: \"exclusive-directory\",\n processCrashRecovery: true,\n powerLossGuarantee: this.directorySync ? \"file-and-directory-sync\" : \"file-sync-only\",\n };\n }\n\n public getMetrics(): Readonly<StorageDriverMetrics> {\n return { ...this.metrics };\n }\n\n private async initialize(): Promise<void> {\n await this.ownership.acquire();\n await mkdir(join(this.root, OBJECTS_DIRECTORY), { recursive: true });\n await this.recoverJournalRotation();\n\n const journalPath = join(this.root, JOURNAL_FILE);\n\n if (!(await exists(journalPath))) {\n const created = await open(journalPath, \"wx\", 0o600);\n await syncAndClose(created, \"New storage journal\");\n await this.syncDirectory(this.root);\n }\n\n const input = await open(journalPath, \"r\");\n let decoded: Awaited<ReturnType<typeof replayJournal>>;\n\n try {\n decoded = await replayJournal(input, this.options.maxJournalBytes, (frame) => {\n this.validateKey(frame.key);\n this.sequence = frame.sequence;\n\n if (frame.op == \"put\")\n this.setEntry(frame.key, {\n version: frame.version,\n createdAt: frame.createdAt,\n size: frame.size,\n digest: frame.digest,\n });\n else this.deleteEntry(frame.key);\n });\n } finally {\n await input.close();\n }\n\n if (decoded.incompleteTail) {\n await truncate(journalPath, decoded.validBytes);\n const repaired = await open(journalPath, \"r+\");\n await syncAndClose(repaired, \"Repaired storage journal\");\n }\n\n this.journalBytes = decoded.validBytes;\n this.journal = await open(journalPath, \"r+\");\n\n await this.assertCurrentObjectsExist();\n await this.cleanupPhysicalObjects();\n }\n\n private setEntry(key: string, value: StoredMetadata): void {\n const size = this.entries.has(key) ? 0 : key.length * 2 + 256;\n\n if (this.metadataBytes + size > (this.options.maxMetadataBytes ?? 64 * 1024 * 1024))\n throw new StorageError(\"Resident storage metadata limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.metadataBytes += size;\n this.entries.set(key, value);\n }\n\n private deleteEntry(key: string): void {\n if (this.entries.delete(key)) this.metadataBytes -= key.length * 2 + 256;\n }\n\n private validateKey(key: string): void {\n assertStorageKey(key);\n\n if (Buffer.byteLength(key, \"utf8\") > this.options.maxKeyBytes)\n throw new StorageError(\"Storage key exceeds configured byte limit\", \"INVALID_KEY\");\n }\n\n private assertUsable(): void {\n if (this.closed || this.closing) throw new StorageError(\"Storage driver is closed\", \"CLOSED\");\n\n if (this.poisoned)\n throw new StorageError(\n \"Storage outcome is unknown; close and reopen before continuing\",\n \"OUTCOME_UNKNOWN\",\n );\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n this.assertUsable();\n\n if (this.queuedOperations >= (this.options.maxQueuedOperations ?? 256))\n throw new StorageError(\"Storage operation admission limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.queuedOperations++;\n\n const before = performance.now();\n const previous = this.operationTail;\n\n let release!: () => void;\n\n this.operationTail = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await previous;\n this.metrics.synchronizationWaitMs += performance.now() - before;\n\n try {\n this.assertUsable();\n return await operation();\n } finally {\n this.queuedOperations--;\n release();\n }\n }\n\n public get(\n key: string,\n options: { readonly signal?: AbortSignal; readonly maxBytes?: number } = {},\n ): Promise<StorageObject | null> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n options.signal?.throwIfAborted();\n this.metrics.reads++;\n\n const metadata = this.entries.get(key);\n\n if (!metadata) return null;\n\n if (metadata.size > (options.maxBytes ?? this.options.maxObjectBytes))\n throw new StorageError(\"Storage read exceeds byte limit\", \"RESOURCE_LIMIT\");\n\n const path = this.objectPath(key, metadata.version);\n\n let info;\n\n try {\n info = await stat(path);\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\")\n throw new StorageError(`Missing physical object for key ${key}`, \"CORRUPTION\", {\n cause: error,\n });\n throw error;\n }\n\n if (info.size > this.options.maxObjectBytes + 32 * 1024)\n throw new StorageError(\"Physical object exceeds configured size\", \"CORRUPTION\");\n\n const physical = await readFile(path, { signal: options.signal });\n\n this.metrics.bytesRead += physical.byteLength;\n\n return { data: decodePhysicalObject(physical, key, metadata), version: metadata.version };\n });\n }\n\n public put(key: string, data: Uint8Array, options: WriteOptions): Promise<WriteResult> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n if (!(data instanceof Uint8Array)) throw new TypeError(\"Storage data must be a Uint8Array\");\n\n if (data.byteLength > this.options.maxObjectBytes)\n throw new StorageError(\"Storage object exceeds configured byte limit\", \"RESOURCE_LIMIT\");\n\n assertWriteCondition(options?.condition);\n\n const current = this.entries.get(key);\n\n if (\n options.condition.type == \"if-absent\"\n ? current != null\n : current == null || current.version != options.condition.version\n )\n return { success: false, reason: \"conflict\" };\n\n if (\n !this.entries.has(key) &&\n this.metadataBytes + key.length * 2 + 256 >\n (this.options.maxMetadataBytes ?? 64 * 1024 * 1024)\n )\n throw new StorageError(\"Resident storage metadata limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.metrics.writes++;\n\n const metadata: StoredMetadata = {\n version: randomUUID(),\n createdAt: Date.now(),\n size: data.byteLength,\n digest: sha256(data),\n };\n\n const physical = encodePhysicalObject(key, metadata, data);\n const finalPath = this.objectPath(key, metadata.version);\n const parent = dirname(finalPath);\n\n await mkdir(parent, { recursive: true });\n\n const temporary = join(parent, `.${metadata.version}.${randomUUID()}.tmp`);\n\n let published = false;\n\n try {\n const handle = await open(temporary, \"wx\", 0o600);\n\n try {\n await writeAll(handle, physical);\n await handle.sync();\n } finally {\n await handle.close();\n }\n\n await this.fault(\"after-object-sync\", { operation: \"put\", key });\n await rename(temporary, finalPath);\n\n published = true;\n\n await this.fault(\"after-object-publish\", { operation: \"put\", key });\n await this.syncDirectory(parent);\n await this.fault(\"after-object-directory-sync\", { operation: \"put\", key });\n\n const frame: JournalPayload = {\n format: 1,\n sequence: this.sequence + 1,\n op: \"put\",\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n };\n\n await this.append(frame);\n\n this.setEntry(key, metadata);\n this.sequence = frame.sequence;\n this.metrics.bytesWritten += physical.byteLength;\n\n if (current) await this.removeObsolete(this.objectPath(key, current.version));\n\n return { success: true, version: metadata.version };\n } catch (error) {\n if (!published) await this.removeObsolete(temporary);\n throw error;\n }\n });\n }\n\n public delete(key: string, options: DeleteOptions): Promise<DeleteResult> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n assertWriteCondition(options?.condition);\n\n const current = this.entries.get(key);\n\n if (options.condition.type == \"if-absent\")\n return current ? { success: false, reason: \"conflict\" } : { success: true };\n\n if (!current || current.version != options.condition.version)\n return { success: false, reason: \"conflict\" };\n\n this.metrics.deletes++;\n\n const frame: JournalPayload = {\n format: 1,\n sequence: this.sequence + 1,\n op: \"delete\",\n key,\n };\n\n await this.append(frame);\n\n this.deleteEntry(key);\n this.sequence = frame.sequence;\n\n await this.removeObsolete(this.objectPath(key, current.version));\n\n return { success: true };\n });\n }\n\n public verifyExclusiveOwnership(): Promise<void> {\n return this.exclusive(() => this.ownership.verify());\n }\n public async *iterate(\n prefix: string,\n options: { readonly pageSize?: number; readonly signal?: AbortSignal } = {},\n ): AsyncIterable<StorageObjectInfo> {\n if (typeof prefix != \"string\" || prefix.includes(\"\\0\"))\n throw new StorageError(\"Invalid storage prefix\", \"INVALID_KEY\");\n\n const size = options.pageSize ?? 256;\n\n if (!Number.isSafeInteger(size) || size < 1 || size > 1000)\n throw new RangeError(\"Invalid listing page size\");\n\n const iterator = this.entries.entries();\n\n let done = false;\n\n while (!done) {\n options.signal?.throwIfAborted();\n\n const page = await this.exclusive(async () => {\n const entries: StorageObjectInfo[] = [];\n\n let visited = 0;\n\n while (visited++ < size) {\n const next = iterator.next();\n\n if (next.done) {\n done = true;\n break;\n }\n\n const [key, value] = next.value;\n\n if (key.startsWith(prefix))\n entries.push({ key, version: value.version, createdAt: value.createdAt });\n }\n\n return entries;\n });\n\n for (const entry of page) {\n options.signal?.throwIfAborted();\n yield entry;\n }\n }\n }\n\n public list(prefix: string): Promise<readonly StorageObjectInfo[]> {\n return this.exclusive(async () => {\n if (\n typeof prefix != \"string\" ||\n prefix.includes(\"\\0\") ||\n Buffer.byteLength(prefix, \"utf8\") > this.options.maxKeyBytes\n )\n throw new StorageError(\"Invalid storage prefix\", \"INVALID_KEY\");\n\n this.metrics.lists++;\n\n const result: StorageObjectInfo[] = [];\n\n for (const [key, value] of this.entries)\n if (key.startsWith(prefix)) {\n if (result.length >= 100_000)\n throw new StorageError(\n \"Legacy listing limit exceeded; use iterate()\",\n \"RESOURCE_LIMIT\",\n );\n result.push({ key, version: value.version, createdAt: value.createdAt });\n }\n\n return result.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n });\n }\n\n private async append(frame: JournalPayload): Promise<void> {\n const encoded = encodeJournalFrame(frame);\n\n if (this.journalBytes + encoded.byteLength > this.options.maxJournalBytes)\n throw new StorageError(\n \"Storage journal limit reached; compact before writing\",\n \"RESOURCE_LIMIT\",\n );\n\n try {\n await writeAll(this.journal, encoded, this.journalBytes);\n await this.fault(\"after-journal-write\", { operation: frame.op, key: frame.key });\n await this.journal.sync();\n await this.fault(\"after-journal-sync\", { operation: frame.op, key: frame.key });\n\n this.journalBytes += encoded.byteLength;\n this.metrics.bytesWritten += encoded.byteLength;\n } catch (cause) {\n this.poisoned = true;\n throw new StorageError(\"Storage publication outcome is unknown\", \"OUTCOME_UNKNOWN\", {\n cause,\n });\n }\n }\n\n public compact(): Promise<void> {\n return this.exclusive(async () => {\n try {\n const nextPath = join(this.root, NEXT_JOURNAL);\n const previousPath = join(this.root, PREVIOUS_JOURNAL);\n const currentPath = join(this.root, JOURNAL_FILE);\n\n await this.removeObsolete(nextPath);\n await this.removeObsolete(previousPath);\n\n const next = await open(nextPath, \"wx\", 0o600);\n\n let offset = 0;\n let sequence = 0;\n\n try {\n for (const [key, metadata] of this.entries) {\n const bytes = encodeJournalFrame({\n format: 1,\n sequence: ++sequence,\n op: \"put\",\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n });\n\n if (offset + bytes.byteLength > this.options.maxJournalBytes)\n throw new StorageError(\n \"Compacted journal exceeds configured limit\",\n \"RESOURCE_LIMIT\",\n );\n\n await writeAll(next, bytes, offset);\n offset += bytes.byteLength;\n }\n\n await next.sync();\n } finally {\n await next.close();\n }\n\n await this.journal.close();\n\n await rename(currentPath, previousPath);\n await rename(nextPath, currentPath);\n\n await this.syncDirectory(this.root);\n await this.fault(\"after-journal-rotation\", { operation: \"compact\" });\n\n this.journal = await open(currentPath, \"r+\");\n this.journalBytes = offset;\n this.sequence = sequence;\n\n await this.removeObsolete(previousPath);\n } catch (cause) {\n this.poisoned = true;\n throw new StorageError(\"Journal compaction outcome is unknown\", \"OUTCOME_UNKNOWN\", {\n cause,\n });\n }\n });\n }\n\n public close(): Promise<void> {\n if (!this.ownership.isOwned && this.closed) return Promise.resolve();\n if (this.closePromise) return this.closePromise;\n\n this.closing = true;\n const attempt = this.closeAttempt();\n this.closePromise = attempt;\n\n const clearAttempt = () => {\n if (this.closePromise == attempt) this.closePromise = undefined;\n };\n\n void attempt.then(clearAttempt, clearAttempt);\n\n return attempt;\n }\n\n private async closeAttempt(): Promise<void> {\n const failures: unknown[] = [];\n await this.operationTail;\n\n try {\n if (!this.resourcesClosed) {\n try {\n if (this.journal) await this.journal.close();\n this.resourcesClosed = true;\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length == 0) {\n try {\n await this.ownership.release();\n } catch (error) {\n failures.push(error);\n }\n }\n } finally {\n this.closed = true;\n this.closing = false;\n\n if (!this.ownership.isOwned)\n AsyncDiskStorageDriver.activeDirectories.delete(this.registryKey);\n }\n\n if (failures.length == 1) throw failures[0];\n\n if (failures.length > 1)\n throw new AggregateError(failures, \"Storage shutdown encountered multiple failures\");\n }\n\n private objectPath(key: string, version: string): string {\n const hash = sha256(new TextEncoder().encode(key));\n return join(this.root, OBJECTS_DIRECTORY, hash.slice(0, 2), hash, `${version}.obj`);\n }\n\n private async assertCurrentObjectsExist(): Promise<void> {\n for (const [key, metadata] of this.entries)\n try {\n await stat(this.objectPath(key, metadata.version));\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\")\n throw new StorageError(`Journal references a missing object: ${key}`, \"CORRUPTION\", {\n cause: error,\n });\n\n throw error;\n }\n }\n\n private async cleanupPhysicalObjects(): Promise<void> {\n const referenced = new Map<string, string>();\n\n for (const [key, metadata] of this.entries)\n referenced.set(sha256(new TextEncoder().encode(key)), metadata.version);\n\n const walk = async (directory: string): Promise<void> => {\n let items;\n\n try {\n items = await opendir(directory);\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\") return;\n throw error;\n }\n\n for await (const item of items) {\n const path = join(directory, item.name);\n\n if (item.isDirectory()) await walk(path);\n else if (\n item.isFile() &&\n (item.name.endsWith(\".tmp\") ||\n (item.name.endsWith(\".obj\") &&\n referenced.get(basename(dirname(path))) + \".obj\" != item.name))\n )\n await this.removeObsolete(path);\n }\n };\n\n await walk(join(this.root, OBJECTS_DIRECTORY));\n }\n\n private async recoverJournalRotation(): Promise<void> {\n const current = join(this.root, JOURNAL_FILE);\n const previous = join(this.root, PREVIOUS_JOURNAL);\n const next = join(this.root, NEXT_JOURNAL);\n\n const hasCurrent = await exists(current);\n const hasPrevious = await exists(previous);\n const hasNext = await exists(next);\n\n if (!hasCurrent) {\n if (hasNext) await rename(next, current);\n else if (hasPrevious) await rename(previous, current);\n } else if (hasPrevious) {\n try {\n const input = await open(current, \"r\");\n\n try {\n await replayJournal(input, this.options.maxJournalBytes, () => {});\n } finally {\n await input.close();\n }\n\n await this.removeObsolete(previous);\n } catch (cause) {\n throw new StorageError(\n \"Cannot establish journal rotation outcome; refusing to restore stale journal\",\n \"CORRUPTION\",\n { cause },\n );\n }\n }\n\n if ((await exists(current)) && (await exists(next))) await this.removeObsolete(next);\n if ((await exists(current)) && (await exists(previous))) await this.removeObsolete(previous);\n\n await this.syncDirectory(this.root);\n }\n\n private async fault(point: DiskFaultPoint, context: DiskFaultContext): Promise<void> {\n await this.options.faultInjector?.(point, context);\n }\n\n private async removeObsolete(path: string): Promise<void> {\n try {\n await rm(path, { force: true });\n } catch {\n /* Cleanup is retried during the next open. */\n }\n }\n\n private async syncDirectory(directory: string): Promise<void> {\n if (!this.directorySync) return;\n\n try {\n await AsyncDiskStorageDriver.syncDirectoryStatic(directory);\n } catch (error) {\n if ([\"EINVAL\", \"ENOTSUP\", \"EBADF\", \"EISDIR\", \"EPERM\"].includes(nodeErrorCode(error) ?? \"\"))\n this.directorySync = false;\n else throw error;\n }\n }\n\n private static async syncDirectoryStatic(directory: string): Promise<void> {\n const handle = await open(directory, \"r\");\n\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n }\n\n private async cleanupFailedOpen(): Promise<void> {\n const failures: unknown[] = [];\n\n try {\n if (this.journal) await this.journal.close();\n } catch (error) {\n failures.push(error);\n }\n\n if (failures.length == 0) {\n try {\n await this.ownership.release();\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length == 1) throw failures[0];\n\n if (failures.length > 1)\n throw new AggregateError(failures, \"Failed storage initialization cleanup\");\n }\n}\n"],"mappings":";;;;;;AAGA,IAAM,eAAe,OAAO,KAAK,YAAY,OAAO;AACpD,IAAM,mBAAmB;AAyBzB,IAAM,UAAU,IAAI,YAAY;AAChC,IAAM,UAAU,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC;AAExD,SAAgB,OAAO,MAAmC;CACxD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK;AACvD;AAEA,SAAS,WAAW,SAAiB,OAA+B;CAClE,OAAO,IAAI,aAAa,SAAS,cAAc,SAAS,OAAO,KAAA,IAAY,EAAE,MAAM,CAAC;AACtF;AAEA,SAASA,cAAY,OAAmB,OAAwC;CAC9E,IAAI;EACF,MAAM,QAAiB,KAAK,MAAM,QAAQ,OAAO,KAAK,CAAC;EACvD,IAAI,CAAC,SAAS,OAAO,SAAS,YAAY,MAAM,QAAQ,KAAK,GAC3D,MAAM,IAAI,MAAM,eAAe;EACjC,OAAO;CACT,SAAS,OAAO;EACd,MAAM,WAAW,WAAW,SAAS,KAAK;CAC5C;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AK,eAAe;EAEzB,IAAI;GACF,MAAM,uBAAuB,oBAAoB,SAAS;EAC5D,SAAS,OAAO;GACd,IAAI;IAAC;IAAU;IAAW;IAAS;IAAU;GAAO,CAAC,CAAC,SAAS,cAAc,KAAK,KAAK,EAAE,GACvF,KAAK,gBAAgB;QAClB,MAAM;EACb;CACF;CAEA,aAAqB,oBAAoB,WAAkC;EACzE,MAAM,SAAS,MAAM,KAAK,WAAW,GAAG;EAExC,IAAI;GACF,MAAM,OAAO,KAAK;EACpB,UAAU;GACR,MAAM,OAAO,MAAM;EACrB;CACF;CAEA,MAAc,oBAAmC;EAC/C,MAAM,WAAsB,CAAC;EAE7B,IAAI;GACF,IAAI,KAAK,SAAS,MAAM,KAAK,QAAQ,MAAM;EAC7C,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAEA,IAAI,SAAS,UAAU,GACrB,IAAI;GACF,MAAM,KAAK,UAAU,QAAQ;EAC/B,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAGF,IAAI,SAAS,UAAU,GAAG,MAAM,SAAS;EAEzC,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,eAAe,UAAU,uCAAuC;CAC9E;AACF"}
1
+ {"version":3,"file":"index.js","names":["parseRecord","writeAll"],"sources":["../src/disk-format.ts","../src/ownership.ts","../src/async-disk-storage.driver.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { StorageError } from \"@duraxis/storage\";\n\nconst OBJECT_MAGIC = Buffer.from(\"DXOBJ001\", \"ascii\");\nconst MAX_HEADER_BYTES = 16 * 1024;\nexport const MAX_JOURNAL_FRAME_BYTES = 64 * 1024;\n\nexport interface StoredMetadata {\n readonly version: string;\n readonly createdAt: number;\n readonly size: number;\n readonly digest: string;\n}\n\nexport type JournalPayload =\n | ({\n readonly format: 1;\n readonly sequence: number;\n readonly op: \"put\";\n readonly key: string;\n } & StoredMetadata)\n | { readonly format: 1; readonly sequence: number; readonly op: \"delete\"; readonly key: string };\n\nexport interface DecodedJournal {\n readonly frames: readonly JournalPayload[];\n readonly validBytes: number;\n readonly incompleteTail: boolean;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nexport function sha256(data: Uint8Array | string): string {\n return createHash(\"sha256\").update(data).digest(\"hex\");\n}\n\nfunction corruption(message: string, cause?: unknown): StorageError {\n return new StorageError(message, \"CORRUPTION\", cause == null ? undefined : { cause });\n}\n\nfunction parseRecord(bytes: Uint8Array, label: string): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(decoder.decode(bytes));\n if (!value || typeof value != \"object\" || Array.isArray(value))\n throw new Error(\"not an object\");\n return value as Record<string, unknown>;\n } catch (cause) {\n throw corruption(`Invalid ${label}`, cause);\n }\n}\n\nfunction validDigest(value: unknown): value is string {\n return typeof value == \"string\" && /^[0-9a-f]{64}$/.test(value);\n}\n\nfunction validateMetadata(\n value: Record<string, unknown>,\n): asserts value is Record<string, unknown> & StoredMetadata {\n if (\n typeof value.version != \"string\" ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(\n value.version,\n ) ||\n !Number.isSafeInteger(value.createdAt) ||\n (value.createdAt as number) < 0 ||\n !Number.isSafeInteger(value.size) ||\n (value.size as number) < 0 ||\n !validDigest(value.digest)\n )\n throw corruption(\"Invalid physical object metadata\");\n}\n\nexport function encodePhysicalObject(\n key: string,\n metadata: StoredMetadata,\n data: Uint8Array,\n): Uint8Array {\n const headerPayload = {\n format: 1 as const,\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n };\n const canonical = JSON.stringify(headerPayload);\n const header = encoder.encode(JSON.stringify({ ...headerPayload, checksum: sha256(canonical) }));\n if (header.byteLength > MAX_HEADER_BYTES)\n throw new StorageError(\"Object metadata is too large\", \"RESOURCE_LIMIT\");\n const result = new Uint8Array(OBJECT_MAGIC.length + 4 + header.length + data.length);\n result.set(OBJECT_MAGIC, 0);\n new DataView(result.buffer).setUint32(OBJECT_MAGIC.length, header.length, false);\n result.set(header, OBJECT_MAGIC.length + 4);\n result.set(data, OBJECT_MAGIC.length + 4 + header.length);\n return result;\n}\n\nexport function decodePhysicalObject(\n bytes: Uint8Array,\n expectedKey: string,\n expected: StoredMetadata,\n): Uint8Array {\n if (\n bytes.byteLength < OBJECT_MAGIC.length + 4 ||\n !Buffer.from(bytes.subarray(0, OBJECT_MAGIC.length)).equals(OBJECT_MAGIC)\n )\n throw corruption(\"Invalid physical object magic\");\n const headerLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(\n OBJECT_MAGIC.length,\n false,\n );\n if (\n headerLength == 0 ||\n headerLength > MAX_HEADER_BYTES ||\n OBJECT_MAGIC.length + 4 + headerLength > bytes.byteLength\n )\n throw corruption(\"Invalid physical object header length\");\n const header = parseRecord(\n bytes.subarray(OBJECT_MAGIC.length + 4, OBJECT_MAGIC.length + 4 + headerLength),\n \"physical object header\",\n );\n const fields = Object.keys(header).sort().join(\",\");\n if (\n fields != \"checksum,createdAt,digest,format,key,size,version\" ||\n header.format != 1 ||\n typeof header.key != \"string\" ||\n typeof header.checksum != \"string\"\n )\n throw corruption(\"Invalid physical object header\");\n validateMetadata(header);\n const canonical = JSON.stringify({\n format: 1,\n key: header.key,\n version: header.version,\n createdAt: header.createdAt,\n size: header.size,\n digest: header.digest,\n });\n if (sha256(canonical) != header.checksum)\n throw corruption(\"Physical metadata integrity check failed\");\n if (\n header.key != expectedKey ||\n header.version != expected.version ||\n header.createdAt != expected.createdAt ||\n header.size != expected.size ||\n header.digest != expected.digest\n )\n throw corruption(\"Physical object does not match journal metadata\");\n const data = bytes.subarray(OBJECT_MAGIC.length + 4 + headerLength);\n if (data.byteLength != expected.size || sha256(data) != expected.digest)\n throw corruption(\"Physical object payload integrity check failed\");\n return new Uint8Array(data);\n}\n\nexport function encodeJournalFrame(payload: JournalPayload): Uint8Array {\n const canonical = JSON.stringify(payload);\n const body = encoder.encode(JSON.stringify({ ...payload, checksum: sha256(canonical) }));\n if (body.byteLength > MAX_JOURNAL_FRAME_BYTES)\n throw new StorageError(\"Journal frame is too large\", \"RESOURCE_LIMIT\");\n const result = new Uint8Array(4 + body.byteLength);\n new DataView(result.buffer).setUint32(0, body.byteLength, false);\n result.set(body, 4);\n return result;\n}\n\nfunction decodeFrame(bytes: Uint8Array, expectedSequence: number): JournalPayload {\n const record = parseRecord(bytes, \"storage journal frame\");\n if (\n record.format != 1 ||\n record.sequence != expectedSequence ||\n (record.op != \"put\" && record.op != \"delete\") ||\n typeof record.key != \"string\" ||\n typeof record.checksum != \"string\"\n )\n throw corruption(\"Invalid storage journal frame\");\n let payload: JournalPayload;\n if (record.op == \"put\") {\n if (\n Object.keys(record).sort().join(\",\") !=\n \"checksum,createdAt,digest,format,key,op,sequence,size,version\"\n )\n throw corruption(\"Invalid put journal frame layout\");\n validateMetadata(record);\n payload = {\n format: 1,\n sequence: expectedSequence,\n op: \"put\",\n key: record.key,\n version: record.version,\n createdAt: record.createdAt,\n size: record.size,\n digest: record.digest,\n };\n } else {\n if (Object.keys(record).sort().join(\",\") != \"checksum,format,key,op,sequence\")\n throw corruption(\"Invalid delete journal frame layout\");\n payload = { format: 1, sequence: expectedSequence, op: \"delete\", key: record.key };\n }\n if (sha256(JSON.stringify(payload)) != record.checksum)\n throw corruption(\"Storage journal integrity check failed\");\n return payload;\n}\n\nexport function decodeJournal(bytes: Uint8Array): DecodedJournal {\n const frames: JournalPayload[] = [];\n let offset = 0;\n let sequence = 1;\n while (offset < bytes.byteLength) {\n if (bytes.byteLength - offset < 4) return { frames, validBytes: offset, incompleteTail: true };\n const length = new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(0, false);\n if (length == 0 || length > MAX_JOURNAL_FRAME_BYTES)\n throw corruption(\"Invalid storage journal frame length\");\n if (bytes.byteLength - offset - 4 < length)\n return { frames, validBytes: offset, incompleteTail: true };\n frames.push(decodeFrame(bytes.subarray(offset + 4, offset + 4 + length), sequence++));\n offset += 4 + length;\n }\n return { frames, validBytes: offset, incompleteTail: false };\n}\n\nexport async function replayJournal(\n handle: {\n stat(): Promise<{ readonly size: number }>;\n read(\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): Promise<{ readonly bytesRead: number }>;\n },\n maxBytes: number,\n consume: (payload: JournalPayload) => void,\n): Promise<Omit<DecodedJournal, \"frames\">> {\n const info = await handle.stat();\n\n if (info.size > maxBytes)\n throw new StorageError(\"Storage journal exceeds configured limit\", \"RESOURCE_LIMIT\");\n\n let offset = 0;\n let sequence = 1;\n\n const read = async (buffer: Uint8Array, position: number) => {\n let received = 0;\n\n while (received < buffer.byteLength) {\n const result = await handle.read(\n buffer,\n received,\n buffer.byteLength - received,\n position + received,\n );\n\n if (!result.bytesRead) break;\n\n received += result.bytesRead;\n }\n\n return received;\n };\n\n while (offset < info.size) {\n const header = new Uint8Array(4);\n\n if ((await read(header, offset)) != 4) return { validBytes: offset, incompleteTail: true };\n\n const length = new DataView(header.buffer).getUint32(0, false);\n\n if (!length || length > MAX_JOURNAL_FRAME_BYTES)\n throw corruption(\"Invalid storage journal frame length\");\n\n const payload = new Uint8Array(length);\n\n if ((await read(payload, offset + 4)) != length)\n return { validBytes: offset, incompleteTail: true };\n\n consume(decodeFrame(payload, sequence++));\n\n offset += 4 + length;\n }\n\n return { validBytes: offset, incompleteTail: false };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { open, readFile, readlink, stat, statfs, unlink, type FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { join } from \"node:path\";\nimport { StorageError } from \"@duraxis/storage\";\nimport { sha256 } from \"./disk-format.js\";\n\nconst LOCK_FILE = \".duraxis-owner.lock\";\nconst RECOVERY_GUARD_FILE = \".duraxis-owner.recovery\";\nconst OWNERSHIP_CONFIRMATION = \"I_HAVE_VERIFIED_EXCLUSIVE_ACCESS\";\nconst OWNER_FIELDS = \"applicationId,checksum,createdAt,format,hostname,ownerId,pid,processIdentity\";\nconst GUARD_FIELDS = \"checksum,createdAt,format,guardId,hostname,pid\";\nconst 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}$/;\nconst APPLICATION_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._:/-]{0,126}[A-Za-z0-9])?$/;\nconst PROCESS_IDENTITY_PATTERN = /^(?:linux:(?:pid:\\[\\d+\\]|unavailable)|[a-z0-9]+:unverified)$/;\nconst MAX_METADATA_BYTES = 4096;\n\nconst LINUX_LOCAL_FILESYSTEMS = new Set([\n 0x0000ef53, // ext2/3/4\n 0x01021994, // tmpfs\n 0x2fc12fc1, // zfs\n 0x58465342, // xfs\n 0x794c7630, // overlayfs\n 0x858458f6, // ramfs\n 0x9123683e, // btrfs\n]);\n\nexport interface OwnershipRecoveryOptions {\n readonly mode: \"manual\" | \"dead-process\";\n readonly applicationId?: string;\n}\n\nexport interface RecoverOwnershipOptions {\n readonly directory: string;\n readonly confirmation: typeof OWNERSHIP_CONFIRMATION;\n}\n\nexport interface NormalizedOwnershipRecovery {\n readonly mode: \"manual\" | \"dead-process\";\n readonly applicationId?: string;\n}\n\ninterface OwnerPayload {\n readonly format: 2;\n readonly ownerId: string;\n readonly pid: number;\n readonly hostname: string;\n readonly createdAt: number;\n readonly applicationId: string | null;\n readonly processIdentity: string;\n}\n\ninterface OwnerRecord extends OwnerPayload {\n readonly checksum: string;\n}\n\ninterface GuardPayload {\n readonly format: 1;\n readonly guardId: string;\n readonly pid: number;\n readonly hostname: string;\n readonly createdAt: number;\n}\n\ninterface GuardRecord extends GuardPayload {\n readonly checksum: string;\n}\n\ninterface ObservedFile {\n readonly path: string;\n readonly handle: FileHandle;\n readonly identity: Stats;\n readonly bytes: Buffer;\n}\n\ninterface CoordinationGuard {\n readonly path: string;\n readonly handle: FileHandle;\n readonly identity: Stats;\n readonly bytes: Buffer;\n readonly guardId: string;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return error && typeof error == \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n}\n\nfunction ownershipConflict(message: string, cause?: unknown): StorageError {\n return new StorageError(message, \"OWNERSHIP_CONFLICT\", cause == null ? undefined : { cause });\n}\n\nfunction canonicalOwner(payload: OwnerPayload): string {\n return JSON.stringify(payload);\n}\n\nfunction canonicalGuard(payload: GuardPayload): string {\n return JSON.stringify(payload);\n}\n\nfunction validHostname(value: unknown): value is string {\n return (\n typeof value == \"string\" &&\n value.length > 0 &&\n value.length <= 255 &&\n !/[\\0-\\x1f\\x7f]/.test(value)\n );\n}\n\nfunction sameIdentity(left: Stats, right: Stats): boolean {\n return left.dev == right.dev && left.ino == right.ino;\n}\n\nasync function writeAll(handle: FileHandle, bytes: Uint8Array): Promise<void> {\n let offset = 0;\n\n while (offset < bytes.byteLength) {\n const result = await handle.write(bytes, offset, bytes.byteLength - offset, offset);\n\n if (result.bytesWritten <= 0)\n throw new StorageError(\"Ownership metadata write made no progress\", \"UNAVAILABLE\");\n\n offset += result.bytesWritten;\n }\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n let handle: FileHandle | undefined;\n\n try {\n handle = await open(directory, \"r\");\n await handle.sync();\n } catch (error) {\n if (![\"EINVAL\", \"ENOTSUP\", \"EBADF\", \"EISDIR\", \"EPERM\"].includes(errorCode(error) ?? \"\"))\n throw error;\n } finally {\n await handle?.close();\n }\n}\n\nasync function observe(path: string): Promise<ObservedFile | null> {\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"r\");\n } catch (error) {\n if (errorCode(error) == \"ENOENT\") return null;\n throw error;\n }\n\n try {\n const identity = await handle.stat();\n const bytes = await handle.readFile();\n\n return { path, handle, identity, bytes };\n } catch (error) {\n await handle.close().catch(() => undefined);\n throw error;\n }\n}\n\nasync function assertObservedUnchanged(observed: ObservedFile): Promise<void> {\n let currentIdentity: Stats;\n let currentBytes: Buffer;\n\n try {\n [currentIdentity, currentBytes] = await Promise.all([\n stat(observed.path),\n readFile(observed.path),\n ]);\n } catch (cause) {\n throw ownershipConflict(\"Ownership metadata changed during inspection\", cause);\n }\n\n if (!sameIdentity(observed.identity, currentIdentity) || !observed.bytes.equals(currentBytes))\n throw ownershipConflict(\"Ownership metadata changed during inspection\");\n}\n\nasync function removeObserved(observed: ObservedFile): Promise<void> {\n try {\n await assertObservedUnchanged(observed);\n } finally {\n await observed.handle.close();\n }\n\n try {\n await unlink(observed.path);\n } catch (cause) {\n throw ownershipConflict(\"Failed to remove the observed ownership lock\", cause);\n }\n}\n\nasync function removeCreatedFile(path: string, handle: FileHandle, identity: Stats): Promise<void> {\n await handle.close().catch(() => undefined);\n\n try {\n const current = await stat(path);\n\n if (!sameIdentity(identity, current))\n throw ownershipConflict(\"Created ownership file was replaced unexpectedly\");\n\n await unlink(path);\n } catch (error) {\n if (errorCode(error) != \"ENOENT\") throw error;\n }\n}\n\nfunction parseRecord(bytes: Uint8Array, label: string): Record<string, unknown> {\n if (bytes.byteLength == 0 || bytes.byteLength > MAX_METADATA_BYTES)\n throw ownershipConflict(`Invalid ${label}`);\n\n try {\n const value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (!value || typeof value != \"object\" || Array.isArray(value))\n throw new Error(\"not an object\");\n\n return value as Record<string, unknown>;\n } catch (cause) {\n throw ownershipConflict(`Invalid ${label}`, cause);\n }\n}\n\nfunction parseOwner(bytes: Uint8Array): OwnerRecord {\n const record = parseRecord(bytes, \"owner lock metadata\");\n\n if (record.format != 2)\n throw ownershipConflict(\n \"Owner lock format is incompatible with automatic recovery; use explicit manual recovery\",\n );\n\n if (\n Object.keys(record).sort().join(\",\") != OWNER_FIELDS ||\n !UUID_PATTERN.test(String(record.ownerId)) ||\n !Number.isSafeInteger(record.pid) ||\n (record.pid as number) <= 0 ||\n !validHostname(record.hostname) ||\n !Number.isSafeInteger(record.createdAt) ||\n (record.createdAt as number) < 0 ||\n (record.applicationId !== null &&\n (typeof record.applicationId != \"string\" ||\n !APPLICATION_ID_PATTERN.test(record.applicationId))) ||\n typeof record.processIdentity != \"string\" ||\n !PROCESS_IDENTITY_PATTERN.test(record.processIdentity) ||\n typeof record.checksum != \"string\" ||\n !/^[0-9a-f]{64}$/.test(record.checksum)\n )\n throw ownershipConflict(\"Invalid owner lock metadata\");\n\n const payload: OwnerPayload = {\n format: 2,\n ownerId: record.ownerId as string,\n pid: record.pid as number,\n hostname: record.hostname,\n createdAt: record.createdAt as number,\n applicationId: record.applicationId as string | null,\n processIdentity: record.processIdentity,\n };\n\n if (sha256(canonicalOwner(payload)) != record.checksum)\n throw ownershipConflict(\"Owner lock metadata checksum is invalid\");\n\n return { ...payload, checksum: record.checksum };\n}\n\nfunction parseGuard(bytes: Uint8Array): GuardRecord {\n const record = parseRecord(bytes, \"ownership recovery guard\");\n\n if (\n Object.keys(record).sort().join(\",\") != GUARD_FIELDS ||\n record.format != 1 ||\n !UUID_PATTERN.test(String(record.guardId)) ||\n !Number.isSafeInteger(record.pid) ||\n (record.pid as number) <= 0 ||\n !validHostname(record.hostname) ||\n !Number.isSafeInteger(record.createdAt) ||\n (record.createdAt as number) < 0 ||\n typeof record.checksum != \"string\" ||\n !/^[0-9a-f]{64}$/.test(record.checksum)\n )\n throw ownershipConflict(\"Invalid ownership recovery guard\");\n\n const payload: GuardPayload = {\n format: 1,\n guardId: record.guardId as string,\n pid: record.pid as number,\n hostname: record.hostname,\n createdAt: record.createdAt as number,\n };\n\n if (sha256(canonicalGuard(payload)) != record.checksum)\n throw ownershipConflict(\"Ownership recovery guard checksum is invalid\");\n\n return { ...payload, checksum: record.checksum };\n}\n\nasync function acquireGuard(root: string): Promise<CoordinationGuard> {\n const path = join(root, RECOVERY_GUARD_FILE);\n\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"wx\", 0o600);\n } catch (cause) {\n if (errorCode(cause) == \"EEXIST\")\n throw ownershipConflict(\n \"Another ownership operation is active or left an uncertain recovery guard\",\n cause,\n );\n\n throw cause;\n }\n let identity: Stats;\n try {\n identity = await handle.stat();\n } catch (cause) {\n await handle.close().catch(() => undefined);\n\n throw cause;\n }\n\n const payload: GuardPayload = {\n format: 1,\n guardId: randomUUID(),\n pid: process.pid,\n hostname: hostname(),\n createdAt: Date.now(),\n };\n\n const bytes = Buffer.from(\n JSON.stringify({ ...payload, checksum: sha256(canonicalGuard(payload)) }),\n );\n\n try {\n await writeAll(handle, bytes);\n await handle.sync();\n await syncDirectory(root);\n\n return { path, handle, identity, bytes, guardId: payload.guardId };\n } catch (cause) {\n try {\n await removeCreatedFile(path, handle, identity);\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Ownership guard creation and cleanup both failed\",\n );\n }\n throw cause;\n }\n}\n\nasync function releaseGuard(root: string, guard: CoordinationGuard): Promise<void> {\n try {\n const currentIdentity = await stat(guard.path);\n const currentBytes = await readFile(guard.path);\n const record = parseGuard(currentBytes);\n\n if (\n !sameIdentity(guard.identity, currentIdentity) ||\n !guard.bytes.equals(currentBytes) ||\n record.guardId != guard.guardId\n )\n throw ownershipConflict(\"Ownership recovery guard changed unexpectedly\");\n } finally {\n await guard.handle.close();\n }\n\n await unlink(guard.path);\n await syncDirectory(root);\n}\n\nasync function withGuard<T>(root: string, operation: () => Promise<T>): Promise<T> {\n const guard = await acquireGuard(root);\n let result: T | undefined;\n let operationFailure: unknown;\n\n try {\n result = await operation();\n } catch (error) {\n operationFailure = error;\n }\n\n try {\n await releaseGuard(root, guard);\n } catch (guardFailure) {\n if (operationFailure != null)\n throw new AggregateError(\n [operationFailure, guardFailure],\n \"Ownership operation and recovery-guard release both failed\",\n );\n\n throw guardFailure;\n }\n\n if (operationFailure != null) throw operationFailure;\n\n return result as T;\n}\n\nasync function automaticProcessIdentity(root: string): Promise<string> {\n if (process.platform != \"linux\")\n throw ownershipConflict(\n \"Automatic dead-process recovery is supported only on validated Linux environments\",\n );\n\n let namespace: string;\n\n try {\n namespace = await readlink(\"/proc/self/ns/pid\");\n } catch (cause) {\n throw ownershipConflict(\"The Linux PID namespace cannot be established\", cause);\n }\n\n if (!/^pid:\\[\\d+\\]$/.test(namespace))\n throw ownershipConflict(\"The Linux PID namespace identity is invalid\");\n\n let filesystemType: number;\n\n try {\n filesystemType = (await statfs(root)).type >>> 0;\n } catch (cause) {\n throw ownershipConflict(\"The storage filesystem type cannot be established\", cause);\n }\n\n if (!LINUX_LOCAL_FILESYSTEMS.has(filesystemType))\n throw ownershipConflict(\n `Automatic recovery is not supported on filesystem type 0x${filesystemType.toString(16)}`,\n );\n\n return `linux:${namespace}`;\n}\n\nasync function processIdentityForLock(root: string, mode: \"manual\" | \"dead-process\") {\n if (mode == \"dead-process\") return await automaticProcessIdentity(root);\n\n if (process.platform == \"linux\") {\n try {\n return `linux:${await readlink(\"/proc/self/ns/pid\")}`;\n } catch {\n return \"linux:unavailable\";\n }\n }\n return `${process.platform}:unverified`;\n}\n\nfunction assertRecoverableOwner(\n owner: OwnerRecord,\n recovery: NormalizedOwnershipRecovery,\n processIdentity: string,\n): void {\n if (owner.hostname != hostname())\n throw ownershipConflict(\"Owner lock belongs to a different host\");\n\n if (owner.processIdentity != processIdentity)\n throw ownershipConflict(\"Owner lock belongs to a different or unsupported process namespace\");\n\n if (owner.applicationId != (recovery.applicationId ?? null))\n throw ownershipConflict(\"Owner lock belongs to a different application identity\");\n\n try {\n process.kill(owner.pid, 0);\n } catch (cause) {\n if (errorCode(cause) == \"ESRCH\") return;\n\n if (errorCode(cause) == \"EPERM\")\n throw ownershipConflict(\"Owner process existence is inconclusive\", cause);\n\n throw ownershipConflict(\"Owner process existence could not be determined\", cause);\n }\n\n throw ownershipConflict(\n \"Owner process may still be running; PID reuse is treated as an ownership conflict\",\n );\n}\n\nasync function createOwnerFile(\n root: string,\n ownerId: string,\n recovery: NormalizedOwnershipRecovery,\n processIdentity: string,\n): Promise<{ handle: FileHandle; identity: Stats } | null> {\n const path = join(root, LOCK_FILE);\n let handle: FileHandle;\n\n try {\n handle = await open(path, \"wx\", 0o600);\n } catch (error) {\n if (errorCode(error) == \"EEXIST\") return null;\n throw error;\n }\n\n let identity: Stats;\n\n try {\n identity = await handle.stat();\n } catch (cause) {\n await handle.close().catch(() => undefined);\n throw cause;\n }\n\n const payload: OwnerPayload = {\n format: 2,\n ownerId,\n pid: process.pid,\n hostname: hostname(),\n createdAt: Date.now(),\n applicationId: recovery.applicationId ?? null,\n processIdentity,\n };\n\n const bytes = Buffer.from(\n JSON.stringify({ ...payload, checksum: sha256(canonicalOwner(payload)) }),\n );\n\n try {\n await writeAll(handle, bytes);\n await handle.sync();\n await syncDirectory(root);\n return { handle, identity };\n } catch (cause) {\n try {\n await removeCreatedFile(path, handle, identity);\n } catch (cleanupCause) {\n throw new AggregateError(\n [cause, cleanupCause],\n \"Owner lock creation and cleanup both failed\",\n );\n }\n\n throw cause;\n }\n}\n\nexport function normalizeOwnershipRecovery(\n options: OwnershipRecoveryOptions | undefined,\n): NormalizedOwnershipRecovery {\n if (options == null) return { mode: \"manual\" };\n\n if (options.mode != \"manual\" && options.mode != \"dead-process\")\n throw new TypeError('ownershipRecovery.mode must be \"manual\" or \"dead-process\"');\n\n if (\n options.applicationId != null &&\n (typeof options.applicationId != \"string\" ||\n !APPLICATION_ID_PATTERN.test(options.applicationId))\n )\n throw new TypeError(\"ownershipRecovery.applicationId must be 1-128 safe identifier characters\");\n\n return {\n mode: options.mode,\n ...(options.applicationId == null ? {} : { applicationId: options.applicationId }),\n };\n}\n\nexport class DirectoryOwnership {\n readonly #ownerId = randomUUID();\n #lockHandle?: FileHandle;\n #owned = false;\n\n public constructor(\n private readonly root: string,\n private readonly recovery: NormalizedOwnershipRecovery,\n ) {}\n\n public get isOwned(): boolean {\n return this.#owned;\n }\n\n public async acquire(): Promise<void> {\n const processIdentity = await processIdentityForLock(this.root, this.recovery.mode);\n\n await withGuard(this.root, async () => {\n let created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);\n if (!created) {\n if (this.recovery.mode == \"manual\")\n throw ownershipConflict(\n \"Storage directory has an owner lock; close the owner or perform explicit abandoned-lock recovery\",\n );\n\n const observed = await observe(join(this.root, LOCK_FILE));\n\n if (observed) {\n let owner: OwnerRecord;\n\n try {\n owner = parseOwner(observed.bytes);\n assertRecoverableOwner(owner, this.recovery, processIdentity);\n await removeObserved(observed);\n } catch (error) {\n await observed.handle.close().catch(() => undefined);\n throw error;\n }\n\n await syncDirectory(this.root);\n }\n\n created = await createOwnerFile(this.root, this.#ownerId, this.recovery, processIdentity);\n\n if (!created)\n throw ownershipConflict(\"Another process acquired storage ownership during recovery\");\n }\n this.#lockHandle = created.handle;\n this.#owned = true;\n });\n }\n\n public async verify(): Promise<void> {\n if (!this.#owned) throw ownershipConflict(\"Storage directory is not owned\");\n\n await withGuard(this.root, async () => {\n const observed = await observe(join(this.root, LOCK_FILE));\n\n if (!observed) throw ownershipConflict(\"Storage owner lock is missing\");\n\n try {\n if (parseOwner(observed.bytes).ownerId != this.#ownerId)\n throw ownershipConflict(\"Storage ownership changed\");\n\n await assertObservedUnchanged(observed);\n } finally {\n await observed.handle.close();\n }\n });\n }\n\n public async release(): Promise<void> {\n if (!this.#owned) return;\n\n await withGuard(this.root, async () => {\n const observed = await observe(join(this.root, LOCK_FILE));\n if (!observed) {\n this.#owned = false;\n await this.#lockHandle?.close().catch(() => undefined);\n\n this.#lockHandle = undefined;\n throw ownershipConflict(\"Current owner lock is missing\");\n }\n\n try {\n const owner = parseOwner(observed.bytes);\n\n if (owner.ownerId != this.#ownerId)\n throw ownershipConflict(\"Storage ownership changed unexpectedly\");\n\n await this.#lockHandle?.close();\n this.#lockHandle = undefined;\n\n await removeObserved(observed);\n this.#owned = false;\n\n await syncDirectory(this.root);\n } catch (error) {\n await observed.handle.close().catch(() => undefined);\n throw error;\n }\n });\n }\n}\n\nexport async function manuallyRecoverOwnership(root: string): Promise<void> {\n await withGuard(root, async () => {\n const observed = await observe(join(root, LOCK_FILE));\n if (!observed) return;\n await removeObserved(observed);\n await syncDirectory(root);\n });\n}\n\nexport function validateManualRecoveryConfirmation(\n confirmation: RecoverOwnershipOptions[\"confirmation\"],\n): void {\n if (confirmation != OWNERSHIP_CONFIRMATION)\n throw new StorageError(\"Explicit exclusive-access confirmation is required\", \"ACCESS_DENIED\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport {\n mkdir,\n open,\n readFile,\n opendir,\n realpath,\n rename,\n rm,\n stat,\n truncate,\n type FileHandle,\n} from \"node:fs/promises\";\nimport {\n assertStorageKey,\n assertWriteCondition,\n StorageError,\n type DeleteOptions,\n type DeleteResult,\n type StorageDriver,\n type StorageDriverMetrics,\n type StorageObject,\n type StorageObjectInfo,\n type WriteOptions,\n type WriteResult,\n} from \"@duraxis/storage\";\nimport {\n replayJournal,\n decodePhysicalObject,\n encodeJournalFrame,\n encodePhysicalObject,\n sha256,\n type JournalPayload,\n type StoredMetadata,\n} from \"./disk-format.js\";\nimport {\n DirectoryOwnership,\n manuallyRecoverOwnership,\n normalizeOwnershipRecovery,\n validateManualRecoveryConfirmation,\n type NormalizedOwnershipRecovery,\n type OwnershipRecoveryOptions,\n type RecoverOwnershipOptions,\n} from \"./ownership.js\";\n\nconst JOURNAL_FILE = \"journal.log\";\nconst PREVIOUS_JOURNAL = \"journal.previous\";\nconst NEXT_JOURNAL = \"journal.next\";\nconst OBJECTS_DIRECTORY = \"objects\";\n\nconst MAX_KEY_BYTES = 4096;\nconst MAX_OBJECT_BYTES = 256 * 1024 * 1024;\nconst MAX_JOURNAL_BYTES = 1024 * 1024 * 1024;\n\nexport type { OwnershipRecoveryOptions, RecoverOwnershipOptions } from \"./ownership.js\";\n\nexport type DiskFaultPoint =\n | \"after-object-sync\"\n | \"after-object-publish\"\n | \"after-object-directory-sync\"\n | \"after-journal-write\"\n | \"after-journal-sync\"\n | \"after-journal-rotation\";\n\nexport interface DiskFaultContext {\n readonly operation: \"put\" | \"delete\" | \"compact\";\n readonly key?: string;\n}\n\nexport interface AsyncDiskStorageOptions {\n readonly directory: string;\n readonly ownershipRecovery?: OwnershipRecoveryOptions;\n readonly maxKeyBytes?: number;\n readonly maxObjectBytes?: number;\n readonly maxJournalBytes?: number;\n readonly maxMetadataBytes?: number;\n readonly maxQueuedOperations?: number;\n readonly nodeCacheHint?: number;\n readonly faultInjector?: (\n point: DiskFaultPoint,\n context: DiskFaultContext,\n ) => void | Promise<void>;\n}\n\nexport interface DiskDurabilityCapabilities {\n readonly fileDataSync: true;\n readonly directoryEntrySync: boolean;\n readonly ownership: \"exclusive-directory\";\n readonly processCrashRecovery: true;\n readonly powerLossGuarantee: \"file-and-directory-sync\" | \"file-sync-only\";\n}\n\ninterface MutableMetrics {\n reads: number;\n writes: number;\n deletes: number;\n lists: number;\n bytesRead: number;\n bytesWritten: number;\n synchronizationWaitMs: number;\n}\n\nfunction nodeErrorCode(error: unknown): string | undefined {\n return error && typeof error == \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\") return false;\n throw error;\n }\n}\n\nasync function writeAll(handle: FileHandle, bytes: Uint8Array, position = 0): Promise<void> {\n let offset = 0;\n\n while (offset < bytes.byteLength) {\n const result = await handle.write(bytes, offset, bytes.byteLength - offset, position + offset);\n\n if (result.bytesWritten <= 0)\n throw new StorageError(\"Disk write made no progress\", \"UNAVAILABLE\");\n\n offset += result.bytesWritten;\n }\n}\n\nasync function syncAndClose(handle: FileHandle, context: string): Promise<void> {\n let syncFailure: unknown;\n\n try {\n await handle.sync();\n } catch (error) {\n syncFailure = error;\n }\n\n try {\n await handle.close();\n } catch (closeFailure) {\n if (syncFailure != null)\n throw new AggregateError(\n [syncFailure, closeFailure],\n `${context} sync and close both failed`,\n );\n\n throw closeFailure;\n }\n\n if (syncFailure != null) throw syncFailure;\n}\n\nexport class AsyncDiskStorageDriver implements StorageDriver {\n public readonly capabilities = Object.freeze({ boundedReads: true });\n private static readonly activeDirectories = new Set<string>();\n\n private readonly entries = new Map<string, StoredMetadata>();\n private readonly ownership: DirectoryOwnership;\n private readonly metrics: MutableMetrics = {\n reads: 0,\n writes: 0,\n deletes: 0,\n lists: 0,\n bytesRead: 0,\n bytesWritten: 0,\n synchronizationWaitMs: 0,\n };\n\n private metadataBytes = 0;\n private queuedOperations = 0;\n\n private operationTail: Promise<void> = Promise.resolve();\n private journal!: FileHandle;\n private journalBytes = 0;\n private sequence = 0;\n private directorySync = true;\n private closed = false;\n private closing = false;\n private resourcesClosed = false;\n private closePromise?: Promise<void>;\n private poisoned = false;\n\n private constructor(\n private readonly root: string,\n private readonly registryKey: string,\n private readonly options: Required<\n Pick<AsyncDiskStorageOptions, \"maxKeyBytes\" | \"maxObjectBytes\" | \"maxJournalBytes\">\n > &\n AsyncDiskStorageOptions & { readonly ownershipRecovery: NormalizedOwnershipRecovery },\n ) {\n this.ownership = new DirectoryOwnership(root, options.ownershipRecovery);\n }\n\n public static async open(options: AsyncDiskStorageOptions): Promise<AsyncDiskStorageDriver> {\n if (!options || typeof options.directory != \"string\" || options.directory.trim() == \"\")\n throw new TypeError(\"A storage directory is required\");\n\n const maxKeyBytes = options.maxKeyBytes ?? MAX_KEY_BYTES;\n const maxObjectBytes = options.maxObjectBytes ?? MAX_OBJECT_BYTES;\n const maxJournalBytes = options.maxJournalBytes ?? MAX_JOURNAL_BYTES;\n\n const ownershipRecovery = normalizeOwnershipRecovery(options.ownershipRecovery);\n\n if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes < 64 || maxKeyBytes > 64 * 1024)\n throw new RangeError(\"Invalid maximum storage key size\");\n\n if (\n !Number.isSafeInteger(maxObjectBytes) ||\n maxObjectBytes < 0 ||\n maxObjectBytes > MAX_JOURNAL_BYTES\n )\n throw new RangeError(\"Invalid maximum object size\");\n\n if (!Number.isSafeInteger(maxJournalBytes) || maxJournalBytes < 1024 * 1024)\n throw new RangeError(\"Invalid maximum journal size\");\n\n for (const value of [options.maxMetadataBytes, options.maxQueuedOperations])\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1))\n throw new RangeError(\"Invalid storage resource limit\");\n\n const requested = resolve(options.directory);\n\n await mkdir(requested, { recursive: true });\n\n const root = await realpath(requested);\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\n \"Storage directory is already owned by this process\",\n \"OWNERSHIP_CONFLICT\",\n );\n\n this.activeDirectories.add(registryKey);\n\n const driver = new AsyncDiskStorageDriver(root, registryKey, {\n ...options,\n directory: root,\n maxKeyBytes,\n maxObjectBytes,\n maxJournalBytes,\n ownershipRecovery,\n });\n\n try {\n await driver.initialize();\n return driver;\n } catch (cause) {\n try {\n await driver.cleanupFailedOpen();\n } catch (cleanupCause) {\n if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);\n throw new AggregateError(\n [cause, cleanupCause],\n \"Storage initialization and ownership cleanup both failed\",\n );\n }\n if (!driver.ownership.isOwned) this.activeDirectories.delete(registryKey);\n throw cause;\n }\n }\n\n public static async recoverAbandonedOwnership(options: RecoverOwnershipOptions): Promise<void> {\n validateManualRecoveryConfirmation(options.confirmation);\n\n const root = await realpath(resolve(options.directory));\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\"Cannot recover ownership held by this process\", \"OWNERSHIP_CONFLICT\");\n\n await manuallyRecoverOwnership(root);\n }\n\n public get durability(): DiskDurabilityCapabilities {\n return {\n fileDataSync: true,\n directoryEntrySync: this.directorySync,\n ownership: \"exclusive-directory\",\n processCrashRecovery: true,\n powerLossGuarantee: this.directorySync ? \"file-and-directory-sync\" : \"file-sync-only\",\n };\n }\n\n public getMetrics(): Readonly<StorageDriverMetrics> {\n return { ...this.metrics };\n }\n\n private async initialize(): Promise<void> {\n await this.ownership.acquire();\n await mkdir(join(this.root, OBJECTS_DIRECTORY), { recursive: true });\n await this.recoverJournalRotation();\n\n const journalPath = join(this.root, JOURNAL_FILE);\n\n if (!(await exists(journalPath))) {\n const created = await open(journalPath, \"wx\", 0o600);\n await syncAndClose(created, \"New storage journal\");\n await this.syncDirectory(this.root);\n }\n\n const input = await open(journalPath, \"r\");\n let decoded: Awaited<ReturnType<typeof replayJournal>>;\n\n try {\n decoded = await replayJournal(input, this.options.maxJournalBytes, (frame) => {\n this.validateKey(frame.key);\n this.sequence = frame.sequence;\n\n if (frame.op == \"put\")\n this.setEntry(frame.key, {\n version: frame.version,\n createdAt: frame.createdAt,\n size: frame.size,\n digest: frame.digest,\n });\n else this.deleteEntry(frame.key);\n });\n } finally {\n await input.close();\n }\n\n if (decoded.incompleteTail) {\n await truncate(journalPath, decoded.validBytes);\n const repaired = await open(journalPath, \"r+\");\n await syncAndClose(repaired, \"Repaired storage journal\");\n }\n\n this.journalBytes = decoded.validBytes;\n this.journal = await open(journalPath, \"r+\");\n\n await this.assertCurrentObjectsExist();\n await this.cleanupPhysicalObjects();\n }\n\n private setEntry(key: string, value: StoredMetadata): void {\n const size = this.entries.has(key) ? 0 : key.length * 2 + 256;\n\n if (this.metadataBytes + size > (this.options.maxMetadataBytes ?? 64 * 1024 * 1024))\n throw new StorageError(\"Resident storage metadata limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.metadataBytes += size;\n this.entries.set(key, value);\n }\n\n private deleteEntry(key: string): void {\n if (this.entries.delete(key)) this.metadataBytes -= key.length * 2 + 256;\n }\n\n private validateKey(key: string): void {\n assertStorageKey(key);\n\n if (Buffer.byteLength(key, \"utf8\") > this.options.maxKeyBytes)\n throw new StorageError(\"Storage key exceeds configured byte limit\", \"INVALID_KEY\");\n }\n\n private assertUsable(): void {\n if (this.closed || this.closing) throw new StorageError(\"Storage driver is closed\", \"CLOSED\");\n\n if (this.poisoned)\n throw new StorageError(\n \"Storage outcome is unknown; close and reopen before continuing\",\n \"OUTCOME_UNKNOWN\",\n );\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n this.assertUsable();\n\n if (this.queuedOperations >= (this.options.maxQueuedOperations ?? 256))\n throw new StorageError(\"Storage operation admission limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.queuedOperations++;\n\n const before = performance.now();\n const previous = this.operationTail;\n\n let release!: () => void;\n\n this.operationTail = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await previous;\n this.metrics.synchronizationWaitMs += performance.now() - before;\n\n try {\n this.assertUsable();\n return await operation();\n } finally {\n this.queuedOperations--;\n release();\n }\n }\n\n public get(\n key: string,\n options: { readonly signal?: AbortSignal; readonly maxBytes?: number } = {},\n ): Promise<StorageObject | null> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n options.signal?.throwIfAborted();\n this.metrics.reads++;\n\n const metadata = this.entries.get(key);\n\n if (!metadata) return null;\n\n if (metadata.size > (options.maxBytes ?? this.options.maxObjectBytes))\n throw new StorageError(\"Storage read exceeds byte limit\", \"RESOURCE_LIMIT\");\n\n const path = this.objectPath(key, metadata.version);\n\n let info;\n\n try {\n info = await stat(path);\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\")\n throw new StorageError(`Missing physical object for key ${key}`, \"CORRUPTION\", {\n cause: error,\n });\n throw error;\n }\n\n if (info.size > this.options.maxObjectBytes + 32 * 1024)\n throw new StorageError(\"Physical object exceeds configured size\", \"CORRUPTION\");\n\n const physical = await readFile(path, { signal: options.signal });\n\n this.metrics.bytesRead += physical.byteLength;\n\n return { data: decodePhysicalObject(physical, key, metadata), version: metadata.version };\n });\n }\n\n public put(key: string, data: Uint8Array, options: WriteOptions): Promise<WriteResult> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n if (!(data instanceof Uint8Array)) throw new TypeError(\"Storage data must be a Uint8Array\");\n\n if (data.byteLength > this.options.maxObjectBytes)\n throw new StorageError(\"Storage object exceeds configured byte limit\", \"RESOURCE_LIMIT\");\n\n assertWriteCondition(options?.condition);\n\n const current = this.entries.get(key);\n\n if (\n options.condition.type == \"if-absent\"\n ? current != null\n : current == null || current.version != options.condition.version\n )\n return { success: false, reason: \"conflict\" };\n\n if (\n !this.entries.has(key) &&\n this.metadataBytes + key.length * 2 + 256 >\n (this.options.maxMetadataBytes ?? 64 * 1024 * 1024)\n )\n throw new StorageError(\"Resident storage metadata limit exceeded\", \"RESOURCE_LIMIT\");\n\n this.metrics.writes++;\n\n const metadata: StoredMetadata = {\n version: randomUUID(),\n createdAt: Date.now(),\n size: data.byteLength,\n digest: sha256(data),\n };\n\n const physical = encodePhysicalObject(key, metadata, data);\n const finalPath = this.objectPath(key, metadata.version);\n const parent = dirname(finalPath);\n\n await mkdir(parent, { recursive: true });\n\n const temporary = join(parent, `.${metadata.version}.${randomUUID()}.tmp`);\n\n let published = false;\n\n try {\n const handle = await open(temporary, \"wx\", 0o600);\n\n try {\n await writeAll(handle, physical);\n await handle.sync();\n } finally {\n await handle.close();\n }\n\n await this.fault(\"after-object-sync\", { operation: \"put\", key });\n await rename(temporary, finalPath);\n\n published = true;\n\n await this.fault(\"after-object-publish\", { operation: \"put\", key });\n await this.syncDirectory(parent);\n await this.fault(\"after-object-directory-sync\", { operation: \"put\", key });\n\n const frame: JournalPayload = {\n format: 1,\n sequence: this.sequence + 1,\n op: \"put\",\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n };\n\n await this.append(frame);\n\n this.setEntry(key, metadata);\n this.sequence = frame.sequence;\n this.metrics.bytesWritten += physical.byteLength;\n\n if (current) await this.removeObsolete(this.objectPath(key, current.version));\n\n return { success: true, version: metadata.version };\n } catch (error) {\n if (!published) await this.removeObsolete(temporary);\n throw error;\n }\n });\n }\n\n public delete(key: string, options: DeleteOptions): Promise<DeleteResult> {\n return this.exclusive(async () => {\n this.validateKey(key);\n\n assertWriteCondition(options?.condition);\n\n const current = this.entries.get(key);\n\n if (options.condition.type == \"if-absent\")\n return current ? { success: false, reason: \"conflict\" } : { success: true };\n\n if (!current || current.version != options.condition.version)\n return { success: false, reason: \"conflict\" };\n\n this.metrics.deletes++;\n\n const frame: JournalPayload = {\n format: 1,\n sequence: this.sequence + 1,\n op: \"delete\",\n key,\n };\n\n await this.append(frame);\n\n this.deleteEntry(key);\n this.sequence = frame.sequence;\n\n await this.removeObsolete(this.objectPath(key, current.version));\n\n return { success: true };\n });\n }\n\n public verifyExclusiveOwnership(): Promise<void> {\n return this.exclusive(() => this.ownership.verify());\n }\n public async *iterate(\n prefix: string,\n options: { readonly pageSize?: number; readonly signal?: AbortSignal } = {},\n ): AsyncIterable<StorageObjectInfo> {\n if (typeof prefix != \"string\" || prefix.includes(\"\\0\"))\n throw new StorageError(\"Invalid storage prefix\", \"INVALID_KEY\");\n\n const size = options.pageSize ?? 256;\n\n if (!Number.isSafeInteger(size) || size < 1 || size > 1000)\n throw new RangeError(\"Invalid listing page size\");\n\n const iterator = this.entries.entries();\n\n let done = false;\n\n while (!done) {\n options.signal?.throwIfAborted();\n\n const page = await this.exclusive(async () => {\n const entries: StorageObjectInfo[] = [];\n\n let visited = 0;\n\n while (visited++ < size) {\n const next = iterator.next();\n\n if (next.done) {\n done = true;\n break;\n }\n\n const [key, value] = next.value;\n\n if (key.startsWith(prefix))\n entries.push({ key, version: value.version, createdAt: value.createdAt });\n }\n\n return entries;\n });\n\n for (const entry of page) {\n options.signal?.throwIfAborted();\n yield entry;\n }\n }\n }\n\n public list(prefix: string): Promise<readonly StorageObjectInfo[]> {\n return this.exclusive(async () => {\n if (\n typeof prefix != \"string\" ||\n prefix.includes(\"\\0\") ||\n Buffer.byteLength(prefix, \"utf8\") > this.options.maxKeyBytes\n )\n throw new StorageError(\"Invalid storage prefix\", \"INVALID_KEY\");\n\n this.metrics.lists++;\n\n const result: StorageObjectInfo[] = [];\n\n for (const [key, value] of this.entries)\n if (key.startsWith(prefix)) {\n if (result.length >= 100_000)\n throw new StorageError(\"Listing limit exceeded; use iterate()\", \"RESOURCE_LIMIT\");\n result.push({ key, version: value.version, createdAt: value.createdAt });\n }\n\n return result.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n });\n }\n\n private async append(frame: JournalPayload): Promise<void> {\n const encoded = encodeJournalFrame(frame);\n\n if (this.journalBytes + encoded.byteLength > this.options.maxJournalBytes)\n throw new StorageError(\n \"Storage journal limit reached; compact before writing\",\n \"RESOURCE_LIMIT\",\n );\n\n try {\n await writeAll(this.journal, encoded, this.journalBytes);\n await this.fault(\"after-journal-write\", { operation: frame.op, key: frame.key });\n await this.journal.sync();\n await this.fault(\"after-journal-sync\", { operation: frame.op, key: frame.key });\n\n this.journalBytes += encoded.byteLength;\n this.metrics.bytesWritten += encoded.byteLength;\n } catch (cause) {\n this.poisoned = true;\n throw new StorageError(\"Storage publication outcome is unknown\", \"OUTCOME_UNKNOWN\", {\n cause,\n });\n }\n }\n\n public compact(): Promise<void> {\n return this.exclusive(async () => {\n try {\n const nextPath = join(this.root, NEXT_JOURNAL);\n const previousPath = join(this.root, PREVIOUS_JOURNAL);\n const currentPath = join(this.root, JOURNAL_FILE);\n\n await this.removeObsolete(nextPath);\n await this.removeObsolete(previousPath);\n\n const next = await open(nextPath, \"wx\", 0o600);\n\n let offset = 0;\n let sequence = 0;\n\n try {\n for (const [key, metadata] of this.entries) {\n const bytes = encodeJournalFrame({\n format: 1,\n sequence: ++sequence,\n op: \"put\",\n key,\n version: metadata.version,\n createdAt: metadata.createdAt,\n size: metadata.size,\n digest: metadata.digest,\n });\n\n if (offset + bytes.byteLength > this.options.maxJournalBytes)\n throw new StorageError(\n \"Compacted journal exceeds configured limit\",\n \"RESOURCE_LIMIT\",\n );\n\n await writeAll(next, bytes, offset);\n offset += bytes.byteLength;\n }\n\n await next.sync();\n } finally {\n await next.close();\n }\n\n await this.journal.close();\n\n await rename(currentPath, previousPath);\n await rename(nextPath, currentPath);\n\n await this.syncDirectory(this.root);\n await this.fault(\"after-journal-rotation\", { operation: \"compact\" });\n\n this.journal = await open(currentPath, \"r+\");\n this.journalBytes = offset;\n this.sequence = sequence;\n\n await this.removeObsolete(previousPath);\n } catch (cause) {\n this.poisoned = true;\n throw new StorageError(\"Journal compaction outcome is unknown\", \"OUTCOME_UNKNOWN\", {\n cause,\n });\n }\n });\n }\n\n public close(): Promise<void> {\n if (!this.ownership.isOwned && this.closed) return Promise.resolve();\n if (this.closePromise) return this.closePromise;\n\n this.closing = true;\n const attempt = this.closeAttempt();\n this.closePromise = attempt;\n\n const clearAttempt = () => {\n if (this.closePromise == attempt) this.closePromise = undefined;\n };\n\n void attempt.then(clearAttempt, clearAttempt);\n\n return attempt;\n }\n\n private async closeAttempt(): Promise<void> {\n const failures: unknown[] = [];\n await this.operationTail;\n\n try {\n if (!this.resourcesClosed) {\n try {\n if (this.journal) await this.journal.close();\n this.resourcesClosed = true;\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length == 0) {\n try {\n await this.ownership.release();\n } catch (error) {\n failures.push(error);\n }\n }\n } finally {\n this.closed = true;\n this.closing = false;\n\n if (!this.ownership.isOwned)\n AsyncDiskStorageDriver.activeDirectories.delete(this.registryKey);\n }\n\n if (failures.length == 1) throw failures[0];\n\n if (failures.length > 1)\n throw new AggregateError(failures, \"Storage shutdown encountered multiple failures\");\n }\n\n private objectPath(key: string, version: string): string {\n const hash = sha256(new TextEncoder().encode(key));\n return join(this.root, OBJECTS_DIRECTORY, hash.slice(0, 2), hash, `${version}.obj`);\n }\n\n private async assertCurrentObjectsExist(): Promise<void> {\n for (const [key, metadata] of this.entries)\n try {\n await stat(this.objectPath(key, metadata.version));\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\")\n throw new StorageError(`Journal references a missing object: ${key}`, \"CORRUPTION\", {\n cause: error,\n });\n\n throw error;\n }\n }\n\n private async cleanupPhysicalObjects(): Promise<void> {\n const referenced = new Map<string, string>();\n\n for (const [key, metadata] of this.entries)\n referenced.set(sha256(new TextEncoder().encode(key)), metadata.version);\n\n const walk = async (directory: string): Promise<void> => {\n let items;\n\n try {\n items = await opendir(directory);\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\") return;\n throw error;\n }\n\n for await (const item of items) {\n const path = join(directory, item.name);\n\n if (item.isDirectory()) await walk(path);\n else if (\n item.isFile() &&\n (item.name.endsWith(\".tmp\") ||\n (item.name.endsWith(\".obj\") &&\n referenced.get(basename(dirname(path))) + \".obj\" != item.name))\n )\n await this.removeObsolete(path);\n }\n };\n\n await walk(join(this.root, OBJECTS_DIRECTORY));\n }\n\n private async recoverJournalRotation(): Promise<void> {\n const current = join(this.root, JOURNAL_FILE);\n const previous = join(this.root, PREVIOUS_JOURNAL);\n const next = join(this.root, NEXT_JOURNAL);\n\n const hasCurrent = await exists(current);\n const hasPrevious = await exists(previous);\n const hasNext = await exists(next);\n\n if (!hasCurrent) {\n if (hasNext) await rename(next, current);\n else if (hasPrevious) await rename(previous, current);\n } else if (hasPrevious) {\n try {\n const input = await open(current, \"r\");\n\n try {\n await replayJournal(input, this.options.maxJournalBytes, () => {});\n } finally {\n await input.close();\n }\n\n await this.removeObsolete(previous);\n } catch (cause) {\n throw new StorageError(\n \"Cannot establish journal rotation outcome; refusing to restore stale journal\",\n \"CORRUPTION\",\n { cause },\n );\n }\n }\n\n if ((await exists(current)) && (await exists(next))) await this.removeObsolete(next);\n if ((await exists(current)) && (await exists(previous))) await this.removeObsolete(previous);\n\n await this.syncDirectory(this.root);\n }\n\n private async fault(point: DiskFaultPoint, context: DiskFaultContext): Promise<void> {\n await this.options.faultInjector?.(point, context);\n }\n\n private async removeObsolete(path: string): Promise<void> {\n try {\n await rm(path, { force: true });\n } catch {\n /* Cleanup is retried during the next open. */\n }\n }\n\n private async syncDirectory(directory: string): Promise<void> {\n if (!this.directorySync) return;\n\n try {\n await AsyncDiskStorageDriver.syncDirectoryStatic(directory);\n } catch (error) {\n if ([\"EINVAL\", \"ENOTSUP\", \"EBADF\", \"EISDIR\", \"EPERM\"].includes(nodeErrorCode(error) ?? \"\"))\n this.directorySync = false;\n else throw error;\n }\n }\n\n private static async syncDirectoryStatic(directory: string): Promise<void> {\n const handle = await open(directory, \"r\");\n\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n }\n\n private async cleanupFailedOpen(): Promise<void> {\n const failures: unknown[] = [];\n\n try {\n if (this.journal) await this.journal.close();\n } catch (error) {\n failures.push(error);\n }\n\n if (failures.length == 0) {\n try {\n await this.ownership.release();\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length == 1) throw failures[0];\n\n if (failures.length > 1)\n throw new AggregateError(failures, \"Failed storage initialization cleanup\");\n }\n}\n"],"mappings":";;;;;;AAGA,IAAM,eAAe,OAAO,KAAK,YAAY,OAAO;AACpD,IAAM,mBAAmB;AAyBzB,IAAM,UAAU,IAAI,YAAY;AAChC,IAAM,UAAU,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC;AAExD,SAAgB,OAAO,MAAmC;CACxD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK;AACvD;AAEA,SAAS,WAAW,SAAiB,OAA+B;CAClE,OAAO,IAAI,aAAa,SAAS,cAAc,SAAS,OAAO,KAAA,IAAY,EAAE,MAAM,CAAC;AACtF;AAEA,SAASA,cAAY,OAAmB,OAAwC;CAC9E,IAAI;EACF,MAAM,QAAiB,KAAK,MAAM,QAAQ,OAAO,KAAK,CAAC;EACvD,IAAI,CAAC,SAAS,OAAO,SAAS,YAAY,MAAM,QAAQ,KAAK,GAC3D,MAAM,IAAI,MAAM,eAAe;EACjC,OAAO;CACT,SAAS,OAAO;EACd,MAAM,WAAW,WAAW,SAAS,KAAK;CAC5C;AACF;AAEA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,SAAS,YAAY,iBAAiB,KAAK,KAAK;AAChE;AAEA,SAAS,iBACP,OA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AAW;IAAS;IAAU;GAAO,CAAC,CAAC,SAAS,cAAc,KAAK,KAAK,EAAE,GACvF,KAAK,gBAAgB;QAClB,MAAM;EACb;CACF;CAEA,aAAqB,oBAAoB,WAAkC;EACzE,MAAM,SAAS,MAAM,KAAK,WAAW,GAAG;EAExC,IAAI;GACF,MAAM,OAAO,KAAK;EACpB,UAAU;GACR,MAAM,OAAO,MAAM;EACrB;CACF;CAEA,MAAc,oBAAmC;EAC/C,MAAM,WAAsB,CAAC;EAE7B,IAAI;GACF,IAAI,KAAK,SAAS,MAAM,KAAK,QAAQ,MAAM;EAC7C,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAEA,IAAI,SAAS,UAAU,GACrB,IAAI;GACF,MAAM,KAAK,UAAU,QAAQ;EAC/B,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAGF,IAAI,SAAS,UAAU,GAAG,MAAM,SAAS;EAEzC,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,eAAe,UAAU,uCAAuC;CAC9E;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duraxis/storage-disk",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Asynchronous filesystem StorageDriver implementation for Duraxis.",
5
5
  "license": "ISC",
6
6
  "author": "João Paulo Dias <joaopdias.dev@gmail.com>",
@@ -46,11 +46,11 @@
46
46
  ],
47
47
  "sideEffects": false,
48
48
  "dependencies": {
49
- "@duraxis/storage": "0.2.0"
49
+ "@duraxis/storage": "0.2.1"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@duraxis/storage-testkit": "0.1.0",
53
- "@duraxis/core": "0.4.0"
53
+ "@duraxis/core": "0.5.0"
54
54
  },
55
55
  "scripts": {
56
56
  "build": "vite build && tsc -p tsconfig.build.json",