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