@yaks/process 0.0.0-stage → 0.2.36

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 (111) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +249 -2
  3. package/_dist/clock.d.ts +5 -0
  4. package/_dist/clock.d.ts.map +1 -0
  5. package/_dist/command.d.ts +43 -0
  6. package/_dist/command.d.ts.map +1 -0
  7. package/_dist/comp.d.ts +49 -0
  8. package/_dist/comp.d.ts.map +1 -0
  9. package/_dist/env.d.ts +8 -0
  10. package/_dist/env.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +3 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/http.d.ts +11 -0
  14. package/_dist/http.d.ts.map +1 -0
  15. package/_dist/isolate.d.ts +11 -0
  16. package/_dist/isolate.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +49 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/modules.d.ts +31 -0
  20. package/_dist/modules.d.ts.map +1 -0
  21. package/_dist/platform.d.ts +7 -0
  22. package/_dist/platform.d.ts.map +1 -0
  23. package/_dist/plugin.d.ts +15 -0
  24. package/_dist/plugin.d.ts.map +1 -0
  25. package/_dist/run.d.ts +219 -0
  26. package/_dist/run.d.ts.map +1 -0
  27. package/_dist/self.d.ts +32 -0
  28. package/_dist/self.d.ts.map +1 -0
  29. package/_dist/socket.d.ts +11 -0
  30. package/_dist/socket.d.ts.map +1 -0
  31. package/_dist/store.d.ts +22 -0
  32. package/_dist/store.d.ts.map +1 -0
  33. package/_dist/system.d.ts +64 -0
  34. package/_dist/system.d.ts.map +1 -0
  35. package/_dist/trash.d.ts +6 -0
  36. package/_dist/trash.d.ts.map +1 -0
  37. package/_dist/views.d.ts +4 -0
  38. package/_dist/views.d.ts.map +1 -0
  39. package/_dist/vocab.d.ts +8 -0
  40. package/_dist/vocab.d.ts.map +1 -0
  41. package/_dist/wind.d.ts +35 -0
  42. package/_dist/wind.d.ts.map +1 -0
  43. package/clock.js +11 -0
  44. package/clock.js.map +1 -0
  45. package/clock.ts +11 -0
  46. package/command.js +172 -0
  47. package/command.js.map +1 -0
  48. package/command.ts +215 -0
  49. package/comp.js +54 -0
  50. package/comp.js.map +1 -0
  51. package/comp.ts +123 -0
  52. package/deno.json +1 -0
  53. package/detached.js +60 -0
  54. package/detached.js.map +1 -0
  55. package/detached.ts +92 -0
  56. package/detached_worker.ts +22 -0
  57. package/env.js +13 -0
  58. package/env.js.map +1 -0
  59. package/env.ts +24 -0
  60. package/graph.js +7 -0
  61. package/graph.js.map +1 -0
  62. package/graph.ts +8 -0
  63. package/http.js +158 -0
  64. package/http.js.map +1 -0
  65. package/http.ts +184 -0
  66. package/isolate.js +41 -0
  67. package/isolate.js.map +1 -0
  68. package/isolate.ts +52 -0
  69. package/mod.js +49 -0
  70. package/mod.js.map +1 -0
  71. package/mod.ts +50 -0
  72. package/modules.js +41 -0
  73. package/modules.js.map +1 -0
  74. package/modules.ts +69 -0
  75. package/package.json +81 -4
  76. package/platform.js +9 -0
  77. package/platform.js.map +1 -0
  78. package/platform.ts +9 -0
  79. package/plugin.js +27 -0
  80. package/plugin.js.map +1 -0
  81. package/plugin.ts +28 -0
  82. package/run.js +899 -0
  83. package/run.js.map +1 -0
  84. package/run.ts +1139 -0
  85. package/self.js +93 -0
  86. package/self.js.map +1 -0
  87. package/self.ts +144 -0
  88. package/socket.js +38 -0
  89. package/socket.js.map +1 -0
  90. package/socket.ts +49 -0
  91. package/store.js +30 -0
  92. package/store.js.map +1 -0
  93. package/store.ts +50 -0
  94. package/system.js +161 -0
  95. package/system.js.map +1 -0
  96. package/system.ts +216 -0
  97. package/testing.ts +39 -0
  98. package/tidy.ts +28 -0
  99. package/trash.js +117 -0
  100. package/trash.js.map +1 -0
  101. package/trash.ts +117 -0
  102. package/views.js +28 -0
  103. package/views.js.map +1 -0
  104. package/views.ts +30 -0
  105. package/vocab.js +16 -0
  106. package/vocab.js.map +1 -0
  107. package/vocab.json +154 -0
  108. package/vocab.ts +18 -0
  109. package/wind.js +88 -0
  110. package/wind.js.map +1 -0
  111. package/wind.ts +114 -0
package/run.ts ADDED
@@ -0,0 +1,1139 @@
1
+ import * as disk from 'node:fs/promises'
2
+ import { createHash } from 'node:crypto'
3
+ import { resolve } from 'node:path'
4
+ import * as system from './system.js'
5
+ import { detached } from './detached.js'
6
+ import { trash } from './trash.js'
7
+ // The supervisor: start a process, adopt one that is already running, pick
8
+ // every unfinished one back up at start-up, and keep the wanted ones running.
9
+ // Four entry points over one loop — watch the pid, write what the process
10
+ // prints, record how it ended.
11
+ //
12
+ // Exactly one supervisor sits above this one, and it is not this one. In the
13
+ // fleet that is systemd, which owns the daemon this code runs inside; this
14
+ // code owns everything below it and nothing above. So `supervise` refuses a
15
+ // service whose command would start its own program: a supervisor that
16
+ // restarts itself is a fork bomb with a restart policy, and its own exit is
17
+ // the one thing it cannot observe. The same asymmetry is why a bug here costs
18
+ // a restart and never a downed web server — every child outlives us (below),
19
+ // so this process dying leaves everything it started running.
20
+ //
21
+ // The child outlives us, because the process supervising another process
22
+ // must be restartable without taking that process with it. The technique is
23
+ // the fleet's (src/sessions.ts, T-7127/T-9261), reused rather than reinvented:
24
+ // our direct child is a launcher that backgrounds the rest and exits
25
+ // immediately, so a supervisor that kills the pids it tracks finds nothing to
26
+ // kill; the wrapper starts in a session and process group of its own; and on a
27
+ // machine whose service manager stops more than our process group, the run is
28
+ // lifted out of its reach too, which is what survives a full restart of the
29
+ // unit we run in. The wrapper starts ignoring INT and TERM strictly after
30
+ // forking the child — so the child does not inherit them ignored — writes
31
+ // "$$ $!" (the group to signal, and the child to watch) to the pidfile, and
32
+ // writes the exit code when the child ends. That pidfile and those two output
33
+ // files are enough to adopt the run back, which is why nothing here calls
34
+ // waitpid or reaps child processes.
35
+ //
36
+ // Only the detaching differs from one machine to the next, and `platforms`
37
+ // below is the whole difference, as data. Everything else here is POSIX: sh,
38
+ // signals, and files.
39
+ //
40
+ // What a process prints stays in those two files, never in the graph: output
41
+ // is a log, and the graph records the process, not its log. A caller reads the
42
+ // end of it with `tail`, and moves the files into trash once it is done with them.
43
+
44
+ import { bus, service } from './isolate.js'
45
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
46
+ import {
47
+ EXIT,
48
+ type Exit,
49
+ PROCESS,
50
+ type Process,
51
+ type Restart,
52
+ SERVICE,
53
+ type Service,
54
+ } from './comp.js'
55
+ import type { Store } from './store.ts'
56
+
57
+ // A component another package declares, which a host composes beside this
58
+ // one: a `stop` on a service's entity (@yaks/session) is the wish that it stop.
59
+ let STOP = 'stop'
60
+
61
+ /** What to run. */
62
+ export type Spec = {
63
+ /** the program */
64
+ command: string
65
+ /** its arguments */
66
+ args?: string[]
67
+ /** where to run it (default the supervisor's own working directory) */
68
+ cwd?: string
69
+ /** its whole environment — the child inherits nothing else */
70
+ env?: Record<string, string>
71
+ }
72
+
73
+ /** How the supervisor works, all optional. */
74
+ export type Opts = {
75
+ /** where the pidfiles and output files live (default `$PROCESS_DIR`, else
76
+ * `$TASKS_HOME/processes`, else `~/.tasks/processes`) */
77
+ dir?: string
78
+ /** how long the wrapper has to write its pidfile before the child is treated
79
+ * as having never started (ms, default 10_000) */
80
+ birth?: number
81
+ /** how often the pid and the output files are read (ms, default 1000) —
82
+ * every pass probes the pid, and noticing an exit within a second is
83
+ * plenty */
84
+ poll?: number
85
+ /** mint the process entity's eid (default a uuid) */
86
+ mint?: () => string
87
+ /** write the process row on this entity instead of a fresh one — what a
88
+ * supervisor passes so the attempt is recorded on the service row that
89
+ * wanted it. The previous attempt's `exit` is deleted by the same
90
+ * transaction, so nothing ever reads a fresh pid beside a stale exit code. */
91
+ eid?: string
92
+ /** which machine's launcher to use (default this one's, `system.build.os`);
93
+ * the macOS one runs anywhere perl does, which is how Linux tests it */
94
+ os?: string
95
+ /** whether a pid is running (default: `kill -0`) */
96
+ running?: (pid: number) => Promise<boolean>
97
+ /** when this machine last started (ms since the epoch, default from its
98
+ * uptime): a run launched before then went with the restart */
99
+ booted?: () => number
100
+ /** Stop retrying a failed exit write when the supervisor is shutting down. */
101
+ signal?: AbortSignal
102
+ /** Where to report a disk-full graph write while the observation waits. */
103
+ report?: (
104
+ error: unknown,
105
+ context?: { tags?: Record<string, string> },
106
+ ) => unknown
107
+ }
108
+
109
+ /** What a caller holds of a tracked process. */
110
+ export type Run = {
111
+ /** Elapsed wall-clock milliseconds, including time before adoption when known. */
112
+ elapsed: () => number
113
+ /** the process entity */
114
+ eid: string
115
+ /** its pid — 0 when the wrapper never reported one */
116
+ pid: number
117
+ /** the exit code, once it has been recorded; null when it was not
118
+ * observed */
119
+ done: Promise<number | null>
120
+ }
121
+
122
+ /** How an adopted process is described, when the adopter knows more than a
123
+ * pid. */
124
+ export type Adoption = Opts & {
125
+ /** the command line, if the adopter knows it */
126
+ command?: string | null
127
+ /** where it runs, if the adopter knows it */
128
+ cwd?: string | null
129
+ /** the exit code, read by whoever did launch it (the fleet's session
130
+ * launcher keeps an exit-code file of its own) */
131
+ code?: () => number | null
132
+ }
133
+
134
+ let uuid = () => crypto.randomUUID() as string
135
+ let sleep = (ms: number) => new Promise((go) => setTimeout(go, ms))
136
+
137
+ // The two moments that last only milliseconds — the wrapper writing its
138
+ // pidfile, and the wrapper writing its exit code — are polled on their own
139
+ // short interval. Checking that the process is still alive can wait for
140
+ // `poll`; polling these two any slower would only add delay.
141
+ let BEAT = 20
142
+ let beat = (o: Opts) => Math.min(o.poll ?? 1000, BEAT)
143
+
144
+ /** Where this supervisor keeps its files. */
145
+ export let dirOf = (
146
+ o: Opts = {},
147
+ env: (name: string) => string | undefined = system.env.get,
148
+ ): string =>
149
+ o.dir ?? env('PROCESS_DIR') ??
150
+ `${env('TASKS_HOME') || `${env('HOME')}/.tasks`}/processes`
151
+
152
+ let files = (dir: string, eid: string) => ({
153
+ out: `${dir}/${eid}.out`,
154
+ err: `${dir}/${eid}.err`,
155
+ pid: `${dir}/${eid}.pid`,
156
+ code: `${dir}/${eid}.code`,
157
+ started: `${dir}/${eid}.started`,
158
+ })
159
+
160
+ // The Linux user manager keeps this directory on tmpfs across yak restarts.
161
+ // Only failed disk writes leave a receipt there. Scope names by the log
162
+ // directory as well as by eid, so independent stores can use the same eid.
163
+ let recoveryOf = (dir: string, eid: string, o: Opts) => {
164
+ if ((o.os ?? system.build.os) != 'linux') return undefined
165
+ let key = createHash('sha256').update(resolve(dir)).digest('hex')
166
+ return `${bus(system.uid() ?? 0).XDG_RUNTIME_DIR}/yak-exit-${key}/${eid}`
167
+ }
168
+
169
+ /**
170
+ * The files one run keeps, named after the entity it is recorded on: its
171
+ * stdout and stderr files, the pidfile the wrapper writes its pid to, the
172
+ * file it writes the exit code to, and the file holding when it started.
173
+ *
174
+ * ```ts
175
+ * import { paths } from '@yaks/process'
176
+ *
177
+ * // paths('7f3…').out // the stdout file to read
178
+ * ```
179
+ *
180
+ * A caller that reads the output itself — @yaks/spawn imports a provider's
181
+ * JSON-lines stdout as transcript entries — needs the name of the file this
182
+ * package writes, and this package should state that layout rather than leave
183
+ * callers to assume it.
184
+ */
185
+ export let paths = (
186
+ eid: string,
187
+ o: Opts = {},
188
+ ): Record<'out' | 'err' | 'pid' | 'code' | 'started', string> =>
189
+ files(dirOf(o), eid)
190
+
191
+ // The wrapper script, run detached as `sh <this file> <argv…>`. It is kept in
192
+ // a file, not passed as `sh -c '<script>'`, because a detaching command may
193
+ // expand its own command line (systemd-run does; see `literal`), and a bare
194
+ // path gives it nothing to expand. When the child ended is the exit-code
195
+ // file's mtime, not a date(1) the wrapper runs: date's sub-second format is
196
+ // not POSIX, macOS prints `%N` as a letter, and shell arithmetic on that
197
+ // would end the wrapper before it wrote the code. After the code, on the same
198
+ // line, comes what the platform counts of how the child ended (`count`).
199
+ let wrapper = (count: string) =>
200
+ '"$@" >> "$TASKS_OUT" 2>> "$TASKS_ERR" & trap "" INT TERM; ' +
201
+ `echo "$$ $!" > "$TASKS_PID"; wait $!; c=$?; oom="${count}"; ` +
202
+ 'if ! printf "%s %s\\n" "$c" "${oom:-0}" > "$TASKS_CODE"; then ' +
203
+ 'reason=exit_write_failed; dir=${TASKS_CODE%/*}; ' +
204
+ 'if [ "$(df -Pk "$dir" | awk \'NR == 2 { print $4 }\')" = 0 ] || ' +
205
+ '[ "$(df -Pi "$dir" | awk \'NR == 2 { print $4 }\')" = 0 ]; then ' +
206
+ 'reason=disk_full; fi; ' +
207
+ '[ -n "$TASKS_RECOVERY" ] && ' +
208
+ 'printf "%s %s %s\\n" "$c" "${oom:-0}" "$reason" > "$TASKS_RECOVERY"; fi'
209
+
210
+ // How many processes the kernel's OOM killer has ended in the wrapper's own
211
+ // cgroup, the run's scope: its memory.events, under the cgroup v2 path
212
+ // /proc/self/cgroup names. Nothing when the run has no memory controller.
213
+ let OOM = '$(sed -n "s/^oom_kill //p" ' +
214
+ '"/sys/fs/cgroup$(sed -n "s/^0:://p" /proc/self/cgroup)/memory.events" ' +
215
+ '2>/dev/null)'
216
+
217
+ // The launcher, our direct child: it backgrounds the detaching command and
218
+ // exits at once. The whole command line arrives as its arguments, so nothing
219
+ // in it is parsed as shell, and a detaching command that fails says why in
220
+ // the stderr file.
221
+ let LAUNCHER = '"$@" 2>> "$TASKS_ERR" &'
222
+
223
+ // A transient scope name, unique per launch: systemd refuses a name whose
224
+ // previous unit is still loaded, and --collect frees a finished scope but not
225
+ // synchronously, so starting the program again would race the name it just
226
+ // released.
227
+ let launches = 0
228
+ let unit = (eid: string) =>
229
+ `process-${eid}-${Date.now().toString(36)}${++launches}`
230
+
231
+ // systemd expands `$VAR` and `${VAR}` in the command line it launches, so an
232
+ // argv element containing a shell variable, a template literal or a heredoc
233
+ // body reaches the program mangled: a hosted shell wrote a test file with
234
+ // every `${…}` deleted and systemd's "Referenced but unset environment
235
+ // variable" note in its stderr (T-37332). `$$` is systemd's escape for a
236
+ // literal `$`, so the program receives exactly the argv the caller passed.
237
+ // Only the command line is expanded — `%` specifiers are not — so this is the
238
+ // whole quoting rule.
239
+ export let literal = (arg: string): string => arg.replaceAll('$', '$$$$')
240
+
241
+ /** How one machine detaches a run, given this launch's name and the user it
242
+ * runs as. */
243
+ type Platform = (launch: {
244
+ unit: string
245
+ uid: number
246
+ cwd: string
247
+ env: Record<string, string>
248
+ }) => {
249
+ /** the command that starts the wrapper in a session and process group of
250
+ * its own, beyond whatever stops the host */
251
+ detach: string[]
252
+ /** what that command needs in its environment */
253
+ env: Record<string, string>
254
+ /** one word of the wrapper's command line, written so the detaching
255
+ * command passes it on unchanged */
256
+ word: (arg: string) => string
257
+ /** shell words the wrapper prints after the exit code: how many of the
258
+ * run's processes the machine's memory limit ended (none by default) */
259
+ count?: string
260
+ }
261
+
262
+ let platforms: Record<string, Platform> = {
263
+ // A transient service lifts the run out of our cgroup and ends its entire
264
+ // cgroup when the wrapper exits; `setsid` gives it its session. The
265
+ // two variables are how systemd-run reaches the --user manager's D-Bus
266
+ // socket; that socket exists only while user@<uid> is active, so a missing
267
+ // one fails loudly into the stderr file rather than silently running the
268
+ // child in our own cgroup.
269
+ linux: ({ unit, uid, cwd, env }) => ({
270
+ detach: [
271
+ ...service(unit, cwd, Object.keys(env)),
272
+ 'setsid',
273
+ // A service starts as a session leader, so setsid forks. Keep its main
274
+ // process waiting for the wrapper instead of ending the service here.
275
+ '--wait',
276
+ ],
277
+ env: bus(uid),
278
+ word: literal,
279
+ count: OOM,
280
+ }),
281
+ // launchd stops a job by signalling its process group (launchd.plist(5),
282
+ // AbandonProcessGroup), so a session of its own is the whole lift. macOS
283
+ // ships no setsid(1); its perl makes the setsid(2) call and execs the rest,
284
+ // with no shell and no expansion between.
285
+ darwin: () => ({
286
+ detach: [
287
+ 'perl',
288
+ '-MPOSIX=setsid',
289
+ '-e',
290
+ 'setsid or die "setsid: $!\\n"; exec { $ARGV[0] } @ARGV or die "exec: $!\\n"',
291
+ ],
292
+ env: {},
293
+ word: (arg) => arg,
294
+ }),
295
+ }
296
+
297
+ // The command line as a row records it, for a person reading which program
298
+ // this is. A word longer than a paragraph (a document passed as an argument,
299
+ // such as the persona an agent runs with) is cut short there, so the row stays
300
+ // small enough to send every page that lists the run; the program itself is
301
+ // given every byte.
302
+ let WORD = 1024
303
+ let line = (argv: string[]): string =>
304
+ argv.map((a) => a.length > WORD ? `${a.slice(0, WORD)}…` : a).join(' ')
305
+
306
+ let platformOf = (o: Opts): Platform => {
307
+ let os = o.os ?? system.build.os
308
+ let platform = platforms[os]
309
+ if (!platform) throw new Error(`@yaks/process cannot launch on ${os}`)
310
+ return platform
311
+ }
312
+
313
+ let spawn = async (
314
+ eid: string,
315
+ argv: string[],
316
+ cwd: string,
317
+ env: Record<string, string>,
318
+ dir: string,
319
+ platform: Platform,
320
+ recovery?: string,
321
+ ) => {
322
+ let f = files(dir, eid)
323
+ let script = `${dir}/wrapper.sh`
324
+ let envs = {
325
+ ...env,
326
+ TASKS_OUT: f.out,
327
+ TASKS_ERR: f.err,
328
+ TASKS_PID: f.pid,
329
+ TASKS_CODE: f.code,
330
+ TASKS_RECOVERY: recovery ?? '',
331
+ }
332
+ let p = platform({
333
+ unit: unit(eid),
334
+ uid: system.uid() ?? 0,
335
+ cwd,
336
+ env: envs,
337
+ })
338
+ // Every launch shares this file, and a write truncates before it writes: a
339
+ // `sh wrapper.sh` opened in between ran an empty script, so its child never
340
+ // started. A rename replaces the file whole, and a shell already reading the
341
+ // old one keeps reading all of it.
342
+ await disk.writeFile(`${script}.${eid}`, wrapper(p.count ?? ''))
343
+ await disk.rename(`${script}.${eid}`, script)
344
+ await detached('sh', {
345
+ args: [
346
+ '-c',
347
+ LAUNCHER,
348
+ 'sh',
349
+ ...p.detach,
350
+ ...['sh', script, ...argv].map(p.word),
351
+ ],
352
+ cwd,
353
+ clearEnv: true,
354
+ env: {
355
+ ...envs,
356
+ ...p.env,
357
+ },
358
+ })
359
+ }
360
+
361
+ // The pidfile holds two numbers: the process group, then the child's pid.
362
+ let pids = async (path: string) => {
363
+ try {
364
+ return (await disk.readFile(path, 'utf8')).trim().split(/\s+/)
365
+ .map(Number).filter((n) => n > 0)
366
+ } catch {
367
+ return []
368
+ }
369
+ }
370
+
371
+ // The child is the pid to test for liveness.
372
+ let pidOf = async (path: string) => (await pids(path)).at(-1) ?? 0
373
+
374
+ // The wrapper is what a signal should be sent to: setsid made it the process
375
+ // group leader, so signalling the negated group id reaches the wrapper, the
376
+ // child and anything the child started — nothing is left holding a port. A
377
+ // process we only adopted has no pidfile, and then the pid we were given is
378
+ // all there is.
379
+ let groupOf = async (path: string) => {
380
+ let ns = await pids(path)
381
+ return ns.length > 1 ? ns[0] : 0
382
+ }
383
+
384
+ let textOf = async (path: string) => {
385
+ try {
386
+ return await disk.readFile(path, 'utf8')
387
+ } catch {
388
+ return '' // not written yet
389
+ }
390
+ }
391
+
392
+ // A number the wrapper wrote, or null until it is there. `Number('')` is 0,
393
+ // so an empty file must not reach it.
394
+ let numberIn = (text: string) => {
395
+ let n = Number(text.trim())
396
+ return text.trim() && Number.isFinite(n) ? n : null
397
+ }
398
+
399
+ let codeOf = async (path: string) => numberIn(await textOf(path))
400
+
401
+ // How the run ended, once the wrapper has written all of it: the exit code,
402
+ // then the memory limit's kills where the platform counts them. Its `echo …
403
+ // > file` creates the file empty and writes the line a moment later; a load
404
+ // that stretches that moment let a read see the empty file and stamp a clean
405
+ // exit on a child that exited 3 (T-38290). echo ends the line with a newline,
406
+ // so a complete write is one that ends with one.
407
+ let endingIn = async (path: string): Promise<Exit | null> => {
408
+ let text = await textOf(path)
409
+ if (!text.endsWith('\n')) return null
410
+ let [status, count, reason] = text.trim().split(/\s+/)
411
+ let code = numberIn(status ?? '')
412
+ let oom = numberIn(count ?? '')
413
+ return code == null ? null : {
414
+ code,
415
+ ...oom ? { oom } : {},
416
+ ...reason == 'disk_full' || reason == 'exit_write_failed' ? { reason } : {},
417
+ }
418
+ }
419
+
420
+ let exitIn = async (path: string) => (await endingIn(path))?.code ?? null
421
+
422
+ // Whether a run was launched before this machine last started. Its wrapper and
423
+ // its child went with the restart, writing no code, and its pids may name
424
+ // other processes now.
425
+ let restarted = async (f: ReturnType<typeof files>, o: Opts) => {
426
+ let at = await codeOf(f.started)
427
+ return at != null && at < (o.booted ?? system.booted)()
428
+ }
429
+
430
+ let mtimeOf = async (path: string) => {
431
+ try {
432
+ return (await disk.stat(path)).mtime?.getTime() ?? null
433
+ } catch {
434
+ return null // not written yet
435
+ }
436
+ }
437
+
438
+ // The start and end times are kept in files, so a process picked back up
439
+ // after a restart reports its whole running time and not just the last wait.
440
+ // The end is when the wrapper wrote the exit code.
441
+ let elapsedOf = async (dir: string, eid: string) => {
442
+ let f = files(dir, eid)
443
+ let start = await codeOf(f.started) ?? Date.now()
444
+ let end = await mtimeOf(f.code)
445
+ return {
446
+ elapsed: () => Math.max(0, (end ?? Date.now()) - start),
447
+ finish: async () => {
448
+ end ??= await mtimeOf(f.code)
449
+ },
450
+ }
451
+ }
452
+
453
+ // A native signal needs no child process or executable read. Spawning kill(1)
454
+ // for every liveness probe could itself sleep in kernel_clone on the main thread.
455
+ let kill = (target: number, sig: string | number) => {
456
+ try {
457
+ system.kill(
458
+ target,
459
+ typeof sig == 'number'
460
+ ? sig
461
+ : sig == '0'
462
+ ? 0
463
+ : (sig.startsWith('SIG') ? sig : `SIG${sig}`) as system.Signal,
464
+ )
465
+ return true
466
+ } catch (e) {
467
+ if (['ESRCH', 'EPERM'].includes((e as NodeJS.ErrnoException).code ?? '')) {
468
+ return false
469
+ }
470
+ throw e
471
+ }
472
+ }
473
+
474
+ /** Whether a pid runs on this computer, asked with signal 0. */
475
+ export let runs = (pid: number): Promise<boolean> =>
476
+ Promise.resolve(kill(pid, 0))
477
+
478
+ // Whether a pid runs, asked the way the caller looks.
479
+ let alive = (o: Opts) => o.running ?? runs
480
+
481
+ /**
482
+ * Send a signal to a tracked run: to its process group where we launched it —
483
+ * the wrapper leads that group, so the child and anything the child started
484
+ * get the signal too — and to the bare pid where we only adopted it.
485
+ *
486
+ * ```ts
487
+ * import { signal } from '@yaks/process'
488
+ *
489
+ * // await signal(run.eid, run.pid, 'TERM')
490
+ * ```
491
+ *
492
+ * Nothing waits here: the exit code is written by the code watching the pid,
493
+ * in this case as in every other.
494
+ */
495
+ export let signal = async (
496
+ eid: string,
497
+ pid: number,
498
+ sig: string,
499
+ o: Opts = {},
500
+ ): Promise<boolean> => {
501
+ let group = await groupOf(paths(eid, o).pid)
502
+ return kill(group ? -group : pid, sig)
503
+ }
504
+
505
+ // Delete a file the previous attempt left behind, so this attempt is not
506
+ // handed the previous attempt's result.
507
+ let clear = async (path: string) => {
508
+ try {
509
+ await disk.unlink(path)
510
+ } catch (e) {
511
+ if ((e as NodeJS.ErrnoException).code != 'ENOENT') throw e
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Trash a finished run's files: its output, and the supervisor's own.
517
+ *
518
+ * Whoever reads the output cleans once it is done with it, and nothing else
519
+ * does: a service's output files are its log, appended to across attempts.
520
+ */
521
+ export let clean = async (eid: string, o: Opts = {}): Promise<void> => {
522
+ let dir = dirOf(o)
523
+ let recovery = recoveryOf(dir, eid, o)
524
+ if (recovery) await clear(recovery)
525
+ for (let path of Object.values(files(dir, eid))) {
526
+ let info = await fileInfo(path)
527
+ if (info?.isDirectory()) {
528
+ throw new Error(`A process file is a directory: ${path}`)
529
+ }
530
+ if (info) await trash(path, `${dir}/.trash`)
531
+ }
532
+ }
533
+
534
+ let fileInfo = async (path: string) => {
535
+ try {
536
+ return await disk.lstat(path)
537
+ } catch (e) {
538
+ if ((e as NodeJS.ErrnoException).code != 'ENOENT') throw e
539
+ return undefined
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Clean every run in the directory that ended more than `age` ms ago, by its
545
+ * exit-code file's time: what a reader that never cleaned leaves behind, such
546
+ * as a call nobody waited on or an answer lost to a crash. Requires a launch
547
+ * marker and a complete exit code. With a store, preserves sessions, services
548
+ * and processes whose exit has not been recorded. Answers how many.
549
+ *
550
+ * ```ts
551
+ * import { sweep } from '@yaks/process'
552
+ *
553
+ * // await sweep(24 * 60 * 60 * 1000) // every run that ended a day ago
554
+ * ```
555
+ */
556
+ export let sweep = async (
557
+ age: number,
558
+ o: Opts = {},
559
+ processes?: Pick<Store, 'get'>,
560
+ ): Promise<number> => {
561
+ let dir = dirOf(o)
562
+ let before = Date.now() - age
563
+ let n = 0
564
+ let candidates: string[] = []
565
+ let remove = async () => {
566
+ let rows = processes ? await processes.get(candidates) : []
567
+ let held = new Set(
568
+ rows.filter((b) => b.session || b[SERVICE] || (b[PROCESS] && !b[EXIT]))
569
+ .map((b) => b.entity.eid),
570
+ )
571
+ for (let eid of candidates) {
572
+ if (held.has(eid)) continue
573
+ let f = files(dir, eid)
574
+ // An old .code alone is not ours to remove. Require the launch marker
575
+ // and the wrapper's complete ending, and recheck after the graph read:
576
+ // a service or managed session may already be on its next attempt.
577
+ let code = await fileInfo(f.code)
578
+ let started = await fileInfo(f.started)
579
+ let start = await codeOf(f.started)
580
+ let end = code?.mtime?.getTime()
581
+ let exit = await exitIn(f.code)
582
+ if (
583
+ !code?.isFile() || !started?.isFile() || start == null || start <= 0 ||
584
+ end == null || end >= before || start > end ||
585
+ exit == null || !Number.isInteger(exit) || exit < 0 || exit > 255
586
+ ) continue
587
+ await clean(eid, o)
588
+ n++
589
+ }
590
+ candidates = []
591
+ }
592
+ try {
593
+ for (let e of await disk.readdir(dir, { withFileTypes: true })) {
594
+ if (!e.isFile() || !e.name.endsWith('.code')) continue
595
+ if ((await mtimeOf(`${dir}/${e.name}`) ?? before) >= before) continue
596
+ let eid = e.name.slice(0, -'.code'.length)
597
+ // No launch marker means another package's file, not a finished run.
598
+ if (await mtimeOf(files(dir, eid).started) == null) continue
599
+ candidates.push(eid)
600
+ if (candidates.length == 128) await remove()
601
+ }
602
+ await remove()
603
+ } catch (e) {
604
+ if ((e as NodeJS.ErrnoException).code != 'ENOENT') throw e
605
+ }
606
+ return n
607
+ }
608
+
609
+ // The last `n` whole lines of one output file, read backward a block at a
610
+ // time until the bytes hold n + 1 newlines or the file's start: enough that
611
+ // the line the first block cuts in half is not among them, however long the
612
+ // lines. The bytes are joined before they are decoded, so only that dropped
613
+ // line can hold a character split at a block's edge.
614
+ let BLOCK = 64 * 1024
615
+ let ending = async (path: string, n: number): Promise<string[]> => {
616
+ let f
617
+ try {
618
+ f = await disk.open(path, 'r')
619
+ } catch {
620
+ return [] // the file does not exist yet: nothing has been printed
621
+ }
622
+ try {
623
+ let at = (await f.stat()).size
624
+ let blocks: Uint8Array[] = []
625
+ for (let breaks = 0; at > 0 && breaks <= n;) {
626
+ let from = Math.max(0, at - BLOCK)
627
+ let buf = new Uint8Array(at - from)
628
+ for (let got = 0; got < buf.length;) {
629
+ let { bytesRead: k } = await f.read(
630
+ buf,
631
+ got,
632
+ buf.length - got,
633
+ from + got,
634
+ )
635
+ if (!k) break
636
+ got += k
637
+ }
638
+ blocks.unshift(buf)
639
+ breaks += buf.filter((c) => c == 10).length
640
+ at = from
641
+ }
642
+ let all = lines(new TextDecoder().decode(join(blocks)))
643
+ return (at > 0 ? all.slice(1) : all).slice(-n)
644
+ } finally {
645
+ await f.close()
646
+ }
647
+ }
648
+
649
+ let join = (blocks: Uint8Array[]) => {
650
+ let out = new Uint8Array(blocks.reduce((sum, b) => sum + b.length, 0))
651
+ blocks.reduce((at, b) => (out.set(b, at), at + b.length), 0)
652
+ return out
653
+ }
654
+
655
+ let lines = (text: string) => {
656
+ if (!text) return []
657
+ let out = text.split('\n')
658
+ if (text.endsWith('\n')) out.pop()
659
+ return out
660
+ }
661
+
662
+ /**
663
+ * The last `n` lines a run printed: its stdout's, then its stderr's. Read from
664
+ * the run's files, so it answers whoever asks for as long as they are kept.
665
+ *
666
+ * ```ts
667
+ * import { tail } from '@yaks/process'
668
+ *
669
+ * // await tail(run.eid, 40) // ['hi']
670
+ * ```
671
+ */
672
+ export let tail = async (
673
+ eid: string,
674
+ n: number,
675
+ o: Opts = {},
676
+ ): Promise<string[]> => {
677
+ if (n <= 0) return []
678
+ let f = files(dirOf(o), eid)
679
+ return [...await ending(f.out, n), ...await ending(f.err, n)].slice(-n)
680
+ }
681
+
682
+ // The wrapper writes the exit-code file just after the child it waited on is
683
+ // gone, so we know the process ended a moment before we know its code. It is
684
+ // waited for while the wrapper lives, since load can stretch that moment past
685
+ // any fixed count of polls; once the wrapper is gone the file is final. A run
686
+ // with no wrapper pid on file gets the old short grace, and WRITE bounds a
687
+ // wrapper pid another process took over. This is the reader for runs whose
688
+ // files are ours; a caller that adopted a process and keeps its own exit code
689
+ // reads that once, with no delay to wait out.
690
+ let WRITE = 10_000
691
+ let reported = (
692
+ f: ReturnType<typeof files>,
693
+ o: Opts,
694
+ recovery?: string,
695
+ ) =>
696
+ async () => {
697
+ let read = async () =>
698
+ await endingIn(f.code) ?? (recovery ? await endingIn(recovery) : null)
699
+ let withDisk = async (exit: Exit): Promise<Exit> => {
700
+ if (exit.code === 0 || exit.reason == 'disk_full') return exit
701
+ if (exit.reason == 'reboot') return exit
702
+ let started = await codeOf(f.started)
703
+ let last = await mtimeOf(f.err)
704
+ if (
705
+ started != null && last != null && last >= started &&
706
+ (await ending(f.err, 32)).some(diskFull)
707
+ ) return { ...exit, reason: 'disk_full' }
708
+ return exit
709
+ }
710
+ let lost = await restarted(f, o)
711
+ let wrapper = lost ? 0 : await groupOf(f.pid)
712
+ let none: Exit = lost ? { code: null, reason: 'reboot' } : { code: null }
713
+ for (let i = 0, end = Date.now() + WRITE;; i++) {
714
+ let exit = await read()
715
+ if (exit) return await withDisk(exit)
716
+ let over = lost || (wrapper ? !(await alive(o)(wrapper)) : i >= 20)
717
+ if (over || Date.now() >= end) {
718
+ return await withDisk(await read() ?? none)
719
+ }
720
+ await sleep(beat(o))
721
+ }
722
+ }
723
+
724
+ /** Whether a write failed because the filesystem or SQLite was out of space. */
725
+ let diskFull = (error: unknown): boolean =>
726
+ /\b(?:ENOSPC|SQLITE_FULL|no space left on device|database or disk is full)\b/i
727
+ .test(String(error)) ||
728
+ (error as NodeJS.ErrnoException | undefined)?.code == 'ENOSPC'
729
+
730
+ // The one loop: watch the pid, record how it ended.
731
+ let follow = async (
732
+ store: Store,
733
+ eid: string,
734
+ pid: number,
735
+ ending: () => Exit | Promise<Exit>,
736
+ o: Opts,
737
+ ) => {
738
+ let poll = o.poll ?? 1000
739
+ while (pid && await alive(o)(pid)) await sleep(poll)
740
+ let ended = await ending()
741
+ let told = false
742
+ while (!o.signal?.aborted) {
743
+ try {
744
+ await store.apply([{ entity: { eid }, [EXIT]: ended }])
745
+ break
746
+ } catch (error) {
747
+ if (!diskFull(error)) throw error
748
+ if (!told) {
749
+ told = true
750
+ let report = o.report ?? console.error
751
+ void Promise.resolve().then(() =>
752
+ report(error, {
753
+ tags: { package: '@yaks/process', step: 'record process exit' },
754
+ })
755
+ ).catch(console.error)
756
+ }
757
+ await sleep(5000)
758
+ }
759
+ }
760
+ return ended.code ?? null
761
+ }
762
+
763
+ /**
764
+ * Start a process, write its row, and record how it ended. What it prints
765
+ * stays in its files, for {@link tail} to read.
766
+ *
767
+ * ```ts
768
+ * import { launch, store } from '@yaks/process'
769
+ *
770
+ * // let run = await launch(store(graph), { command: 'sh', args: ['-c', 'echo hi'] })
771
+ * // await run.done // 0
772
+ * ```
773
+ *
774
+ * Resolves once the pid is known, or once the wrapper has run out of time to
775
+ * report one; `done` resolves when the exit code has been written.
776
+ */
777
+ export let launch = async (
778
+ store: Store,
779
+ spec: Spec,
780
+ o: Opts = {},
781
+ ): Promise<Run> => {
782
+ let platform = platformOf(o)
783
+ let eid = o.eid ?? (o.mint ?? uuid)()
784
+ let dir = dirOf(o)
785
+ await disk.mkdir(dir, { recursive: true })
786
+ let f = files(dir, eid)
787
+ let recovery = recoveryOf(dir, eid, o)
788
+ let argv = [spec.command, ...(spec.args ?? [])]
789
+ let cwd = spec.cwd ?? system.cwd()
790
+ // Deal with everything the last attempt on this row left behind before this
791
+ // one starts: the pidfile and exit-code file are deleted — read as if they
792
+ // belonged to this attempt, they would report the previous process both
793
+ // alive and already finished. The output files are appended to.
794
+ await clear(f.pid)
795
+ await clear(f.code)
796
+ if (recovery) {
797
+ await disk.mkdir(resolve(recovery, '..'), { recursive: true, mode: 0o700 })
798
+ await clear(recovery)
799
+ }
800
+ await disk.writeFile(f.started, String(Date.now()))
801
+ await spawn(eid, argv, cwd, spec.env ?? {}, dir, platform, recovery)
802
+ let pid = 0
803
+ for (let end = Date.now() + (o.birth ?? 10_000); !pid && Date.now() < end;) {
804
+ pid = await pidOf(f.pid)
805
+ if (!pid) await sleep(beat(o))
806
+ }
807
+ await store.apply([{
808
+ entity: { eid },
809
+ [PROCESS]: { pid: pid || null, command: line(argv), cwd },
810
+ // A row we were handed may still carry the last attempt's exit code. One
811
+ // transaction, so no reader ever sees the new pid beside it.
812
+ ...(o.eid ? { [EXIT]: null } : {}),
813
+ }])
814
+ let timing = await elapsedOf(dir, eid)
815
+ let done = follow(store, eid, pid, reported(f, o, recovery), o).then(
816
+ async (code) => {
817
+ // Cache the ending before a caller cleans its file away, so a held Run
818
+ // keeps reporting the whole elapsed time after cleanup.
819
+ await timing.finish()
820
+ return code
821
+ },
822
+ )
823
+ return { eid, pid, done, elapsed: timing.elapsed }
824
+ }
825
+
826
+ /**
827
+ * Track a process nobody here launched. A pid is all it takes — `command` and
828
+ * `cwd` are recorded only when the caller happens to know them.
829
+ *
830
+ * ```ts
831
+ * import { adopt, store } from '@yaks/process'
832
+ *
833
+ * // let run = await adopt(store(graph), 4242)
834
+ * ```
835
+ */
836
+ export let adopt = async (
837
+ store: Store,
838
+ pid: number,
839
+ o: Adoption = {},
840
+ ): Promise<Run> => {
841
+ let eid = (o.mint ?? uuid)()
842
+ await store.apply([{
843
+ entity: { eid },
844
+ [PROCESS]: { pid, command: o.command ?? null, cwd: o.cwd ?? null },
845
+ }])
846
+ let timing = await elapsedOf(dirOf(o), eid)
847
+ return {
848
+ eid,
849
+ pid,
850
+ elapsed: timing.elapsed,
851
+ done: follow(store, eid, pid, () => ({ code: o.code?.() ?? null }), o).then(
852
+ async (code) => {
853
+ await timing.finish()
854
+ return code
855
+ },
856
+ ),
857
+ }
858
+ }
859
+
860
+ /**
861
+ * The start-up pass: pick every process that has not exited back up. One that
862
+ * is still alive is watched again; one that is already gone has its exit
863
+ * recorded now — with the code its wrapper wrote when we launched it. When
864
+ * nothing observed the code, the exit component has no code property and the
865
+ * returned run’s `done` resolves to `null`. One launched before the machine
866
+ * last restarted went with it: its exit says `reason: 'reboot'`.
867
+ *
868
+ * ```ts
869
+ * import { store, watch } from '@yaks/process'
870
+ *
871
+ * // let runs = await watch(store(graph))
872
+ * ```
873
+ */
874
+ export let watch = async (store: Store, o: Opts = {}): Promise<Run[]> => {
875
+ let dir = dirOf(o)
876
+ let runs: Run[] = []
877
+ for (let b of await store.running()) {
878
+ // Workspace-qualified runs are observed at their original connector.
879
+ if ((b[PROCESS] as Process)?.workspace) continue
880
+ let eid = b.entity.eid
881
+ let f = files(dir, eid)
882
+ // The pidfile wins: it is where the wrapper wrote its own pid, and it is
883
+ // current even for a row whose pid was never written. A run launched
884
+ // before the machine restarted has no pid left to follow.
885
+ let pid = await restarted(f, o)
886
+ ? 0
887
+ : await pidOf(f.pid) || Number((b[PROCESS] as Process)?.pid ?? 0)
888
+ let timing = await elapsedOf(dir, eid)
889
+ runs.push({
890
+ eid,
891
+ pid,
892
+ elapsed: timing.elapsed,
893
+ done: follow(store, eid, pid, reported(f, o, recoveryOf(dir, eid, o)), o)
894
+ .then(async (code) => {
895
+ await timing.finish()
896
+ return code
897
+ }),
898
+ })
899
+ }
900
+ return runs
901
+ }
902
+
903
+ /**
904
+ * The processes whose row says they are running on this machine and whose pid
905
+ * is gone: a run that ended without writing its own `exit` — killed, crashed,
906
+ * or the machine restarted under it. A run this package launched is left out,
907
+ * since its wrapper writes the ending and {@link watch} records it with the
908
+ * code, and so is `me`, the process asking.
909
+ *
910
+ * ```ts
911
+ * import { selfEid, store, vanished } from '@yaks/process'
912
+ *
913
+ * // let dead = await vanished(store(graph), { me: selfEid() })
914
+ * ```
915
+ */
916
+ export let vanished = async (
917
+ store: Store,
918
+ o: Asking = {},
919
+ ): Promise<Bundle[]> => {
920
+ let out: Bundle[] = []
921
+ for (let b of await store.running()) if (await dead(b, o)) out.push(b)
922
+ return out
923
+ }
924
+
925
+ /** Who is asking after the dead. */
926
+ export type Asking = Opts & {
927
+ /** the process asking, never counted among them */
928
+ me?: string
929
+ }
930
+
931
+ /**
932
+ * Whether a process is over, so nothing it held is held any more: its row
933
+ * records an `exit`, or it is among the {@link vanished}. A Worker thread is a
934
+ * row of its own in the pid it runs in (./self.ts), and that pid outlives it;
935
+ * the `exit` the process that ended it writes is what says it is over. What a
936
+ * process contending for something another holds asks (@yaks/effects `take`).
937
+ * `me`, the process asking, is never over to itself.
938
+ *
939
+ * ```ts
940
+ * import { gone, selfEid, store } from '@yaks/process'
941
+ *
942
+ * // if (await gone(store(graph), holder, { me: selfEid() })) …
943
+ * ```
944
+ */
945
+ export let gone = async (
946
+ store: Store,
947
+ eid: string,
948
+ o: Asking = {},
949
+ ): Promise<boolean> => {
950
+ if (eid == o.me) return false
951
+ let [b] = await store.get([eid])
952
+ return !!b?.[EXIT] || (!!b?.[PROCESS] && await dead(b, o))
953
+ }
954
+
955
+ // A running row whose pid is gone. A run this package launched is not one:
956
+ // its wrapper writes the ending, and `watch` records it with the code.
957
+ let dead = async (b: Bundle, o: Asking): Promise<boolean> => {
958
+ if ((b[PROCESS] as Process)?.workspace) return false
959
+ let eid = b.entity.eid
960
+ let pid = Number((b[PROCESS] as Process)?.pid ?? 0)
961
+ if (
962
+ eid == o.me || !pid || await mtimeOf(files(dirOf(o), eid).started) != null
963
+ ) {
964
+ return false
965
+ }
966
+ return !await alive(o)(pid)
967
+ }
968
+
969
+ /** How supervision behaves, in addition to how a process is watched. */
970
+ export type Care = Opts & {
971
+ /** the first backoff step (ms, default 1000): the nth respawn waits
972
+ * `min(step * 2 ** (n - 1), ceiling)` from the attempt it follows */
973
+ step?: number
974
+ /** the longest a backoff ever waits (ms, default 60_000) — and the age at
975
+ * which a run stops counting as part of a crash loop, so the count of
976
+ * attempts starts over */
977
+ ceiling?: number
978
+ /** how long a stopped process has after SIGTERM before SIGKILL follows (ms,
979
+ * default 10_000) */
980
+ grace?: number
981
+ /** commands this supervisor must not run, in addition to its own program,
982
+ * which is always refused (see the header) */
983
+ refuse?: (command: string) => boolean
984
+ }
985
+
986
+ // What a pass remembers between passes — the only state here that is not in
987
+ // the graph, and it is all timestamps. The graph holds the count
988
+ // (`service.attempts`); turning that count into a wait also needs the time of
989
+ // the last attempt, and a property for that would be a timestamp rewritten on
990
+ // every restart. A supervisor that has just restarted forgets these waits,
991
+ // which is what we want anyway: a restart is a fair reason to try again now.
992
+ type Wait = {
993
+ /** when the last attempt was launched */
994
+ at?: number
995
+ /** the earliest the next attempt may be launched */
996
+ after?: number
997
+ /** the last attempt's pid — needed to shut the process down after the
998
+ * service row has been deleted */
999
+ pid?: number
1000
+ /** when SIGTERM was sent, so SIGKILL can follow after the grace period */
1001
+ termed?: number
1002
+ /** this command was refused, and has been warned about once */
1003
+ told?: boolean
1004
+ }
1005
+
1006
+ let backoff = (n: number, o: Care) =>
1007
+ Math.min((o.step ?? 1000) * 2 ** (n - 1), o.ceiling ?? 60_000)
1008
+
1009
+ // A shell runs the command line, because one text property cannot hold an argv
1010
+ // without somebody parsing quotes, and `sh -c` is the parser every machine
1011
+ // already has. It also makes a service row exactly what you would have typed.
1012
+ let shell = (s: Service): Spec => ({
1013
+ command: 'sh',
1014
+ args: ['-c', String(s.command)],
1015
+ cwd: s.cwd ?? undefined,
1016
+ })
1017
+
1018
+ // An exit code nobody could read does not count as a success.
1019
+ let again = (restart: Restart | null | undefined, code: number) =>
1020
+ restart == 'always' ? true : restart == 'on-failure' ? code != 0 : false
1021
+
1022
+ // This supervisor's own program, by the name it was started with — the one
1023
+ // command it may never run (see the header). Matching the basename catches
1024
+ // every way of writing the path that would start it again.
1025
+ let mine = () => {
1026
+ let name = (system.mainModule ?? '').split('/').pop() ?? ''
1027
+ return (command: string) =>
1028
+ !!name && command.split(/\s+/).some((a) => a.split('/').pop() == name)
1029
+ }
1030
+
1031
+ /**
1032
+ * Keep the wanted programs running. What is wanted is a `service` row; this is
1033
+ * the pass that makes the machine match it, returned as a function for the
1034
+ * caller's own timer to drive (the fleet's `tick()` in src/doing.ts).
1035
+ *
1036
+ * ```ts
1037
+ * import { store, supervise } from '@yaks/process'
1038
+ *
1039
+ * // let pass = supervise(store(graph))
1040
+ * // await pass() // start what is missing, restart what exited, stop what stopped
1041
+ * ```
1042
+ *
1043
+ * One pass, four decisions per row:
1044
+ *
1045
+ * - a `stop` component beside the service → SIGTERM the process group, then
1046
+ * SIGKILL after the grace period, and never start it again. The row stays,
1047
+ * so the fact that the program was wanted is recorded as over rather than
1048
+ * deleted.
1049
+ * - no `process` component at all → launch it.
1050
+ * - an `exit` on the process → launch it again if `restart` calls for it,
1051
+ * after a backoff that grows with `attempts` and stops at `ceiling`.
1052
+ * - the service row deleted → shut the process down too, since nobody wants it
1053
+ * any more.
1054
+ *
1055
+ * A process with no `exit` belongs to the code watching it, not to this pass:
1056
+ * `launch`'s own follow loop and `watch` at start-up are what record an exit
1057
+ * code, so there is exactly one writer of that component and this pass never
1058
+ * infers one.
1059
+ *
1060
+ * The pass returns the runs it started, so a caller that wants to wait for one
1061
+ * — a test, mostly — has the handle.
1062
+ */
1063
+ export let supervise = (store: Store, o: Care = {}): () => Promise<Run[]> => {
1064
+ let waits = new Map<string, Wait>()
1065
+ let own = mine()
1066
+ let wait = (eid: string) => {
1067
+ let w = waits.get(eid)
1068
+ if (!w) waits.set(eid, w = {})
1069
+ return w
1070
+ }
1071
+ // Shut it down, politely and then not: SIGTERM on the pass that first sees
1072
+ // the stop, SIGKILL on the first pass after the grace period. Nothing here
1073
+ // waits — the timer calls us again.
1074
+ let down = async (eid: string, w: Wait, pid: number) => {
1075
+ if (!pid || !(await alive(o)(pid))) return
1076
+ if (!w.termed) {
1077
+ w.termed = Date.now()
1078
+ return signal(eid, pid, 'TERM', o)
1079
+ }
1080
+ if (Date.now() - w.termed >= (o.grace ?? 10_000)) {
1081
+ return signal(eid, pid, 'KILL', o)
1082
+ }
1083
+ }
1084
+ return async (): Promise<Run[]> => {
1085
+ let started: Run[] = []
1086
+ let seen = new Set<string>()
1087
+ for (let b of await store.services()) {
1088
+ let eid = b.entity.eid
1089
+ seen.add(eid)
1090
+ let s = (b[SERVICE] ?? {}) as Service
1091
+ let p = b[PROCESS] as Process | undefined
1092
+ let w = wait(eid)
1093
+ let pid = Number(p?.pid ?? 0) || 0
1094
+ if (pid) w.pid = pid
1095
+ let over = b[EXIT] != null
1096
+
1097
+ if (b[STOP] != null) {
1098
+ if (!over) await down(eid, w, pid)
1099
+ continue
1100
+ }
1101
+ if (!s.command) continue
1102
+ if (own(s.command) || o.refuse?.(s.command)) {
1103
+ if (!w.told) console.warn(`supervise refused ${eid} — ${s.command}`)
1104
+ w.told = true
1105
+ continue
1106
+ }
1107
+ // Running, or exiting: either way the code watching the pid makes the
1108
+ // next write.
1109
+ if (p && !over) continue
1110
+ if (p && !again(s.restart, Number((b[EXIT] as Exit)?.code ?? 1))) continue
1111
+ if (w.after && Date.now() < w.after) continue
1112
+
1113
+ // A run that outlived the longest backoff was not part of a crash loop,
1114
+ // so the next attempt starts the count over.
1115
+ let flap = !!w.at && Date.now() - w.at < (o.ceiling ?? 60_000)
1116
+ let attempts = (flap ? Number(s.attempts ?? 0) : 0) + 1
1117
+ if (p) await store.apply([{ entity: { eid }, [SERVICE]: { attempts } }])
1118
+ w.at = Date.now()
1119
+ w.after = w.at + backoff(p ? attempts : 1, o)
1120
+ w.termed = undefined
1121
+ let run = await launch(store, shell(s), { ...o, eid })
1122
+ w.pid = run.pid
1123
+ // Nothing holds this promise, and in Deno an unhandled rejection ends
1124
+ // the process — which would be this supervisor dying because a child
1125
+ // did.
1126
+ run.done.catch((e) => console.warn(`supervise ${eid} —`, e))
1127
+ started.push(run)
1128
+ }
1129
+ // A deleted service row is a program nobody wants any more. Only this
1130
+ // pass's own memory still knows its pid, since the row that held it is
1131
+ // gone, so the shutdown lasts exactly as long as this supervisor does.
1132
+ for (let [eid, w] of waits) {
1133
+ if (seen.has(eid)) continue
1134
+ if (w.pid && await alive(o)(w.pid)) await down(eid, w, w.pid)
1135
+ else waits.delete(eid)
1136
+ }
1137
+ return started
1138
+ }
1139
+ }