@antelopejs/dms 0.18.2 → 0.19.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +1 -1
  3. package/bin/control/backend.mjs +1 -1
  4. package/bin/control/base.mjs +24 -9
  5. package/bin/control/base.test.mjs +88 -0
  6. package/bin/control/browser-client.mjs +1 -1
  7. package/bin/control/commands-stack.mjs +3 -1
  8. package/bin/control/consumer-install.test.mjs +73 -0
  9. package/bin/control/database.mjs +66 -0
  10. package/bin/control/doctor.mjs +7 -0
  11. package/bin/control/frontend-check.mjs +2 -1
  12. package/bin/control/frontend-mode.test.mjs +24 -0
  13. package/bin/control/identity.mjs +45 -16
  14. package/bin/control/journey.mjs +31 -3
  15. package/bin/control/journey.test.mjs +207 -2
  16. package/bin/control/launch.mjs +123 -0
  17. package/bin/control/module-root.mjs +40 -0
  18. package/bin/control/module-root.test.mjs +67 -0
  19. package/bin/control/mongo-server.test.mjs +91 -0
  20. package/bin/control/mongo.mjs +125 -12
  21. package/bin/control/options.mjs +1 -0
  22. package/bin/control/pid-reuse.test.mjs +278 -0
  23. package/bin/control/processes.mjs +91 -29
  24. package/bin/control/renderer.test.mjs +1 -1
  25. package/bin/control/run-copy.mjs +6 -1
  26. package/bin/control/run-state.mjs +4 -1
  27. package/bin/control/stack.mjs +78 -165
  28. package/bin/control/verify/behaviour.test.mjs +36 -23
  29. package/bin/control/verify/decode.mjs +1 -0
  30. package/bin/control/verify/emit.mjs +11 -11
  31. package/bin/control/verify/formal.mjs +28 -14
  32. package/bin/control/verify/formal.test.mjs +15 -0
  33. package/bin/control/verify/types.mjs +1 -1
  34. package/bin/dms-control.mjs +4 -2
  35. package/dist/db/models/userNotifications.model.js +14 -8
  36. package/dist/db/models/userNotifications.model.js.map +1 -1
  37. package/dist/pages/public/auth/not-a-member.d.ts +9 -0
  38. package/dist/pages/public/auth/not-a-member.js +27 -0
  39. package/dist/pages/public/auth/not-a-member.js.map +1 -0
  40. package/dist/pages/public/index.d.ts +1 -0
  41. package/dist/pages/public/index.js +1 -0
  42. package/dist/pages/public/index.js.map +1 -1
  43. package/dist/routes/auth/oauth/identity-resolution.js +10 -0
  44. package/dist/routes/auth/oauth/identity-resolution.js.map +1 -1
  45. package/dist/routes/onboarding.js +1 -5
  46. package/dist/routes/onboarding.js.map +1 -1
  47. package/dist/utils/ensure-default-tenant.js +23 -3
  48. package/dist/utils/ensure-default-tenant.js.map +1 -1
  49. package/frontend-vue/layers/dms-auth/app/build/utils/noWorkspaceRoute.ts +19 -0
  50. package/frontend-vue/layers/dms-auth/app/custom-pages/auth/login.vue +4 -6
  51. package/frontend-vue/layers/dms-auth/app/custom-pages/auth/not-a-member.vue +21 -0
  52. package/frontend-vue/layers/dms-auth/app/custom-pages/auth/oauth-complete.vue +2 -4
  53. package/frontend-vue/layers/dms-auth/i18n/locales/auth-en-GB.json +6 -0
  54. package/frontend-vue/layers/dms-auth/i18n/locales/auth-fr-FR.json +6 -0
  55. package/frontend-vue/layers/dms-core/app/types/live.ts +2 -0
  56. package/frontend-vue/layers/dms-ui/app/build/components/containers/drawer/DynamicDrawer.vue +9 -3
  57. package/frontend-vue/layers/dms-ui/app/build/composables/live/currentPageLive.ts +7 -0
  58. package/frontend-vue/layers/dms-ui/app/build/composables/live/pageLiveController.ts +23 -3
  59. package/frontend-vue/layers/dms-ui/app/build/composables/live/usePageDataRefresh.ts +2 -1
  60. package/frontend-vue/layers/dms-ui/app/build/composables/table-view/tableViewRealtime.ts +21 -2
  61. package/frontend-vue/layers/dms-ui/app/build/composables/table-view/useTableLiveHold.ts +4 -3
  62. package/frontend-vue/layers/dms-ui/app/build/utils/accessibilityPreferences.ts +1 -21
  63. package/frontend-vue/layers/dms-ui/app/build/utils/blockPreview.ts +8 -4
  64. package/frontend-vue/layers/dms-ui/app/build/utils/link.ts +35 -7
  65. package/frontend-vue/layers/dms-ui/app/components/chart/ApexChartHost.vue +51 -8
  66. package/frontend-vue/layers/dms-ui/app/composables/chart/useApexChart.ts +1 -1
  67. package/frontend-vue/layers/dms-ui/app/utils/reducedMotion.ts +22 -0
  68. package/package.json +4 -4
  69. package/skills/dms-pages/REFERENCE.md +1 -1
@@ -2,9 +2,23 @@ import { spawnSync } from "node:child_process";
2
2
  import { mkdirSync } from "node:fs";
3
3
  import { createRequire } from "node:module";
4
4
  import { join } from "node:path";
5
+ import { setTimeout as sleep } from "node:timers/promises";
5
6
  import { pathToFileURL } from "node:url";
6
- import { arrayOf, decode, isRecord, isString, objectOf } from "./json.mjs";
7
- import { freePort, startDetached, waitForPort } from "./processes.mjs";
7
+ import {
8
+ arrayOf,
9
+ decode,
10
+ isBoolean,
11
+ isRecord,
12
+ isString,
13
+ objectOf,
14
+ recordOf,
15
+ } from "./json.mjs";
16
+ import {
17
+ freePort,
18
+ startDetached,
19
+ stopRecorded,
20
+ waitForOwnPort,
21
+ } from "./processes.mjs";
8
22
 
9
23
  /**
10
24
  * @typedef {(...args: unknown[]) => unknown} Callable A function whose result is read as `unknown`
@@ -12,11 +26,19 @@ import { freePort, startDetached, waitForPort } from "./processes.mjs";
12
26
  * @typedef {{ connect: Callable, close: Callable, db: Callable }} Client The calls made on a driver client
13
27
  * @typedef {{ admin: Callable, dropDatabase: Callable }} Database The calls made on a driver database
14
28
  * @typedef {{ listDatabases: Callable }} Admin The call made on a driver's admin handle
29
+ * @typedef {{ command: Callable }} Commander The call that runs a server command on a driver's admin handle
15
30
  */
16
31
 
17
32
  /** The server version the backend test harness pins, already cached by it. */
18
33
  const MONGO_VERSION = "8.0.8";
19
34
  const READY_TIMEOUT_MS = 30_000;
35
+ const PRIMARY_POLL_MS = 100;
36
+
37
+ /** The code mongod answers `replSetInitiate` with when its data folder already holds the set, as on a restart. */
38
+ const ALREADY_INITIALIZED = 23;
39
+
40
+ /** The single-node replica set the run's mongod serves, so change streams work on it. */
41
+ const REPLICA_SET = "dms-control";
20
42
 
21
43
  /**
22
44
  * @param {unknown} value
@@ -100,10 +122,30 @@ function isAdmin(value) {
100
122
  );
101
123
  }
102
124
 
125
+ /**
126
+ * @param {unknown} value
127
+ * @returns {value is Commander} True for an object with a `command` function
128
+ */
129
+ function isCommander(value) {
130
+ return isObjectLike(value) && "command" in value && isCallable(value.command);
131
+ }
132
+
103
133
  const isDatabaseList = objectOf({
104
134
  databases: arrayOf(objectOf({ name: isString })),
105
135
  });
106
136
 
137
+ const isHello = objectOf({ isWritablePrimary: isBoolean });
138
+
139
+ /**
140
+ * @param {unknown} error
141
+ * @returns {boolean} True for the answer of a mongod whose replica set is already initiated
142
+ */
143
+ function isAlreadyInitialized(error) {
144
+ return (
145
+ isObjectLike(error) && "code" in error && error.code === ALREADY_INITIALIZED
146
+ );
147
+ }
148
+
107
149
  /**
108
150
  * @param {unknown} namespace A module namespace
109
151
  * @returns {Record<string, unknown>} Its exports, with those of a CommonJS `default` added
@@ -123,7 +165,7 @@ function withDefaultExports(namespace) {
123
165
  * @param {string} name The package name
124
166
  * @param {string[]} from Folders to resolve from, in order
125
167
  * @returns {Promise<Record<string, unknown>>} The module namespace
126
- * @throws When no folder resolves it, saying which devDependency to add
168
+ * @throws When no folder resolves it, saying how to install it
127
169
  */
128
170
  async function importNamespace(name, from) {
129
171
  for (const folder of from) {
@@ -138,9 +180,28 @@ async function importNamespace(name, from) {
138
180
  continue;
139
181
  }
140
182
  }
141
- throw new Error(
142
- `dms-control needs ${name}: add it to the playground's devDependencies.`,
183
+ throw new Error(missingPackage(name));
184
+ }
185
+
186
+ /**
187
+ * What to do about a package no folder resolves. A package that
188
+ * `@antelopejs/dms` declares optional was skipped by the install, so the
189
+ * message names the command that adds it at the declared range.
190
+ *
191
+ * @param {string} name The package name
192
+ * @returns {string} The error message
193
+ */
194
+ function missingPackage(name) {
195
+ const { optionalDependencies } = decode(
196
+ objectOf({ optionalDependencies: recordOf(isString) }),
197
+ createRequire(import.meta.url)("../../package.json"),
198
+ "@antelopejs/dms package.json",
199
+ "optionalDependencies of version ranges",
143
200
  );
201
+ if (!Object.hasOwn(optionalDependencies, name))
202
+ return `dms-control needs ${name}: add it to the playground's devDependencies.`;
203
+ const spec = `${name}@${optionalDependencies[name]}`;
204
+ return `dms-control needs ${name}, an optional dependency of @antelopejs/dms that this install skipped: run \`npm install --save-dev ${spec}\` (or \`pnpm add --save-dev ${spec}\`) in the module that runs dms-control.`;
144
205
  }
145
206
 
146
207
  /**
@@ -151,7 +212,7 @@ async function importNamespace(name, from) {
151
212
  * @param {string} name The package name
152
213
  * @param {string[]} from Folders to resolve from, in order
153
214
  * @returns {Promise<any>} The module namespace
154
- * @throws When no folder resolves it, saying which devDependency to add
215
+ * @throws When no folder resolves it, saying how to install it
155
216
  */
156
217
  export async function importFrom(name, from) {
157
218
  return importNamespace(name, from);
@@ -188,16 +249,19 @@ export async function mongodBinary(from) {
188
249
  }
189
250
 
190
251
  /**
191
- * Starts a mongod owned by the run, on a free port, with its data under the
192
- * run folder.
252
+ * Starts a mongod owned by the run, on `port` or a free one, with its data
253
+ * under the run folder, as the only member of a replica set, so change
254
+ * streams work. A mongod that does not become primary is stopped before the
255
+ * error is thrown.
193
256
  *
194
257
  * @param {{ mongo: string, logs: string }} paths The run's folders
195
258
  * @param {string[]} from Folders to resolve mongodb-memory-server-core from
196
- * @returns {Promise<{ url: string, record: ReturnType<typeof startDetached> }>} Its URL and process record
259
+ * @param {number} [port] The port, which a restart keeps so the backend's URL still reaches it
260
+ * @returns {Promise<{ url: string, record: ReturnType<typeof startDetached> & { port: number } }>} Its URL and process record
197
261
  */
198
- export async function startMongod(paths, from) {
262
+ export async function startMongod(paths, from, port) {
199
263
  const binary = await mongodBinary(from);
200
- const port = await freePort();
264
+ port ??= await freePort();
201
265
  mkdirSync(paths.mongo, { recursive: true });
202
266
  const record = startDetached({
203
267
  name: "mongod",
@@ -209,12 +273,20 @@ export async function startMongod(paths, from) {
209
273
  String(port),
210
274
  "--bind_ip",
211
275
  "127.0.0.1",
276
+ "--replSet",
277
+ REPLICA_SET,
212
278
  ],
213
279
  cwd: paths.mongo,
214
280
  env: process.env,
215
281
  logs: paths.logs,
216
282
  });
217
- await waitForPort(port, record, READY_TIMEOUT_MS);
283
+ try {
284
+ await waitForOwnPort(port, record, READY_TIMEOUT_MS);
285
+ await initiateReplicaSet(port, from);
286
+ } catch (error) {
287
+ await stopRecorded([record]);
288
+ throw error;
289
+ }
218
290
  return { url: `mongodb://127.0.0.1:${port}`, record: { ...record, port } };
219
291
  }
220
292
 
@@ -288,6 +360,47 @@ async function withClient(url, from, use) {
288
360
  }
289
361
  }
290
362
 
363
+ /**
364
+ * Makes the mongod on `port` the only member of the replica set, unless its
365
+ * data folder already holds the set, and waits until it accepts writes.
366
+ *
367
+ * @param {number} port The port of the mongod
368
+ * @param {string[]} from Folders to resolve the driver from
369
+ * @returns {Promise<void>} Resolves once the member is primary
370
+ * @throws When it is not primary within the startup timeout
371
+ */
372
+ function initiateReplicaSet(port, from) {
373
+ const url = `mongodb://127.0.0.1:${port}/?directConnection=true`;
374
+ return withClient(url, from, async (client) => {
375
+ /** @type {unknown} */
376
+ const admin = databaseOf(client, "admin").admin();
377
+ if (!isCommander(admin))
378
+ throw new TypeError("The admin handle of the driver has no command");
379
+ try {
380
+ await admin.command({
381
+ replSetInitiate: {
382
+ _id: REPLICA_SET,
383
+ members: [{ _id: 0, host: `127.0.0.1:${port}` }],
384
+ },
385
+ });
386
+ } catch (error) {
387
+ if (!isAlreadyInitialized(error)) throw error;
388
+ }
389
+ const deadline = Date.now() + READY_TIMEOUT_MS;
390
+ while (Date.now() < deadline) {
391
+ const hello = decode(
392
+ isHello,
393
+ await admin.command({ hello: 1 }),
394
+ "hello",
395
+ "the state of a replica set member",
396
+ );
397
+ if (hello.isWritablePrimary) return;
398
+ await sleep(PRIMARY_POLL_MS);
399
+ }
400
+ throw new Error(`mongod on ${port} did not become primary`);
401
+ });
402
+ }
403
+
291
404
  /**
292
405
  * Drops every database whose name starts with the run's prefix, through the
293
406
  * MongoDB driver that mongodb-memory-server-core depends on, or the
@@ -5,6 +5,7 @@ export const OPTIONS = /** @type {const} */ ({
5
5
  prepare: { type: "boolean" },
6
6
  "no-standby": { type: "boolean" },
7
7
  "no-build-cache": { type: "boolean" },
8
+ "dev-frontend": { type: "boolean" },
8
9
  playground: { type: "string" },
9
10
  renderer: { type: "string" },
10
11
  runs: { type: "string" },
@@ -0,0 +1,278 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawnSync } from "node:child_process";
3
+ import test from "node:test";
4
+ import { decode, isBoolean, isNumber, objectOf } from "./json.mjs";
5
+
6
+ const NESTED_TIMEOUT_MS = 60_000;
7
+
8
+ /** The imports, helpers and signal recorder every nested script shares. `run(sh)` starts `sh` leading a group of its own and returns it with the pid of the `sleep` it starts in the background; `gone(pid)` waits until the pid is free; `recordSignalsTo(pid)` records instead of sends every signal aimed at it. */
9
+ const PRELUDE = `
10
+ import fs, { mkdtempSync, writeFileSync } from "node:fs";
11
+ import { spawn } from "node:child_process";
12
+ import { tmpdir } from "node:os";
13
+ import { setTimeout as sleep } from "node:timers/promises";
14
+ import { syncBuiltinESMExports } from "node:module";
15
+ import { createInterface } from "node:readline";
16
+ const [control, mode] = process.argv.slice(1);
17
+ const { killRecorded, stopRecorded } = await import(control + "/processes.mjs");
18
+ const { isRunning, startTimeOf } = await import(control + "/identity.mjs");
19
+ const realKill = process.kill.bind(process);
20
+ const { readdirSync, readFileSync } = fs;
21
+ const run = async (script) => {
22
+ const shell = spawn("sh", ["-c", script], { detached: true, stdio: ["ignore", "pipe", "ignore"] });
23
+ const lines = createInterface({ input: shell.stdout })[Symbol.asyncIterator]();
24
+ return { shell, child: Number((await lines.next()).value) };
25
+ };
26
+ const gone = (pid) => {
27
+ const deadline = Date.now() + 5000;
28
+ while (fs.existsSync("/proc/" + pid) && Date.now() < deadline);
29
+ };
30
+ const nextPid = (pid) => writeFileSync("/proc/sys/kernel/ns_last_pid", String(pid - 1));
31
+ const recordSignalsTo = (target) => {
32
+ const signals = [];
33
+ process.kill = (pid, signal) => {
34
+ if (Math.abs(pid) !== target || signal === 0) return realKill(pid, signal);
35
+ signals.push(signal);
36
+ return true;
37
+ };
38
+ return signals;
39
+ };
40
+ const REAPER = "sleep 60 & echo $!; wait; exec sleep 60";
41
+ `;
42
+
43
+ /**
44
+ * A shell runs `sleep`, the victim, and reaps it. The run records the
45
+ * victim (`root`) or the shell (`child`), at least ten clock ticks before
46
+ * the new process starts, so their start times differ. Inside
47
+ * `killRecorded` the victim dies and a new process takes its pid: in `root`
48
+ * mode when the walk lists /proc, in `child` mode after the second read of
49
+ * the victim's stat, once the tree is read and confirmed.
50
+ */
51
+ const TAKE_PID = `${PRELUDE}
52
+ const { shell, child: victim } = await run(REAPER);
53
+ const recordedPid = mode === "root" ? victim : shell.pid;
54
+ const record = { pid: recordedPid, startTime: startTimeOf(recordedPid) };
55
+ await sleep(100);
56
+ let taker;
57
+ let reads = 0;
58
+ const takePid = () => {
59
+ if (taker) return;
60
+ realKill(victim, "SIGKILL");
61
+ gone(victim);
62
+ nextPid(victim);
63
+ taker = spawn("sleep", ["60"], { stdio: "ignore" });
64
+ };
65
+ fs.readdirSync = (path, ...rest) => {
66
+ if (mode === "root" && path === "/proc") takePid();
67
+ return readdirSync(path, ...rest);
68
+ };
69
+ fs.readFileSync = (path, ...rest) => {
70
+ const read = readFileSync(path, ...rest);
71
+ if (mode === "child" && path === "/proc/" + victim + "/stat" && ++reads === 2) takePid();
72
+ return read;
73
+ };
74
+ syncBuiltinESMExports();
75
+ const signals = recordSignalsTo(victim);
76
+ await killRecorded([record]).catch(() => []);
77
+ console.log(JSON.stringify({ taken: taker?.pid === victim, signals: signals.length, running: isRunning(victim) }));
78
+ process.exit(0);
79
+ `;
80
+
81
+ /**
82
+ * The run records a shell whose child is a member of its tree; an unrelated
83
+ * shell has a child at pid 96, which the walk reads after the member since
84
+ * /proc lists in string order. Right after the walk reads the member's
85
+ * stat, both children die, a newcomer takes the member's pid and forks a
86
+ * child that takes pid 96, so the walk finds that child under the member's
87
+ * pid.
88
+ */
89
+ const LINK_CHILD = `${PRELUDE}
90
+ const { shell, child: member } = await run(REAPER);
91
+ nextPid(95);
92
+ const { child: foreign } = await run(REAPER);
93
+ const record = { pid: shell.pid, startTime: startTimeOf(shell.pid) };
94
+ await sleep(100);
95
+ const dir = mkdtempSync(tmpdir() + "/pid-reuse-");
96
+ let newcomer;
97
+ let parent;
98
+ fs.readFileSync = (path, ...rest) => {
99
+ const read = readFileSync(path, ...rest);
100
+ if (!newcomer && path === "/proc/" + member + "/stat") {
101
+ realKill(member, "SIGKILL");
102
+ gone(member);
103
+ realKill(foreign, "SIGKILL");
104
+ gone(foreign);
105
+ nextPid(member);
106
+ newcomer = spawn("sh", ["-c", "while [ ! -e " + dir + "/go ]; do :; done; sleep 60 & wait"], { stdio: "ignore" });
107
+ nextPid(foreign);
108
+ writeFileSync(dir + "/go", "");
109
+ const deadline = Date.now() + 5000;
110
+ while (!fs.existsSync("/proc/" + foreign) && Date.now() < deadline);
111
+ parent = Number(readFileSync("/proc/" + foreign + "/stat", "utf8").split(") ")[1].split(" ")[1]);
112
+ }
113
+ return read;
114
+ };
115
+ syncBuiltinESMExports();
116
+ const signals = recordSignalsTo(foreign);
117
+ await killRecorded([record]).catch(() => []);
118
+ console.log(JSON.stringify({ linked: newcomer?.pid === member && parent === member, signals: signals.length }));
119
+ process.exit(0);
120
+ `;
121
+
122
+ /**
123
+ * The run records a shell that starts a group leader and never reaps it:
124
+ * the leader starts `sleep` in its group and exits, so it stays a zombie
125
+ * and its `sleep` moves to pid 1, out of the tree the walk finds. Only the
126
+ * signal to the leader's group reaches that `sleep`.
127
+ */
128
+ const ZOMBIE_LEADER = `${PRELUDE}
129
+ const { shell, child: member } = await run("setsid sh -c 'sleep 60 & echo $!; exit 0' & exec sleep 60");
130
+ const record = { pid: shell.pid, startTime: startTimeOf(shell.pid) };
131
+ await sleep(300);
132
+ const leader = Number(readFileSync("/proc/" + member + "/stat", "utf8").split(") ")[1].split(" ")[2]);
133
+ const zombie = readFileSync("/proc/" + leader + "/stat", "utf8").split(") ")[1].startsWith("Z");
134
+ await (mode === "stop" ? stopRecorded : killRecorded)([record]);
135
+ await sleep(200);
136
+ console.log(JSON.stringify({ zombie, running: isRunning(member) }));
137
+ process.exit(0);
138
+ `;
139
+
140
+ /**
141
+ * Runs where /proc is hidden behind an empty mount, as on a system with no
142
+ * /proc: the run records one group leader twice, as two records with its
143
+ * pid.
144
+ */
145
+ const TWICE_WITHOUT_PROC = `${PRELUDE}
146
+ const { child } = await run("echo $$; exec sleep 60");
147
+ const signals = [];
148
+ process.kill = (pid, signal) => {
149
+ if (Math.abs(pid) === child && signal !== 0) signals.push(signal);
150
+ return realKill(pid, signal);
151
+ };
152
+ const startedAt = new Date().toISOString();
153
+ const lines = await killRecorded([{ pid: child, startedAt }, { pid: child, startedAt }]);
154
+ console.log(JSON.stringify({ lines: lines.length, signals: signals.length }));
155
+ process.exit(0);
156
+ `;
157
+
158
+ const isTakeReport = objectOf({
159
+ taken: isBoolean,
160
+ signals: isNumber,
161
+ running: isBoolean,
162
+ });
163
+
164
+ const isLinkReport = objectOf({ linked: isBoolean, signals: isNumber });
165
+
166
+ const isZombieReport = objectOf({ zombie: isBoolean, running: isBoolean });
167
+
168
+ const isTwiceReport = objectOf({ lines: isNumber, signals: isNumber });
169
+
170
+ /** @returns {boolean} True where the test may make a user and PID namespace */
171
+ function canUnshare() {
172
+ return (
173
+ spawnSync("unshare", ["-Ur", "--fork", "--pid", "--mount-proc", "true"])
174
+ .status === 0
175
+ );
176
+ }
177
+
178
+ /**
179
+ * Runs a nested script as pid 1 of a PID namespace of its own, so the pid
180
+ * it frees is the next one the kernel gives, and decodes the one line it
181
+ * prints. In mode `no-proc`, /proc is hidden behind an empty mount instead.
182
+ *
183
+ * @template T
184
+ * @param {string} script The script
185
+ * @param {string} mode Its mode argument
186
+ * @param {import("./json.mjs").Guard<T>} guard The shape of its report
187
+ * @returns {T} Its report
188
+ */
189
+ function nested(script, mode, guard) {
190
+ const namespace =
191
+ mode === "no-proc"
192
+ ? ["--mount", "sh", "-c", 'mount -t tmpfs none /proc && exec "$@"', "sh"]
193
+ : ["--mount-proc"];
194
+ const result = spawnSync(
195
+ "unshare",
196
+ [
197
+ "-Ur",
198
+ "--fork",
199
+ "--pid",
200
+ ...namespace,
201
+ process.execPath,
202
+ "--input-type=module",
203
+ "-e",
204
+ script,
205
+ import.meta.dirname,
206
+ mode,
207
+ ],
208
+ { encoding: "utf8", timeout: NESTED_TIMEOUT_MS },
209
+ );
210
+ assert.equal(result.status, 0, result.stderr);
211
+ /** @type {unknown} */
212
+ const parsed = JSON.parse(result.stdout);
213
+ return decode(guard, parsed, "the nested script", "a report");
214
+ }
215
+
216
+ const options = {
217
+ skip: !canUnshare() && "this host does not let the test make a PID namespace",
218
+ timeout: NESTED_TIMEOUT_MS,
219
+ };
220
+
221
+ await test(
222
+ "killRecorded sends no signal to a process that took a recorded pid after the record was checked; a version that reads the start time again after the check kills it",
223
+ options,
224
+ () => {
225
+ assert.deepEqual(nested(TAKE_PID, "root", isTakeReport), {
226
+ taken: true,
227
+ signals: 0,
228
+ running: true,
229
+ });
230
+ },
231
+ );
232
+
233
+ await test(
234
+ "killRecorded sends no signal to a process that took a descendant's pid after the tree was read and confirmed; a version that does not check its start time again right before the signal kills it",
235
+ options,
236
+ () => {
237
+ assert.deepEqual(nested(TAKE_PID, "child", isTakeReport), {
238
+ taken: true,
239
+ signals: 0,
240
+ running: true,
241
+ });
242
+ },
243
+ );
244
+
245
+ await test(
246
+ "killRecorded sends no signal to a child forked by a process that took the pid of a tree member while the tree was read; a version that does not confirm the tree after the walk kills it",
247
+ options,
248
+ () => {
249
+ assert.deepEqual(nested(LINK_CHILD, "kill", isLinkReport), {
250
+ linked: true,
251
+ signals: 0,
252
+ });
253
+ },
254
+ );
255
+
256
+ for (const mode of ["kill", "stop"]) {
257
+ await test(
258
+ `${mode === "kill" ? "killRecorded" : "stopRecorded"} stops the group of a tree member that exited and was never reaped; a version that signals only processes that still run leaves that group running`,
259
+ options,
260
+ () => {
261
+ assert.deepEqual(nested(ZOMBIE_LEADER, mode, isZombieReport), {
262
+ zombie: true,
263
+ running: false,
264
+ });
265
+ },
266
+ );
267
+ }
268
+
269
+ await test(
270
+ "on a system with no /proc, killRecorded signals and reports a process recorded twice once; a version that keeps one target per record signals it twice",
271
+ options,
272
+ () => {
273
+ assert.deepEqual(nested(TWICE_WITHOUT_PROC, "no-proc", isTwiceReport), {
274
+ lines: 1,
275
+ signals: 1,
276
+ });
277
+ },
278
+ );
@@ -13,10 +13,13 @@ import { setTimeout as sleep } from "node:timers/promises";
13
13
  import {
14
14
  assertOwnProc,
15
15
  assertSignalable,
16
+ hasProc,
16
17
  isAlive,
17
18
  isSameProcess,
18
19
  isSignalable,
20
+ startedAs,
19
21
  startTimeOf,
22
+ statOf,
20
23
  } from "./identity.mjs";
21
24
 
22
25
  const POLL_MS = 500;
@@ -244,39 +247,50 @@ function procEntries() {
244
247
  }
245
248
  }
246
249
 
247
- /** @param {string} pid */
248
- function parentOf(pid) {
249
- try {
250
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
251
- return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
252
- } catch {
253
- return -1;
250
+ /** @typedef {Map<number, { parent: number, startTime: number }>} ProcessTable Each process /proc lists, with its parent and start time from one read of its stat */
251
+
252
+ /** @returns {ProcessTable} */
253
+ function processTable() {
254
+ /** @type {ProcessTable} */
255
+ const table = new Map();
256
+ for (const pid of procEntries().map(Number)) {
257
+ const stat = statOf(pid);
258
+ if (stat) table.set(pid, stat);
254
259
  }
260
+ return table;
255
261
  }
256
262
 
257
263
  /**
258
- * Every live descendant of `pids`, read from /proc. Empty where /proc is
259
- * missing. A child that left the process group is found here too.
260
- *
261
- * @param {number[]} pids The roots
262
- * @returns {number[]} The descendants, roots excluded
264
+ * @param {number[]} roots
265
+ * @param {ProcessTable} table
266
+ * @returns {Set<number>} The roots and every process of `table` below one of them
263
267
  */
264
- export function descendantsOf(pids) {
265
- const parents = new Map(
266
- procEntries().map((entry) => [Number(entry), parentOf(entry)]),
267
- );
268
- const found = new Set(pids);
268
+ function familyOf(roots, table) {
269
+ const found = new Set(roots);
269
270
  let grew = true;
270
271
  while (grew) {
271
272
  grew = false;
272
- for (const [pid, parent] of parents) {
273
+ for (const [pid, { parent }] of table) {
273
274
  if (!found.has(pid) && found.has(parent)) {
274
275
  found.add(pid);
275
276
  grew = true;
276
277
  }
277
278
  }
278
279
  }
279
- return [...found].filter((pid) => !pids.includes(pid));
280
+ return found;
281
+ }
282
+
283
+ /**
284
+ * Every live descendant of `pids`, read from /proc. Empty where /proc is
285
+ * missing. A child that left the process group is found here too.
286
+ *
287
+ * @param {number[]} pids The roots
288
+ * @returns {number[]} The descendants, roots excluded
289
+ */
290
+ export function descendantsOf(pids) {
291
+ return [...familyOf(pids, processTable())].filter(
292
+ (pid) => !pids.includes(pid),
293
+ );
280
294
  }
281
295
 
282
296
  /** @param {number} port */
@@ -349,17 +363,64 @@ function signalGroup(pid, signal) {
349
363
  /**
350
364
  * The recorded processes that still run as the run started them, and their
351
365
  * descendants, each with the start time that tells it apart from a later
352
- * process given its pid. A record whose pid another process holds now, or
353
- * whose pid is not a whole number above 1, is left out, so no descendant of
354
- * 0 or 1 is ever looked up.
366
+ * process given its pid. Each process is found and identified by one read
367
+ * of its stat, so a pid another process takes while the tree is read never
368
+ * joins it with the newcomer's start time. Once the tree is read, a process
369
+ * whose start time changed is left out with everything found below it, so
370
+ * a child of a process that took a parent's pid during the walk never joins
371
+ * it. A record whose pid another process holds now, or whose pid is not a
372
+ * whole number above 1, is left out, so no descendant of 0 or 1 is ever
373
+ * looked up.
355
374
  *
356
375
  * @param {RecordedProcess[]} records The recorded processes
357
376
  * @returns {{ pid: number, startTime: number | null }[]} One entry per process
358
377
  */
359
378
  function ownProcesses(records) {
360
- const roots = records.filter(isSameProcess).map((record) => record.pid);
361
- const pids = [...new Set([...roots, ...descendantsOf(roots)])];
362
- return pids.map((pid) => ({ pid, startTime: startTimeOf(pid) }));
379
+ const live = records.filter(isSameProcess);
380
+ if (!hasProc()) {
381
+ return [...new Set(live.map(({ pid }) => pid))].map((pid) => ({
382
+ pid,
383
+ startTime: null,
384
+ }));
385
+ }
386
+ const table = processTable();
387
+ const roots = live
388
+ .filter((record) => {
389
+ const stat = table.get(record.pid);
390
+ return stat !== undefined && startedAs(record, stat.startTime);
391
+ })
392
+ .map(({ pid }) => pid);
393
+ /** @type {ProcessTable} */
394
+ const unchanged = new Map();
395
+ for (const pid of familyOf(roots, table)) {
396
+ const stat = table.get(pid);
397
+ if (stat && startTimeOf(pid) === stat.startTime) unchanged.set(pid, stat);
398
+ }
399
+ const kept = roots.filter((pid) => unchanged.has(pid));
400
+ return [...familyOf(kept, unchanged)].flatMap((pid) => {
401
+ const stat = unchanged.get(pid);
402
+ return stat ? [{ pid, startTime: stat.startTime }] : [];
403
+ });
404
+ }
405
+
406
+ /**
407
+ * Signals the group of `target` only while its pid still names that
408
+ * process, checked by its start time right before the signal. A zombie
409
+ * still has its start time, and its pid cannot be reused until it is
410
+ * reaped, so a group whose leader exited unreaped still gets the signal.
411
+ *
412
+ * @param {{ pid: number, startTime: number | null }} target A process of {@link ownProcesses}
413
+ * @param {NodeJS.Signals} signal The signal
414
+ * @returns {boolean} True when the signal was sent
415
+ */
416
+ function signalIfSame(target, signal) {
417
+ const same =
418
+ target.startTime === null
419
+ ? isSameProcess(target)
420
+ : startTimeOf(target.pid) === target.startTime;
421
+ if (!same) return false;
422
+ signalGroup(target.pid, signal);
423
+ return true;
363
424
  }
364
425
 
365
426
  /**
@@ -387,13 +448,14 @@ function skippedRecords(records) {
387
448
  */
388
449
  export async function stopRecorded(records) {
389
450
  const targets = ownProcesses(records);
390
- for (const target of targets) signalGroup(target.pid, "SIGTERM");
451
+ for (const target of targets) signalIfSame(target, "SIGTERM");
391
452
  const deadline = Date.now() + STOP_GRACE_MS;
392
453
  while (targets.some(isSameProcess) && Date.now() < deadline) {
393
454
  await sleep(READY_POLL_MS);
394
455
  }
395
- const stubborn = targets.filter(isSameProcess);
396
- for (const target of stubborn) signalGroup(target.pid, "SIGKILL");
456
+ const stubborn = targets
457
+ .filter(isSameProcess)
458
+ .filter((target) => signalIfSame(target, "SIGKILL"));
397
459
  return [
398
460
  ...skippedRecords(records),
399
461
  ...targets.map(
@@ -420,7 +482,7 @@ export async function stopRecorded(records) {
420
482
  */
421
483
  export async function killRecorded(records) {
422
484
  const targets = ownProcesses(records);
423
- for (const target of targets) signalGroup(target.pid, "SIGKILL");
485
+ for (const target of targets) signalIfSame(target, "SIGKILL");
424
486
  const deadline = Date.now() + STOP_GRACE_MS;
425
487
  while (targets.some(isSameProcess)) {
426
488
  if (Date.now() >= deadline) {