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