@kabxx/dsh-message-revision 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/README.md +48 -2
- package/cordis.patch.yml +3 -0
- package/icon.svg +23 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +45 -4
- package/src/bounded-commit.js +121 -0
- package/src/bounded-revision.js +250 -0
- package/src/client.js +1421 -0
- package/src/index.js +742 -0
- package/src/native-lease.js +143 -0
- package/src/platform.js +623 -0
- package/src/revision-candidates.js +341 -0
- package/src/revision-notifications.js +122 -0
- package/src/revision.js +601 -0
- package/src/rewrite-journal.js +895 -0
- package/src/rollback-events.js +8 -0
- package/src/rollout-process.js +259 -0
- package/src/rollout-stream.js +521 -0
- package/src/rollout-worker.js +452 -0
|
@@ -0,0 +1,895 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, open, readFile, readdir, readlink, rm, statfs, unlink } from 'node:fs/promises';
|
|
4
|
+
import { hostname } from 'node:os';
|
|
5
|
+
import { basename, dirname, join } from 'node:path';
|
|
6
|
+
import manifest from '../package.json' with { type: 'json' };
|
|
7
|
+
import {
|
|
8
|
+
isCanonicalPath, isSamePath, moveEntryDurable, pathKey, readDarwinProcessScope,
|
|
9
|
+
readDarwinProcessStart, readWin32BootId, readWin32ProcessCreationTime, replaceFileDurable, resolveRolloutPath,
|
|
10
|
+
} from './platform.js';
|
|
11
|
+
|
|
12
|
+
const release = /^v\d+\.\d+\.\d+(?:-[0-9a-z.-]+)?$/iu;
|
|
13
|
+
const sessionFile = /^session\.v4\.jsonl(?:\.zstd)?$/u;
|
|
14
|
+
const digestPattern = /^[a-f0-9]{64}$/u;
|
|
15
|
+
const garbageName = /^discard-[a-f0-9-]{36}$/u;
|
|
16
|
+
const preparationName = /^preparing-[a-f0-9-]{36}$/u;
|
|
17
|
+
const limit = 256 * 1024 * 1024;
|
|
18
|
+
const streamLimit = 16 * 1024 * 1024 * 1024;
|
|
19
|
+
const chunkSize = 128 * 1024;
|
|
20
|
+
const intentLimit = 4 * 1024 * 1024;
|
|
21
|
+
const ownerHost = hostname();
|
|
22
|
+
const busyKey = Symbol.for('dsh-message-revision.active-transactions');
|
|
23
|
+
const active = globalThis[busyKey] ??= new Set();
|
|
24
|
+
const retirementKey = Symbol.for('dsh-message-revision.settled-retirements');
|
|
25
|
+
const settledRetirements = globalThis[retirementKey] ??= new Map();
|
|
26
|
+
const retirementDelays = [0, 100, 500, 2000];
|
|
27
|
+
const cleanupQueue = [];
|
|
28
|
+
let cleaning = false;
|
|
29
|
+
|
|
30
|
+
function assert(condition, detail) {
|
|
31
|
+
if (!condition) throw new Error(detail);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function optionalStat(path) {
|
|
35
|
+
return lstat(path).catch(error => {
|
|
36
|
+
if (error.code !== 'ENOENT') throw error;
|
|
37
|
+
return undefined;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function assertDirectory(path) {
|
|
42
|
+
const entry = await optionalStat(path);
|
|
43
|
+
if (entry === undefined) return false;
|
|
44
|
+
let canonical;
|
|
45
|
+
try { canonical = await isCanonicalPath(path); }
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (error.code === 'ENOENT') return false;
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
assert(entry.isDirectory() && canonical, 'Unsafe transaction directory');
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function syncDirectory(path) {
|
|
55
|
+
if (process.platform === 'win32') return;
|
|
56
|
+
const handle = await open(path, 'r');
|
|
57
|
+
try { await handle.sync(); } finally { await handle.close(); }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function ensureDirectory(path) {
|
|
61
|
+
await mkdir(path, { mode: 0o700 }).catch(error => {
|
|
62
|
+
if (error.code !== 'EEXIST') throw error;
|
|
63
|
+
});
|
|
64
|
+
assert(await assertDirectory(path), 'Missing transaction directory');
|
|
65
|
+
await syncDirectory(dirname(path));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function writeFileDurably(path, bytes) {
|
|
69
|
+
const file = await open(path, 'wx', 0o600);
|
|
70
|
+
try {
|
|
71
|
+
await file.writeFile(bytes);
|
|
72
|
+
await file.sync();
|
|
73
|
+
} finally { await file.close(); }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function readRegular(path, max = limit) {
|
|
77
|
+
const entry = await lstat(path);
|
|
78
|
+
assert(entry.isFile() && entry.size <= max && await isCanonicalPath(path), 'Unsafe transaction file');
|
|
79
|
+
return readFile(path);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const digest = data => createHash('sha256').update(data).digest('hex');
|
|
83
|
+
|
|
84
|
+
async function regularIdentity(path) {
|
|
85
|
+
const entry = await lstat(path, { bigint: true });
|
|
86
|
+
assert(entry.isFile() && await isCanonicalPath(path), 'Unsafe transaction file');
|
|
87
|
+
return entry;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Copy and hash with one bounded buffer, optionally reading just a prefix. */
|
|
91
|
+
async function streamFile(path, { destination, mode = 0o600, max = streamLimit, length, sourceIdentity } = {}) {
|
|
92
|
+
const expected = await regularIdentity(path);
|
|
93
|
+
requireGivenIdentity(sourceIdentity, expected);
|
|
94
|
+
const source = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
95
|
+
let target;
|
|
96
|
+
try {
|
|
97
|
+
assert(sameIdentity(fileIdentity(await source.stat({ bigint: true })), fileIdentity(expected)),
|
|
98
|
+
'Transaction source changed while opening');
|
|
99
|
+
if (destination !== undefined) target = await open(destination, 'wx', mode);
|
|
100
|
+
const digest = createHash('sha256');
|
|
101
|
+
const buffer = Buffer.allocUnsafe(chunkSize);
|
|
102
|
+
let size = 0;
|
|
103
|
+
while (length === undefined || size < length) {
|
|
104
|
+
const count = length === undefined ? buffer.length : Math.min(buffer.length, length - size);
|
|
105
|
+
const { bytesRead } = await source.read(buffer, 0, count, null);
|
|
106
|
+
if (bytesRead === 0) break;
|
|
107
|
+
size += bytesRead;
|
|
108
|
+
assert(size <= max, 'Streamed transaction artifact exceeds size limit');
|
|
109
|
+
digest.update(buffer.subarray(0, bytesRead));
|
|
110
|
+
if (target !== undefined) {
|
|
111
|
+
for (let offset = 0; offset < bytesRead;) {
|
|
112
|
+
const { bytesWritten } = await target.write(buffer, offset, bytesRead - offset, null);
|
|
113
|
+
assert(bytesWritten > 0, 'Unable to make progress writing rewrite artifact');
|
|
114
|
+
offset += bytesWritten;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
assert(length === undefined || length === size, 'Transaction artifact is shorter than its candidate');
|
|
119
|
+
const after = await regularIdentity(path);
|
|
120
|
+
assert(sameIdentity(fileIdentity(after), fileIdentity(expected)), 'Transaction source changed during streaming');
|
|
121
|
+
if (target !== undefined) await target.sync();
|
|
122
|
+
return { size, digest: digest.digest('hex') };
|
|
123
|
+
} finally {
|
|
124
|
+
try { await target?.close(); } finally { await source.close(); }
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function safeComponent(value) {
|
|
129
|
+
return typeof value === 'string' && value.length > 0 && value !== '.' && value !== '..' && !/[\\/\u0000]/u.test(value);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function namespace(parentPath) {
|
|
133
|
+
return join(dirname(parentPath), 'plugins', ...manifest.name.split('/'));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function childPath(parentPath, child) {
|
|
137
|
+
assert(safeComponent(child.project) && safeComponent(child.directory) && sessionFile.test(child.filename),
|
|
138
|
+
'Unsafe recorded child path');
|
|
139
|
+
const store = dirname(dirname(dirname(parentPath)));
|
|
140
|
+
const path = join(store, child.project, child.directory, child.filename);
|
|
141
|
+
assert(!isSamePath(dirname(path), dirname(parentPath)), 'Transaction cannot move its parent directory');
|
|
142
|
+
return path;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function moveDirectory(from, to, expectedIdentity) {
|
|
146
|
+
assert(await assertDirectory(from), 'Transaction source directory disappeared');
|
|
147
|
+
assert(await assertDirectory(dirname(to)), 'Transaction destination parent disappeared');
|
|
148
|
+
assert(!await optionalStat(to), 'Transaction destination is already occupied');
|
|
149
|
+
const current = expectedIdentity && await transactionDirectoryIdentity(from);
|
|
150
|
+
if (expectedIdentity && current !== expectedIdentity) return false;
|
|
151
|
+
await moveEntryDurable(from, to);
|
|
152
|
+
await syncDirectory(dirname(from));
|
|
153
|
+
if (!isSamePath(dirname(to), dirname(from))) await syncDirectory(dirname(to));
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function transactionDirectoryIdentity(path) {
|
|
158
|
+
const entry = await lstat(path, { bigint: true }).catch(error => {
|
|
159
|
+
if (error.code !== 'ENOENT') throw error;
|
|
160
|
+
return undefined;
|
|
161
|
+
});
|
|
162
|
+
if (!entry) return undefined;
|
|
163
|
+
let canonical;
|
|
164
|
+
try { canonical = await isCanonicalPath(path); }
|
|
165
|
+
catch (error) {
|
|
166
|
+
if (error.code === 'ENOENT') return undefined;
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
assert(entry.isDirectory() && canonical, 'Unsafe transaction directory');
|
|
170
|
+
return `${entry.dev}:${entry.ino}`;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function removeRetiredDirectory(directory) {
|
|
174
|
+
if (!await assertDirectory(directory)) return;
|
|
175
|
+
await rm(directory, process.platform === 'win32'
|
|
176
|
+
? { recursive: true, maxRetries: 5, retryDelay: 50 }
|
|
177
|
+
: { recursive: true });
|
|
178
|
+
await syncDirectory(dirname(directory));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function listedProcessStart(pid) {
|
|
182
|
+
try {
|
|
183
|
+
const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
|
|
184
|
+
// The comm field can contain spaces and parentheses. Field 22 is starttime.
|
|
185
|
+
const close = stat.lastIndexOf(')');
|
|
186
|
+
const ticks = stat.slice(close + 1).trim().split(/\s+/u)[19];
|
|
187
|
+
assert(close > 0 && typeof ticks === 'string' && /^\d+$/u.test(ticks), 'Cannot identify transaction owner process');
|
|
188
|
+
return ticks;
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (error.code === 'ENOENT' || error.code === 'ESRCH') return undefined;
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
let processScope;
|
|
196
|
+
function readProcessScope() {
|
|
197
|
+
if (process.platform !== 'linux') return undefined;
|
|
198
|
+
return processScope ??= Promise.all([
|
|
199
|
+
readFile('/proc/sys/kernel/random/boot_id', 'utf8'), readlink('/proc/self/ns/pid'),
|
|
200
|
+
]).then(([bootId, pidNamespace]) => ({ bootId: bootId.trim(), pidNamespace })).catch(() => undefined);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function transactionOwner() {
|
|
204
|
+
const owner = { host: ownerHost, pid: process.pid };
|
|
205
|
+
if (process.platform === 'linux') {
|
|
206
|
+
const scope = await readProcessScope();
|
|
207
|
+
if (!scope) return owner;
|
|
208
|
+
const startTicks = await listedProcessStart(process.pid);
|
|
209
|
+
assert(startTicks !== undefined, 'Cannot identify current process for transaction recovery');
|
|
210
|
+
return { ...owner, ...scope, startTicks };
|
|
211
|
+
}
|
|
212
|
+
if (process.platform === 'darwin') {
|
|
213
|
+
const scope = await readDarwinProcessScope();
|
|
214
|
+
const darwinStartLabel = await readDarwinProcessStart(process.pid);
|
|
215
|
+
if (scope && darwinStartLabel) return { ...owner, ...scope, darwinStartLabel };
|
|
216
|
+
return owner;
|
|
217
|
+
}
|
|
218
|
+
if (process.platform === 'win32') {
|
|
219
|
+
const win32CreationTime = readWin32ProcessCreationTime(process.pid);
|
|
220
|
+
const win32BootId = readWin32BootId();
|
|
221
|
+
if (typeof win32CreationTime === 'string') {
|
|
222
|
+
return { ...owner, win32CreationTime, ...(win32BootId ? { win32BootId } : {}) };
|
|
223
|
+
}
|
|
224
|
+
return owner;
|
|
225
|
+
}
|
|
226
|
+
return owner;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function assertOwnerReleased(owner) {
|
|
230
|
+
assert(owner?.host === ownerHost && Number.isSafeInteger(owner.pid) && owner.pid > 0,
|
|
231
|
+
'Transaction belongs to another host or has invalid ownership');
|
|
232
|
+
if (owner.bootId !== undefined || owner.pidNamespace !== undefined || owner.startTicks !== undefined) {
|
|
233
|
+
assert(typeof owner.bootId === 'string' && typeof owner.pidNamespace === 'string'
|
|
234
|
+
&& typeof owner.startTicks === 'string' && /^\d+$/u.test(owner.startTicks), 'Invalid transaction process identity');
|
|
235
|
+
const scope = await readProcessScope();
|
|
236
|
+
assert(scope, 'Cannot verify transaction owner process identity');
|
|
237
|
+
if (scope.bootId !== owner.bootId) return;
|
|
238
|
+
assert(scope.pidNamespace === owner.pidNamespace, 'Transaction belongs to another PID namespace');
|
|
239
|
+
const startTicks = await listedProcessStart(owner.pid);
|
|
240
|
+
if (startTicks !== owner.startTicks || owner.pid === process.pid) return;
|
|
241
|
+
} else if (owner.darwinBootId !== undefined || owner.darwinStartLabel !== undefined) {
|
|
242
|
+
assert(typeof owner.darwinBootId === 'string' && owner.darwinBootId.length > 0
|
|
243
|
+
&& typeof owner.darwinStartLabel === 'string' && owner.darwinStartLabel.length > 0,
|
|
244
|
+
'Invalid transaction process identity');
|
|
245
|
+
const scope = await readDarwinProcessScope();
|
|
246
|
+
assert(scope, 'Cannot verify transaction owner process identity');
|
|
247
|
+
if (scope.darwinBootId !== owner.darwinBootId) return;
|
|
248
|
+
const startLabel = await readDarwinProcessStart(owner.pid);
|
|
249
|
+
if (startLabel === null || startLabel !== owner.darwinStartLabel || owner.pid === process.pid) return;
|
|
250
|
+
} else if (owner.win32CreationTime !== undefined || owner.win32BootId !== undefined) {
|
|
251
|
+
assert(typeof owner.win32CreationTime === 'string' && /^\d+$/u.test(owner.win32CreationTime)
|
|
252
|
+
&& (owner.win32BootId === undefined || (typeof owner.win32BootId === 'string' && /^[a-f0-9]{32}$/u.test(owner.win32BootId))),
|
|
253
|
+
'Invalid transaction process identity');
|
|
254
|
+
if (owner.pid === process.pid) return;
|
|
255
|
+
if (owner.win32BootId !== undefined) {
|
|
256
|
+
const currentBootId = readWin32BootId();
|
|
257
|
+
if (currentBootId && currentBootId !== owner.win32BootId) return;
|
|
258
|
+
}
|
|
259
|
+
const creationTime = readWin32ProcessCreationTime(owner.pid);
|
|
260
|
+
assert(creationTime !== undefined, 'Cannot verify transaction owner process identity');
|
|
261
|
+
if (creationTime === null || creationTime !== owner.win32CreationTime) return;
|
|
262
|
+
} else {
|
|
263
|
+
// Older pending journals only contain a PID. A live numeric PID cannot
|
|
264
|
+
// prove who owned one of those journals, so keep it recoverable on disk.
|
|
265
|
+
if (owner.pid === process.pid) return;
|
|
266
|
+
try { process.kill(owner.pid, 0); } catch (error) {
|
|
267
|
+
if (error.code === 'ESRCH') return;
|
|
268
|
+
throw error;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
throw new Error('The process that started this rewrite is still running');
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function verifyChildFile(path, expected) {
|
|
275
|
+
if (expected.identity !== undefined) {
|
|
276
|
+
const directory = await lstat(dirname(path), { bigint: true });
|
|
277
|
+
const identity = await regularIdentity(path);
|
|
278
|
+
assert(directory.isDirectory() && String(directory.dev) === expected.directoryIdentity.dev
|
|
279
|
+
&& String(directory.ino) === expected.directoryIdentity.ino
|
|
280
|
+
&& sameIdentity(fileIdentity(identity), expected.identity), 'Recorded child data has changed');
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
assert((await streamFile(path, { max: limit })).digest === expected.digest, 'Recorded child data has changed');
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export async function hasPendingRewrite(parentPath) {
|
|
287
|
+
const root = namespace(parentPath);
|
|
288
|
+
for (const path of [join(dirname(parentPath), 'plugins'), dirname(root), root]) {
|
|
289
|
+
if (!await assertDirectory(path)) return false;
|
|
290
|
+
}
|
|
291
|
+
for (const name of await readdir(root)) {
|
|
292
|
+
if (!release.test(name)) continue;
|
|
293
|
+
const directory = join(root, name);
|
|
294
|
+
if (await assertDirectory(directory) && await assertDirectory(join(directory, 'rewrite'))) return true;
|
|
295
|
+
}
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function fileIdentity(entry) {
|
|
300
|
+
return {
|
|
301
|
+
dev: String(entry.dev), ino: String(entry.ino), size: String(entry.size),
|
|
302
|
+
mtimeNs: String(entry.mtimeNs), ctimeNs: String(entry.ctimeNs),
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function sameIdentity(left, right) {
|
|
307
|
+
return left.dev === right.dev && left.ino === right.ino && left.size === right.size
|
|
308
|
+
&& left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function entryRecord(entry) {
|
|
312
|
+
const header = entry.header ?? entry.handle?.header;
|
|
313
|
+
return {
|
|
314
|
+
id: header?.id,
|
|
315
|
+
parentSession: header?.parentSession,
|
|
316
|
+
createdAt: header?.createdAt,
|
|
317
|
+
project: basename(dirname(dirname(entry.path))),
|
|
318
|
+
directory: basename(dirname(entry.path)),
|
|
319
|
+
filename: basename(entry.path),
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function v2ArtifactPath(journal, artifact) {
|
|
324
|
+
return artifact.index === 0 ? journal.parentPath : childPath(journal.parentPath, artifact);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function v2StoredPath(journal, artifact, kind) {
|
|
328
|
+
return join(journal.directory, 'artifacts', `artifact-${artifact.index}.${kind}`);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function requireGivenIdentity(given, actual) {
|
|
332
|
+
if (given !== undefined) {
|
|
333
|
+
assert(sameIdentity(fileIdentity(given), fileIdentity(actual)), 'Rewrite source changed since preparation');
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export class RewriteJournalSpaceError extends Error {
|
|
338
|
+
constructor(requiredBytes, availableBytes) {
|
|
339
|
+
super('磁盘可用空间不足,无法暂存本次编辑的候选日志和备份。');
|
|
340
|
+
this.name = 'RewriteJournalSpaceError';
|
|
341
|
+
this.requiredBytes = requiredBytes;
|
|
342
|
+
this.availableBytes = availableBytes;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function assertJournalSpace(destination, sizes, metadataBytes = intentLimit) {
|
|
347
|
+
const filesystem = await statfs(destination, { bigint: true });
|
|
348
|
+
const blockSize = filesystem.frsize > 0n ? filesystem.frsize : filesystem.bsize;
|
|
349
|
+
assert(blockSize > 0n && filesystem.bavail >= 0n, 'Cannot verify available transaction disk space');
|
|
350
|
+
const blocks = size => (size + blockSize - 1n) / blockSize;
|
|
351
|
+
// Allow for the intent, enclosing directories and allocation bookkeeping.
|
|
352
|
+
const overhead = blocks(BigInt(metadataBytes)) + BigInt(sizes.length + 4);
|
|
353
|
+
const required = (sizes.reduce((total, size) => total + blocks(size), overhead)) * blockSize;
|
|
354
|
+
const available = filesystem.bavail * blockSize;
|
|
355
|
+
if (required > available) throw new RewriteJournalSpaceError(required, available);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
async function planRewriteSetCopies(parent, artifacts) {
|
|
359
|
+
const parentPath = parent.path;
|
|
360
|
+
assert(Array.isArray(artifacts) && artifacts.length > 0 && isSamePath(artifacts[0].path, parentPath), 'Parent artifact must be first');
|
|
361
|
+
const copies = [];
|
|
362
|
+
for (const [index, artifact] of artifacts.entries()) {
|
|
363
|
+
const record = { ...entryRecord(artifact), index };
|
|
364
|
+
assert(isSamePath(v2ArtifactPath({ parentPath }, record), artifact.path), 'Rewrite artifact is outside the session storage root');
|
|
365
|
+
assert(typeof artifact.candidatePath === 'string' && !isSamePath(artifact.candidatePath, artifact.path), 'Missing rewrite candidate');
|
|
366
|
+
const originalIdentity = await regularIdentity(artifact.path);
|
|
367
|
+
requireGivenIdentity(artifact.identity ?? (index === 0 ? parent.identity : undefined), originalIdentity);
|
|
368
|
+
const candidateIdentity = await regularIdentity(artifact.candidatePath);
|
|
369
|
+
assert(artifact.size === undefined || candidateIdentity.size === BigInt(artifact.size), 'Rewrite candidate changed since preparation');
|
|
370
|
+
assert(originalIdentity.size <= BigInt(streamLimit) && candidateIdentity.size <= BigInt(streamLimit),
|
|
371
|
+
'Streamed transaction artifact exceeds size limit');
|
|
372
|
+
copies.push({ artifact, record, originalIdentity, candidateIdentity });
|
|
373
|
+
}
|
|
374
|
+
return copies;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async function assertRewriteSetCopiesFit(destination, copies) {
|
|
378
|
+
const journalDev = (await lstat(destination, { bigint: true })).dev;
|
|
379
|
+
assert(copies.every(({ originalIdentity }) => originalIdentity.dev === journalDev),
|
|
380
|
+
'Rewrite artifacts must be on the transaction filesystem');
|
|
381
|
+
// Space already used by the originals and prepared candidates is reflected
|
|
382
|
+
// in bavail. Only their additional journal copies consume new file blocks.
|
|
383
|
+
const sizes = copies.flatMap(({ originalIdentity, candidateIdentity }) => [originalIdentity.size, candidateIdentity.size]);
|
|
384
|
+
await assertJournalSpace(destination, sizes);
|
|
385
|
+
return journalDev;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Allow the Host to fail early before releasing the live Agent. */
|
|
389
|
+
export async function assertRewriteSetSpace(parent, artifacts) {
|
|
390
|
+
const root = namespace(parent.path);
|
|
391
|
+
let destination = dirname(parent.path);
|
|
392
|
+
for (const path of [join(destination, 'plugins'), dirname(root), root, join(root, `v${manifest.version}`)]) {
|
|
393
|
+
if (!await assertDirectory(path)) break;
|
|
394
|
+
destination = path;
|
|
395
|
+
}
|
|
396
|
+
await assertRewriteSetCopiesFit(destination, await planRewriteSetCopies(parent, artifacts));
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Prepare a durable multi-log journal under caller-held native writer locks. */
|
|
400
|
+
export async function prepareRewriteSetJournal(parent, children, artifacts, { messageId } = {}) {
|
|
401
|
+
const parentPath = parent.path;
|
|
402
|
+
const parentKey = pathKey(parentPath);
|
|
403
|
+
const header = parent.header ?? parent.handle?.header;
|
|
404
|
+
assert(typeof header?.id === 'string' && header.id.length > 0 && sessionFile.test(basename(parentPath)),
|
|
405
|
+
'Missing parent session header or path');
|
|
406
|
+
assert(Array.isArray(artifacts) && artifacts.length > 0 && isSamePath(artifacts[0].path, parentPath), 'Parent artifact must be first');
|
|
407
|
+
const root = namespace(parentPath);
|
|
408
|
+
const versionPath = join(root, `v${manifest.version}`);
|
|
409
|
+
for (const path of [join(dirname(parentPath), 'plugins'), dirname(root), root, versionPath]) await ensureDirectory(path);
|
|
410
|
+
assert(!active.has(parentKey) && !await hasPendingRewrite(parentPath), 'A previous rewrite still needs recovery');
|
|
411
|
+
active.add(parentKey);
|
|
412
|
+
const temporary = join(versionPath, `preparing-${randomUUID()}`);
|
|
413
|
+
const directory = join(versionPath, 'rewrite');
|
|
414
|
+
try {
|
|
415
|
+
const copies = await planRewriteSetCopies(parent, artifacts);
|
|
416
|
+
await mkdir(temporary, { mode: 0o700 });
|
|
417
|
+
await mkdir(join(temporary, 'artifacts'), { mode: 0o700 });
|
|
418
|
+
const journal = { directory: temporary, parentPath };
|
|
419
|
+
const intent = {
|
|
420
|
+
format: 2, parentId: header.id, filename: basename(parentPath), owner: await transactionOwner(),
|
|
421
|
+
artifacts: [], children: [],
|
|
422
|
+
...(messageId === undefined ? {} : { delivery: { messageId } }),
|
|
423
|
+
};
|
|
424
|
+
const journalDev = await assertRewriteSetCopiesFit(journal.directory, copies);
|
|
425
|
+
for (const { artifact, record, originalIdentity, candidateIdentity } of copies) {
|
|
426
|
+
const candidatePath = v2StoredPath(journal, record, 'candidate');
|
|
427
|
+
const candidate = await streamFile(artifact.candidatePath, {
|
|
428
|
+
destination: candidatePath, mode: Number(originalIdentity.mode & 0o777n), sourceIdentity: candidateIdentity,
|
|
429
|
+
});
|
|
430
|
+
assert((artifact.size === undefined || candidate.size === artifact.size)
|
|
431
|
+
&& (artifact.digest === undefined || candidate.digest === artifact.digest), 'Rewrite candidate changed since preparation');
|
|
432
|
+
const original = await streamFile(artifact.path, {
|
|
433
|
+
destination: v2StoredPath(journal, record, 'original'), sourceIdentity: originalIdentity,
|
|
434
|
+
});
|
|
435
|
+
intent.artifacts.push({
|
|
436
|
+
...record,
|
|
437
|
+
original: { ...original, mode: Number(originalIdentity.mode & 0o777n), identity: fileIdentity(originalIdentity) },
|
|
438
|
+
candidate: { ...candidate, records: artifact.retained, identity: fileIdentity(await regularIdentity(candidatePath)) },
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
for (const child of children) {
|
|
442
|
+
const record = entryRecord(child);
|
|
443
|
+
assert(isSamePath(childPath(parentPath, record), child.path), 'Child is outside the session storage root');
|
|
444
|
+
const identity = await regularIdentity(child.path);
|
|
445
|
+
requireGivenIdentity(child.identity, identity);
|
|
446
|
+
const directoryIdentity = await lstat(dirname(child.path), { bigint: true });
|
|
447
|
+
assert(directoryIdentity.isDirectory() && directoryIdentity.dev === journalDev,
|
|
448
|
+
'Withdrawn child must be on the transaction filesystem');
|
|
449
|
+
intent.children.push({ ...record, identity: fileIdentity(identity),
|
|
450
|
+
directoryIdentity: { dev: String(directoryIdentity.dev), ino: String(directoryIdentity.ino) } });
|
|
451
|
+
}
|
|
452
|
+
validateIntent(intent, { header }, parentPath);
|
|
453
|
+
const bytes = JSON.stringify(intent);
|
|
454
|
+
assert(Buffer.byteLength(bytes) <= intentLimit, 'Rewrite transaction metadata exceeds size limit');
|
|
455
|
+
await writeFileDurably(join(temporary, 'intent.json'), bytes);
|
|
456
|
+
await syncDirectory(join(temporary, 'artifacts'));
|
|
457
|
+
await syncDirectory(temporary);
|
|
458
|
+
const directoryIdentity = await transactionDirectoryIdentity(temporary);
|
|
459
|
+
await moveDirectory(temporary, directory);
|
|
460
|
+
return { directory, directoryIdentity, intent, parentPath, dshPath: parent.dshPath };
|
|
461
|
+
} catch (error) {
|
|
462
|
+
active.delete(parentKey);
|
|
463
|
+
await removeRetiredDirectory(temporary).catch(() => {});
|
|
464
|
+
throw error;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
export function rewriteSetArtifactPath(journal, index = 0) {
|
|
469
|
+
assert(journal.intent?.format === 2 && Number.isSafeInteger(index) && journal.intent.artifacts[index], 'Unknown rewrite artifact');
|
|
470
|
+
return v2ArtifactPath(journal, journal.intent.artifacts[index]);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
async function matchRewriteSetArtifact(journal, index = 0) {
|
|
474
|
+
const path = rewriteSetArtifactPath(journal, index);
|
|
475
|
+
const artifact = journal.intent.artifacts[index];
|
|
476
|
+
const candidate = artifact.candidate;
|
|
477
|
+
const original = artifact.original;
|
|
478
|
+
const current = await regularIdentity(path);
|
|
479
|
+
if (sameIdentity(fileIdentity(current), original.identity)) return { kind: 'original', current };
|
|
480
|
+
// A prior recovery may have restored the bytes at a new inode.
|
|
481
|
+
if (current.size === BigInt(original.size) && (await streamFile(path)).digest === original.digest) {
|
|
482
|
+
return { kind: 'original', current };
|
|
483
|
+
}
|
|
484
|
+
if (current.size >= BigInt(candidate.size)
|
|
485
|
+
&& (await streamFile(path, { length: candidate.size })).digest === candidate.digest) {
|
|
486
|
+
return { kind: 'candidate', current };
|
|
487
|
+
}
|
|
488
|
+
return { kind: 'conflict', current };
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** Publish child candidates first so recovery can identify a partial publication. */
|
|
492
|
+
export async function publishRewriteSetArtifacts(journal) {
|
|
493
|
+
assert(journal.intent?.format === 2, 'Not a multi-log rewrite journal');
|
|
494
|
+
const order = [...journal.intent.artifacts.slice(1), journal.intent.artifacts[0]];
|
|
495
|
+
for (const artifact of order) {
|
|
496
|
+
const path = v2ArtifactPath(journal, artifact);
|
|
497
|
+
const source = v2StoredPath(journal, artifact, 'candidate');
|
|
498
|
+
assert(sameIdentity(fileIdentity(await regularIdentity(path)), artifact.original.identity), 'Rewrite source changed before publish');
|
|
499
|
+
assert(sameIdentity(fileIdentity(await regularIdentity(source)), artifact.candidate.identity), 'Rewrite candidate changed before publish');
|
|
500
|
+
await replaceFileDurable(source, path);
|
|
501
|
+
await syncDirectory(dirname(path));
|
|
502
|
+
await syncDirectory(dirname(source));
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
export async function restoreRewriteSetArtifacts(journal, { canRestoreArtifact } = {}) {
|
|
507
|
+
assert(journal.intent?.format === 2 && !journal.committed, 'Not an uncommitted multi-log rewrite journal');
|
|
508
|
+
const pending = [];
|
|
509
|
+
for (const artifact of journal.intent.artifacts) {
|
|
510
|
+
const path = v2ArtifactPath(journal, artifact);
|
|
511
|
+
const { kind, current } = await matchRewriteSetArtifact(journal, artifact.index);
|
|
512
|
+
assert(kind !== 'conflict', 'Rewrite artifact changed after publish');
|
|
513
|
+
if (kind !== 'candidate') continue;
|
|
514
|
+
const hasSuffix = current.size > BigInt(artifact.candidate.size);
|
|
515
|
+
const allowed = await canRestoreArtifact?.(artifact, kind, artifact.index, path);
|
|
516
|
+
assert(hasSuffix ? allowed === true : allowed !== false, 'Candidate artifact cannot be restored safely');
|
|
517
|
+
const original = v2StoredPath(journal, artifact, 'original');
|
|
518
|
+
const backup = await regularIdentity(original);
|
|
519
|
+
const restored = await streamFile(original);
|
|
520
|
+
assert(restored.size === artifact.original.size && restored.digest === artifact.original.digest, 'Original rewrite backup changed');
|
|
521
|
+
pending.push({ artifact, path, original, backup: fileIdentity(backup), current: fileIdentity(current) });
|
|
522
|
+
}
|
|
523
|
+
for (const { path, current } of pending) {
|
|
524
|
+
assert(sameIdentity(fileIdentity(await regularIdentity(path)), current), 'Rewrite artifact changed during recovery');
|
|
525
|
+
}
|
|
526
|
+
await restoreWithdrawnChildren(journal);
|
|
527
|
+
for (const { artifact, path, original, backup } of pending.reverse()) {
|
|
528
|
+
const openFlags = (process.platform === 'win32' ? constants.O_RDWR : constants.O_RDONLY) | (constants.O_NOFOLLOW ?? 0);
|
|
529
|
+
const handle = await open(original, openFlags);
|
|
530
|
+
try {
|
|
531
|
+
assert(sameIdentity(fileIdentity(await handle.stat({ bigint: true })), backup), 'Original rewrite backup changed');
|
|
532
|
+
if (process.platform !== 'win32') await handle.chmod(artifact.original.mode);
|
|
533
|
+
await handle.sync();
|
|
534
|
+
} finally { await handle.close(); }
|
|
535
|
+
// A crash after this rename can resume using the original digest to
|
|
536
|
+
// identify the already restored native file at its new inode.
|
|
537
|
+
await replaceFileDurable(original, path);
|
|
538
|
+
await syncDirectory(dirname(path));
|
|
539
|
+
await syncDirectory(dirname(original));
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** Keep the original journal API for version 1 callers and transactions. */
|
|
544
|
+
export async function prepareRewriteJournal(parent, children, replacement) {
|
|
545
|
+
const parentPath = parent.path;
|
|
546
|
+
const parentKey = pathKey(parentPath);
|
|
547
|
+
const parentId = parent.handle.header.id;
|
|
548
|
+
const root = namespace(parentPath);
|
|
549
|
+
const versionPath = join(root, `v${manifest.version}`);
|
|
550
|
+
for (const path of [join(dirname(parentPath), 'plugins'), dirname(root), root, versionPath]) {
|
|
551
|
+
await ensureDirectory(path);
|
|
552
|
+
}
|
|
553
|
+
assert(!active.has(parentKey) && !await hasPendingRewrite(parentPath), 'A previous rewrite still needs recovery');
|
|
554
|
+
active.add(parentKey);
|
|
555
|
+
const temporary = join(versionPath, `preparing-${randomUUID()}`);
|
|
556
|
+
const directory = join(versionPath, 'rewrite');
|
|
557
|
+
try {
|
|
558
|
+
const records = [];
|
|
559
|
+
for (const child of children) {
|
|
560
|
+
const path = child.path;
|
|
561
|
+
const project = basename(dirname(dirname(path)));
|
|
562
|
+
const localDirectory = basename(dirname(path));
|
|
563
|
+
const { id, parentSession, createdAt } = child.handle.header;
|
|
564
|
+
const record = { id, parentSession, createdAt, project, directory: localDirectory, filename: basename(path),
|
|
565
|
+
digest: (await streamFile(path, { max: limit })).digest };
|
|
566
|
+
assert(isSamePath(childPath(parentPath, record), path), 'Child and parent use different storage roots');
|
|
567
|
+
records.push(record);
|
|
568
|
+
}
|
|
569
|
+
const candidate = createHash('sha256');
|
|
570
|
+
let size = 0;
|
|
571
|
+
for (const bytes of replacement.buffers) { candidate.update(bytes); size += bytes.length; }
|
|
572
|
+
assert(size <= limit, 'Replacement transcript is too large');
|
|
573
|
+
const intent = {
|
|
574
|
+
format: 1, parentId, filename: basename(parentPath), owner: await transactionOwner(),
|
|
575
|
+
original: digest(replacement.original), candidate: { digest: candidate.digest('hex'), size, records: replacement.retained },
|
|
576
|
+
children: records,
|
|
577
|
+
};
|
|
578
|
+
await mkdir(temporary, { mode: 0o700 });
|
|
579
|
+
await writeFileDurably(join(temporary, 'original'), replacement.original);
|
|
580
|
+
await writeFileDurably(join(temporary, 'intent.json'), JSON.stringify(intent));
|
|
581
|
+
await syncDirectory(temporary);
|
|
582
|
+
const directoryIdentity = await transactionDirectoryIdentity(temporary);
|
|
583
|
+
await moveDirectory(temporary, directory);
|
|
584
|
+
return { directory, directoryIdentity, intent, parentPath };
|
|
585
|
+
} catch (error) {
|
|
586
|
+
active.delete(parentKey);
|
|
587
|
+
// The preparation directory never contains moved children. Keep an already
|
|
588
|
+
// published intent intact so the next recovery can make the same decision.
|
|
589
|
+
await removeRetiredDirectory(temporary).catch(() => {});
|
|
590
|
+
throw error;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
export function forgetRewriteJournal(journal) {
|
|
595
|
+
if (journal) active.delete(pathKey(journal.parentPath));
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
function childLocations(journal, entry, index) {
|
|
599
|
+
const path = childPath(journal.parentPath, entry);
|
|
600
|
+
return { from: dirname(path), to: join(journal.directory, `child-${index}`), path };
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
export async function stageWithdrawnChildren(journal) {
|
|
604
|
+
for (const [index, entry] of journal.intent.children.entries()) {
|
|
605
|
+
const { from, to, path } = childLocations(journal, entry, index);
|
|
606
|
+
await verifyChildFile(path, entry);
|
|
607
|
+
await moveDirectory(from, to);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
async function resolveChildLocation(journal, entry, index) {
|
|
612
|
+
const { from, to, path } = childLocations(journal, entry, index);
|
|
613
|
+
const original = await assertDirectory(from);
|
|
614
|
+
const held = await assertDirectory(to);
|
|
615
|
+
assert(original !== held, 'Cannot distinguish the original child directory from a conflict');
|
|
616
|
+
const rollout = original ? path : join(to, entry.filename);
|
|
617
|
+
await verifyChildFile(rollout, entry);
|
|
618
|
+
return { from, to, rollout, original };
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
export async function resolveRewriteSetChildPath(journal, index) {
|
|
622
|
+
const entry = journal.intent?.format === 2 && Number.isSafeInteger(index) && journal.intent.children[index];
|
|
623
|
+
assert(entry, 'Unknown withdrawn child');
|
|
624
|
+
return (await resolveChildLocation(journal, entry, index)).rollout;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
export async function restoreWithdrawnChildren(journal) {
|
|
628
|
+
const restore = [];
|
|
629
|
+
// Validate every move before making any. A repeat after a crash accepts an
|
|
630
|
+
// already restored directory only if it still holds the exact same rollout.
|
|
631
|
+
for (const [index, entry] of journal.intent.children.entries()) {
|
|
632
|
+
const location = await resolveChildLocation(journal, entry, index);
|
|
633
|
+
if (!location.original) restore.push(location);
|
|
634
|
+
}
|
|
635
|
+
for (const { from, to } of restore.toReversed()) await moveDirectory(to, from);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
export async function markRewriteCommitted(journal) {
|
|
639
|
+
// fsync an empty regular marker after the native Agent has accepted the
|
|
640
|
+
// candidate. Once present, recovery can only finish cleanup.
|
|
641
|
+
const temporary = join(journal.directory, `commit-${randomUUID()}.tmp`);
|
|
642
|
+
await writeFileDurably(temporary, Buffer.alloc(0));
|
|
643
|
+
await replaceFileDurable(temporary, join(journal.directory, 'committed'));
|
|
644
|
+
await syncDirectory(journal.directory);
|
|
645
|
+
journal.committed = true;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
export async function clearFailedCommitMarker(journal) {
|
|
649
|
+
try { await unlink(join(journal.directory, 'committed')); }
|
|
650
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
651
|
+
await syncDirectory(journal.directory);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function reportCleanupFailure(onCleanupError, error) {
|
|
655
|
+
try { onCleanupError?.(error); } catch { /* The durable directory remains recoverable. */ }
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
async function drainCleanup() {
|
|
659
|
+
try {
|
|
660
|
+
while (cleanupQueue.length > 0) {
|
|
661
|
+
const { garbage, onCleanupError } = cleanupQueue.shift();
|
|
662
|
+
await removeRetiredDirectory(garbage).catch(error => reportCleanupFailure(onCleanupError, error));
|
|
663
|
+
}
|
|
664
|
+
} finally {
|
|
665
|
+
cleaning = false;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
export async function retireRewriteJournal(journal, { deferCleanup = false, onCleanupError } = {}) {
|
|
670
|
+
const garbage = join(dirname(journal.directory), `discard-${randomUUID()}`);
|
|
671
|
+
// Rename first. Startup will resume cleanup of any detached directory.
|
|
672
|
+
if (!await moveDirectory(journal.directory, garbage, journal.directoryIdentity)) return;
|
|
673
|
+
if (!deferCleanup) return removeRetiredDirectory(garbage);
|
|
674
|
+
if (cleanupQueue.length >= 64) {
|
|
675
|
+
reportCleanupFailure(onCleanupError, new Error('Deferred rewrite cleanup will resume on startup'));
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
cleanupQueue.push({ garbage, onCleanupError });
|
|
679
|
+
if (!cleaning) {
|
|
680
|
+
cleaning = true;
|
|
681
|
+
setImmediate(() => { void drainCleanup(); });
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function completeSettledRetirement(path, state) {
|
|
686
|
+
clearTimeout(state.timer);
|
|
687
|
+
if (settledRetirements.get(path) === state) settledRetirements.delete(path);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function scheduleRetirementAttempt(path, state) {
|
|
691
|
+
const delay = retirementDelays[state.attempts];
|
|
692
|
+
if (state.timer || delay === undefined) return;
|
|
693
|
+
state.timer = setTimeout(() => {
|
|
694
|
+
state.timer = undefined;
|
|
695
|
+
void retrySettledRewriteRetirement(path);
|
|
696
|
+
}, delay);
|
|
697
|
+
state.timer.unref();
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** Remember only durable commits whose native prompt is already settled. */
|
|
701
|
+
export function scheduleSettledRewriteRetirement(journal, { onCleanupError } = {}) {
|
|
702
|
+
const { parentPath, directory, directoryIdentity, committed } = journal;
|
|
703
|
+
assert(committed && directoryIdentity, 'Cannot retire an unverified or unsettled transaction');
|
|
704
|
+
const key = pathKey(parentPath);
|
|
705
|
+
const known = settledRetirements.get(key);
|
|
706
|
+
if (known?.journal.directoryIdentity === directoryIdentity) return;
|
|
707
|
+
if (known) completeSettledRetirement(key, known);
|
|
708
|
+
const state = { journal: { directory, directoryIdentity }, onCleanupError, attempts: 0 };
|
|
709
|
+
settledRetirements.set(key, state);
|
|
710
|
+
scheduleRetirementAttempt(key, state);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** Retry on edit admission as well as on the bounded background schedule. */
|
|
714
|
+
export async function retrySettledRewriteRetirement(path) {
|
|
715
|
+
const key = pathKey(path);
|
|
716
|
+
const state = settledRetirements.get(key);
|
|
717
|
+
if (!state) return;
|
|
718
|
+
if (state.running) return state.running;
|
|
719
|
+
clearTimeout(state.timer);
|
|
720
|
+
state.timer = undefined;
|
|
721
|
+
state.attempts++;
|
|
722
|
+
state.running = (async () => {
|
|
723
|
+
try {
|
|
724
|
+
const { journal, onCleanupError } = state;
|
|
725
|
+
if (await transactionDirectoryIdentity(journal.directory) === journal.directoryIdentity) {
|
|
726
|
+
assert((await readRegular(join(journal.directory, 'committed'), 0)).length === 0, 'Invalid transaction commit marker');
|
|
727
|
+
await retireRewriteJournal(journal, { deferCleanup: true, onCleanupError });
|
|
728
|
+
}
|
|
729
|
+
completeSettledRetirement(key, state);
|
|
730
|
+
} catch (error) {
|
|
731
|
+
if (state.attempts >= retirementDelays.length) reportCleanupFailure(state.onCleanupError, error);
|
|
732
|
+
if (settledRetirements.get(key) === state) scheduleRetirementAttempt(key, state);
|
|
733
|
+
}
|
|
734
|
+
})();
|
|
735
|
+
try { await state.running; } finally { state.running = undefined; }
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
function validIdentity(identity, keys = ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs']) {
|
|
739
|
+
return identity !== null && typeof identity === 'object'
|
|
740
|
+
&& keys.every(key => typeof identity[key] === 'string' && /^-?\d{1,40}$/u.test(identity[key]));
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
function validFile(record) {
|
|
744
|
+
return Number.isSafeInteger(record?.size) && record.size > 0 && record.size <= streamLimit
|
|
745
|
+
&& typeof record.digest === 'string' && digestPattern.test(record.digest)
|
|
746
|
+
&& validIdentity(record.identity) && BigInt(record.identity.size) === BigInt(record.size);
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
function validChildRecord(record) {
|
|
750
|
+
return typeof record?.id === 'string' && record.id.length > 0 && typeof record.parentSession === 'string'
|
|
751
|
+
&& record.parentSession.length > 0 && record.parentSession !== record.id && Number.isSafeInteger(record.createdAt)
|
|
752
|
+
&& record.createdAt >= 0;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function validateSetIntent(intent, path) {
|
|
756
|
+
assert(Array.isArray(intent.artifacts) && intent.artifacts.length > 0 && Array.isArray(intent.children),
|
|
757
|
+
'Invalid multi-log transaction artifacts');
|
|
758
|
+
const ids = new Set();
|
|
759
|
+
const paths = new Set();
|
|
760
|
+
const withdrawnIds = new Set(intent.children.map(record => record?.id));
|
|
761
|
+
const seenWithdrawn = new Set();
|
|
762
|
+
for (const [index, artifact] of intent.artifacts.entries()) {
|
|
763
|
+
assert(artifact?.index === index && validFile(artifact.original) && validFile(artifact.candidate)
|
|
764
|
+
&& Number.isInteger(artifact.original.mode) && artifact.original.mode >= 0 && artifact.original.mode <= 0o777
|
|
765
|
+
&& Number.isSafeInteger(artifact.candidate.records) && artifact.candidate.records >= 0,
|
|
766
|
+
'Invalid multi-log artifact metadata');
|
|
767
|
+
if (index === 0) {
|
|
768
|
+
assert(artifact.id === intent.parentId && artifact.filename === basename(path), 'Invalid parent artifact metadata');
|
|
769
|
+
} else {
|
|
770
|
+
assert(validChildRecord(artifact) && !withdrawnIds.has(artifact.parentSession), 'Invalid child artifact metadata');
|
|
771
|
+
}
|
|
772
|
+
const directory = pathKey(dirname(index === 0 ? path : childPath(path, artifact)));
|
|
773
|
+
assert(!ids.has(artifact.id) && !paths.has(directory), 'Duplicate transaction identifier or path');
|
|
774
|
+
ids.add(artifact.id);
|
|
775
|
+
paths.add(directory);
|
|
776
|
+
}
|
|
777
|
+
for (const child of intent.children) {
|
|
778
|
+
assert(validChildRecord(child) && validIdentity(child.identity) && validIdentity(child.directoryIdentity, ['dev', 'ino'])
|
|
779
|
+
&& child.identity.dev === child.directoryIdentity.dev
|
|
780
|
+
&& (!withdrawnIds.has(child.parentSession) || seenWithdrawn.has(child.parentSession)), 'Invalid recorded child lineage');
|
|
781
|
+
const directory = pathKey(dirname(childPath(path, child)));
|
|
782
|
+
assert(!ids.has(child.id) && !paths.has(directory), 'Duplicate transaction identifier or path');
|
|
783
|
+
ids.add(child.id);
|
|
784
|
+
seenWithdrawn.add(child.id);
|
|
785
|
+
paths.add(directory);
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
function validateIntent(intent, snapshot, path) {
|
|
790
|
+
const { id } = snapshot.header;
|
|
791
|
+
assert((intent?.format === 1 || intent?.format === 2) && intent.parentId === id && intent.filename === basename(path), 'Unknown transaction format or parent');
|
|
792
|
+
if (intent.format === 2) {
|
|
793
|
+
if (intent.delivery !== undefined) {
|
|
794
|
+
const { messageId } = intent.delivery ?? {};
|
|
795
|
+
assert(typeof messageId === 'string' && messageId.length > 0 && messageId.length <= 2048,
|
|
796
|
+
'Invalid pending delivery metadata');
|
|
797
|
+
}
|
|
798
|
+
return validateSetIntent(intent, path);
|
|
799
|
+
}
|
|
800
|
+
assert(digestPattern.test(intent.original) && digestPattern.test(intent.candidate?.digest)
|
|
801
|
+
&& Number.isSafeInteger(intent.candidate.size) && intent.candidate.size > 0 && intent.candidate.size <= limit
|
|
802
|
+
&& Number.isSafeInteger(intent.candidate.records) && intent.candidate.records >= 0 && Array.isArray(intent.children),
|
|
803
|
+
'Invalid transaction hashes or boundaries');
|
|
804
|
+
const ids = new Set([id]);
|
|
805
|
+
const paths = new Set([pathKey(dirname(path))]);
|
|
806
|
+
for (const child of intent.children) {
|
|
807
|
+
const directory = pathKey(dirname(childPath(path, child)));
|
|
808
|
+
assert(typeof child.id === 'string' && child.id.length > 0 && !ids.has(child.id)
|
|
809
|
+
&& ids.has(child.parentSession) && !paths.has(directory) && Number.isSafeInteger(child.createdAt)
|
|
810
|
+
&& digestPattern.test(child.digest), 'Invalid recorded child lineage');
|
|
811
|
+
ids.add(child.id);
|
|
812
|
+
paths.add(directory);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/** Scan only artifacts located by the native persistence backend. */
|
|
817
|
+
export async function readRewriteJournals(snapshot) {
|
|
818
|
+
const dshPath = snapshot?.location?.path;
|
|
819
|
+
if (snapshot?.location?.kind !== 'jsonl' || typeof dshPath !== 'string' || !sessionFile.test(basename(dshPath))) return [];
|
|
820
|
+
const path = await resolveRolloutPath(dshPath).catch(error => {
|
|
821
|
+
if (error.code !== 'ENOENT') throw error;
|
|
822
|
+
return undefined;
|
|
823
|
+
});
|
|
824
|
+
if (!path || !await assertDirectory(dirname(path))) return [];
|
|
825
|
+
const root = namespace(path);
|
|
826
|
+
for (const directory of [join(dirname(path), 'plugins'), dirname(root), root]) {
|
|
827
|
+
if (!await assertDirectory(directory)) return [];
|
|
828
|
+
}
|
|
829
|
+
if (active.has(pathKey(path))) return [];
|
|
830
|
+
const journals = [];
|
|
831
|
+
for (const name of await readdir(root)) {
|
|
832
|
+
if (!release.test(name)) continue;
|
|
833
|
+
const versionPath = join(root, name);
|
|
834
|
+
if (!await assertDirectory(versionPath)) continue;
|
|
835
|
+
const directory = join(versionPath, 'rewrite');
|
|
836
|
+
const directoryIdentity = await transactionDirectoryIdentity(directory);
|
|
837
|
+
if (!directoryIdentity) continue;
|
|
838
|
+
try {
|
|
839
|
+
const intent = JSON.parse(await readRegular(join(directory, 'intent.json'), intentLimit));
|
|
840
|
+
validateIntent(intent, snapshot, path);
|
|
841
|
+
await assertOwnerReleased(intent.owner);
|
|
842
|
+
const marker = join(directory, 'committed');
|
|
843
|
+
const committed = await optionalStat(marker) !== undefined;
|
|
844
|
+
if (committed) assert((await readRegular(marker, 0)).length === 0, 'Invalid transaction commit marker');
|
|
845
|
+
if (await transactionDirectoryIdentity(directory) === directoryIdentity) {
|
|
846
|
+
journals.push({ directory, directoryIdentity, intent, parentPath: path, dshPath, committed });
|
|
847
|
+
}
|
|
848
|
+
} catch (error) {
|
|
849
|
+
// Retirement atomically moves the entire directory out of this path.
|
|
850
|
+
// A missing file in a directory that still exists remains an error.
|
|
851
|
+
if (error.code !== 'ENOENT' || await transactionDirectoryIdentity(directory) === directoryIdentity) throw error;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
assert(journals.length <= 1, 'Multiple unresolved rewrites for the same session');
|
|
855
|
+
return journals;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/** Enumerate only names this version uses for incomplete preparations or retired journals. */
|
|
859
|
+
export async function listRewriteDebris(path) {
|
|
860
|
+
const root = namespace(path);
|
|
861
|
+
const preparations = [];
|
|
862
|
+
const retired = [];
|
|
863
|
+
for (const directory of [join(dirname(path), 'plugins'), dirname(root), root]) {
|
|
864
|
+
if (!await assertDirectory(directory)) return { preparations, retired };
|
|
865
|
+
}
|
|
866
|
+
for (const name of await readdir(root)) {
|
|
867
|
+
if (!release.test(name)) continue;
|
|
868
|
+
const versionPath = join(root, name);
|
|
869
|
+
if (!await assertDirectory(versionPath)) continue;
|
|
870
|
+
for (const entry of await readdir(versionPath)) {
|
|
871
|
+
if (garbageName.test(entry)) retired.push(join(versionPath, entry));
|
|
872
|
+
else if (preparationName.test(entry)) preparations.push(join(versionPath, entry));
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
return { preparations, retired };
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
export async function cleanRewriteDebris(paths) {
|
|
879
|
+
for (const path of paths) await removeRetiredDirectory(path);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
export async function readRewriteOriginal(journal) {
|
|
883
|
+
const original = await readRegular(join(journal.directory, 'original'));
|
|
884
|
+
assert(digest(original) === journal.intent.original, 'The original transcript copy has changed');
|
|
885
|
+
return original;
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
export async function matchJournalRevision(journal, index = 0) {
|
|
889
|
+
if (journal.intent?.format === 2) return (await matchRewriteSetArtifact(journal, index)).kind;
|
|
890
|
+
if ((await streamFile(journal.parentPath, { max: limit })).digest === journal.intent.original) return 'original';
|
|
891
|
+
const { size, digest: hash } = journal.intent.candidate;
|
|
892
|
+
const current = await regularIdentity(journal.parentPath);
|
|
893
|
+
if (current.size >= BigInt(size) && (await streamFile(journal.parentPath, { length: size })).digest === hash) return 'candidate';
|
|
894
|
+
return 'conflict';
|
|
895
|
+
}
|