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