@trama-dev/runtime 0.3.1 → 0.5.0
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 +4 -3
- package/dist/abort.d.ts +12 -0
- package/dist/abort.js +31 -0
- package/dist/agent-backend.d.ts +0 -6
- package/dist/agent-backend.js +1 -21
- package/dist/agent.d.ts +16 -1
- package/dist/agent.js +108 -35
- package/dist/bridge-client.js +44 -14
- package/dist/child-process.d.ts +1 -20
- package/dist/child-process.js +11 -86
- package/dist/client.d.ts +2 -1
- package/dist/client.js +5 -15
- package/dist/context.d.ts +36 -7
- package/dist/context.js +83 -92
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/index.d.ts +12 -1
- package/dist/index.js +93 -53
- package/dist/ipc-server.d.ts +12 -6
- package/dist/ipc-server.js +124 -136
- package/dist/journal-view.d.ts +9 -0
- package/dist/journal-view.js +139 -0
- package/dist/journal.d.ts +70 -0
- package/dist/journal.js +454 -0
- package/dist/meta.d.ts +18 -0
- package/dist/meta.js +29 -0
- package/dist/path-guard.d.ts +128 -19
- package/dist/path-guard.js +384 -68
- package/dist/pi-adapter.d.ts +7 -6
- package/dist/pi-adapter.js +15 -26
- package/dist/replace-file.d.ts +31 -0
- package/dist/replace-file.js +75 -0
- package/dist/runner-types.d.ts +2 -0
- package/dist/runner.d.ts +37 -37
- package/dist/runner.js +565 -239
- package/dist/serializable.d.ts +10 -4
- package/dist/serializable.js +56 -31
- package/dist/{watchdog.d.ts → stopping.d.ts} +15 -0
- package/dist/stopping.js +268 -0
- package/dist/tools.js +44 -13
- package/dist/tree.d.ts +234 -0
- package/dist/tree.js +1409 -0
- package/dist/types.d.ts +6 -3
- package/dist/workspace.d.ts +7 -0
- package/dist/workspace.js +93 -104
- package/package.json +2 -2
- package/dist/watchdog.js +0 -167
package/dist/types.d.ts
CHANGED
|
@@ -6,13 +6,13 @@ export interface Ctx {
|
|
|
6
6
|
};
|
|
7
7
|
/**
|
|
8
8
|
* Persistent state. Must be strictly JSON-serializable.
|
|
9
|
-
* Local working copy — only checkpoint() and done() persist to disk.
|
|
9
|
+
* Local working copy — only checkpoint(), yield() and done() persist to disk.
|
|
10
10
|
* Reserved keys: any key starting with `__trama_` is reserved.
|
|
11
11
|
*/
|
|
12
12
|
state: Record<string, unknown>;
|
|
13
13
|
/**
|
|
14
14
|
* Current iteration counter (starts at 0).
|
|
15
|
-
* Advances only when checkpoint() or done() is called.
|
|
15
|
+
* Advances only when checkpoint(), yield() or done() is called.
|
|
16
16
|
*/
|
|
17
17
|
iteration: number;
|
|
18
18
|
/** Max iterations hint. Not enforced by runtime. */
|
|
@@ -30,7 +30,10 @@ export interface Ctx {
|
|
|
30
30
|
* Idempotent: second call is a no-op.
|
|
31
31
|
*/
|
|
32
32
|
ready(data?: Record<string, unknown>): Promise<void>;
|
|
33
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Persist current ctx.state to disk.
|
|
35
|
+
* Throws once done() or yield() has been called: the run has ended, and its state is settled.
|
|
36
|
+
*/
|
|
34
37
|
checkpoint(): Promise<void>;
|
|
35
38
|
/**
|
|
36
39
|
* Signal program completion. Persists state (logging is best-effort).
|
package/dist/workspace.d.ts
CHANGED
|
@@ -1,2 +1,9 @@
|
|
|
1
1
|
import type { Workspace } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Make sure a workspace directory exists where `workspaceDir` leads, and
|
|
4
|
+
* return its resolved path. Unlike a project, a workspace is nothing but its
|
|
5
|
+
* path and is made as needed — also when `workspaceDir` is a link whose target
|
|
6
|
+
* is not there yet.
|
|
7
|
+
*/
|
|
8
|
+
export declare function ensureWorkspaceDir(workspaceDir: string): string;
|
|
2
9
|
export declare function createWorkspace(workspaceDir: string, signal?: AbortSignal): Workspace;
|
package/dist/workspace.js
CHANGED
|
@@ -1,27 +1,24 @@
|
|
|
1
|
-
import { readFileSync,
|
|
2
|
-
import { resolve,
|
|
3
|
-
import {
|
|
1
|
+
import { readFileSync, mkdirSync, readdirSync, statSync } from "fs";
|
|
2
|
+
import { resolve, relative, sep } from "path";
|
|
3
|
+
import { onAbort } from "./abort.js";
|
|
4
|
+
import { guardPath, realRootOf } from "./path-guard.js";
|
|
5
|
+
import { isStagedName, stageFile } from "./replace-file.js";
|
|
4
6
|
const OBSERVE_POLL_MS = 250;
|
|
5
7
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
8
|
+
* Compile a simple glob pattern for matching relative paths: `*` is any run
|
|
9
|
+
* of characters within a segment, `?` one of them, `**` any run of characters
|
|
10
|
+
* at all, and `**` with its slash any number of whole segments, none included
|
|
11
|
+
* (so `**` + `/*.md` matches at the root too). Every other character is itself.
|
|
12
|
+
*
|
|
13
|
+
* The pattern is taken apart at its operators and each piece between them
|
|
14
|
+
* escaped whole — nothing is put into the pattern on the way, so there is no
|
|
15
|
+
* text a pattern could hold that is mistaken for an operator.
|
|
9
16
|
*/
|
|
10
|
-
function
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
// Escape regex special chars except * and ?
|
|
16
|
-
regex = regex
|
|
17
|
-
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
18
|
-
.replace(/\*/g, "[^/]*")
|
|
19
|
-
.replace(/\?/g, "[^/]");
|
|
20
|
-
// Restore placeholders
|
|
21
|
-
regex = regex
|
|
22
|
-
.replace(/\x00GLOBSTARSLASH\x00/g, "(?:.+/)?")
|
|
23
|
-
.replace(/\x00GLOBSTAR\x00/g, ".*");
|
|
24
|
-
return new RegExp(`^${regex}$`).test(filePath);
|
|
17
|
+
function compileGlob(pattern) {
|
|
18
|
+
const literal = (text) => text.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
19
|
+
const within = (segment) => segment.split("?").map((part) => part.split("*").map(literal).join("[^/]*")).join("[^/]");
|
|
20
|
+
const regex = pattern.split("**/").map((part) => part.split("**").map(within).join(".*")).join("(?:.+/)?");
|
|
21
|
+
return new RegExp(`^${regex}$`);
|
|
25
22
|
}
|
|
26
23
|
/**
|
|
27
24
|
* A pattern with no glob operators names exactly one artifact.
|
|
@@ -31,81 +28,89 @@ function isExactPath(pattern) {
|
|
|
31
28
|
return !/[*?]/.test(pattern);
|
|
32
29
|
}
|
|
33
30
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
31
|
+
* List the files under a directory of a workspace, as forward-slash paths
|
|
32
|
+
* relative to `root`, into `found`. Links to files are included, and links
|
|
33
|
+
* to directories followed, but only those the guard lets through: what is
|
|
34
|
+
* listed is what can be read.
|
|
37
35
|
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
36
|
+
* A link to a directory is an alias: what is in that directory is listed
|
|
37
|
+
* under the link's name too. It is followed where it really is — in a
|
|
38
|
+
* directory reached by no link — and not again where it is come upon by way
|
|
39
|
+
* of another link (`byLink`). So every alias of a shared directory is listed,
|
|
40
|
+
* a loop is gone round once, and the work is bounded by the links there are
|
|
41
|
+
* times what they lead to; following links found through links, it is
|
|
42
|
+
* bounded by nothing but the length of a path. What this leaves unlisted,
|
|
43
|
+
* though it can be read: what lies beyond a second link to a directory. (A
|
|
44
|
+
* link to a file costs nothing to list, wherever it is come upon.)
|
|
43
45
|
*/
|
|
44
|
-
function
|
|
45
|
-
const results = [];
|
|
46
|
+
function listFiles(dir, root, found, byLink = false) {
|
|
46
47
|
let entries;
|
|
47
48
|
try {
|
|
48
49
|
entries = readdirSync(dir, { withFileTypes: true });
|
|
49
50
|
}
|
|
50
51
|
catch {
|
|
51
|
-
return
|
|
52
|
+
return;
|
|
52
53
|
}
|
|
53
|
-
|
|
54
|
+
// A temp file left by a write that was cut off is not an artifact.
|
|
55
|
+
const addFile = (full) => { if (!isStagedName(full))
|
|
56
|
+
found.push(relative(root, full).split(sep).join("/")); };
|
|
54
57
|
for (const entry of entries) {
|
|
55
58
|
const full = resolve(dir, entry.name);
|
|
56
59
|
if (entry.isSymbolicLink()) {
|
|
57
|
-
let
|
|
60
|
+
let stat;
|
|
58
61
|
try {
|
|
59
|
-
|
|
62
|
+
guardPath(root, full); // leads out of the workspace, or nowhere: not listed
|
|
63
|
+
stat = statSync(full);
|
|
60
64
|
}
|
|
61
65
|
catch {
|
|
62
|
-
continue;
|
|
66
|
+
continue;
|
|
63
67
|
}
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
if (stat.isDirectory()) {
|
|
69
|
-
if (visited.has(real))
|
|
70
|
-
continue;
|
|
71
|
-
visited.add(real);
|
|
72
|
-
results.push(...listFilesRecursive(full, root, realRoot, visited));
|
|
73
|
-
}
|
|
74
|
-
else if (stat.isFile()) {
|
|
75
|
-
addFile(full);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
catch { /* stat failed */ }
|
|
68
|
+
if (stat.isFile())
|
|
69
|
+
addFile(full);
|
|
70
|
+
else if (stat.isDirectory() && !byLink)
|
|
71
|
+
listFiles(full, root, found, true);
|
|
79
72
|
}
|
|
80
73
|
else if (entry.isDirectory()) {
|
|
81
|
-
|
|
74
|
+
listFiles(full, root, found, byLink);
|
|
82
75
|
}
|
|
83
76
|
else if (entry.isFile()) {
|
|
84
77
|
addFile(full);
|
|
85
78
|
}
|
|
86
79
|
}
|
|
87
|
-
return results;
|
|
88
80
|
}
|
|
89
81
|
/** Resolve after `ms`, or reject as soon as `signal` aborts. */
|
|
90
82
|
function sleep(ms, signal) {
|
|
91
83
|
return new Promise((resolve, reject) => {
|
|
92
|
-
const onAbort = () => {
|
|
93
|
-
clearTimeout(timer);
|
|
94
|
-
reject(new Error("workspace.observe() aborted"));
|
|
95
|
-
};
|
|
96
84
|
const timer = setTimeout(() => {
|
|
97
|
-
|
|
85
|
+
offAbort();
|
|
98
86
|
resolve();
|
|
99
87
|
}, ms);
|
|
100
|
-
|
|
88
|
+
const offAbort = onAbort(signal, () => {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
reject(new Error("workspace.observe() aborted"));
|
|
91
|
+
});
|
|
101
92
|
});
|
|
102
93
|
}
|
|
103
|
-
|
|
94
|
+
/**
|
|
95
|
+
* Make sure a workspace directory exists where `workspaceDir` leads, and
|
|
96
|
+
* return its resolved path. Unlike a project, a workspace is nothing but its
|
|
97
|
+
* path and is made as needed — also when `workspaceDir` is a link whose target
|
|
98
|
+
* is not there yet.
|
|
99
|
+
*/
|
|
100
|
+
export function ensureWorkspaceDir(workspaceDir) {
|
|
104
101
|
const root = resolve(workspaceDir);
|
|
105
|
-
mkdirSync(root, { recursive: true });
|
|
106
|
-
|
|
102
|
+
mkdirSync(realRootOf(root), { recursive: true });
|
|
103
|
+
return root;
|
|
104
|
+
}
|
|
105
|
+
export function createWorkspace(workspaceDir, signal) {
|
|
106
|
+
const root = ensureWorkspaceDir(workspaceDir);
|
|
107
107
|
/** All artifact paths matching a glob, sorted. */
|
|
108
|
-
const listMatching = (pattern) =>
|
|
108
|
+
const listMatching = (pattern) => {
|
|
109
|
+
const re = compileGlob(pattern);
|
|
110
|
+
const found = [];
|
|
111
|
+
listFiles(root, root, found);
|
|
112
|
+
return found.filter(f => re.test(f)).sort();
|
|
113
|
+
};
|
|
109
114
|
/** Read an artifact, or null if it is missing, unreadable, or escapes the workspace. */
|
|
110
115
|
const readIfPresent = (path) => {
|
|
111
116
|
try {
|
|
@@ -128,42 +133,9 @@ export function createWorkspace(workspaceDir, signal) {
|
|
|
128
133
|
}
|
|
129
134
|
},
|
|
130
135
|
async write(path, content) {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
// replacing the link (matches tools.write). guardPath has already
|
|
135
|
-
// verified the destination stays inside the workspace.
|
|
136
|
-
let writePath = target;
|
|
137
|
-
try {
|
|
138
|
-
if (lstatSync(target).isSymbolicLink()) {
|
|
139
|
-
try {
|
|
140
|
-
writePath = realpathSync(target);
|
|
141
|
-
}
|
|
142
|
-
catch (e) {
|
|
143
|
-
if (e.code !== "ENOENT")
|
|
144
|
-
throw e;
|
|
145
|
-
// Dangling symlink — resolve the link destination manually
|
|
146
|
-
writePath = resolve(dirname(target), readlinkSync(target));
|
|
147
|
-
mkdirSync(dirname(writePath), { recursive: true });
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
catch (e) {
|
|
152
|
-
if (e.code !== "ENOENT")
|
|
153
|
-
throw e;
|
|
154
|
-
}
|
|
155
|
-
// Atomic write: temp file in the same directory, fsync, rename.
|
|
156
|
-
// Readers see either the old content or the new — never a partial file.
|
|
157
|
-
const tmpFile = writePath + `.trama-tmp-${process.pid}-${Date.now()}`;
|
|
158
|
-
const fd = openSync(tmpFile, "w");
|
|
159
|
-
try {
|
|
160
|
-
writeFileSync(fd, content);
|
|
161
|
-
fdatasyncSync(fd);
|
|
162
|
-
}
|
|
163
|
-
finally {
|
|
164
|
-
closeSync(fd);
|
|
165
|
-
}
|
|
166
|
-
renameSync(tmpFile, writePath);
|
|
136
|
+
// One move, so that readers see either the old content or the new, never
|
|
137
|
+
// a partial file. A link is written through rather than replaced.
|
|
138
|
+
stageFile(root, path, content).commit();
|
|
167
139
|
},
|
|
168
140
|
async list(pattern) {
|
|
169
141
|
return listMatching(pattern);
|
|
@@ -177,10 +149,24 @@ export function createWorkspace(workspaceDir, signal) {
|
|
|
177
149
|
throw new Error(`workspace.observe(): timeout must be a non-negative number (got ${timeout})`);
|
|
178
150
|
}
|
|
179
151
|
const needed = expect ?? 1;
|
|
152
|
+
const exact = isExactPath(pattern);
|
|
180
153
|
// One exact path, one artifact wanted → the caller gets its content as a string.
|
|
181
|
-
const single =
|
|
182
|
-
|
|
183
|
-
|
|
154
|
+
const single = exact && needed === 1;
|
|
155
|
+
// A path that will never be read is refused now, rather than waited for: one that leads out of the
|
|
156
|
+
// workspace, or cannot be followed as things stand, whatever is asked of it. (What comes to be in its way
|
|
157
|
+
// later, while it waits — a link, a file where a directory is to be — is waited out like anything that is
|
|
158
|
+
// not there yet.)
|
|
159
|
+
if (exact)
|
|
160
|
+
guardPath(root, pattern);
|
|
161
|
+
// And one path, wanted as one text, is none while a directory is there: that is said as soon as it is seen.
|
|
162
|
+
const isDirectory = () => {
|
|
163
|
+
try {
|
|
164
|
+
return statSync(guardPath(root, pattern)).isDirectory();
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
184
170
|
const collectMatches = () => {
|
|
185
171
|
const matches = [];
|
|
186
172
|
for (const path of single ? [pattern] : listMatching(pattern)) {
|
|
@@ -191,14 +177,17 @@ export function createWorkspace(workspaceDir, signal) {
|
|
|
191
177
|
return matches;
|
|
192
178
|
};
|
|
193
179
|
// Level-triggered: artifacts that already exist count immediately.
|
|
194
|
-
const startTime =
|
|
180
|
+
const startTime = performance.now();
|
|
195
181
|
while (true) {
|
|
196
182
|
if (signal?.aborted)
|
|
197
183
|
throw new Error("workspace.observe() aborted");
|
|
184
|
+
if (single && isDirectory()) {
|
|
185
|
+
throw Object.assign(new Error(`EISDIR: illegal operation on a directory, read '${pattern}'`), { code: "EISDIR" });
|
|
186
|
+
}
|
|
198
187
|
const matches = collectMatches();
|
|
199
188
|
if (matches.length >= needed)
|
|
200
189
|
return single ? matches[0].content : matches;
|
|
201
|
-
if (timeout !== undefined && (
|
|
190
|
+
if (timeout !== undefined && (performance.now() - startTime) >= timeout) {
|
|
202
191
|
throw new Error(`workspace.observe("${pattern}") timed out after ${timeout}ms. ` +
|
|
203
192
|
`Found ${matches.length}/${needed} matching artifacts.`);
|
|
204
193
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trama-dev/runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
15
|
"scripts": {
|
|
16
|
-
"build": "tsc"
|
|
16
|
+
"build": "rm -rf dist && tsc"
|
|
17
17
|
},
|
|
18
18
|
"publishConfig": {
|
|
19
19
|
"access": "public"
|
package/dist/watchdog.js
DELETED
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
// What must not outlive this process: the process groups it started, and the
|
|
2
|
-
// temp directories it made.
|
|
3
|
-
//
|
|
4
|
-
// A program, and every shell command it runs, leads its own process group — so
|
|
5
|
-
// that a timeout can take down everything it started. The cost is that none of
|
|
6
|
-
// them die with the runner. Something has to stop them when the runner goes,
|
|
7
|
-
// and it cannot be the runner: a process that is killed outright, or runs out
|
|
8
|
-
// of memory, or crashes, runs no code on its way out.
|
|
9
|
-
//
|
|
10
|
-
// So it is a process of its own, the watchdog. The runner keeps a pipe to it
|
|
11
|
-
// open, and tells it what it has started and what has ended. When the pipe
|
|
12
|
-
// closes — the runner is gone, however it went — the watchdog stops whatever
|
|
13
|
-
// is still on its list and deletes what is left of the directories. One runner
|
|
14
|
-
// carries every run of a session, so one list covers the whole tree.
|
|
15
|
-
//
|
|
16
|
-
// Nothing here listens for a signal or for the process exiting: the process
|
|
17
|
-
// that hosts a runner keeps its own way of handling both.
|
|
18
|
-
import { spawn } from "child_process";
|
|
19
|
-
import { rmSync } from "fs";
|
|
20
|
-
import { STOP_TIMINGS, onGroupAskedToStop } from "./child-process.js";
|
|
21
|
-
// Run by the watchdog process. It applies the same policy as stopGroups (see
|
|
22
|
-
// child-process.ts): ask, wait out the grace period, kill what is left. A
|
|
23
|
-
// group the runner had already asked is not asked a second time.
|
|
24
|
-
const WATCHDOG = `
|
|
25
|
-
const { rmSync } = require("fs");
|
|
26
|
-
const { grace, settle, poll } = JSON.parse(process.argv[1]);
|
|
27
|
-
const lists = { g: new Set(), d: new Set(), asked: new Set() };
|
|
28
|
-
const alive = (pgid) => { try { process.kill(-pgid, 0); return true; } catch { return false; } };
|
|
29
|
-
const signal = (pgid, name) => { try { process.kill(-pgid, name); } catch {} };
|
|
30
|
-
|
|
31
|
-
let unread = "";
|
|
32
|
-
process.stdin.setEncoding("utf8");
|
|
33
|
-
process.stdin.on("data", (chunk) => {
|
|
34
|
-
unread += chunk;
|
|
35
|
-
for (let end; (end = unread.indexOf("\\n")) !== -1; unread = unread.slice(end + 1)) {
|
|
36
|
-
const [op, list, item] = JSON.parse(unread.slice(0, end));
|
|
37
|
-
lists[list][op === "+" ? "add" : "delete"](item);
|
|
38
|
-
}
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
// The pipe has closed: the runner is gone.
|
|
42
|
-
let leaving = false;
|
|
43
|
-
const takeOver = () => {
|
|
44
|
-
if (leaving) return;
|
|
45
|
-
leaving = true;
|
|
46
|
-
const finish = () => {
|
|
47
|
-
for (const dir of lists.d) { try { rmSync(dir, { recursive: true, force: true }); } catch {} }
|
|
48
|
-
process.exit(0);
|
|
49
|
-
};
|
|
50
|
-
let left = [...lists.g].filter(alive);
|
|
51
|
-
for (const pgid of left) { if (!lists.asked.has(pgid)) signal(pgid, "SIGTERM"); }
|
|
52
|
-
let deadline = performance.now() + grace;
|
|
53
|
-
let killed = false;
|
|
54
|
-
const check = () => {
|
|
55
|
-
// A group seen gone is never signalled again: its id may belong to another by now.
|
|
56
|
-
left = left.filter(alive);
|
|
57
|
-
if (left.length === 0) return finish();
|
|
58
|
-
if (performance.now() < deadline) return;
|
|
59
|
-
if (killed) return finish();
|
|
60
|
-
for (const pgid of left) signal(pgid, "SIGKILL");
|
|
61
|
-
killed = true;
|
|
62
|
-
deadline = performance.now() + settle;
|
|
63
|
-
};
|
|
64
|
-
check();
|
|
65
|
-
setInterval(check, poll);
|
|
66
|
-
};
|
|
67
|
-
process.stdin.on("end", takeOver);
|
|
68
|
-
process.stdin.on("close", takeOver);
|
|
69
|
-
process.stdin.on("error", takeOver);
|
|
70
|
-
`;
|
|
71
|
-
/** What this process has told the watchdog about and not yet taken back. */
|
|
72
|
-
const pending = { g: new Set(), d: new Set(), asked: new Set() };
|
|
73
|
-
let watchdog = null;
|
|
74
|
-
const tell = (to, op, list, item) => {
|
|
75
|
-
to.stdin?.write(JSON.stringify([op, list, item]) + "\n");
|
|
76
|
-
};
|
|
77
|
-
/**
|
|
78
|
-
* Start the watchdog if there is none, and return it — or null if it cannot be
|
|
79
|
-
* started. A watchdog that has itself died is replaced, and told again what is
|
|
80
|
-
* still pending.
|
|
81
|
-
*/
|
|
82
|
-
function startWatchdog() {
|
|
83
|
-
if (watchdog)
|
|
84
|
-
return watchdog;
|
|
85
|
-
let child;
|
|
86
|
-
try {
|
|
87
|
-
child = spawn(process.execPath, ["-e", WATCHDOG, JSON.stringify(STOP_TIMINGS)], {
|
|
88
|
-
detached: true, // a signal sent to this process's group must not reach it
|
|
89
|
-
stdio: ["pipe", "ignore", "ignore"],
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
catch {
|
|
93
|
-
return null;
|
|
94
|
-
}
|
|
95
|
-
const lost = () => { if (watchdog === child)
|
|
96
|
-
watchdog = null; };
|
|
97
|
-
child.on("error", lost);
|
|
98
|
-
child.on("exit", lost);
|
|
99
|
-
child.stdin?.on("error", lost);
|
|
100
|
-
if (child.pid === undefined)
|
|
101
|
-
return null; // a failed spawn has no pid from the start
|
|
102
|
-
// Neither the watchdog nor the pipe to it keeps this process alive.
|
|
103
|
-
child.unref();
|
|
104
|
-
child.stdin?.unref?.();
|
|
105
|
-
watchdog = child;
|
|
106
|
-
for (const list of ["g", "d", "asked"]) {
|
|
107
|
-
for (const item of pending[list])
|
|
108
|
-
tell(child, "+", list, item);
|
|
109
|
-
}
|
|
110
|
-
return child;
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Make sure there is a watchdog before anything is started that would need
|
|
114
|
-
* one. Throws if one cannot be started: running without it would mean leaving
|
|
115
|
-
* processes behind with nobody to stop them.
|
|
116
|
-
*/
|
|
117
|
-
export function requireWatchdog() {
|
|
118
|
-
if (!startWatchdog()) {
|
|
119
|
-
throw new Error("Could not start trama's watchdog process, which stops what a run started if the runner dies.");
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
/** Keep `item` on the watchdog's list until the returned function is called. */
|
|
123
|
-
function watch(list, item) {
|
|
124
|
-
pending[list].add(item);
|
|
125
|
-
const to = startWatchdog();
|
|
126
|
-
if (to)
|
|
127
|
-
tell(to, "+", list, item);
|
|
128
|
-
return () => {
|
|
129
|
-
if (!pending[list].delete(item))
|
|
130
|
-
return;
|
|
131
|
-
if (watchdog)
|
|
132
|
-
tell(watchdog, "-", list, item);
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* Register a process group this process started: if this process ends before
|
|
137
|
-
* the returned function is called, the group is stopped.
|
|
138
|
-
*/
|
|
139
|
-
export function stopWithThisProcess(pgid) {
|
|
140
|
-
const forget = watch("g", pgid);
|
|
141
|
-
return () => {
|
|
142
|
-
forget();
|
|
143
|
-
asked.get(pgid)?.();
|
|
144
|
-
asked.delete(pgid);
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
/** Groups on the watchdog's list that this process has asked to stop, and how to take each off again. */
|
|
148
|
-
const asked = new Map();
|
|
149
|
-
onGroupAskedToStop((pgid) => {
|
|
150
|
-
if (pending.g.has(pgid) && !asked.has(pgid))
|
|
151
|
-
asked.set(pgid, watch("asked", pgid));
|
|
152
|
-
});
|
|
153
|
-
/**
|
|
154
|
-
* Register a temp directory this process created: if this process ends before
|
|
155
|
-
* the returned function is called, the directory is removed — once the groups
|
|
156
|
-
* that may be writing to it are gone.
|
|
157
|
-
*/
|
|
158
|
-
export function removeWithThisProcess(dir) {
|
|
159
|
-
return watch("d", dir);
|
|
160
|
-
}
|
|
161
|
-
/** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
|
|
162
|
-
export function removeTempDir(dir) {
|
|
163
|
-
try {
|
|
164
|
-
rmSync(dir, { recursive: true, force: true });
|
|
165
|
-
}
|
|
166
|
-
catch { /* left for the OS to reap */ }
|
|
167
|
-
}
|