pi-durable-subagents 1.5.1 → 1.6.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 +41 -0
- package/README.md +69 -14
- package/dist/agent/capabilities.js +19 -11
- package/dist/agent/child/live.js +10 -2
- package/dist/agent/child.js +1 -1
- package/dist/agent/exact/capture.js +22 -2
- package/dist/agent/exact/child.js +8 -1
- package/dist/agent/exact/session.js +4 -2
- package/dist/agent/extension.js +13 -0
- package/dist/agent/main/snapshots.js +10 -9
- package/dist/agent/main.js +2 -1
- package/dist/cli/chaos/stack.js +53 -21
- package/dist/cli/control.js +4 -3
- package/dist/cli/doctor.js +3 -1
- package/dist/cli/drill/index.js +35 -17
- package/dist/cli/hold.js +221 -16
- package/dist/cli/main.js +7 -2
- package/dist/cli/restart.js +14 -2
- package/dist/cli/service.js +77 -2
- package/dist/cli/smoke.js +10 -6
- package/dist/compat/agents.js +47 -13
- package/dist/events/log.js +33 -11
- package/dist/kernel/cache.js +3 -2
- package/dist/kernel/fsx.js +203 -0
- package/dist/kernel/ids.js +11 -0
- package/dist/kernel/journal.js +42 -25
- package/dist/kernel/mailbox.js +7 -4
- package/dist/orchestrator/engine.js +49 -46
- package/dist/orchestrator/evaluator-client.js +11 -3
- package/dist/orchestrator/executor/command.js +21 -6
- package/dist/orchestrator/executor/digest.js +2 -2
- package/dist/orchestrator/executor/effects/gate.js +291 -56
- package/dist/orchestrator/executor/effects/index.js +3 -4
- package/dist/orchestrator/executor/effects/output.js +9 -5
- package/dist/orchestrator/executor/effects/prepare.js +34 -32
- package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
- package/dist/orchestrator/executor/ended.js +7 -3
- package/dist/orchestrator/executor/index.js +216 -62
- package/dist/orchestrator/executor/memory.js +15 -0
- package/dist/orchestrator/executor/observe.js +6 -1
- package/dist/orchestrator/executor/session.js +10 -4
- package/dist/orchestrator/executor/sweep.js +34 -1
- package/dist/orchestrator/executor/usage.js +19 -5
- package/dist/orchestrator/executor/worktree.js +1 -1
- package/dist/orchestrator/main.js +4 -2
- package/dist/orchestrator/reader-ledger.js +3 -2
- package/dist/orchestrator/settled.js +2 -1
- package/dist/orchestrator/snapshot.js +24 -19
- package/dist/orchestrator/stats.js +2 -1
- package/dist/orchestrator/store.js +3 -2
- package/dist/platform/cmdline.js +3 -0
- package/dist/platform/command.js +184 -20
- package/dist/platform/containment.js +204 -40
- package/dist/platform/job.js +1404 -0
- package/dist/platform/launch.js +262 -29
- package/dist/platform/lease.js +351 -32
- package/dist/platform/lock.js +464 -16
- package/dist/platform/proctable.js +31 -2
- package/dist/platform/windows.js +642 -0
- package/dist/requests.js +1 -1
- package/dist/types.js +1 -0
- package/dist/ui/data.js +7 -6
- package/dist/ui/session.js +6 -5
- package/package.json +3 -3
package/dist/compat/agents.js
CHANGED
|
@@ -4,6 +4,8 @@ import { homedir } from "node:os";
|
|
|
4
4
|
import { execFileSync } from "node:child_process";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.js";
|
|
7
|
+
import { resolveNode, shimScript } from "../platform/launch.js";
|
|
8
|
+
import { comspec } from "../platform/windows.js";
|
|
7
9
|
import { cacheDir, dsaHome } from "../paths.js";
|
|
8
10
|
const stamp = (p) => { if (!p)
|
|
9
11
|
return null; try {
|
|
@@ -13,9 +15,10 @@ const stamp = (p) => { if (!p)
|
|
|
13
15
|
catch {
|
|
14
16
|
return `${p}@-`;
|
|
15
17
|
} };
|
|
16
|
-
/** The first `name` on PATH, resolved, with its stamp: what execFileSync would start.
|
|
17
|
-
|
|
18
|
-
|
|
18
|
+
/** The first `name` on PATH, resolved, with its stamp: what execFileSync would start. Windows has no extensionless
|
|
19
|
+
* executable (`npm` beside `npm.cmd` is a POSIX script, which Node refuses to run), so only PATHEXT names count. */
|
|
20
|
+
function onPath(name, env, platform) {
|
|
21
|
+
const exts = platform === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
|
|
19
22
|
for (const dir of (env.PATH ?? env.Path ?? "").split(path.delimiter)) {
|
|
20
23
|
if (!dir)
|
|
21
24
|
continue;
|
|
@@ -30,19 +33,45 @@ function onPath(name, env) {
|
|
|
30
33
|
}
|
|
31
34
|
return null;
|
|
32
35
|
}
|
|
36
|
+
function npmLayout(npm, platform) {
|
|
37
|
+
if (platform !== "win32")
|
|
38
|
+
return { builtin: path.join(path.dirname(path.dirname(npm)), "npmrc"), fixed: /[\\/]npm[\\/]bin[\\/]npm(-cli\.js)?$/.test(npm) };
|
|
39
|
+
if (!/\.(?:cmd|bat)$/i.test(npm))
|
|
40
|
+
return { fixed: false };
|
|
41
|
+
const install = path.join(path.dirname(npm), "node_modules", "npm", "bin", "npm-cli.js");
|
|
42
|
+
const fixed = fs.existsSync(install);
|
|
43
|
+
const cli = fixed ? install : shimScript(npm);
|
|
44
|
+
return { cli, builtin: cli ? path.join(path.dirname(path.dirname(cli)), "npmrc") : undefined, fixed };
|
|
45
|
+
}
|
|
46
|
+
/** The `npm root -g` process. POSIX runs `npm` from PATH. Windows runs the script behind `npm.cmd` under the node PATH
|
|
47
|
+
* selects (npm takes its global prefix from the node running it, exactly as npm.cmd's own node would), else a PE
|
|
48
|
+
* `npm.exe`; a batch file that names no npm package script (a generated `npm.cmd` shim) runs through the command
|
|
49
|
+
* processor as a shell would, in the `"..."` form cmd /s unquotes at either end. */
|
|
50
|
+
function npmCommand(npm, node, env, platform) {
|
|
51
|
+
if (platform !== "win32")
|
|
52
|
+
return { command: "npm", args: ["root", "-g"] };
|
|
53
|
+
const { cli } = npmLayout(npm, platform);
|
|
54
|
+
const runtime = node ?? resolveNode(env, { platform, peOnly: true }).path;
|
|
55
|
+
if (cli && runtime)
|
|
56
|
+
return { command: runtime, args: [cli, "root", "-g"] };
|
|
57
|
+
if (!/\.(?:cmd|bat)$/i.test(npm))
|
|
58
|
+
return { command: npm, args: ["root", "-g"] };
|
|
59
|
+
return { command: comspec(env), args: ["/d", "/s", "/c", `""${npm}" root -g"`], verbatim: true };
|
|
60
|
+
}
|
|
33
61
|
/** Everything `npm root -g` reads to decide its answer, except npm's own code: which npm and node PATH selects, the
|
|
34
62
|
* prefix environment, and the user, global and builtin npmrc files. -g ignores the project's .npmrc, so cwd is not
|
|
35
63
|
* part of it, unless `npm` is a version manager's shim (asdf, mise, Volta) rather than npm itself: the shim picks a
|
|
36
64
|
* node per directory from files this key does not see, so its answer is only `fixed` for a few seconds. */
|
|
37
|
-
function npmRootKey(env) {
|
|
38
|
-
const npm = onPath("npm", env), node = onPath("node", env);
|
|
65
|
+
function npmRootKey(env, platform) {
|
|
66
|
+
const npm = onPath("npm", env, platform), node = onPath("node", env, platform);
|
|
67
|
+
const layout = npm ? npmLayout(npm, platform) : undefined;
|
|
39
68
|
const vars = Object.keys(env).filter(k => /^(npm_config_(prefix|userconfig|globalconfig)|PREFIX|DESTDIR)$/i.test(k)).sort().map(k => `${k}=${env[k]}`);
|
|
40
69
|
const userconfig = Object.entries(env).find(([k]) => /^npm_config_userconfig$/i.test(k))?.[1] ?? path.join(env.HOME || env.USERPROFILE || homedir(), ".npmrc");
|
|
41
|
-
const prefix = env.PREFIX ?? (node ? (
|
|
70
|
+
const prefix = env.PREFIX ?? (node ? (platform === "win32" ? path.dirname(node) : path.dirname(path.dirname(node))) : undefined);
|
|
42
71
|
const globalconfig = Object.entries(env).find(([k]) => /^npm_config_globalconfig$/i.test(k))?.[1] ?? (prefix && path.join(prefix, "etc", "npmrc"));
|
|
43
|
-
const builtin =
|
|
44
|
-
const fixed =
|
|
45
|
-
return { npm, fixed, key: JSON.stringify([stamp(npm ?? undefined), stamp(node ?? undefined), vars, stamp(userconfig), stamp(globalconfig), stamp(builtin),
|
|
72
|
+
const builtin = layout?.builtin;
|
|
73
|
+
const fixed = layout?.fixed ?? false;
|
|
74
|
+
return { npm, node, fixed, key: JSON.stringify([stamp(npm ?? undefined), stamp(node ?? undefined), vars, stamp(userconfig), stamp(globalconfig), stamp(builtin), platform === "win32" ? null : stamp("/etc/npmrc"), fixed ? null : process.cwd()]) };
|
|
46
75
|
}
|
|
47
76
|
const NPM_ROOT_ENTRIES = 8, NPM_ROOT_RETRY_MS = 60_000, NPM_ROOT_SHIM_MS = 10_000;
|
|
48
77
|
let npmRootMemo;
|
|
@@ -50,10 +79,11 @@ let npmRootMemo;
|
|
|
50
79
|
* a busy machine, while every pi start, run admission and CLI request discovers agents. The answer is kept in this
|
|
51
80
|
* process and in a small rebuildable cache file, keyed on npmRootKey; a changed input asks npm again. A failed answer
|
|
52
81
|
* is null and is retried after a minute, never written to disk. A shim's answer stays in this process for ten seconds
|
|
53
|
-
* and is never written to disk. No npm on PATH is null without starting anything.
|
|
82
|
+
* and is never written to disk. No npm on PATH is null without starting anything. Windows runs the CLI behind `npm.cmd`
|
|
83
|
+
* under the node PATH selects, and a real npm install's answer is cached like npm itself's (npmCommand). */
|
|
54
84
|
export function globalNpmRoot(options = {}) {
|
|
55
|
-
const env = options.env ?? process.env;
|
|
56
|
-
const { key, npm, fixed } = npmRootKey(env);
|
|
85
|
+
const env = options.env ?? process.env, platform = options.platform ?? process.platform;
|
|
86
|
+
const { key, npm, node, fixed } = npmRootKey(env, platform);
|
|
57
87
|
if (!npm)
|
|
58
88
|
return null;
|
|
59
89
|
const now = Date.now();
|
|
@@ -75,8 +105,12 @@ export function globalNpmRoot(options = {}) {
|
|
|
75
105
|
}
|
|
76
106
|
}
|
|
77
107
|
let root = null;
|
|
108
|
+
const ask = () => {
|
|
109
|
+
const { command, args, verbatim } = npmCommand(npm, node, env, platform);
|
|
110
|
+
return execFileSync(command, args, { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"], env, ...(verbatim ? { windowsVerbatimArguments: true } : {}) });
|
|
111
|
+
};
|
|
78
112
|
try {
|
|
79
|
-
root = (options.run ??
|
|
113
|
+
root = (options.run ?? ask)().trim() || null;
|
|
80
114
|
}
|
|
81
115
|
catch {
|
|
82
116
|
root = null;
|
package/dist/events/log.js
CHANGED
|
@@ -25,6 +25,7 @@ import { open, readdir, rename, rm } from "node:fs/promises";
|
|
|
25
25
|
import { randomBytes } from "node:crypto";
|
|
26
26
|
import { basename, dirname, join } from "node:path";
|
|
27
27
|
import { frameLine, syncDirectory, unframeLine } from "../kernel/journal.js";
|
|
28
|
+
import { replacePath, writeAt } from "../kernel/fsx.js";
|
|
28
29
|
import { EVENT_SEQ_SKIP } from "./types.js";
|
|
29
30
|
export const EPOCH = /^[0-9a-f]{16}$/;
|
|
30
31
|
const CHUNK = 1 << 16, NEWLINE = Buffer.from("\n");
|
|
@@ -187,9 +188,11 @@ export class EventLog {
|
|
|
187
188
|
if (!scan) {
|
|
188
189
|
const epoch = randomBytes(8).toString("hex"), text = frameLine(JSON.stringify({ k: "log", v: 1, epoch, dropped: 0 }));
|
|
189
190
|
await replace(path, async (file) => { await file.writeFile(text); });
|
|
190
|
-
const file = await open(path, "
|
|
191
|
+
const file = await open(path, "r+");
|
|
191
192
|
return { log: new EventLog(path, file, { epoch, dropped: 0, head: 0, end: Buffer.byteLength(text), records: 0, events: 0 }), created: true, marks: new Map(), ...(corrupt ? { corrupt } : {}) };
|
|
192
193
|
}
|
|
194
|
+
// A read/write handle (not append mode): Windows append handles cannot truncate a torn tail, and every append writes
|
|
195
|
+
// at an explicit position anyway.
|
|
193
196
|
const file = await open(path, "r+");
|
|
194
197
|
try {
|
|
195
198
|
if (scan.end !== (await file.stat()).size) {
|
|
@@ -197,10 +200,11 @@ export class EventLog {
|
|
|
197
200
|
await file.sync();
|
|
198
201
|
}
|
|
199
202
|
}
|
|
200
|
-
|
|
201
|
-
await file.close();
|
|
203
|
+
catch (error) {
|
|
204
|
+
await file.close().catch(() => { });
|
|
205
|
+
throw error;
|
|
202
206
|
}
|
|
203
|
-
const log = new EventLog(path,
|
|
207
|
+
const log = new EventLog(path, file, scan);
|
|
204
208
|
// The pump retries a broken log's reopen every second: a failed start skip must not leak the handle.
|
|
205
209
|
try {
|
|
206
210
|
await log.write(frameLine(JSON.stringify({ k: "head", seq: log.head + EVENT_SEQ_SKIP })), log.head + EVENT_SEQ_SKIP);
|
|
@@ -223,7 +227,7 @@ export class EventLog {
|
|
|
223
227
|
* (or break the log when that fails too). */
|
|
224
228
|
async write(text, position) {
|
|
225
229
|
try {
|
|
226
|
-
await this.file.
|
|
230
|
+
await writeAt(this.file, Buffer.from(text), this.size);
|
|
227
231
|
await this.file.sync();
|
|
228
232
|
}
|
|
229
233
|
catch (error) {
|
|
@@ -278,7 +282,7 @@ export class EventLog {
|
|
|
278
282
|
* records pile up), keeping the header's epoch, a monotone `dropped`, every other event and the watermarks. */
|
|
279
283
|
compact(drop, marks) {
|
|
280
284
|
return this.serial(async () => {
|
|
281
|
-
|
|
285
|
+
let fd = openSync(this.path, "r");
|
|
282
286
|
let count = 0, highest = this.dropped;
|
|
283
287
|
try {
|
|
284
288
|
scanLines(fd, 0, this.size, line => {
|
|
@@ -326,18 +330,35 @@ export class EventLog {
|
|
|
326
330
|
throw error;
|
|
327
331
|
}
|
|
328
332
|
closeSync(out);
|
|
333
|
+
// The scan handle also names the log: close it (and the writer) before the replace, or Windows refuses it.
|
|
334
|
+
closeSync(fd);
|
|
335
|
+
fd = undefined;
|
|
336
|
+
// Windows cannot replace a file that a handle has open, and the append handle names this log: close it around
|
|
337
|
+
// the rename, then reopen (on every platform: one code path, and the writer never keeps a stale handle).
|
|
338
|
+
try {
|
|
339
|
+
await this.file.close();
|
|
340
|
+
}
|
|
341
|
+
catch (error) {
|
|
342
|
+
this.failed = error;
|
|
343
|
+
throw error;
|
|
344
|
+
}
|
|
329
345
|
try {
|
|
330
|
-
await
|
|
346
|
+
await replacePath(temp, this.path);
|
|
331
347
|
}
|
|
332
348
|
catch (error) {
|
|
333
349
|
await rm(temp, { force: true });
|
|
350
|
+
try {
|
|
351
|
+
this.file = await open(this.path, "r+");
|
|
352
|
+
}
|
|
353
|
+
catch (cause) {
|
|
354
|
+
this.failed = cause;
|
|
355
|
+
}
|
|
334
356
|
throw error;
|
|
335
357
|
}
|
|
336
358
|
// Past the rename this handle names the replaced file: any failure breaks the writer (the owner reopens).
|
|
337
359
|
try {
|
|
338
360
|
await syncDirectory(dirname(this.path));
|
|
339
|
-
await this.
|
|
340
|
-
this.file = await open(this.path, "a");
|
|
361
|
+
this.file = await open(this.path, "r+");
|
|
341
362
|
}
|
|
342
363
|
catch (error) {
|
|
343
364
|
this.failed = error;
|
|
@@ -350,7 +371,8 @@ export class EventLog {
|
|
|
350
371
|
return count;
|
|
351
372
|
}
|
|
352
373
|
finally {
|
|
353
|
-
|
|
374
|
+
if (fd !== undefined)
|
|
375
|
+
closeSync(fd);
|
|
354
376
|
}
|
|
355
377
|
});
|
|
356
378
|
}
|
|
@@ -370,7 +392,7 @@ async function replace(path, fill) {
|
|
|
370
392
|
}
|
|
371
393
|
await file.close();
|
|
372
394
|
try {
|
|
373
|
-
await
|
|
395
|
+
await replacePath(temp, path);
|
|
374
396
|
}
|
|
375
397
|
catch (error) {
|
|
376
398
|
await rm(temp, { force: true });
|
package/dist/kernel/cache.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// Rebuildable reader caches: checked payloads, published whole, with no durable authority.
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { existsSync, mkdirSync, readFileSync,
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { dirname } from "node:path";
|
|
5
5
|
import { crc32 } from "./journal.js";
|
|
6
|
+
import { replacePathSync } from "./fsx.js";
|
|
6
7
|
export function readCache(path) {
|
|
7
8
|
try {
|
|
8
9
|
const { checksum, ...record } = JSON.parse(readFileSync(path, "utf8"));
|
|
@@ -20,7 +21,7 @@ export function writeCache(path, record, journal) {
|
|
|
20
21
|
return;
|
|
21
22
|
mkdirSync(dirname(path), { recursive: true });
|
|
22
23
|
writeFileSync(tmp, JSON.stringify({ ...record, checksum: crc32(Buffer.from(JSON.stringify(record))) }), { flag: "wx" });
|
|
23
|
-
|
|
24
|
+
replacePathSync(tmp, path);
|
|
24
25
|
if (!existsSync(journal)) {
|
|
25
26
|
rmSync(path, { force: true });
|
|
26
27
|
// A facts cache has one directory per workflow; remove it only if it is empty.
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// Cross-platform filesystem primitives the durable writers and derived-cache readers share. Windows refuses to replace
|
|
2
|
+
// a file that another handle has open (POSIX allows it), so a replacement retries briefly: readers close their handles,
|
|
3
|
+
// and a live writer closes its own handle around the rename. File identities (`dev`, `ino`) are read as `bigint`s and
|
|
4
|
+
// kept as canonical lossless decimal strings so 64-bit NTFS/ReFS file IDs above 2^53 never collide under IEEE-754 rounding.
|
|
5
|
+
import fs, { renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { rename, unlink, writeFile } from "node:fs/promises";
|
|
7
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
8
|
+
const DECIMAL_ID = /^(?:0|[1-9]\d*)$/;
|
|
9
|
+
const MAX_SAFE_SIZE = BigInt(Number.MAX_SAFE_INTEGER);
|
|
10
|
+
/** Whether `value` is a canonical unsigned decimal file/device ID string (never a float-rounded JSON number). */
|
|
11
|
+
export function isFileId(value) {
|
|
12
|
+
return typeof value === "string" && DECIMAL_ID.test(value);
|
|
13
|
+
}
|
|
14
|
+
/** Whether `value` is a non-negative safe integer byte length. */
|
|
15
|
+
export function isFileSize(value) {
|
|
16
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
17
|
+
}
|
|
18
|
+
function toFileId(value, name) {
|
|
19
|
+
if (typeof value !== "bigint" || value < 0n)
|
|
20
|
+
throw new RangeError(`Invalid ${name}: ${String(value)}`);
|
|
21
|
+
return value.toString();
|
|
22
|
+
}
|
|
23
|
+
/** Convert a `bigint` stat size to a validated non-negative safe integer `number`. */
|
|
24
|
+
export function toFileSize(value) {
|
|
25
|
+
if (typeof value !== "bigint" || value < 0n || value > MAX_SAFE_SIZE)
|
|
26
|
+
throw new RangeError(`Invalid file size: ${String(value)}`);
|
|
27
|
+
return Number(value);
|
|
28
|
+
}
|
|
29
|
+
export function fileIdentityOf(stat) {
|
|
30
|
+
return { dev: toFileId(stat.dev, "device id"), ino: toFileId(stat.ino, "file id"), size: toFileSize(stat.size) };
|
|
31
|
+
}
|
|
32
|
+
export function fileIdentityKey(id) {
|
|
33
|
+
return `${id.dev}:${id.ino}:${id.size}`;
|
|
34
|
+
}
|
|
35
|
+
export function isFileIdentityKey(value) {
|
|
36
|
+
if (typeof value !== "string")
|
|
37
|
+
return false;
|
|
38
|
+
const parts = value.split(":");
|
|
39
|
+
if (parts.length !== 3)
|
|
40
|
+
return false;
|
|
41
|
+
const [dev, ino, size] = parts;
|
|
42
|
+
return isFileId(dev) && isFileId(ino) && isFileId(size) && isFileSize(Number(size));
|
|
43
|
+
}
|
|
44
|
+
export function statIdentitySync(path) {
|
|
45
|
+
const stats = fs.statSync(path, { bigint: true });
|
|
46
|
+
return { ...fileIdentityOf(stats), stats };
|
|
47
|
+
}
|
|
48
|
+
export function fstatIdentitySync(fd) {
|
|
49
|
+
const stats = fs.fstatSync(fd, { bigint: true });
|
|
50
|
+
return { ...fileIdentityOf(stats), stats };
|
|
51
|
+
}
|
|
52
|
+
export async function statHandleIdentity(file) {
|
|
53
|
+
const stats = await file.stat({ bigint: true });
|
|
54
|
+
return { ...fileIdentityOf(stats), stats };
|
|
55
|
+
}
|
|
56
|
+
const WIN_SHARING_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
57
|
+
const SYNC_WAIT_BUF = new Int32Array(new SharedArrayBuffer(4));
|
|
58
|
+
/** Whether `error` is a Windows transient sharing/AV/indexer conflict (`EACCES`, `EBUSY`, `EPERM`). */
|
|
59
|
+
export function isWinSharingError(error) {
|
|
60
|
+
return WIN_SHARING_CODES.has(error?.code ?? "");
|
|
61
|
+
}
|
|
62
|
+
const defaultSleepSync = (ms) => {
|
|
63
|
+
if (ms > 0)
|
|
64
|
+
Atomics.wait(SYNC_WAIT_BUF, 0, 0, ms);
|
|
65
|
+
};
|
|
66
|
+
/** Run `op` with bounded retries on Windows transient sharing errors (`EACCES`, `EBUSY`, `EPERM`). Non-Windows
|
|
67
|
+
* platforms and non-sharing errors fail immediately without sleeping. */
|
|
68
|
+
export async function retryWinSharing(op, options = {}) {
|
|
69
|
+
const platform = options.platform ?? process.platform;
|
|
70
|
+
const maxAttempts = Math.max(1, options.maxAttempts ?? 10);
|
|
71
|
+
const timeoutMs = Math.max(0, options.timeoutMs ?? 2_000);
|
|
72
|
+
const baseDelayMs = Math.max(1, options.baseDelayMs ?? 10);
|
|
73
|
+
const maxDelayMs = Math.max(baseDelayMs, options.maxDelayMs ?? 100);
|
|
74
|
+
const sleep = options.sleep ?? (ms => delay(ms));
|
|
75
|
+
const deadline = Date.now() + timeoutMs;
|
|
76
|
+
for (let attempt = 0;; attempt++) {
|
|
77
|
+
try {
|
|
78
|
+
return await op();
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (platform !== "win32" || !isWinSharingError(error) || attempt + 1 >= maxAttempts)
|
|
82
|
+
throw error;
|
|
83
|
+
const left = deadline - Date.now();
|
|
84
|
+
if (left <= 0)
|
|
85
|
+
throw error;
|
|
86
|
+
await sleep(Math.min(left, Math.min(maxDelayMs, baseDelayMs * (attempt + 1))));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Synchronous counterpart of {@link retryWinSharing}. */
|
|
91
|
+
export function retryWinSharingSync(op, options = {}) {
|
|
92
|
+
const platform = options.platform ?? process.platform;
|
|
93
|
+
const maxAttempts = Math.max(1, options.maxAttempts ?? 10);
|
|
94
|
+
const timeoutMs = Math.max(0, options.timeoutMs ?? 2_000);
|
|
95
|
+
const baseDelayMs = Math.max(1, options.baseDelayMs ?? 10);
|
|
96
|
+
const maxDelayMs = Math.max(baseDelayMs, options.maxDelayMs ?? 100);
|
|
97
|
+
const sleepSync = options.sleepSync ?? defaultSleepSync;
|
|
98
|
+
const deadline = Date.now() + timeoutMs;
|
|
99
|
+
for (let attempt = 0;; attempt++) {
|
|
100
|
+
try {
|
|
101
|
+
return op();
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
if (platform !== "win32" || !isWinSharingError(error) || attempt + 1 >= maxAttempts)
|
|
105
|
+
throw error;
|
|
106
|
+
const left = deadline - Date.now();
|
|
107
|
+
if (left <= 0)
|
|
108
|
+
throw error;
|
|
109
|
+
sleepSync(Math.min(left, Math.min(maxDelayMs, baseDelayMs * (attempt + 1))));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** Publish `content` at `target` atomically via temp-file + rename (never writing directly to `target`, so readers
|
|
114
|
+
* never observe partial content). On Windows, transient sharing conflicts (`EACCES`, `EBUSY`, `EPERM`) during temp
|
|
115
|
+
* write and rename are retried within a bounded budget; on failure, the temporary file is removed best-effort. */
|
|
116
|
+
export async function writeFileAtomic(target, content, options = {}) {
|
|
117
|
+
const temp = options.tempPath ?? `${target}.tmp`;
|
|
118
|
+
const encoding = options.encoding ?? "utf8";
|
|
119
|
+
const writeFn = options.writeFile ?? ((path, data, enc) => typeof data === "string" ? writeFile(path, data, enc) : writeFile(path, data));
|
|
120
|
+
const renameFn = options.rename ?? rename;
|
|
121
|
+
const unlinkFn = options.unlink ?? unlink;
|
|
122
|
+
const timeoutMs = Math.max(0, options.timeoutMs ?? 2_500);
|
|
123
|
+
const maxAttempts = Math.max(1, options.maxAttempts ?? 25);
|
|
124
|
+
const deadline = Date.now() + timeoutMs;
|
|
125
|
+
const stepOptions = () => ({
|
|
126
|
+
...options,
|
|
127
|
+
maxAttempts,
|
|
128
|
+
timeoutMs: Math.max(0, deadline - Date.now()),
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
await retryWinSharing(() => writeFn(temp, content, encoding), stepOptions());
|
|
132
|
+
await retryWinSharing(() => renameFn(temp, target), stepOptions());
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
await unlinkFn(temp).catch(() => { });
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Synchronous counterpart of {@link writeFileAtomic}. */
|
|
140
|
+
export function writeFileAtomicSync(target, content, options = {}) {
|
|
141
|
+
const temp = options.tempPath ?? `${target}.tmp`;
|
|
142
|
+
const encoding = options.encoding ?? "utf8";
|
|
143
|
+
const writeFn = options.writeFileSync ?? ((path, data, enc) => typeof data === "string" ? writeFileSync(path, data, enc) : writeFileSync(path, data));
|
|
144
|
+
const renameFn = options.renameSync ?? renameSync;
|
|
145
|
+
const unlinkFn = options.unlinkSync ?? unlinkSync;
|
|
146
|
+
const timeoutMs = Math.max(0, options.timeoutMs ?? 2_500);
|
|
147
|
+
const maxAttempts = Math.max(1, options.maxAttempts ?? 25);
|
|
148
|
+
const deadline = Date.now() + timeoutMs;
|
|
149
|
+
const stepOptions = () => ({
|
|
150
|
+
...options,
|
|
151
|
+
maxAttempts,
|
|
152
|
+
timeoutMs: Math.max(0, deadline - Date.now()),
|
|
153
|
+
});
|
|
154
|
+
try {
|
|
155
|
+
retryWinSharingSync(() => writeFn(temp, content, encoding), stepOptions());
|
|
156
|
+
retryWinSharingSync(() => renameFn(temp, target), stepOptions());
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
try {
|
|
160
|
+
unlinkFn(temp);
|
|
161
|
+
}
|
|
162
|
+
catch { /* best effort */ }
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** Rename `from` over `to`. On Windows a transient sharing violation is retried (10 attempts, up to ~450 ms). */
|
|
167
|
+
export async function replacePath(from, to) {
|
|
168
|
+
for (let attempt = 0;; attempt++) {
|
|
169
|
+
try {
|
|
170
|
+
await rename(from, to);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
if (process.platform !== "win32" || !isWinSharingError(error) || attempt >= 9)
|
|
175
|
+
throw error;
|
|
176
|
+
await delay(10 * (attempt + 1));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
export function replacePathSync(from, to) {
|
|
181
|
+
for (let attempt = 0;; attempt++) {
|
|
182
|
+
try {
|
|
183
|
+
renameSync(from, to);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
if (process.platform !== "win32" || !isWinSharingError(error) || attempt >= 9)
|
|
188
|
+
throw error;
|
|
189
|
+
// The synchronous callers write small files in a tight loop; a short spin is enough for a closing reader.
|
|
190
|
+
defaultSleepSync(10 * (attempt + 1));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/** Write `bytes` at `position`, looping over short writes. A positional write works with a read/write handle on every
|
|
195
|
+
* platform (Windows append-mode handles cannot truncate, which journal repair needs). */
|
|
196
|
+
export async function writeAt(file, bytes, position) {
|
|
197
|
+
for (let at = 0; at < bytes.length;) {
|
|
198
|
+
const { bytesWritten } = await file.write(bytes, at, bytes.length - at, position + at);
|
|
199
|
+
if (!bytesWritten)
|
|
200
|
+
throw new Error("short write");
|
|
201
|
+
at += bytesWritten;
|
|
202
|
+
}
|
|
203
|
+
}
|
package/dist/kernel/ids.js
CHANGED
|
@@ -35,3 +35,14 @@ export function contentHash(obj) {
|
|
|
35
35
|
export function forwardRid(rid, widRev, key, hash) {
|
|
36
36
|
return contentHash([rid, widRev, key, hash]);
|
|
37
37
|
}
|
|
38
|
+
/** A file name for an identity. Windows refuses `:` (and several other characters) in a name, while request ids may
|
|
39
|
+
* contain them (`req:r1`, a sender `cli:user@host`); percent-encoding keeps the mapping deterministic and reversible
|
|
40
|
+
* inside the code. Other platforms keep the historical raw names. */
|
|
41
|
+
export function fileId(id) {
|
|
42
|
+
if (/[/\\\0]/.test(id))
|
|
43
|
+
throw new Error('Invalid file identity');
|
|
44
|
+
if (process.platform !== "win32")
|
|
45
|
+
return id;
|
|
46
|
+
const encoded = id.replace(/[%:/\\<>"|?*\x00-\x1f]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
|
|
47
|
+
return /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i.test(encoded) ? `_${encoded}` : encoded;
|
|
48
|
+
}
|
package/dist/kernel/journal.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { open, mkdir } from 'node:fs/promises';
|
|
2
|
-
import { closeSync, constants,
|
|
2
|
+
import { closeSync, constants, fsyncSync, ftruncateSync, openSync, readFileSync, readSync } from 'node:fs';
|
|
3
3
|
import { dirname } from 'node:path';
|
|
4
4
|
import * as zlib from 'node:zlib';
|
|
5
|
+
import { fstatIdentitySync, isFileId, isFileSize, statHandleIdentity, writeAt } from "./fsx.js";
|
|
5
6
|
const TABLE = new Uint32Array(256).map((_, n) => { let c = n; for (let k = 0; k < 8; k++)
|
|
6
7
|
c = (c & 1) ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
|
|
7
8
|
/** The CRC-32 (IEEE) of `bytes` as an unsigned number: node's native one when it has it (22.2+), else a table. */
|
|
@@ -73,8 +74,11 @@ function decode(bytes, prior = []) {
|
|
|
73
74
|
}
|
|
74
75
|
return { entries, length: offset };
|
|
75
76
|
}
|
|
76
|
-
/** C11: Make directory changes durable before reporting publication success.
|
|
77
|
+
/** C11: Make directory changes durable before reporting publication success. Windows cannot open a directory for
|
|
78
|
+
* FlushFileBuffers (fsync fails with EPERM); NTFS journals metadata itself, so there is nothing to add there. */
|
|
77
79
|
export async function syncDirectory(path) {
|
|
80
|
+
if (process.platform === 'win32')
|
|
81
|
+
return;
|
|
78
82
|
const file = await open(path, 'r');
|
|
79
83
|
try {
|
|
80
84
|
await file.sync();
|
|
@@ -113,7 +117,7 @@ export function readJournalRecord(path) {
|
|
|
113
117
|
throw error;
|
|
114
118
|
}
|
|
115
119
|
try {
|
|
116
|
-
const { dev, ino, size } =
|
|
120
|
+
const { dev, ino, size } = fstatIdentitySync(fd), cached = snapshots.get(path);
|
|
117
121
|
if (cached && cached.dev === dev && cached.ino === ino && cached.size === size)
|
|
118
122
|
return cached;
|
|
119
123
|
const from = cached && cached.dev === dev && cached.ino === ino && size > cached.size ? cached.length : 0;
|
|
@@ -148,9 +152,9 @@ export function readJournalUncached(path) {
|
|
|
148
152
|
throw error;
|
|
149
153
|
}
|
|
150
154
|
try {
|
|
151
|
-
const { dev, ino, size } =
|
|
155
|
+
const { dev, ino, size } = fstatIdentitySync(fd), cached = snapshots.get(path);
|
|
152
156
|
if (cached && cached.dev === dev && cached.ino === ino && cached.size === size)
|
|
153
|
-
return { ino, size, entries: cached.entries };
|
|
157
|
+
return { dev, ino, size, entries: cached.entries };
|
|
154
158
|
const bytes = Buffer.alloc(size);
|
|
155
159
|
for (let read = 0; read < bytes.length;) {
|
|
156
160
|
const n = readSync(fd, bytes, read, bytes.length - read, read);
|
|
@@ -158,7 +162,7 @@ export function readJournalUncached(path) {
|
|
|
158
162
|
break;
|
|
159
163
|
read += n;
|
|
160
164
|
}
|
|
161
|
-
return { ino, size, entries: decode(bytes).entries };
|
|
165
|
+
return { dev, ino, size, entries: decode(bytes).entries };
|
|
162
166
|
}
|
|
163
167
|
finally {
|
|
164
168
|
closeSync(fd);
|
|
@@ -205,7 +209,7 @@ export function readJournalFold(path, prior, empty, apply, options = {}) {
|
|
|
205
209
|
throw error;
|
|
206
210
|
}
|
|
207
211
|
try {
|
|
208
|
-
const { dev, ino, size } =
|
|
212
|
+
const { dev, ino, size } = fstatIdentitySync(fd);
|
|
209
213
|
if (prior && prior.dev === dev && prior.ino === ino && prior.size === size)
|
|
210
214
|
return prior;
|
|
211
215
|
const kept = prior && prior.dev === dev && prior.ino === ino && size >= prior.size;
|
|
@@ -322,14 +326,14 @@ export function journalExpectation(journal) {
|
|
|
322
326
|
return undefined;
|
|
323
327
|
}
|
|
324
328
|
try {
|
|
325
|
-
const { ino, size } =
|
|
329
|
+
const { dev, ino, size } = fstatIdentitySync(fd), tail = lastLine(fd, size);
|
|
326
330
|
if (!tail)
|
|
327
331
|
return undefined;
|
|
328
332
|
// The last line must be the last committed entry (a torn tail is truncated by every open, never trusted).
|
|
329
333
|
const json = unframeLine(tail.subarray(0, tail.length - 1));
|
|
330
334
|
if (json === undefined || JSON.parse(json).seq !== count)
|
|
331
335
|
return undefined;
|
|
332
|
-
return { ino, size, count, tail: crc32(tail), tailLength: tail.length };
|
|
336
|
+
return { dev, ino, size, count, tail: crc32(tail), tailLength: tail.length };
|
|
333
337
|
}
|
|
334
338
|
catch {
|
|
335
339
|
return undefined;
|
|
@@ -368,6 +372,10 @@ function lastLine(fd, size) {
|
|
|
368
372
|
* (verifying it as openJournal does) on the first access to its entries or the first append. Undefined when the file
|
|
369
373
|
* is not what was expected: the caller opens it eagerly. Decoding later finds the same bytes or throws (one writer). */
|
|
370
374
|
export async function openLazyJournal(path, expect) {
|
|
375
|
+
if (!expect || !isFileId(expect.dev) || !isFileId(expect.ino) || !isFileSize(expect.size) ||
|
|
376
|
+
!Number.isSafeInteger(expect.count) || expect.count < 1 || !Number.isSafeInteger(expect.tailLength) ||
|
|
377
|
+
expect.tailLength < 10 || expect.tailLength > expect.size || typeof expect.tail !== 'string')
|
|
378
|
+
return undefined;
|
|
371
379
|
let fd;
|
|
372
380
|
try {
|
|
373
381
|
fd = openSync(path, 'r');
|
|
@@ -376,8 +384,8 @@ export async function openLazyJournal(path, expect) {
|
|
|
376
384
|
return undefined;
|
|
377
385
|
}
|
|
378
386
|
try {
|
|
379
|
-
const { ino, size } =
|
|
380
|
-
if (
|
|
387
|
+
const { dev, ino, size } = fstatIdentitySync(fd);
|
|
388
|
+
if (dev !== expect.dev || ino !== expect.ino || size !== expect.size)
|
|
381
389
|
return undefined;
|
|
382
390
|
const tail = Buffer.alloc(expect.tailLength);
|
|
383
391
|
for (let read = 0; read < tail.length;) {
|
|
@@ -406,8 +414,8 @@ export async function openLazyJournal(path, expect) {
|
|
|
406
414
|
function loadSync(path, expect) {
|
|
407
415
|
const fd = openSync(path, 'r+');
|
|
408
416
|
try {
|
|
409
|
-
const { ino, size } =
|
|
410
|
-
if (ino !== expect.ino || size !== expect.size)
|
|
417
|
+
const { dev, ino, size } = fstatIdentitySync(fd);
|
|
418
|
+
if (dev !== expect.dev || ino !== expect.ino || size !== expect.size)
|
|
411
419
|
throw new Error(`Journal changed while not loaded: ${path} has ${size} bytes, ${expect.size} expected`);
|
|
412
420
|
const bytes = readFileSync(fd), decoded = decode(bytes);
|
|
413
421
|
if (decoded.entries.length !== expect.count)
|
|
@@ -416,23 +424,26 @@ function loadSync(path, expect) {
|
|
|
416
424
|
ftruncateSync(fd, decoded.length);
|
|
417
425
|
fsyncSync(fd);
|
|
418
426
|
}
|
|
419
|
-
return { entries: decoded.entries, size: decoded.length };
|
|
427
|
+
return { dev, ino, entries: decoded.entries, size: decoded.length };
|
|
420
428
|
}
|
|
421
429
|
finally {
|
|
422
430
|
closeSync(fd);
|
|
423
431
|
}
|
|
424
432
|
}
|
|
425
433
|
async function openHandle(path, lazy, apply) {
|
|
426
|
-
let entries, size, file, count = lazy?.count ?? 0;
|
|
427
|
-
if (lazy)
|
|
434
|
+
let entries, dev, ino, size, file, count = lazy?.count ?? 0;
|
|
435
|
+
if (lazy) {
|
|
436
|
+
dev = lazy.dev;
|
|
437
|
+
ino = lazy.ino;
|
|
428
438
|
size = lazy.size;
|
|
439
|
+
}
|
|
429
440
|
else {
|
|
430
441
|
await mkdir(dirname(path), { recursive: true });
|
|
431
442
|
let created = false;
|
|
432
|
-
const first = await open(path, '
|
|
443
|
+
const first = await open(path, 'wx+').then(f => { created = true; return f; }, async (error) => {
|
|
433
444
|
if (error.code !== 'EEXIST')
|
|
434
445
|
throw error;
|
|
435
|
-
return open(path, '
|
|
446
|
+
return open(path, 'r+');
|
|
436
447
|
});
|
|
437
448
|
try {
|
|
438
449
|
if (apply) {
|
|
@@ -446,7 +457,10 @@ async function openHandle(path, lazy, apply) {
|
|
|
446
457
|
size = decoded.length;
|
|
447
458
|
count = entries.length;
|
|
448
459
|
}
|
|
449
|
-
|
|
460
|
+
const stat = await statHandleIdentity(first);
|
|
461
|
+
dev = stat.dev;
|
|
462
|
+
ino = stat.ino;
|
|
463
|
+
if (size !== stat.size) {
|
|
450
464
|
await first.truncate(size);
|
|
451
465
|
await first.sync();
|
|
452
466
|
}
|
|
@@ -468,6 +482,8 @@ async function openHandle(path, lazy, apply) {
|
|
|
468
482
|
throw new Error('Folded journal does not retain entries');
|
|
469
483
|
if (!entries) {
|
|
470
484
|
const loaded = loadSync(path, lazy);
|
|
485
|
+
dev = loaded.dev;
|
|
486
|
+
ino = loaded.ino;
|
|
471
487
|
entries = loaded.entries;
|
|
472
488
|
size = loaded.size;
|
|
473
489
|
}
|
|
@@ -480,11 +496,11 @@ async function openHandle(path, lazy, apply) {
|
|
|
480
496
|
const reopen = async () => {
|
|
481
497
|
if (file)
|
|
482
498
|
return file;
|
|
483
|
-
const f = await open(path, constants.
|
|
499
|
+
const f = await open(path, constants.O_RDWR);
|
|
484
500
|
try {
|
|
485
|
-
const now =
|
|
486
|
-
if (now !== size)
|
|
487
|
-
throw new Error(`Journal changed while closed: ${path} has ${now} bytes, ${size} committed`);
|
|
501
|
+
const now = await statHandleIdentity(f);
|
|
502
|
+
if (now.dev !== dev || now.ino !== ino || now.size !== size)
|
|
503
|
+
throw new Error(`Journal changed while closed: ${path} has ${now.size} bytes, ${size} committed`);
|
|
488
504
|
}
|
|
489
505
|
catch (error) {
|
|
490
506
|
await f.close();
|
|
@@ -532,7 +548,7 @@ async function openHandle(path, lazy, apply) {
|
|
|
532
548
|
if (!apply)
|
|
533
549
|
all();
|
|
534
550
|
const entry = { ...frozen, seq: count + 1, ts: Date.now(), type };
|
|
535
|
-
const json = JSON.stringify(entry),
|
|
551
|
+
const json = JSON.stringify(entry), jsonBytes = Buffer.from(json), line = `${crc32(jsonBytes)} ${json}\n`;
|
|
536
552
|
let target;
|
|
537
553
|
try {
|
|
538
554
|
target = await reopen();
|
|
@@ -541,7 +557,8 @@ async function openHandle(path, lazy, apply) {
|
|
|
541
557
|
unwritten.add(error);
|
|
542
558
|
throw error;
|
|
543
559
|
}
|
|
544
|
-
|
|
560
|
+
const bytes = Buffer.from(line);
|
|
561
|
+
await writeAt(target, bytes, size);
|
|
545
562
|
await target.sync();
|
|
546
563
|
const offset = size;
|
|
547
564
|
size += Buffer.byteLength(line);
|