@duraxis/storage-disk 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/LICENSE +15 -0
- package/README.md +170 -2
- package/dist/async-disk-storage.driver.d.ts +69 -0
- package/dist/disk-format.d.ts +28 -0
- package/dist/index.cjs +1065 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1064 -0
- package/dist/index.js.map +1 -0
- package/dist/ownership.d.ts +28 -0
- package/package.json +57 -3
|
@@ -0,0 +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","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\n// Explicit allowlist. Unknown, remote, and userspace filesystems fail closed.\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 /** Defaults to manual. dead-process is restricted to validated local Linux environments. */\n readonly mode: \"manual\" | \"dead-process\";\n /** Stable application identity across restarts. It is not an owner token or a secret. */\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 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 { dirname, join, resolve } from \"node:path\";\nimport {\n mkdir,\n open,\n readFile,\n readdir,\n realpath,\n rename,\n rm,\n stat,\n truncate,\n type FileHandle,\n} from \"node:fs/promises\";\nimport {\n assertStorageKey,\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 decodeJournal,\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\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 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 while (offset < bytes.byteLength) {\n const result = await handle.write(bytes, offset, bytes.byteLength - offset, position + offset);\n if (result.bytesWritten <= 0)\n throw new StorageError(\"Disk write made no progress\", \"UNAVAILABLE\");\n offset += result.bytesWritten;\n }\n}\n\nasync function syncAndClose(handle: FileHandle, context: string): Promise<void> {\n let syncFailure: unknown;\n try {\n await handle.sync();\n } catch (error) {\n syncFailure = error;\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 throw closeFailure;\n }\n if (syncFailure != null) throw syncFailure;\n}\n\nexport class AsyncDiskStorageDriver implements StorageDriver {\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 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 const maxKeyBytes = options.maxKeyBytes ?? 4096;\n const maxObjectBytes = options.maxObjectBytes ?? 256 * 1024 * 1024;\n const maxJournalBytes = options.maxJournalBytes ?? 1024 * 1024 * 1024;\n const ownershipRecovery = normalizeOwnershipRecovery(options.ownershipRecovery);\n if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes < 64 || maxKeyBytes > 64 * 1024)\n throw new RangeError(\"Invalid maximum storage key size\");\n if (\n !Number.isSafeInteger(maxObjectBytes) ||\n maxObjectBytes < 0 ||\n maxObjectBytes > 1024 * 1024 * 1024\n )\n throw new RangeError(\"Invalid maximum object size\");\n if (!Number.isSafeInteger(maxJournalBytes) || maxJournalBytes < 1024 * 1024)\n throw new RangeError(\"Invalid maximum journal size\");\n\n const requested = resolve(options.directory);\n await mkdir(requested, { recursive: true });\n const root = await realpath(requested);\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\n \"Storage directory is already owned by this process\",\n \"OWNERSHIP_CONFLICT\",\n );\n this.activeDirectories.add(registryKey);\n const driver = new AsyncDiskStorageDriver(root, registryKey, {\n ...options,\n directory: root,\n maxKeyBytes,\n maxObjectBytes,\n maxJournalBytes,\n ownershipRecovery,\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 const root = await realpath(resolve(options.directory));\n const registryKey = process.platform == \"win32\" ? root.toLocaleLowerCase(\"en-US\") : root;\n if (this.activeDirectories.has(registryKey))\n throw new StorageError(\"Cannot recover ownership held by this process\", \"OWNERSHIP_CONFLICT\");\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 const journalPath = join(this.root, JOURNAL_FILE);\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 const bytes = await readFile(journalPath);\n if (bytes.byteLength > this.options.maxJournalBytes)\n throw new StorageError(\"Storage journal exceeds configured limit\", \"RESOURCE_LIMIT\");\n const decoded = decodeJournal(bytes);\n for (const frame of decoded.frames) {\n this.validateKey(frame.key);\n this.sequence = frame.sequence;\n if (frame.op == \"put\")\n this.entries.set(frame.key, {\n version: frame.version,\n createdAt: frame.createdAt,\n size: frame.size,\n digest: frame.digest,\n });\n else this.entries.delete(frame.key);\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 this.journalBytes = decoded.validBytes;\n this.journal = await open(journalPath, \"r+\");\n await this.assertCurrentObjectsExist();\n await this.cleanupPhysicalObjects();\n }\n\n private validateKey(key: string): void {\n assertStorageKey(key);\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 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 const before = performance.now();\n const previous = this.operationTail;\n let release!: () => void;\n this.operationTail = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previous;\n this.metrics.synchronizationWaitMs += performance.now() - before;\n try {\n this.assertUsable();\n return await operation();\n } finally {\n release();\n }\n }\n\n public get(key: string): Promise<StorageObject | null> {\n return this.exclusive(async () => {\n this.validateKey(key);\n this.metrics.reads++;\n const metadata = this.entries.get(key);\n if (!metadata) return null;\n const path = this.objectPath(key, metadata.version);\n let info;\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 if (info.size > this.options.maxObjectBytes + 32 * 1024)\n throw new StorageError(\"Physical object exceeds configured size\", \"CORRUPTION\");\n const physical = await readFile(path);\n this.metrics.bytesRead += physical.byteLength;\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 if (!(data instanceof Uint8Array)) throw new TypeError(\"Storage data must be a Uint8Array\");\n if (data.byteLength > this.options.maxObjectBytes)\n throw new StorageError(\"Storage object exceeds configured byte limit\", \"RESOURCE_LIMIT\");\n const current = this.entries.get(key);\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 this.metrics.writes++;\n const metadata: StoredMetadata = {\n version: randomUUID(),\n createdAt: Date.now(),\n size: data.byteLength,\n digest: sha256(data),\n };\n const physical = encodePhysicalObject(key, metadata, data);\n const finalPath = this.objectPath(key, metadata.version);\n const parent = dirname(finalPath);\n await mkdir(parent, { recursive: true });\n const temporary = join(parent, `.${metadata.version}.${randomUUID()}.tmp`);\n let published = false;\n try {\n const handle = await open(temporary, \"wx\", 0o600);\n try {\n await writeAll(handle, physical);\n await handle.sync();\n } finally {\n await handle.close();\n }\n await this.fault(\"after-object-sync\", { operation: \"put\", key });\n await rename(temporary, finalPath);\n published = true;\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 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 await this.append(frame);\n this.entries.set(key, metadata);\n this.sequence = frame.sequence;\n this.metrics.bytesWritten += physical.byteLength;\n if (current) await this.removeObsolete(this.objectPath(key, current.version));\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 const current = this.entries.get(key);\n if (options.condition.type == \"if-absent\")\n return current ? { success: false, reason: \"conflict\" } : { success: true };\n if (!current || current.version != options.condition.version)\n return { success: false, reason: \"conflict\" };\n this.metrics.deletes++;\n const frame: JournalPayload = {\n format: 1,\n sequence: this.sequence + 1,\n op: \"delete\",\n key,\n };\n await this.append(frame);\n this.entries.delete(key);\n this.sequence = frame.sequence;\n await this.removeObsolete(this.objectPath(key, current.version));\n return { success: true };\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 this.metrics.lists++;\n return [...this.entries]\n .filter(([key]) => key.startsWith(prefix))\n .map(([key, value]) => ({ key, version: value.version, createdAt: value.createdAt }))\n .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 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 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 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 await this.removeObsolete(nextPath);\n await this.removeObsolete(previousPath);\n const next = await open(nextPath, \"wx\", 0o600);\n let offset = 0;\n let sequence = 0;\n try {\n for (const [key, metadata] of [...this.entries].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n )) {\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 await writeAll(next, bytes, offset);\n offset += bytes.byteLength;\n }\n await next.sync();\n } finally {\n await next.close();\n }\n await this.journal.close();\n await rename(currentPath, previousPath);\n await rename(nextPath, currentPath);\n await this.syncDirectory(this.root);\n await this.fault(\"after-journal-rotation\", { operation: \"compact\" });\n this.journal = await open(currentPath, \"r+\");\n this.journalBytes = offset;\n this.sequence = sequence;\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 this.closing = true;\n const attempt = this.closeAttempt();\n this.closePromise = attempt;\n const clearAttempt = () => {\n if (this.closePromise == attempt) this.closePromise = undefined;\n };\n void attempt.then(clearAttempt, clearAttempt);\n return attempt;\n }\n\n private async closeAttempt(): Promise<void> {\n const failures: unknown[] = [];\n await this.operationTail;\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 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 if (!this.ownership.isOwned)\n AsyncDiskStorageDriver.activeDirectories.delete(this.registryKey);\n }\n if (failures.length == 1) throw failures[0];\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 throw error;\n }\n }\n }\n\n private async cleanupPhysicalObjects(): Promise<void> {\n const referenced = new Set(\n [...this.entries].map(([key, metadata]) => this.objectPath(key, metadata.version)),\n );\n const walk = async (directory: string): Promise<void> => {\n let items;\n try {\n items = await readdir(directory, { withFileTypes: true });\n } catch (error) {\n if (nodeErrorCode(error) == \"ENOENT\") return;\n throw error;\n }\n for (const item of items) {\n const path = join(directory, item.name);\n if (item.isDirectory()) await walk(path);\n else if (\n item.isFile() &&\n (item.name.endsWith(\".tmp\") || (item.name.endsWith(\".obj\") && !referenced.has(path)))\n )\n await this.removeObsolete(path);\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 const hasCurrent = await exists(current);\n const hasPrevious = await exists(previous);\n const hasNext = await exists(next);\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 decodeJournal(await readFile(current));\n await this.removeObsolete(previous);\n } catch {\n await this.removeObsolete(current);\n await rename(previous, current);\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 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 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 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 try {\n if (this.journal) await this.journal.close();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length == 0) {\n try {\n await this.ownership.release();\n } catch (error) {\n failures.push(error);\n }\n }\n if (failures.length == 1) throw failures[0];\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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;EACrB;EAEF,IAAI,SAAS,UAAU,GAAG,MAAM,SAAS;EACzC,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,eAAe,UAAU,uCAAuC;CAC9E;AACF"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
declare const OWNERSHIP_CONFIRMATION = "I_HAVE_VERIFIED_EXCLUSIVE_ACCESS";
|
|
2
|
+
export interface OwnershipRecoveryOptions {
|
|
3
|
+
/** Defaults to manual. dead-process is restricted to validated local Linux environments. */
|
|
4
|
+
readonly mode: "manual" | "dead-process";
|
|
5
|
+
/** Stable application identity across restarts. It is not an owner token or a secret. */
|
|
6
|
+
readonly applicationId?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface RecoverOwnershipOptions {
|
|
9
|
+
readonly directory: string;
|
|
10
|
+
readonly confirmation: typeof OWNERSHIP_CONFIRMATION;
|
|
11
|
+
}
|
|
12
|
+
export interface NormalizedOwnershipRecovery {
|
|
13
|
+
readonly mode: "manual" | "dead-process";
|
|
14
|
+
readonly applicationId?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function normalizeOwnershipRecovery(options: OwnershipRecoveryOptions | undefined): NormalizedOwnershipRecovery;
|
|
17
|
+
export declare class DirectoryOwnership {
|
|
18
|
+
#private;
|
|
19
|
+
private readonly root;
|
|
20
|
+
private readonly recovery;
|
|
21
|
+
constructor(root: string, recovery: NormalizedOwnershipRecovery);
|
|
22
|
+
get isOwned(): boolean;
|
|
23
|
+
acquire(): Promise<void>;
|
|
24
|
+
release(): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
export declare function manuallyRecoverOwnership(root: string): Promise<void>;
|
|
27
|
+
export declare function validateManualRecoveryConfirmation(confirmation: RecoverOwnershipOptions["confirmation"]): void;
|
|
28
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@duraxis/storage-disk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Asynchronous filesystem StorageDriver implementation for Duraxis.",
|
|
5
|
+
"license": "ISC",
|
|
6
|
+
"author": "João Paulo Dias <joaopdias.dev@gmail.com>",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"duraxis",
|
|
9
|
+
"database",
|
|
10
|
+
"storage",
|
|
11
|
+
"filesystem",
|
|
12
|
+
"typescript"
|
|
13
|
+
],
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "https://github.com/Joaopdiasventura/Duraxis.git",
|
|
17
|
+
"directory": "packages/storage-disk"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/Joaopdiasventura/Duraxis/tree/main/packages/storage-disk#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/Joaopdiasventura/Duraxis/issues"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=22.12.0"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public",
|
|
28
|
+
"registry": "https://registry.npmjs.org/"
|
|
29
|
+
},
|
|
30
|
+
"type": "module",
|
|
31
|
+
"main": "./dist/index.cjs",
|
|
32
|
+
"module": "./dist/index.js",
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"exports": {
|
|
35
|
+
".": {
|
|
36
|
+
"types": "./dist/index.d.ts",
|
|
37
|
+
"import": "./dist/index.js",
|
|
38
|
+
"require": "./dist/index.cjs"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"dist",
|
|
43
|
+
"README.md",
|
|
44
|
+
"LICENSE",
|
|
45
|
+
"CHANGELOG.md"
|
|
46
|
+
],
|
|
47
|
+
"sideEffects": false,
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@duraxis/storage": "0.1.0"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@duraxis/storage-testkit": "0.1.0",
|
|
53
|
+
"@duraxis/core": "0.1.0"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"build": "vite build && tsc -p tsconfig.build.json",
|
|
57
|
+
"typecheck": "tsc --noEmit",
|
|
58
|
+
"test": "vitest run"
|
|
59
|
+
}
|
|
6
60
|
}
|