@operad-io/engine 0.1.0 → 0.2.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 (80) hide show
  1. package/config.schema.json +2 -1
  2. package/package.json +1 -1
  3. package/src/config/config.ts +74 -45
  4. package/src/flow/types.ts +4 -0
  5. package/src/flow/validate.ts +5 -0
  6. package/src/http/index.ts +2 -0
  7. package/src/http/plugins.ts +66 -0
  8. package/src/http/server.ts +342 -48
  9. package/src/kernel/decide.ts +115 -30
  10. package/src/kernel/state.ts +9 -0
  11. package/src/kernel/types.ts +25 -40
  12. package/src/log/open-log.ts +2 -5
  13. package/src/log/sqlite.ts +127 -85
  14. package/src/log/types.ts +35 -9
  15. package/src/loop/code-watch.ts +108 -2
  16. package/src/loop/older-code.ts +3 -4
  17. package/src/loop/serve.ts +122 -95
  18. package/src/notify/notify.ts +2 -6
  19. package/src/platform/atomic-write.ts +163 -0
  20. package/src/platform/file-lock.ts +43 -21
  21. package/src/platform/index.ts +2 -0
  22. package/src/platform/kept-workers.ts +290 -0
  23. package/src/platform/process-group.ts +11 -3
  24. package/src/platform/sqlite-open.ts +20 -6
  25. package/src/platform/sqlite-schema.ts +30 -0
  26. package/src/platform/step-reap.ts +33 -18
  27. package/src/platform/watch.ts +1 -11
  28. package/src/plugin/action-schema.ts +59 -1
  29. package/src/plugin/choice-info.ts +133 -0
  30. package/src/plugin/context.ts +279 -0
  31. package/src/plugin/declared-flows.ts +3 -10
  32. package/src/plugin/errors.ts +9 -0
  33. package/src/plugin/freeze.ts +12 -0
  34. package/src/plugin/harness.ts +28 -0
  35. package/src/plugin/index.ts +8 -7
  36. package/src/plugin/install.ts +265 -17
  37. package/src/plugin/keys.ts +2 -12
  38. package/src/plugin/load.ts +47 -23
  39. package/src/plugin/logger.ts +14 -0
  40. package/src/plugin/open-store.ts +0 -6
  41. package/src/plugin/question-form.ts +323 -0
  42. package/src/plugin/registry.ts +512 -76
  43. package/src/plugin/secrets.ts +14 -24
  44. package/src/plugin/semver.ts +52 -0
  45. package/src/plugin/settings.ts +1 -9
  46. package/src/plugin/sqlite-store.ts +94 -64
  47. package/src/plugin/store.ts +5 -0
  48. package/src/plugin/types.ts +566 -21
  49. package/src/plugin/validate.ts +396 -26
  50. package/src/runner/answer.ts +26 -68
  51. package/src/runner/ask.ts +227 -28
  52. package/src/runner/cancel.ts +10 -7
  53. package/src/runner/grants.ts +2 -2
  54. package/src/runner/index.ts +1 -3
  55. package/src/runner/limits.ts +2 -2
  56. package/src/runner/runner.ts +15 -14
  57. package/src/runner/service.ts +52 -19
  58. package/src/runner/step-worker.ts +9 -0
  59. package/src/testing/answer.ts +69 -0
  60. package/src/testing/clock-manual.ts +152 -0
  61. package/src/testing/config.ts +16 -0
  62. package/src/testing/fs.ts +172 -0
  63. package/src/testing/home.ts +43 -0
  64. package/src/testing/index.ts +19 -0
  65. package/src/testing/types.ts +2 -0
  66. package/src/testing/world.ts +9 -2
  67. package/src/trigger/kernel.ts +13 -46
  68. package/src/trigger/rules.ts +22 -12
  69. package/src/trigger/types.ts +2 -6
  70. package/src/util.ts +99 -0
  71. package/src/views/event-line.ts +22 -0
  72. package/src/views/history.ts +36 -19
  73. package/src/views/live-logs.ts +313 -0
  74. package/src/views/pending.ts +23 -5
  75. package/src/views/presentation.ts +629 -81
  76. package/src/views/running.ts +5 -5
  77. package/src/views/settings.ts +205 -66
  78. package/src/views/types.ts +3 -2
  79. package/src/views/uploads.ts +15 -7
  80. package/triggers.schema.json +4 -0
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { dlopen, FFIType } from "bun:ffi";
13
+ import { errorCode, isMissingFile, isRecord } from "../util.ts";
13
14
  import { randomBytes } from "node:crypto";
14
15
  import {
15
16
  closeSync,
@@ -125,6 +126,8 @@ export interface LockFileOptions {
125
126
  readonly onLog?: ((message: string) => void) | undefined;
126
127
  /** Names the lock in log lines; defaults to `lock`. */
127
128
  readonly label?: string | undefined;
129
+ /** How long to wait for a live holder; defaults to `LOCK_TIMEOUT_MS`. */
130
+ readonly timeoutMs?: number | undefined;
128
131
  }
129
132
 
130
133
  /**
@@ -148,12 +151,6 @@ interface LockFile {
148
151
  readonly record: LockRecord | undefined;
149
152
  }
150
153
 
151
- function errorCode(error: unknown): unknown {
152
- return typeof error === "object" && error !== null && "code" in error
153
- ? error.code
154
- : undefined;
155
- }
156
-
157
154
  function newNonce(): string {
158
155
  return randomBytes(16).toString("hex");
159
156
  }
@@ -171,8 +168,8 @@ function readLockFile(path: string): LockFile {
171
168
  } catch {
172
169
  return { raw, record: undefined };
173
170
  }
174
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { raw, record: undefined };
175
- const fields = parsed as Record<string, unknown>;
171
+ if (!isRecord(parsed)) return { raw, record: undefined };
172
+ const fields = parsed;
176
173
  const pid = fields.pid;
177
174
  const nonce = fields.nonce;
178
175
  if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
@@ -207,15 +204,22 @@ let myStartedAt: number | null | undefined;
207
204
  /** The start time of this process, when the platform will say; best effort. */
208
205
  function myStart(): number | null {
209
206
  if (myStartedAt !== undefined) return myStartedAt;
210
- const pid = process.pid;
207
+ myStartedAt = startOf(process.pid);
208
+ return myStartedAt;
209
+ }
210
+
211
+ /**
212
+ * The start time `ps` or `/proc` reports for a pid, in the same unit as
213
+ * `myStart` on this platform, or null when the platform will not say. It is
214
+ * asked afresh for another pid: a record's pid may belong to a new process by
215
+ * the time a waiter looks at it.
216
+ */
217
+ function startOf(pid: number): number | null {
211
218
  try {
212
219
  const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
213
220
  const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
214
221
  const ticks = Number(fields[19]);
215
- if (Number.isFinite(ticks)) {
216
- myStartedAt = ticks;
217
- return ticks;
218
- }
222
+ if (Number.isFinite(ticks)) return ticks;
219
223
  } catch {
220
224
  // Not Linux.
221
225
  }
@@ -226,11 +230,24 @@ function myStart(): number | null {
226
230
  stderr: "pipe",
227
231
  });
228
232
  const at = Date.parse(result.stdout.toString().trim());
229
- myStartedAt = Number.isFinite(at) ? at : null;
233
+ return Number.isFinite(at) ? at : null;
230
234
  } catch {
231
- myStartedAt = null;
235
+ return null;
232
236
  }
233
- return myStartedAt;
237
+ }
238
+
239
+ /**
240
+ * True when the record's holder is gone: its pid is dead, or the pid now
241
+ * belongs to a process that started at another time. Without the start time a
242
+ * reused pid would look like a live holder until the waiter's deadline, but
243
+ * taking the lock over anyway could enter beside a live holder; waiting is the
244
+ * only safe choice when the platform cannot name the process.
245
+ */
246
+ function holderGone(record: LockRecord): boolean {
247
+ if (!isAlive(record.pid)) return true;
248
+ if (record.startedAt === null) return false;
249
+ const start = startOf(record.pid);
250
+ return start !== null && start !== record.startedAt;
234
251
  }
235
252
 
236
253
  function safeUnlink(path: string): void {
@@ -278,7 +295,7 @@ async function acquire(
278
295
  lockPath: string,
279
296
  clock: () => number,
280
297
  wait: (ms: number) => Promise<void>,
281
- log: (message: string) => void,
298
+ timeoutMs: number,
282
299
  ): Promise<LockRecord> {
283
300
  const started = clock();
284
301
  for (;;) {
@@ -313,13 +330,13 @@ async function acquire(
313
330
  const dead =
314
331
  holder.record === undefined
315
332
  ? isStaleUnreadable(lockPath, clock)
316
- : !isAlive(holder.record.pid);
333
+ : holderGone(holder.record);
317
334
  if (dead) {
318
335
  takeOver(lockPath, holder);
319
336
  continue;
320
337
  }
321
338
 
322
- if (clock() - started > LOCK_TIMEOUT_MS) {
339
+ if (clock() - started > timeoutMs) {
323
340
  const who =
324
341
  holder.record === undefined ? "unknown pid" : `pid ${holder.record.pid}`;
325
342
  throw new LockTimeoutError(lockPath, who);
@@ -338,7 +355,7 @@ function release(
338
355
  try {
339
356
  renameSync(lockPath, released);
340
357
  } catch (error) {
341
- if (errorCode(error) === "ENOENT") return;
358
+ if (isMissingFile(error)) return;
342
359
  throw error;
343
360
  }
344
361
 
@@ -376,7 +393,12 @@ export async function withLockFile<T>(
376
393
  const label = options.label ?? "lock";
377
394
  const onLog = options.onLog ?? ((message: string) => console.error(message));
378
395
  const log = (message: string): void => onLog(`${label}: ${message}`);
379
- const mine = await acquire(lockPath, clock, wait, log);
396
+ const mine = await acquire(
397
+ lockPath,
398
+ clock,
399
+ wait,
400
+ options.timeoutMs ?? LOCK_TIMEOUT_MS,
401
+ );
380
402
  try {
381
403
  return await work();
382
404
  } finally {
@@ -4,6 +4,7 @@
4
4
  * `@operad-io/engine/platform` and never writes its own.
5
5
  */
6
6
 
7
+ export * from "./atomic-write.ts";
7
8
  export * from "./file-lock.ts";
8
9
  export * from "./process-group.ts";
9
10
  export * from "./sqlite-open.ts";
@@ -11,3 +12,4 @@ export * from "./watch.ts";
11
12
  export * from "./step-reap.ts";
12
13
  export * from "./load.ts";
13
14
  export * from "./worker-reports.ts";
15
+ export * from "./kept-workers.ts";
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Kept workers: a harness child that may serve more than one reply stays in a
3
+ * directory of its own home and records how another process reaches it.
4
+ *
5
+ * A kept worker has no run marker: the run that started it is over, and the
6
+ * sweep for a step's left-over processes must leave it alone. The record here
7
+ * is how `serve` and its clients tell a kept worker from an ordinary process,
8
+ * find it for the next reply, end it when its owner asks, and never signal a
9
+ * pid that has since been reused by another program. Only the owner may read
10
+ * the directory or open the socket; both are created with owner-only
11
+ * permissions.
12
+ */
13
+
14
+ import { randomBytes } from "node:crypto";
15
+ import {
16
+ chmodSync,
17
+ mkdirSync,
18
+ readFileSync,
19
+ readdirSync,
20
+ rmSync,
21
+ } from "node:fs";
22
+ import { connect } from "node:net";
23
+ import { dirname, join } from "node:path";
24
+ import { writeJsonAtomicSync } from "./atomic-write.ts";
25
+ import { withLockFile } from "./file-lock.ts";
26
+ import { killProcessGroup, systemClock, type Clock } from "./process-group.ts";
27
+ import { readProcessTable } from "./step-reap.ts";
28
+ import { isRecord } from "../util.ts";
29
+
30
+ /** How long a worker is kept after a reply, when nobody asks for another. */
31
+ export const KEPT_WORKER_MS = 10 * 60 * 1000;
32
+
33
+ /** How many workers one home keeps. A fourth ends the one idle longest. */
34
+ export const MAX_KEPT_WORKERS = 3;
35
+
36
+ /** How long a kept worker may take to answer the first line of a new reply. */
37
+ export const KEPT_FIRST_LINE_MS = 5_000;
38
+
39
+ /** How long a kept worker gets to end after the stop request, before SIGKILL. */
40
+ export const KEPT_STOP_GRACE_MS = 500;
41
+
42
+ /** The command-line argument that names a kept worker's record. */
43
+ export const KEPT_WORKER_FLAG = "--operad-kept";
44
+
45
+ /** One kept worker as its owner records it. */
46
+ export interface KeptWorkerRecord {
47
+ readonly pid: number;
48
+ /** The random id that is also on the worker's command line. */
49
+ readonly token: string;
50
+ /** The chat (or other owner) the worker answers. */
51
+ readonly scope: string;
52
+ /** What the worker was started with; a different key means another worker. */
53
+ readonly key: string;
54
+ readonly socket: string;
55
+ /** The record itself; filled in when the record is read. */
56
+ readonly meta: string;
57
+ readonly session: string | null;
58
+ readonly startedAt: number;
59
+ readonly lastUsedAt: number;
60
+ /** True while the worker is answering a reply. */
61
+ readonly busy?: boolean | undefined;
62
+ }
63
+
64
+ export interface KeptWorkerSlot {
65
+ readonly dir: string;
66
+ readonly token: string;
67
+ readonly socket: string;
68
+ readonly meta: string;
69
+ }
70
+
71
+ /** The directory a harness keeps its workers in. */
72
+ export function keptWorkerDirectory(home: string, name: string): string {
73
+ return join(home, "harness", name, "kept");
74
+ }
75
+
76
+ function lockPath(home: string, name: string): string {
77
+ return join(home, "harness", name, "kept.lock");
78
+ }
79
+
80
+ function ownerDirectory(path: string): void {
81
+ mkdirSync(path, { recursive: true, mode: 0o700 });
82
+ chmodSync(path, 0o700);
83
+ }
84
+
85
+ /** A new socket and record path for a worker, with a token that is unique to it. */
86
+ export function newKeptWorkerSlot(home: string, name: string): KeptWorkerSlot {
87
+ const dir = keptWorkerDirectory(home, name);
88
+ ownerDirectory(dir);
89
+ const token = randomBytes(8).toString("hex");
90
+ return {
91
+ dir,
92
+ token,
93
+ socket: join(dir, `${token}.sock`),
94
+ meta: join(dir, `${token}.json`),
95
+ };
96
+ }
97
+
98
+ /** The argument a kept worker carries, so a record's pid can be checked before it is signalled. */
99
+ export function keptWorkerArgument(token: string): string {
100
+ return `${KEPT_WORKER_FLAG}=${token}`;
101
+ }
102
+
103
+ /** Writes a record whole: a reader sees the old one or the new one, never a half. */
104
+ export function writeKeptWorker(record: KeptWorkerRecord): void {
105
+ ownerDirectory(dirname(record.meta));
106
+ writeJsonAtomicSync(record.meta, record, { mode: 0o600 });
107
+ }
108
+
109
+ /** Removes a worker's record and socket; safe when they are already gone. */
110
+ export function removeKeptWorker(record: Pick<KeptWorkerRecord, "meta" | "socket">): void {
111
+ rmSync(record.meta, { force: true });
112
+ rmSync(record.socket, { force: true });
113
+ }
114
+
115
+ function textOf(value: unknown): string | undefined {
116
+ return typeof value === "string" && value.length > 0 ? value : undefined;
117
+ }
118
+
119
+ function recordOf(path: string, value: unknown): KeptWorkerRecord | undefined {
120
+ if (!isRecord(value)) return undefined;
121
+ const fields = value;
122
+ const pid = fields.pid;
123
+ const token = textOf(fields.token);
124
+ const scope = textOf(fields.scope);
125
+ const key = textOf(fields.key);
126
+ const socket = textOf(fields.socket);
127
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 1) return undefined;
128
+ if (token === undefined || scope === undefined || key === undefined || socket === undefined) return undefined;
129
+ const session = fields.session;
130
+ const startedAt = fields.startedAt;
131
+ const lastUsedAt = fields.lastUsedAt;
132
+ return {
133
+ pid,
134
+ token,
135
+ scope,
136
+ key,
137
+ socket,
138
+ meta: path,
139
+ session: typeof session === "string" ? session : null,
140
+ startedAt: typeof startedAt === "number" ? startedAt : 0,
141
+ lastUsedAt: typeof lastUsedAt === "number" ? lastUsedAt : 0,
142
+ ...(fields.busy === true ? { busy: true } : {}),
143
+ };
144
+ }
145
+
146
+ /** One record, or undefined when the file is missing, unreadable or not a record. */
147
+ export function readKeptWorker(path: string): KeptWorkerRecord | undefined {
148
+ try {
149
+ return recordOf(path, JSON.parse(readFileSync(path, "utf8")));
150
+ } catch {
151
+ // A record another process is replacing, or one that is not ours.
152
+ return undefined;
153
+ }
154
+ }
155
+
156
+ /** Every record in one home's kept directory. A record that cannot be read is skipped. */
157
+ export function readKeptWorkers(home: string, name: string): readonly KeptWorkerRecord[] {
158
+ const dir = keptWorkerDirectory(home, name);
159
+ let names: string[];
160
+ try {
161
+ names = readdirSync(dir);
162
+ } catch {
163
+ return [];
164
+ }
165
+ const found: KeptWorkerRecord[] = [];
166
+ for (const entry of names) {
167
+ if (!entry.endsWith(".json")) continue;
168
+ const record = readKeptWorker(join(dir, entry));
169
+ if (record !== undefined) found.push(record);
170
+ }
171
+ return found;
172
+ }
173
+
174
+ /** Every kept worker of every harness in one home. */
175
+ export function readKeptWorkersInHome(home: string): readonly KeptWorkerRecord[] {
176
+ const root = join(home, "harness");
177
+ let names: string[];
178
+ try {
179
+ names = readdirSync(root);
180
+ } catch {
181
+ return [];
182
+ }
183
+ return names.flatMap((name) => readKeptWorkers(home, name));
184
+ }
185
+
186
+ /** True when `pid` is still the kept worker named by `token`, not a reused pid. */
187
+ async function isWorkerProcess(pid: number, token: string): Promise<boolean> {
188
+ const wanted = keptWorkerArgument(token);
189
+ try {
190
+ const rows = await readProcessTable();
191
+ return rows.some((row) => row.pid === pid && row.command.includes(wanted));
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+
197
+ /** Asks a worker to stop over its socket; true when it answered. */
198
+ function requestStop(socketPath: string, timeoutMs: number): Promise<boolean> {
199
+ return new Promise((resolve) => {
200
+ let settled = false;
201
+ const socket = connect(socketPath);
202
+ const finish = (stopped: boolean): void => {
203
+ if (settled) return;
204
+ settled = true;
205
+ socket.destroy();
206
+ resolve(stopped);
207
+ };
208
+ socket.setTimeout(Math.max(1, timeoutMs));
209
+ socket.once("connect", () => {
210
+ socket.write(`${JSON.stringify({ type: "stop" })}\n`);
211
+ socket.end();
212
+ });
213
+ socket.once("close", () => finish(true));
214
+ socket.once("error", () => finish(false));
215
+ socket.once("timeout", () => finish(false));
216
+ });
217
+ }
218
+
219
+ /** Ends one kept worker: ask it over its socket, then signal only its own verified process. */
220
+ export async function stopKeptWorker(
221
+ record: KeptWorkerRecord,
222
+ options: { readonly clock?: Clock | undefined } = {},
223
+ ): Promise<void> {
224
+ const clock = options.clock ?? systemClock;
225
+ const answered = await requestStop(record.socket, KEPT_STOP_GRACE_MS);
226
+ if (answered) {
227
+ // Give the worker its grace to remove the record and leave.
228
+ await clock.sleep(KEPT_STOP_GRACE_MS);
229
+ }
230
+ // A worker that answered may already be gone; a dead one never is signalled.
231
+ if (await isWorkerProcess(record.pid, record.token)) {
232
+ killProcessGroup(record.pid, "SIGTERM");
233
+ await clock.sleep(KEPT_STOP_GRACE_MS);
234
+ if (await isWorkerProcess(record.pid, record.token)) {
235
+ killProcessGroup(record.pid, "SIGKILL");
236
+ }
237
+ }
238
+ removeKeptWorker(record);
239
+ }
240
+
241
+ /** Filters a kept worker; every field that is given must match. */
242
+ export interface KeptWorkerFilter {
243
+ readonly scope?: string | undefined;
244
+ readonly key?: string | undefined;
245
+ /** Keep these records, even when the other fields match. */
246
+ readonly except?: (record: KeptWorkerRecord) => boolean | undefined;
247
+ }
248
+
249
+ /** Ends every kept worker of every harness in one home, oldest first. */
250
+ export async function stopAllKeptWorkers(options: {
251
+ readonly home: string;
252
+ readonly clock?: Clock | undefined;
253
+ }): Promise<readonly KeptWorkerRecord[]> {
254
+ const root = join(options.home, "harness");
255
+ let names: string[];
256
+ try {
257
+ names = readdirSync(root);
258
+ } catch {
259
+ return [];
260
+ }
261
+ const ended: KeptWorkerRecord[] = [];
262
+ for (const name of names) {
263
+ if (readKeptWorkers(options.home, name).length === 0) continue;
264
+ ended.push(...(await stopKeptWorkers({ home: options.home, name, clock: options.clock })));
265
+ }
266
+ return ended;
267
+ }
268
+
269
+ /** Ends the kept workers of one home that match `filter`, oldest first. */
270
+ export async function stopKeptWorkers(options: {
271
+ readonly home: string;
272
+ readonly name: string;
273
+ readonly filter?: KeptWorkerFilter | undefined;
274
+ readonly clock?: Clock | undefined;
275
+ }): Promise<readonly KeptWorkerRecord[]> {
276
+ const filter = options.filter;
277
+ return withLockFile(
278
+ lockPath(options.home, options.name),
279
+ async () => {
280
+ const records = readKeptWorkers(options.home, options.name)
281
+ .filter((record) => filter?.scope === undefined || record.scope === filter.scope)
282
+ .filter((record) => filter?.key === undefined || record.key === filter.key)
283
+ .filter((record) => filter?.except?.(record) !== true)
284
+ .sort((a, b) => a.lastUsedAt - b.lastUsedAt);
285
+ for (const record of records) await stopKeptWorker(record, { clock: options.clock });
286
+ return records;
287
+ },
288
+ { label: `kept ${options.name}` },
289
+ );
290
+ }
@@ -513,14 +513,15 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
513
513
  });
514
514
 
515
515
  let readySeen = false;
516
- const stop = createGroupStop({
516
+ const group: GroupStopOptions = {
517
517
  clock,
518
518
  killGroup: options.killGroup ?? killProcessGroup,
519
519
  pid: () => child.pid,
520
520
  sentinelExited: () => sentinelExited,
521
521
  readySeen: () => readySeen,
522
522
  ready: readyGate,
523
- });
523
+ };
524
+ const stop = createGroupStop(group);
524
525
 
525
526
  let finished = false;
526
527
  let timedOut = false;
@@ -654,7 +655,14 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
654
655
  // line pay 500 ms. A cancellation or timeout still takes the TERM path.
655
656
  if (ended.kind === "end" && !cancelled && !timedOut && !stalled) {
656
657
  const pid = child.pid;
657
- if (pid !== undefined) (options.killGroup ?? killProcessGroup)(pid, "SIGKILL");
658
+ if (pid !== undefined && (options.killGroup ?? killProcessGroup)(pid, "SIGKILL")) {
659
+ // A child forked as the group was signaled missed the signal, and the
660
+ // sentinel's own `sleep` is forked right about now. The killed leader is
661
+ // a zombie until the event loop reaps it, so its id is still ours: look
662
+ // again, as the TERM path does, before taking the straggler for the
663
+ // step's work to stop later.
664
+ sweep(pid, group);
665
+ }
658
666
  } else {
659
667
  await stop();
660
668
  }
@@ -18,13 +18,27 @@ export function setBusyTimeout(database: Database): void {
18
18
  database.run(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
19
19
  }
20
20
 
21
+ /**
22
+ * True for a busy store: SQLITE_BUSY or any extended code of it
23
+ * (SQLITE_BUSY_SNAPSHOT, SQLITE_BUSY_RECOVERY, SQLITE_BUSY_TIMEOUT), whether the
24
+ * error is the one SQLite raised or the `cause` of an error that wrapped it.
25
+ */
21
26
  export function isBusy(error: unknown): boolean {
22
- return (
23
- typeof error === "object" &&
24
- error !== null &&
25
- "code" in error &&
26
- (error as { code?: unknown }).code === "SQLITE_BUSY"
27
- );
27
+ for (let depth = 0; depth < 8; depth += 1) {
28
+ if (typeof error !== "object" || error === null) return false;
29
+ const { code, errno, cause } = error as {
30
+ code?: unknown;
31
+ errno?: unknown;
32
+ cause?: unknown;
33
+ };
34
+ if (code === "SQLITE_BUSY" || (typeof code === "string" && code.startsWith("SQLITE_BUSY_"))) return true;
35
+ // The primary result code is the low byte of an extended one; 5 is BUSY.
36
+ if (typeof errno === "number" && typeof code === "string" && code.startsWith("SQLITE") && (errno & 0xff) === 5) {
37
+ return true;
38
+ }
39
+ error = cause;
40
+ }
41
+ return false;
28
42
  }
29
43
 
30
44
  /**
@@ -0,0 +1,30 @@
1
+ /** Reading a SQLite file's schema version and tables, for both sqlite stores. */
2
+
3
+ import type { Database } from "bun:sqlite";
4
+
5
+ interface VersionRow {
6
+ readonly version: number;
7
+ }
8
+
9
+ /** The recorded version, or undefined when the schema has not been created yet. */
10
+ export function readSchemaVersion(database: Database): number | undefined {
11
+ try {
12
+ const row = database
13
+ .query<VersionRow, []>("SELECT version FROM schema_version WHERE id = 1")
14
+ .get();
15
+ return row !== null && Number.isInteger(row.version) ? row.version : undefined;
16
+ } catch {
17
+ return undefined;
18
+ }
19
+ }
20
+
21
+ /** Whether the database has a table with this name. */
22
+ export function hasTable(database: Database, name: string): boolean {
23
+ return (
24
+ database
25
+ .query<{ name: string }, [string]>(
26
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
27
+ )
28
+ .get(name) !== null
29
+ );
30
+ }
@@ -66,6 +66,8 @@ export function markerEnv(
66
66
  marker: StepMarker | undefined = currentStepMarker(),
67
67
  ): Record<string, string> {
68
68
  if (marker === undefined) return {};
69
+ // What carries the marker must be followed and swept when the step ends.
70
+ startTracker(marker);
69
71
  return {
70
72
  [MARKER_ENV]: markerValue(marker),
71
73
  [MARKER_HOME_ENV]: homeToken(marker.home),
@@ -220,7 +222,7 @@ export interface ProcessRow {
220
222
  export type ProcessTable = () => Promise<readonly ProcessRow[]>;
221
223
 
222
224
  const ROW_PATTERN =
223
- /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3}\s+\S+\s+\S+\s+[\d:]+\s+\d{4})\s+(.*)$/;
225
+ /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\w{3}\s+\S+\s+\S+\s+[\d:]+\s+\d{4})\s+(.*)$/;
224
226
 
225
227
  /** Seconds since the epoch of a `ps` start time (`Mon 9 Nov 00:26:59 2026` or `Mon Nov 9 00:26:59 2026`). */
226
228
  export function parseStart(text: string): number {
@@ -234,22 +236,30 @@ export function parseStart(text: string): number {
234
236
  return Math.floor(Date.UTC(Number(year), months.indexOf(month), Number(day), hours, minutes, seconds) / 1000);
235
237
  }
236
238
 
237
- /** The table of this user's processes, by `ps`; it works the same on macOS and Linux. */
239
+ /**
240
+ * The table of this user's processes, by `ps`; it works the same on macOS and
241
+ * Linux. A process that has ended and waits for its parent to reap it is a
242
+ * zombie: it runs nothing, holds no environment and cannot be stopped, so it
243
+ * is no part of the table. Stopping one would only make a sweep wait out its
244
+ * grace for a process that is already gone.
245
+ */
238
246
  export const readProcessTable: ProcessTable = async () => {
239
247
  const uid = String(process.getuid?.() ?? "");
240
248
  const who = uid === "" ? ["-x"] : ["-U", uid];
241
- const listing = await run("ps", [...who, "-ww", "-o", "pid=,ppid=,pgid=,lstart=,command="]);
249
+ const listing = await run("ps", [...who, "-ww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,command="]);
242
250
  const rows: ProcessRow[] = [];
243
251
  for (const line of listing.out.split("\n")) {
244
252
  const match = ROW_PATTERN.exec(line);
245
253
  if (match === null) continue;
246
254
  if (Number(match[1]) === listing.pid) continue;
255
+ // `Z` and its flags (`ZN`, `Z+`) are the zombie states.
256
+ if ((match[4] ?? "").startsWith("Z")) continue;
247
257
  rows.push({
248
258
  pid: Number(match[1]),
249
259
  ppid: Number(match[2]),
250
260
  pgid: Number(match[3]),
251
- startSec: parseStart(match[4] ?? ""),
252
- command: match[5] ?? "",
261
+ startSec: parseStart(match[5] ?? ""),
262
+ command: match[6] ?? "",
253
263
  });
254
264
  }
255
265
  return rows;
@@ -449,6 +459,19 @@ function keyOf(marker: StepMarker): string {
449
459
  return `${homeToken(marker.home)}/${markerValue(marker)}`;
450
460
  }
451
461
 
462
+ /**
463
+ * Follows a step's processes once it is about to start one. A step that starts
464
+ * none has nothing to find, so it never reads the process table: the table is
465
+ * the expensive part of ending a step.
466
+ */
467
+ function startTracker(marker: StepMarker): void {
468
+ const key = keyOf(marker);
469
+ if (!running.has(key) || trackers.has(key)) return;
470
+ const tracker = new StepTracker({ watcher: createProcessWatch() });
471
+ trackers.set(key, tracker);
472
+ tracker.start();
473
+ }
474
+
452
475
  /**
453
476
  * Tells the platform that the running step started a process of its own (the
454
477
  * sentinel of a command or of a harness), so its descendants are followed.
@@ -456,17 +479,13 @@ function keyOf(marker: StepMarker): string {
456
479
  export function trackRoot(pid: number | undefined): void {
457
480
  const marker = currentStepMarker();
458
481
  if (marker === undefined || pid === undefined) return;
482
+ startTracker(marker);
459
483
  const tracker = trackers.get(keyOf(marker));
460
484
  if (tracker === undefined) return;
461
485
  tracker.addRoot(pid);
462
486
  void tracker.poll();
463
487
  }
464
488
 
465
- /** Looks at the table now for every running step. For a test that must not wait for the timer. */
466
- export async function pollTrackedSteps(table: ProcessTable = readProcessTable): Promise<void> {
467
- await Promise.all([...trackers.values()].map((tracker) => tracker.poll(table)));
468
- }
469
-
470
489
  export interface ReapOptions {
471
490
  /** Which marked processes to stop. */
472
491
  readonly select: (found: MarkedProcess) => boolean;
@@ -590,11 +609,6 @@ const running = new Map<string, number>();
590
609
  export function enterStep(marker: StepMarker): () => boolean {
591
610
  const key = keyOf(marker);
592
611
  running.set(key, (running.get(key) ?? 0) + 1);
593
- if (!trackers.has(key)) {
594
- const tracker = new StepTracker({ watcher: createProcessWatch() });
595
- trackers.set(key, tracker);
596
- tracker.start();
597
- }
598
612
  return () => {
599
613
  const count = (running.get(key) ?? 1) - 1;
600
614
  if (count <= 0) {
@@ -620,10 +634,11 @@ export async function reapStep(
620
634
  const home = homeToken(marker.home);
621
635
  const key = keyOf(marker);
622
636
  const tracker = trackers.get(key);
623
- tracker?.stop(options.clock);
624
- tracker?.finish();
637
+ if (tracker === undefined) return [];
638
+ tracker.stop(options.clock);
639
+ tracker.finish();
625
640
  trackers.delete(key);
626
- if (tracker !== undefined) await tracker.poll(options.table);
641
+ await tracker.poll(options.table);
627
642
  return reapMarked({
628
643
  select: (one) => one.marker === value && one.home === home,
629
644
  tracker,
@@ -50,21 +50,11 @@ export const DEFAULT_POLL_MS = 500;
50
50
  export interface FollowOptions {
51
51
  /** Defaults to true. False opens without a watch or a fallback timer. */
52
52
  readonly follow?: boolean | undefined;
53
- /** The same as `follow: false`: this command only reads what it opens. */
54
- readonly readonly?: boolean | undefined;
55
- /** The same as `follow: false`, in camel case. */
56
- readonly readOnly?: boolean | undefined;
57
- /** The same as `follow: false`: this process opens what it reads once. */
58
- readonly oneShot?: boolean | undefined;
59
53
  }
60
54
 
61
55
  /** Whether a subscription starts a watch and a fallback timer. */
62
56
  export function followsChanges(options: FollowOptions): boolean {
63
- if (options.follow !== undefined) return options.follow;
64
- if (options.readonly !== undefined) return !options.readonly;
65
- if (options.readOnly !== undefined) return !options.readOnly;
66
- if (options.oneShot !== undefined) return !options.oneShot;
67
- return true;
57
+ return options.follow ?? true;
68
58
  }
69
59
 
70
60
  /** The watch, the fallback timer and its period one subscription uses. */