@omercnet/paseo-pr-radar 3.3.0 → 3.4.0-next.543.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 +11 -1
- package/client/directory-observation.ts +16 -3
- package/client/launch.ts +188 -0
- package/client/pr-radar.tsx +16 -73
- package/client/radar.ts +13 -2
- package/client/settings-screen.tsx +14 -0
- package/client/start-agent-modal.tsx +42 -1
- package/index.server.ts +12 -2
- package/package.json +5 -5
- package/server/routing-script.ts +522 -0
- package/server/viewer-scope.ts +94 -18
- package/server/workspace-ops.ts +190 -293
- package/shared/routed-labels.ts +269 -0
- package/shared/settings.ts +22 -1
- package/shared/viewer-scope.ts +4 -0
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
import { type ChildProcessByStdio, spawn } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { access, lstat, readlink, realpath, stat } from "node:fs/promises";
|
|
4
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
5
|
+
import type { Readable, Writable } from "node:stream";
|
|
6
|
+
import type { z } from "zod";
|
|
7
|
+
import { RoutingScriptResultSchema, type runRoutingScript } from "../shared/viewer-scope";
|
|
8
|
+
import {
|
|
9
|
+
allowListedEnv,
|
|
10
|
+
COMMAND_TIMEOUT_MS,
|
|
11
|
+
exists,
|
|
12
|
+
expandUserPath,
|
|
13
|
+
isAbsoluteOrHomePath,
|
|
14
|
+
type ReadWorkspaceSettings,
|
|
15
|
+
} from "./workspace-ops";
|
|
16
|
+
|
|
17
|
+
export interface RoutingScriptLimits {
|
|
18
|
+
timeoutMs: number;
|
|
19
|
+
outputBytes: number;
|
|
20
|
+
killGraceMs: number;
|
|
21
|
+
/** Largest stdin payload the script is sent; `DEFAULT_ROUTING_INPUT_BYTES` when left out. */
|
|
22
|
+
inputBytes?: number;
|
|
23
|
+
/** Candidate PATH directories for the script; `ROUTING_SCRIPT_PATH_DIRS` when left out (tests narrow it). */
|
|
24
|
+
pathDirs?: readonly string[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// The payload carries PR text (title, labels, linked issues) that another person wrote, so it has
|
|
28
|
+
// no natural bound. An oversize one is refused rather than cut: the script would otherwise route
|
|
29
|
+
// on a silently shortened record. The cap matches the output cap.
|
|
30
|
+
const DEFAULT_ROUTING_INPUT_BYTES = 1024 * 1024;
|
|
31
|
+
|
|
32
|
+
const DEFAULT_ROUTING_LIMITS: RoutingScriptLimits = {
|
|
33
|
+
timeoutMs: COMMAND_TIMEOUT_MS,
|
|
34
|
+
outputBytes: 1024 * 1024,
|
|
35
|
+
killGraceMs: 2_000,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const STICKY_BIT = 0o1000;
|
|
39
|
+
|
|
40
|
+
// The script's working directory. It is not the daemon's: an empty or relative PATH entry makes a
|
|
41
|
+
// lookup fall back to the current directory, and the daemon's can hold files other people wrote.
|
|
42
|
+
// The filesystem root belongs to root and is never group or other writable.
|
|
43
|
+
const ROUTING_SCRIPT_CWD = "/";
|
|
44
|
+
|
|
45
|
+
const NO_TRUSTED_PATH_MESSAGE =
|
|
46
|
+
"None of the system directories the routing script searches for tools (/usr/bin, /bin and the like) passed the ownership and permission check, so the script was not run; run chown or chmod go-w on them.";
|
|
47
|
+
|
|
48
|
+
// The script's PATH. The daemon's own PATH can list directories other users or tools write to
|
|
49
|
+
// (~/.local/bin, a project's node_modules/.bin), and the script's `#!/usr/bin/env interpreter` line
|
|
50
|
+
// would search it. These are the system and Homebrew directories; a script that needs a tool
|
|
51
|
+
// elsewhere should name it by absolute path. A directory is dropped at run time unless it passes the
|
|
52
|
+
// same trust check as the script's own directories (a Homebrew prefix owned by another user, or one
|
|
53
|
+
// group-writable, would let that user supply the interpreter).
|
|
54
|
+
const ROUTING_SCRIPT_PATH_DIRS = [
|
|
55
|
+
"/opt/homebrew/bin",
|
|
56
|
+
"/usr/local/bin",
|
|
57
|
+
"/usr/bin",
|
|
58
|
+
"/bin",
|
|
59
|
+
"/usr/sbin",
|
|
60
|
+
"/sbin",
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
export async function trustedScriptPath(
|
|
64
|
+
uid: number | undefined = process.getuid?.(),
|
|
65
|
+
dirs: readonly string[] = ROUTING_SCRIPT_PATH_DIRS,
|
|
66
|
+
// Directories whose own trust is already settled; the walk up from a PATH entry stops at them.
|
|
67
|
+
verified: Set<string> = new Set(),
|
|
68
|
+
): Promise<string> {
|
|
69
|
+
const trustedOwner = (owner: number) => uid === undefined || owner === uid || owner === 0;
|
|
70
|
+
const kept: string[] = [];
|
|
71
|
+
for (const dir of dirs) {
|
|
72
|
+
// A relative entry would be looked up against the script's cwd, which is what this guards against.
|
|
73
|
+
if (!isAbsolute(dir)) continue;
|
|
74
|
+
try {
|
|
75
|
+
// Strict: a sticky bit stops others deleting each other's files, not creating a `python3`.
|
|
76
|
+
// The entry may be, or sit behind, a symbolic link: every link on the way, the directory
|
|
77
|
+
// holding it and that directory's ancestors are checked, then the real directory it ends at
|
|
78
|
+
// and every real parent of that (a link into a directory under a writable parent would
|
|
79
|
+
// otherwise pass, since a walk of the entry's own parents never reaches it).
|
|
80
|
+
await assertTrustedSymlinkChain(dir, trustedOwner, verified, false);
|
|
81
|
+
await assertTrustedDirectories(dir, trustedOwner, verified, false);
|
|
82
|
+
kept.push(dir);
|
|
83
|
+
} catch {
|
|
84
|
+
// Missing, owned by another user, or writable by others: not searched.
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return kept.join(":");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
type OwnerCheck = (owner: number) => boolean;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* `start` and every directory above it must have a trusted owner and not be group/other-writable.
|
|
94
|
+
* A sticky directory (like /tmp) is exempt from the write test unless `allowSticky` is false.
|
|
95
|
+
* `start` is resolved first, so a symbolic link is judged by the real directory it ends at and by
|
|
96
|
+
* that directory's real parents, never by the parents of the link's own spelling.
|
|
97
|
+
*/
|
|
98
|
+
async function assertTrustedDirectories(
|
|
99
|
+
start: string,
|
|
100
|
+
trustedOwner: OwnerCheck,
|
|
101
|
+
verified: Set<string>,
|
|
102
|
+
allowSticky = true,
|
|
103
|
+
): Promise<void> {
|
|
104
|
+
// Remembered as trusted only once the whole walk has passed: a directory is trustworthy only if
|
|
105
|
+
// everything above it is, so one that sat below a failure must not vouch for a later walk that
|
|
106
|
+
// reaches it (say, through a link) and stops there.
|
|
107
|
+
const passed: string[] = [];
|
|
108
|
+
for (let dir = await realpath(start); !verified.has(dir); dir = dirname(dir)) {
|
|
109
|
+
const dirInfo = await stat(dir);
|
|
110
|
+
if (!trustedOwner(dirInfo.uid)) {
|
|
111
|
+
throw new Error(
|
|
112
|
+
`Routing script directory ${dir} is owned by another user; move the script somewhere you own, or run chown on it.`,
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if ((dirInfo.mode & 0o022) !== 0 && !(allowSticky && (dirInfo.mode & STICKY_BIT) !== 0)) {
|
|
116
|
+
throw new Error(
|
|
117
|
+
`Routing script directory ${dir} must not be writable by group or others; run chmod go-w on it.`,
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
passed.push(dir);
|
|
121
|
+
if (dirname(dir) === dir) break;
|
|
122
|
+
}
|
|
123
|
+
for (const dir of passed) verified.add(dir);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// The kernel stops following links after this many (MAXSYMLINKS is 32 on macOS, 40 on Linux).
|
|
127
|
+
const MAX_SYMLINK_HOPS = 32;
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Walks the configured path component by component, as the kernel would, without following a link
|
|
131
|
+
* blindly: every symbolic link met on the way (including links reached through another link, such
|
|
132
|
+
* as /a/l1 -> /b/l2 -> /c/file) must belong to a trusted owner, and the directory that holds it
|
|
133
|
+
* and all that directory's ancestors must not be writable by group or others. A link that anyone
|
|
134
|
+
* else can create, replace or rename could otherwise point the script at any executable the user
|
|
135
|
+
* can run, and that executable would pass every check on the resolved path.
|
|
136
|
+
*/
|
|
137
|
+
async function assertTrustedSymlinkChain(
|
|
138
|
+
expanded: string,
|
|
139
|
+
trustedOwner: OwnerCheck,
|
|
140
|
+
verifiedDirs = new Set<string>(),
|
|
141
|
+
allowSticky = true,
|
|
142
|
+
): Promise<void> {
|
|
143
|
+
const split = (path: string) => path.split("/").filter((part) => part !== "" && part !== ".");
|
|
144
|
+
let pending = split(expanded);
|
|
145
|
+
let current = "/";
|
|
146
|
+
let hops = 0;
|
|
147
|
+
while (pending.length > 0) {
|
|
148
|
+
const [name, ...rest] = pending;
|
|
149
|
+
pending = rest;
|
|
150
|
+
if (name === "..") {
|
|
151
|
+
// The directory being left is part of the path too, even though realpath will not list it.
|
|
152
|
+
await assertTrustedDirectories(current, trustedOwner, verifiedDirs, allowSticky);
|
|
153
|
+
current = dirname(current);
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
const next = join(current, name);
|
|
157
|
+
const info = await lstat(next);
|
|
158
|
+
if (!info.isSymbolicLink()) {
|
|
159
|
+
current = next;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
hops += 1;
|
|
163
|
+
if (hops > MAX_SYMLINK_HOPS) {
|
|
164
|
+
throw new Error(`Routing script path ${expanded} has too many levels of symbolic links.`);
|
|
165
|
+
}
|
|
166
|
+
if (!trustedOwner(info.uid)) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
`Routing script path goes through the symbolic link ${next}, which is owned by another user; point the setting at the real file, or run chown on the link.`,
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
// `current` holds no links (each one is replaced by its target), so this is the real directory
|
|
172
|
+
// that contains the link.
|
|
173
|
+
await assertTrustedDirectories(current, trustedOwner, verifiedDirs, allowSticky);
|
|
174
|
+
const target = await readlink(next);
|
|
175
|
+
pending = [...split(target), ...pending];
|
|
176
|
+
if (isAbsolute(target)) current = "/";
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Resolves the configured script to a real path and refuses anything but a regular, executable
|
|
182
|
+
* file that only this user (or root) can modify: the file must be owned by the user or root, and so
|
|
183
|
+
* must every directory above it, none of them writable by group or others unless sticky (like
|
|
184
|
+
* /tmp). Otherwise another local user could create the script or swap a path component for their
|
|
185
|
+
* own, and it would run as this user. `uid` is a parameter so tests can stand in for another user.
|
|
186
|
+
*/
|
|
187
|
+
export async function resolveRoutingScript(
|
|
188
|
+
rawPath: string,
|
|
189
|
+
uid: number | undefined = process.getuid?.(),
|
|
190
|
+
): Promise<string> {
|
|
191
|
+
const trimmed = rawPath.trim();
|
|
192
|
+
if (!trimmed) {
|
|
193
|
+
throw new Error("No routing script is configured in the PR Radar settings.");
|
|
194
|
+
}
|
|
195
|
+
if (!isAbsoluteOrHomePath(trimmed)) {
|
|
196
|
+
throw new Error(`Routing script path must be an absolute or ~/ path: ${trimmed}`);
|
|
197
|
+
}
|
|
198
|
+
const expanded = expandUserPath(trimmed);
|
|
199
|
+
if (!(await exists(expanded))) {
|
|
200
|
+
throw new Error(`Routing script not found: ${expanded}`);
|
|
201
|
+
}
|
|
202
|
+
const trustedOwner = (owner: number) => uid === undefined || owner === uid || owner === 0;
|
|
203
|
+
await assertTrustedSymlinkChain(expanded, trustedOwner);
|
|
204
|
+
const scriptPath = await realpath(expanded);
|
|
205
|
+
const info = await stat(scriptPath);
|
|
206
|
+
if (!info.isFile()) {
|
|
207
|
+
throw new Error(`Routing script is not a regular file: ${scriptPath}`);
|
|
208
|
+
}
|
|
209
|
+
if (!trustedOwner(info.uid)) {
|
|
210
|
+
throw new Error(
|
|
211
|
+
`Routing script ${scriptPath} is owned by another user; run chown on it, or use a script you own.`,
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
if ((info.mode & 0o022) !== 0) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
`Routing script ${scriptPath} must not be writable by group or others; run chmod go-w on it.`,
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
await assertTrustedDirectories(dirname(scriptPath), trustedOwner, new Set());
|
|
220
|
+
try {
|
|
221
|
+
await access(scriptPath, constants.X_OK);
|
|
222
|
+
} catch {
|
|
223
|
+
throw new Error(`Routing script is not executable: ${scriptPath}`);
|
|
224
|
+
}
|
|
225
|
+
return scriptPath;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
interface ScriptRun {
|
|
229
|
+
/** Settles with the script's stdout, or rejects on failure, timeout or the output cap. */
|
|
230
|
+
result: Promise<string>;
|
|
231
|
+
/** Resolves once the script's process group has exited or has been sent SIGKILL. */
|
|
232
|
+
finished: Promise<void>;
|
|
233
|
+
/** Ends the script now (SIGTERM, then SIGKILL after a short grace) and fails `result`. */
|
|
234
|
+
stop(): void;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function startScriptCapped(
|
|
238
|
+
scriptPath: string,
|
|
239
|
+
stdin: string,
|
|
240
|
+
limits: RoutingScriptLimits,
|
|
241
|
+
path: string,
|
|
242
|
+
): ScriptRun {
|
|
243
|
+
const finishedGate = Promise.withResolvers<void>();
|
|
244
|
+
let stop = () => {};
|
|
245
|
+
const result = new Promise<string>((resolvePromise, rejectPromise) => {
|
|
246
|
+
// Its own process group, so a timeout reaches the script's descendants too.
|
|
247
|
+
let child: ChildProcessByStdio<Writable, Readable, Readable>;
|
|
248
|
+
try {
|
|
249
|
+
child = spawn(scriptPath, [], {
|
|
250
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
251
|
+
env: { ...allowListedEnv(new Set()), PATH: path },
|
|
252
|
+
cwd: ROUTING_SCRIPT_CWD,
|
|
253
|
+
detached: true,
|
|
254
|
+
});
|
|
255
|
+
} catch (spawnError) {
|
|
256
|
+
finishedGate.resolve();
|
|
257
|
+
rejectPromise(spawnError);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const out: Buffer[] = [];
|
|
261
|
+
const err: Buffer[] = [];
|
|
262
|
+
let outBytes = 0;
|
|
263
|
+
let errBytes = 0;
|
|
264
|
+
let settled = false;
|
|
265
|
+
let terminating = false;
|
|
266
|
+
let exited = false;
|
|
267
|
+
let killTimer: NodeJS.Timeout | undefined;
|
|
268
|
+
|
|
269
|
+
// Once the script has exited its process-group id is free to be reused, so nothing may signal
|
|
270
|
+
// it after the one SIGKILL sent from the 'exit' handler.
|
|
271
|
+
function signalGroup(signal: NodeJS.Signals): void {
|
|
272
|
+
if (exited) return;
|
|
273
|
+
try {
|
|
274
|
+
if (child.pid !== undefined) process.kill(-child.pid, signal);
|
|
275
|
+
} catch {
|
|
276
|
+
// The group is already gone.
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function settle(finish: () => void): void {
|
|
280
|
+
if (settled) return;
|
|
281
|
+
settled = true;
|
|
282
|
+
clearTimeout(timer);
|
|
283
|
+
// A surviving descendant could otherwise keep feeding buffers nobody reads any more.
|
|
284
|
+
child.stdout.destroy();
|
|
285
|
+
child.stderr.destroy();
|
|
286
|
+
finish();
|
|
287
|
+
}
|
|
288
|
+
function terminate(graceMs = limits.killGraceMs): void {
|
|
289
|
+
if (terminating) return;
|
|
290
|
+
terminating = true;
|
|
291
|
+
signalGroup("SIGTERM");
|
|
292
|
+
killTimer = setTimeout(() => {
|
|
293
|
+
signalGroup("SIGKILL");
|
|
294
|
+
finishedGate.resolve();
|
|
295
|
+
}, graceMs);
|
|
296
|
+
}
|
|
297
|
+
stop = () => {
|
|
298
|
+
if (terminating) {
|
|
299
|
+
// A timeout or the output cap already sent SIGTERM and armed the full grace, which can
|
|
300
|
+
// outlast the host's own deadline: end the group now.
|
|
301
|
+
clearTimeout(killTimer);
|
|
302
|
+
signalGroup("SIGKILL");
|
|
303
|
+
finishedGate.resolve();
|
|
304
|
+
} else {
|
|
305
|
+
terminate(Math.min(limits.killGraceMs, SHUTDOWN_KILL_GRACE_MS));
|
|
306
|
+
}
|
|
307
|
+
settle(() => rejectPromise(new Error(ROUTING_STOPPED_MESSAGE)));
|
|
308
|
+
};
|
|
309
|
+
function overCap(): void {
|
|
310
|
+
terminate();
|
|
311
|
+
settle(() =>
|
|
312
|
+
rejectPromise(new Error(`Routing script output exceeded ${limits.outputBytes} bytes.`)),
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const timer = setTimeout(() => {
|
|
317
|
+
terminate();
|
|
318
|
+
settle(() =>
|
|
319
|
+
rejectPromise(new Error(`Routing script timed out after ${limits.timeoutMs}ms.`)),
|
|
320
|
+
);
|
|
321
|
+
}, limits.timeoutMs);
|
|
322
|
+
|
|
323
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
324
|
+
if (settled) return;
|
|
325
|
+
outBytes += chunk.length;
|
|
326
|
+
if (outBytes > limits.outputBytes) return overCap();
|
|
327
|
+
out.push(chunk);
|
|
328
|
+
});
|
|
329
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
330
|
+
if (settled) return;
|
|
331
|
+
errBytes += chunk.length;
|
|
332
|
+
if (errBytes > limits.outputBytes) return overCap();
|
|
333
|
+
err.push(chunk);
|
|
334
|
+
});
|
|
335
|
+
child.on("error", (spawnError) => {
|
|
336
|
+
settle(() => rejectPromise(spawnError));
|
|
337
|
+
finishedGate.resolve();
|
|
338
|
+
});
|
|
339
|
+
// 'exit' fires when the script itself has ended, while 'close' waits for every holder of the
|
|
340
|
+
// pipes. A descendant that kept them open would otherwise delay 'close' until the timeout and a
|
|
341
|
+
// script that exited 0 would be reported as timed out. Bytes the script already wrote stay in
|
|
342
|
+
// the pipe, so 'close' still delivers the full output.
|
|
343
|
+
// That one kill is the only group signal once the script has ended: a `setsid` descendant can
|
|
344
|
+
// hold the pipes (and 'close') for up to the timeout, and by then the group id may belong to an
|
|
345
|
+
// unrelated process.
|
|
346
|
+
child.on("exit", () => {
|
|
347
|
+
signalGroup("SIGKILL");
|
|
348
|
+
exited = true;
|
|
349
|
+
});
|
|
350
|
+
child.on("close", (code) => {
|
|
351
|
+
clearTimeout(killTimer);
|
|
352
|
+
finishedGate.resolve();
|
|
353
|
+
settle(() => {
|
|
354
|
+
if (code !== 0) {
|
|
355
|
+
const message = Buffer.concat(err).toString("utf8").trim();
|
|
356
|
+
rejectPromise(new Error(message || `Routing script exited with code ${code}.`));
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
resolvePromise(Buffer.concat(out).toString("utf8").trim());
|
|
360
|
+
});
|
|
361
|
+
});
|
|
362
|
+
child.stdin.on("error", () => {});
|
|
363
|
+
child.stdin.end(stdin);
|
|
364
|
+
});
|
|
365
|
+
return { result, finished: finishedGate.promise, stop: () => stop() };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// The daemon waits 2 s for a plugin's cleanup before it signals the plugin process, so the script
|
|
369
|
+
// must be gone sooner than that.
|
|
370
|
+
const SHUTDOWN_KILL_GRACE_MS = 1_000;
|
|
371
|
+
const ROUTING_STOPPED_MESSAGE = "The routing script was stopped because PR Radar is shutting down.";
|
|
372
|
+
|
|
373
|
+
// One script runs at a time; up to this many further calls wait their turn, the rest are refused.
|
|
374
|
+
const MAX_QUEUED_ROUTING_CALLS = 2;
|
|
375
|
+
const ROUTING_BUSY_MESSAGE = "A routing script is already running; try again when it has finished.";
|
|
376
|
+
|
|
377
|
+
// Resolves when every admitted call has finished its turn: its script's process group is gone or
|
|
378
|
+
// has been sent SIGKILL, which can be after the call itself has failed on a timeout. A queued call
|
|
379
|
+
// waits on this gate (`run.finished`), not on the previous call's result, so a timed-out script
|
|
380
|
+
// that ignores SIGTERM never overlaps the next one.
|
|
381
|
+
let routingTail: Promise<void> = Promise.resolve();
|
|
382
|
+
let routingInFlight = 0;
|
|
383
|
+
let routingWaiting = 0;
|
|
384
|
+
// The script now running, and whether the plugin has been told to stop.
|
|
385
|
+
let activeRun: ScriptRun | undefined;
|
|
386
|
+
let routingStopped = false;
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Plugin cleanup. The script runs in its own process group (so a timeout reaches its descendants),
|
|
390
|
+
* which also means the daemon stopping, reloading or disabling the plugin does not reach it: end
|
|
391
|
+
* it here, and refuse any call still waiting. Resolves once its process group is gone or has been
|
|
392
|
+
* sent SIGKILL. A daemon that is killed outright never runs this; the script then ends on its own.
|
|
393
|
+
*/
|
|
394
|
+
export async function stopRoutingScripts(): Promise<void> {
|
|
395
|
+
routingStopped = true;
|
|
396
|
+
const run = activeRun;
|
|
397
|
+
if (!run) return;
|
|
398
|
+
run.stop();
|
|
399
|
+
await run.finished;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Called when the plugin starts: a plugin process is fresh, and tests start it more than once. */
|
|
403
|
+
export function startRoutingScripts(): void {
|
|
404
|
+
routingStopped = false;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export async function waitForRoutingScriptIdleForTests(): Promise<void> {
|
|
408
|
+
for (let tail = routingTail; ; tail = routingTail) {
|
|
409
|
+
await tail;
|
|
410
|
+
if (tail === routingTail) return;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// Resolves with `work`, or rejects with `message` once `ms` have passed. The work itself cannot be
|
|
415
|
+
// cancelled, but the caller stops waiting for it, so a hung filesystem read cannot hold a turn.
|
|
416
|
+
async function withinBudget<T>(work: Promise<T>, ms: number, message: string): Promise<T> {
|
|
417
|
+
// Work abandoned below may still reject later; nobody is left to hear it.
|
|
418
|
+
work.catch(() => {});
|
|
419
|
+
if (ms <= 0) throw new Error(message);
|
|
420
|
+
let timer: NodeJS.Timeout | undefined;
|
|
421
|
+
const expired = new Promise<never>((_, reject) => {
|
|
422
|
+
timer = setTimeout(() => reject(new Error(message)), ms);
|
|
423
|
+
});
|
|
424
|
+
try {
|
|
425
|
+
return await Promise.race([work, expired]);
|
|
426
|
+
} finally {
|
|
427
|
+
clearTimeout(timer);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const ROUTING_PREFLIGHT_MESSAGE =
|
|
432
|
+
"Reading the routing script settings or checking the script took longer than the time budget.";
|
|
433
|
+
|
|
434
|
+
export async function runRoutingScriptHandler(
|
|
435
|
+
input: z.output<typeof runRoutingScript.input>,
|
|
436
|
+
readSettings: ReadWorkspaceSettings,
|
|
437
|
+
limits: RoutingScriptLimits = DEFAULT_ROUTING_LIMITS,
|
|
438
|
+
): Promise<z.output<typeof runRoutingScript.output>> {
|
|
439
|
+
if (process.platform === "win32") {
|
|
440
|
+
throw new Error("Routing scripts are not supported on Windows.");
|
|
441
|
+
}
|
|
442
|
+
if (routingStopped) throw new Error(ROUTING_STOPPED_MESSAGE);
|
|
443
|
+
// Checked before a place in line is taken: an oversize payload costs nothing to refuse.
|
|
444
|
+
const stdin = `${JSON.stringify(input.payload)}\n`;
|
|
445
|
+
const inputCap = limits.inputBytes ?? DEFAULT_ROUTING_INPUT_BYTES;
|
|
446
|
+
const inputBytes = Buffer.byteLength(stdin);
|
|
447
|
+
if (inputBytes > inputCap) {
|
|
448
|
+
throw new Error(
|
|
449
|
+
`The routing script input is ${inputBytes} bytes, over the ${inputCap} byte limit; the script was not run.`,
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
// Paseo gives a plugin request the same 30 s as one script run, so time spent queued comes out
|
|
453
|
+
// of the run's own budget.
|
|
454
|
+
const startedAt = performance.now();
|
|
455
|
+
const budgetLeft = () => Math.floor(limits.timeoutMs - (performance.now() - startedAt));
|
|
456
|
+
|
|
457
|
+
// Take a place in line before the first await, so calls keep their arrival order however long
|
|
458
|
+
// each one's settings read and path check take, and the capacity check sees every earlier call.
|
|
459
|
+
const queued = routingInFlight > 0;
|
|
460
|
+
if (queued && routingWaiting >= MAX_QUEUED_ROUTING_CALLS) {
|
|
461
|
+
throw new Error(ROUTING_BUSY_MESSAGE);
|
|
462
|
+
}
|
|
463
|
+
const previous = routingTail;
|
|
464
|
+
const myTurn = Promise.withResolvers<void>();
|
|
465
|
+
routingTail = myTurn.promise;
|
|
466
|
+
routingInFlight += 1;
|
|
467
|
+
void myTurn.promise.then(() => {
|
|
468
|
+
routingInFlight -= 1;
|
|
469
|
+
});
|
|
470
|
+
let waiting = queued;
|
|
471
|
+
if (waiting) routingWaiting += 1;
|
|
472
|
+
const stopWaiting = () => {
|
|
473
|
+
if (!waiting) return;
|
|
474
|
+
waiting = false;
|
|
475
|
+
routingWaiting -= 1;
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
let run: ScriptRun;
|
|
479
|
+
try {
|
|
480
|
+
const preflight = async () => resolveRoutingScript((await readSettings()).routingScriptPath);
|
|
481
|
+
let scriptPath = await withinBudget(preflight(), budgetLeft(), ROUTING_PREFLIGHT_MESSAGE);
|
|
482
|
+
if (queued) {
|
|
483
|
+
try {
|
|
484
|
+
await withinBudget(previous, budgetLeft(), ROUTING_BUSY_MESSAGE);
|
|
485
|
+
} finally {
|
|
486
|
+
stopWaiting();
|
|
487
|
+
}
|
|
488
|
+
// The configuration may have changed while this call waited.
|
|
489
|
+
scriptPath = await withinBudget(preflight(), budgetLeft(), ROUTING_PREFLIGHT_MESSAGE);
|
|
490
|
+
}
|
|
491
|
+
const path = await withinBudget(
|
|
492
|
+
trustedScriptPath(undefined, limits.pathDirs),
|
|
493
|
+
budgetLeft(),
|
|
494
|
+
ROUTING_PREFLIGHT_MESSAGE,
|
|
495
|
+
);
|
|
496
|
+
// An empty PATH is not "no directories": the script's `env` lookup would search the current
|
|
497
|
+
// directory instead.
|
|
498
|
+
if (!path) throw new Error(NO_TRUSTED_PATH_MESSAGE);
|
|
499
|
+
// A call that was waiting or reading settings when the plugin stopped must not start a script.
|
|
500
|
+
if (routingStopped) throw new Error(ROUTING_STOPPED_MESSAGE);
|
|
501
|
+
// Taken last, after every await, so the script's own timer starts when the budget says. A first
|
|
502
|
+
// call has spent time on its settings read and path checks too, so it is trimmed like a queued one.
|
|
503
|
+
const remaining = budgetLeft();
|
|
504
|
+
if (remaining <= 0) throw new Error(queued ? ROUTING_BUSY_MESSAGE : ROUTING_PREFLIGHT_MESSAGE);
|
|
505
|
+
run = startScriptCapped(scriptPath, stdin, { ...limits, timeoutMs: remaining }, path);
|
|
506
|
+
} catch (error) {
|
|
507
|
+
// This call never ran: pass the turn on once the one in front is done, so the order holds.
|
|
508
|
+
stopWaiting();
|
|
509
|
+
void previous.then(() => myTurn.resolve());
|
|
510
|
+
throw error;
|
|
511
|
+
}
|
|
512
|
+
activeRun = run;
|
|
513
|
+
void run.finished.then(() => {
|
|
514
|
+
if (activeRun === run) activeRun = undefined;
|
|
515
|
+
myTurn.resolve();
|
|
516
|
+
});
|
|
517
|
+
const stdout = await run.result;
|
|
518
|
+
|
|
519
|
+
if (!stdout) return {};
|
|
520
|
+
const parsed = JSON.parse(stdout) as unknown;
|
|
521
|
+
return RoutingScriptResultSchema.parse(parsed);
|
|
522
|
+
}
|
package/server/viewer-scope.ts
CHANGED
|
@@ -200,16 +200,21 @@ async function searchIssues(
|
|
|
200
200
|
"--order=desc",
|
|
201
201
|
`--json=${fields}`,
|
|
202
202
|
]);
|
|
203
|
-
const parsed = JSON.parse(output);
|
|
204
|
-
return {
|
|
205
|
-
|
|
206
|
-
failed: false,
|
|
207
|
-
};
|
|
203
|
+
const parsed: unknown = JSON.parse(output);
|
|
204
|
+
if (!Array.isArray(parsed)) return { records: [], failed: true };
|
|
205
|
+
return { records: parsed as IssueSearchRecord[], failed: false };
|
|
208
206
|
} catch {
|
|
209
207
|
return { records: [], failed: true };
|
|
210
208
|
}
|
|
211
209
|
}
|
|
212
210
|
|
|
211
|
+
/** When one issue matches several searches it is shown under the highest-ranked role. */
|
|
212
|
+
const ISSUE_ROLE_RANK: Record<GitHubIssueItem["role"], number> = {
|
|
213
|
+
owner: 0,
|
|
214
|
+
assignee: 1,
|
|
215
|
+
author: 2,
|
|
216
|
+
};
|
|
217
|
+
|
|
213
218
|
function toIssueItem(record: IssueSearchRecord, role: GitHubIssueItem["role"]): GitHubIssueItem {
|
|
214
219
|
const labels = record.labels.map(({ name }) => name);
|
|
215
220
|
const authorKind =
|
|
@@ -474,14 +479,27 @@ interface Snapshot {
|
|
|
474
479
|
reviewRequestedScope: string[];
|
|
475
480
|
inboxItems: GitHubInboxItem[];
|
|
476
481
|
issueItems: GitHubIssueItem[];
|
|
482
|
+
/** Every role whose search returned each issue; a row shows only the highest-ranked one. */
|
|
483
|
+
issueRoles: Map<string, Set<GitHubIssueItem["role"]>>;
|
|
477
484
|
issueTruncated: boolean;
|
|
478
485
|
issueSearchFailures: number;
|
|
486
|
+
/** When each role's issue search last succeeded (ms); a role's kept issues age from here. */
|
|
487
|
+
issueFreshAt: Record<GitHubIssueItem["role"], number>;
|
|
488
|
+
/** Whether each role's list hit the search cap; a kept role keeps its flag. */
|
|
489
|
+
issueTruncatedBy: Record<GitHubIssueItem["role"], boolean>;
|
|
479
490
|
enrichmentFailures: number;
|
|
480
491
|
acknowledgedAt: string | null;
|
|
481
492
|
}
|
|
482
493
|
|
|
483
|
-
/**
|
|
484
|
-
|
|
494
|
+
/**
|
|
495
|
+
* The expensive part: ~5 s of gh searches and GraphQL enrichment. `previous` is the window's last
|
|
496
|
+
* snapshot: a failed issue search keeps its role's share of the issues it held, since an empty
|
|
497
|
+
* answer from a failed call says nothing about the issues. Only for the same viewer, and only
|
|
498
|
+
* while that role's last good search is within MAX_STALE_MS, so failures cannot hide behind old
|
|
499
|
+
* data forever (the coverage note keeps reporting them). A snapshot holding kept issues can still
|
|
500
|
+
* be served for up to MAX_STALE_MS more if the refreshes after it throw outright.
|
|
501
|
+
*/
|
|
502
|
+
async function fetchSnapshot(windowDays: number, previous?: Snapshot): Promise<Snapshot> {
|
|
485
503
|
const viewer = await viewerLogin();
|
|
486
504
|
const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1_000).toISOString().slice(0, 10);
|
|
487
505
|
const [
|
|
@@ -502,15 +520,64 @@ async function fetchSnapshot(windowDays: number): Promise<Snapshot> {
|
|
|
502
520
|
searchIssues("owner", viewer, since),
|
|
503
521
|
]);
|
|
504
522
|
const issueMap = new Map<string, GitHubIssueItem>();
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
const
|
|
511
|
-
|
|
512
|
-
assignedIssues
|
|
513
|
-
|
|
523
|
+
const issueRoles = new Map<string, Set<GitHubIssueItem["role"]>>();
|
|
524
|
+
const addRole = (id: string, role: GitHubIssueItem["role"]) => {
|
|
525
|
+
const roles = issueRoles.get(id) ?? new Set<GitHubIssueItem["role"]>();
|
|
526
|
+
issueRoles.set(id, roles.add(role));
|
|
527
|
+
};
|
|
528
|
+
for (const [role, result] of [
|
|
529
|
+
["owner", ownedIssues],
|
|
530
|
+
["assignee", assignedIssues],
|
|
531
|
+
["author", authoredIssues],
|
|
532
|
+
] as const) {
|
|
533
|
+
for (const record of result.records) {
|
|
534
|
+
issueMap.set(record.id, toIssueItem(record, role));
|
|
535
|
+
addRole(record.id, role);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
const searchedAt = Date.now();
|
|
539
|
+
const kept = previous?.viewer === viewer ? previous : undefined;
|
|
540
|
+
const searches = [
|
|
541
|
+
["author", authoredIssues],
|
|
542
|
+
["assignee", assignedIssues],
|
|
543
|
+
["owner", ownedIssues],
|
|
544
|
+
] as const;
|
|
545
|
+
const issueFreshAt = { author: 0, assignee: 0, owner: 0 };
|
|
546
|
+
const issueTruncatedBy = { author: false, assignee: false, owner: false };
|
|
547
|
+
const keptRoles = new Set<GitHubIssueItem["role"]>();
|
|
548
|
+
for (const [role, result] of searches) {
|
|
549
|
+
if (!result.failed) {
|
|
550
|
+
issueFreshAt[role] = searchedAt;
|
|
551
|
+
issueTruncatedBy[role] = result.records.length === SEARCH_LIMIT;
|
|
552
|
+
} else if (kept) {
|
|
553
|
+
issueFreshAt[role] = kept.issueFreshAt[role];
|
|
554
|
+
if (searchedAt - issueFreshAt[role] <= MAX_STALE_MS) {
|
|
555
|
+
keptRoles.add(role);
|
|
556
|
+
issueTruncatedBy[role] = kept.issueTruncatedBy[role];
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
// A kept row keeps every role it matched whose search failed. A role whose search succeeded
|
|
561
|
+
// without it has dropped it, but another failed role's search may still hold it.
|
|
562
|
+
for (const item of kept?.issueItems ?? []) {
|
|
563
|
+
let held = false;
|
|
564
|
+
for (const role of kept?.issueRoles.get(item.id) ?? [item.role]) {
|
|
565
|
+
if (!keptRoles.has(role)) continue;
|
|
566
|
+
addRole(item.id, role);
|
|
567
|
+
held = true;
|
|
568
|
+
}
|
|
569
|
+
// Fresh fields win over the kept row's.
|
|
570
|
+
if (held && !issueMap.has(item.id)) issueMap.set(item.id, item);
|
|
571
|
+
}
|
|
572
|
+
// The row shows the highest-ranked role among all that matched.
|
|
573
|
+
for (const [id, item] of issueMap) {
|
|
574
|
+
const roles = [...(issueRoles.get(id) ?? [item.role])];
|
|
575
|
+
const role = roles.reduce((best, next) =>
|
|
576
|
+
ISSUE_ROLE_RANK[next] > ISSUE_ROLE_RANK[best] ? next : best,
|
|
577
|
+
);
|
|
578
|
+
issueMap.set(id, { ...item, role });
|
|
579
|
+
}
|
|
580
|
+
const issueTruncated = Object.values(issueTruncatedBy).some(Boolean);
|
|
514
581
|
const issueSearchFailures = [authoredIssues, assignedIssues, ownedIssues].filter(
|
|
515
582
|
(res) => res.failed,
|
|
516
583
|
).length;
|
|
@@ -574,8 +641,11 @@ async function fetchSnapshot(windowDays: number): Promise<Snapshot> {
|
|
|
574
641
|
reviewRequestedScope,
|
|
575
642
|
inboxItems,
|
|
576
643
|
issueItems,
|
|
644
|
+
issueRoles,
|
|
577
645
|
issueTruncated,
|
|
578
646
|
issueSearchFailures,
|
|
647
|
+
issueFreshAt,
|
|
648
|
+
issueTruncatedBy,
|
|
579
649
|
enrichmentFailures: enrichment.failures,
|
|
580
650
|
acknowledgedAt,
|
|
581
651
|
};
|
|
@@ -598,7 +668,7 @@ export function projectSnapshot(snapshot: Snapshot, urls: string[]): ViewerScope
|
|
|
598
668
|
}
|
|
599
669
|
if (snapshot.issueSearchFailures > 0) {
|
|
600
670
|
notes.push(
|
|
601
|
-
`${snapshot.issueSearchFailures} GitHub issue search request${snapshot.issueSearchFailures === 1 ? "" : "s"} failed; issue list may be incomplete.`,
|
|
671
|
+
`${snapshot.issueSearchFailures} GitHub issue search request${snapshot.issueSearchFailures === 1 ? "" : "s"} failed; issue list may be stale or incomplete.`,
|
|
602
672
|
);
|
|
603
673
|
}
|
|
604
674
|
const coverageNote =
|
|
@@ -663,7 +733,7 @@ function refreshWindow(windowDays: number): Promise<Snapshot> {
|
|
|
663
733
|
const running = inflight.get(windowDays);
|
|
664
734
|
if (running) return running;
|
|
665
735
|
const started = Date.now();
|
|
666
|
-
const promise = fetchSnapshot(windowDays)
|
|
736
|
+
const promise = fetchSnapshot(windowDays, snapshots.get(windowDays)?.snapshot)
|
|
667
737
|
.then((snapshot) => {
|
|
668
738
|
snapshots.set(windowDays, { snapshot, at: Date.now() });
|
|
669
739
|
console.log(
|
|
@@ -720,6 +790,12 @@ export async function resolveViewerScope({
|
|
|
720
790
|
}
|
|
721
791
|
}
|
|
722
792
|
|
|
793
|
+
/** Test seam: waits for running refreshes to finish, keeping the cache. */
|
|
794
|
+
export async function settleViewerScopeRefreshes(): Promise<void> {
|
|
795
|
+
await Promise.allSettled([...inflight.values()]);
|
|
796
|
+
await stateQueue;
|
|
797
|
+
}
|
|
798
|
+
|
|
723
799
|
/** Test seam: waits for running refreshes so tests do not bleed into each other. */
|
|
724
800
|
export async function resetViewerScopeCache(): Promise<void> {
|
|
725
801
|
await Promise.allSettled([...inflight.values()]);
|