@niwa-labs/proc 0.0.0-stage → 0.0.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.
@@ -0,0 +1,273 @@
1
+ // proc.run: a command in a box, how it ends, and where its output goes.
2
+ //
3
+ // What it proves:
4
+ // 1. a run's box writes its cwd and a temp directory in it, has no network and no host environment
5
+ // but the real HOME, and closes niwa's keys, journal and secrets; it fits nono even for a cwd
6
+ // inside the niwa home
7
+ // 2. the exit code, and the output of both streams, come back; a failing exit is a result
8
+ // 3. a command that runs too long is stopped with what it started
9
+ // 4. a background child that outlives its parent does not hold the run
10
+ // 5. the whole output is an artifact; the result and the record carry only a bounded tail
11
+ // 6. a box that cannot run stops the call before any process exists
12
+ // 7. the box a run and its record name is its manifest, with the policy the sandbox reports it applies
13
+ // 8. a run's temp directory is inside its cwd and gone after it; a run is refused where it cannot have one
14
+ // 9. a run reads the toolchains by default, takes the profiles it asks for, and finds the places of every
15
+ // other profile, an installation's among them, closed; a host it asks for is refused
16
+
17
+ import { chmodSync, existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
18
+ import { homedir } from "node:os";
19
+ import { join } from "node:path";
20
+ import { afterEach, expect, test } from "bun:test";
21
+
22
+ import { nono, sandbox } from "@niwa-labs/sandbox";
23
+ import { eventually } from "@niwa-labs/testing";
24
+
25
+ import { procRun } from "../src/index.ts";
26
+ import type { ProcResult } from "../src/index.ts";
27
+ import { absentSandbox, alive, dirIn, outputOf, procHost, recordingSandbox } from "./support.ts";
28
+
29
+ type Host = Awaited<ReturnType<typeof procHost>>;
30
+ const hosts: Host[] = [];
31
+ afterEach(async () => {
32
+ for (const host of hosts.splice(0)) await host.stop();
33
+ });
34
+
35
+ async function start(options: Parameters<typeof procHost>[0] = {}, at?: string): Promise<Host> {
36
+ const host = await procHost(options, at);
37
+ hosts.push(host);
38
+ return host;
39
+ }
40
+
41
+ const sh = (script: string) => ["/bin/sh", "-c", script];
42
+
43
+ test("a run's box writes its cwd and a temp directory in it, reaches nothing, and holds no host environment but HOME", async () => {
44
+ const sandbox = recordingSandbox();
45
+ const host = await start({ sandbox });
46
+ const cwd = realpathSync(dirIn(host.home, "work"));
47
+ process.env["NIWA_ID"] = "leaked-session";
48
+ process.env["GITLAB_TOKEN"] = "leaked-token";
49
+ try {
50
+ const result = await host.niwa.call(procRun, { cmd: sh("env"), cwd, timeout: 10_000, env: { MODE: "ci" } });
51
+ const [spec] = sandbox.specs;
52
+ expect(sandbox.specs).toHaveLength(1);
53
+ const temp = spec?.env["TMPDIR"] ?? "";
54
+ expect(temp.startsWith(`${cwd}/`)).toBe(true);
55
+ expect(spec?.write.map(String).sort()).toEqual([cwd, temp].sort());
56
+ expect(spec?.net).toEqual([]);
57
+ expect(Object.keys(spec?.env ?? {}).sort()).toEqual(["HOME", "MODE", "PATH", "TEMP", "TMP", "TMPDIR"]);
58
+ expect(spec?.env["HOME"]).toBe(homedir());
59
+ const home = realpathSync(host.home);
60
+ expect(spec?.closed.map(String)).toEqual(
61
+ expect.arrayContaining([join(home, "owner.token"), join(home, "host.key"), join(home, "journal.db"), join(home, "secrets"), join(realpathSync(homedir()), ".ssh")]),
62
+ );
63
+ expect(result.box.request).toEqual({ mode: "allow", items: [{ item: "toolchains", from: "host" }] });
64
+ expect(result.box.paths).toContainEqual({ path: cwd, mode: "write", from: "cwd" });
65
+ expect(result.box.paths).toContainEqual({ path: temp, mode: "write", from: "temp" });
66
+ expect(result.box.env.sort()).toEqual(["HOME", "MODE", "PATH", "TEMP", "TMP", "TMPDIR"]);
67
+ const seen = outputOf(host, result.output);
68
+ expect(seen).toContain("MODE=ci");
69
+ expect(seen).not.toContain("leaked");
70
+ } finally {
71
+ delete process.env["NIWA_ID"];
72
+ delete process.env["GITLAB_TOKEN"];
73
+ }
74
+ });
75
+
76
+ test("the box a run and its record name carries the policy the sandbox applies, not the spec it was given", async () => {
77
+ const sandbox = recordingSandbox((spec) => ({
78
+ write: [...spec.write, join(spec.cwd, ".own")],
79
+ devices: ["/dev/null", "/dev/tty"],
80
+ read: { only: [spec.cwd, "/opt/tool"] },
81
+ net: [],
82
+ }));
83
+ const host = await start({ sandbox });
84
+ const cwd = realpathSync(dirIn(host.home, "work"));
85
+ const result = await host.niwa.call(procRun, { cmd: sh("true"), cwd, timeout: 10_000 });
86
+ expect(result.box.policy.write).toContain(join(cwd, ".own"));
87
+ expect(result.box.policy.devices).toEqual(["/dev/null", "/dev/tty"]);
88
+ expect(result.box.policy.read).toEqual({ only: [cwd, "/opt/tool"] });
89
+ const finished = (await host.niwa.records.read()).filter((row) => row.type === "proc.finished");
90
+ expect((finished[0]?.data as { box?: unknown }).box).toEqual(result.box);
91
+ });
92
+
93
+ test("a run has the real home and a temp directory of its own inside its cwd, and nothing of it is left behind", async () => {
94
+ const sandbox = recordingSandbox();
95
+ const host = await start({ sandbox });
96
+ const cwd = realpathSync(dirIn(host.home, "work"));
97
+ const result = await host.niwa.call(procRun, {
98
+ cmd: sh('echo "$HOME"; echo "$TMPDIR"; echo "$TMP"; echo "$TEMP"; touch "$TMPDIR/scratch"'),
99
+ cwd,
100
+ timeout: 10_000,
101
+ });
102
+ expect(result.exit).toBe(0);
103
+ const [home, temp, tmp, tempToo] = outputOf(host, result.output).trim().split("\n");
104
+ expect(home).toBe(homedir());
105
+ expect(temp?.startsWith(`${cwd}/`)).toBe(true);
106
+ expect([tmp, tempToo]).toEqual([temp, temp]);
107
+ expect(existsSync(temp as string)).toBe(false);
108
+ expect(readdirSync(cwd)).toEqual([]);
109
+
110
+ // A call that names its own TMPDIR keeps it, and nothing is left behind either.
111
+ const named = await host.niwa.call(procRun, { cmd: sh('echo "$TMPDIR"'), cwd, timeout: 10_000, env: { TMPDIR: "/somewhere" } });
112
+ expect(outputOf(host, named.output).trim()).toBe("/somewhere");
113
+ expect(readdirSync(cwd)).toEqual([]);
114
+ });
115
+
116
+ test("a run in a directory it cannot write is refused: it would have no temp directory", async () => {
117
+ const host = await start({ sandbox: recordingSandbox() });
118
+ const cwd = realpathSync(dirIn(host.home, "work"));
119
+ chmodSync(cwd, 0o555);
120
+ try {
121
+ const error = await host.niwa.call(procRun, { cmd: sh("true"), cwd, timeout: 10_000 }).then(
122
+ () => undefined,
123
+ (thrown: unknown) => thrown,
124
+ );
125
+ expect(String(error)).toContain("cannot be written");
126
+ } finally {
127
+ chmodSync(cwd, 0o755);
128
+ }
129
+ });
130
+
131
+ test("a run reads the toolchains by default, and `only` replaces them", async () => {
132
+ const base = realpathSync(mkdtempSync(join(homedir(), ".niwa-proc-path-")));
133
+ const tools = dirIn(base, "bin");
134
+ const saved = process.env["PATH"];
135
+ process.env["PATH"] = `${tools}:relative:${homedir()}:/usr/bin`;
136
+ try {
137
+ const sandbox = recordingSandbox();
138
+ const host = await start({ sandbox });
139
+ const cwd = realpathSync(dirIn(host.home, "work"));
140
+ await host.niwa.call(procRun, { cmd: ["/usr/bin/true"], cwd, timeout: 10_000 });
141
+ expect(sandbox.specs[0]?.read.map(String)).toEqual(expect.arrayContaining([tools, "/usr/bin"]));
142
+ expect(sandbox.specs[0]?.read.map(String)).not.toContain(realpathSync(homedir()));
143
+ await host.niwa.call(procRun, { cmd: ["/usr/bin/true"], cwd, timeout: 10_000, box: { only: [] } });
144
+ expect(sandbox.specs[1]?.read).toEqual([]);
145
+ } finally {
146
+ process.env["PATH"] = saved;
147
+ rmSync(base, { recursive: true, force: true });
148
+ }
149
+ });
150
+
151
+ test("a run takes the profiles it asks for, and the places of every other profile, an installation's among them, are closed", async () => {
152
+ const base = realpathSync(mkdtempSync(join(homedir(), ".niwa-proc-profiles-")));
153
+ try {
154
+ const boxes = sandbox({ profiles: { tool: { write: [join(base, "tool-cache")] } } });
155
+ boxes.install("codex-luna", { write: [join(base, "codex-home")] });
156
+ const recording = recordingSandbox();
157
+ const host = await start({ sandbox: recording, boxes });
158
+ const cwd = realpathSync(dirIn(host.home, "work"));
159
+ const result = await host.niwa.call(procRun, { cmd: ["/usr/bin/true"], cwd, timeout: 10_000, box: { allow: ["tool"] } });
160
+ expect(result.box.paths).toContainEqual({ path: join(base, "tool-cache"), mode: "write", from: "profile:tool" });
161
+ expect(result.box.closed).toContainEqual({ path: join(base, "codex-home"), from: "harness:codex-luna" });
162
+ expect(recording.specs[0]?.write.map(String)).toContain(join(base, "tool-cache"));
163
+
164
+ await host.niwa.call(procRun, { cmd: ["/usr/bin/true"], cwd, timeout: 10_000 });
165
+ expect(recording.specs[1]?.closed.map(String)).toEqual(expect.arrayContaining([join(base, "tool-cache"), join(base, "codex-home")]));
166
+ } finally {
167
+ rmSync(base, { recursive: true, force: true });
168
+ }
169
+ });
170
+
171
+ test("a run that asks for a host, or for a place another profile keeps, is refused before anything starts", async () => {
172
+ const sandbox = recordingSandbox();
173
+ const host = await start({ sandbox });
174
+ const cwd = realpathSync(dirIn(host.home, "work"));
175
+ const error = await host.niwa.call(procRun, { cmd: sh("true"), cwd, timeout: 10_000, box: { allow: [{ net: "registry.npmjs.org" }, { read: "~/.npmrc" }] } }).then(
176
+ () => undefined,
177
+ (thrown: unknown) => String(thrown),
178
+ );
179
+ expect(error).toContain("registry.npmjs.org cannot be reached: this box reaches no network");
180
+ expect(error).toContain("take the profile npm");
181
+ expect(sandbox.specs).toEqual([]);
182
+ });
183
+
184
+ test("the box of a run inside the niwa home, where worktrees live, is one nono can express", async () => {
185
+ const sandbox = recordingSandbox();
186
+ // A home under the user's home, as the host's is.
187
+ const host = await start({ sandbox }, mkdtempSync(join(homedir(), ".niwa-proc-home-")));
188
+ const cwd = dirIn(host.home, "worktrees", "wt-1");
189
+ await host.niwa.call(procRun, { cmd: ["/usr/bin/true"], cwd, timeout: 10_000 });
190
+ const [spec] = sandbox.specs;
191
+ if (spec === undefined) throw new Error("no box was asked for");
192
+ expect(() => nono().manifest(spec)).not.toThrow();
193
+ });
194
+
195
+ test("a failing exit is a result with its code, and both streams are in the output", async () => {
196
+ const host = await start({ sandbox: recordingSandbox() });
197
+ const cwd = dirIn(host.home, "work");
198
+ const result: ProcResult = await host.niwa.call(procRun, { cmd: sh("echo out; echo err >&2; exit 3"), cwd, timeout: 10_000 });
199
+ expect(result.outcome).toBe("exited");
200
+ expect(result.exit).toBe(3);
201
+ expect(result.tail).toContain("out");
202
+ expect(result.tail).toContain("err");
203
+ const stored = outputOf(host, result.output);
204
+ expect(stored.split("\n").sort()).toEqual(["", "err", "out"]);
205
+ });
206
+
207
+ test("a run that outlasts its timeout is stopped, with the child it started", async () => {
208
+ const host = await start({ sandbox: recordingSandbox(), killGraceMs: 200 });
209
+ const cwd = dirIn(host.home, "work");
210
+ const pidFile = join(cwd, "child.pid");
211
+ const began = Date.now();
212
+ const result = await host.niwa.call(procRun, { cmd: sh(`sleep 60 & echo $! > child.pid; wait`), cwd, timeout: 400 });
213
+ expect(result.outcome).toBe("timed-out");
214
+ expect(result.exit).toBeNull();
215
+ expect(Date.now() - began).toBeLessThan(10_000);
216
+ const child = Number(readFileSync(pidFile, "utf8"));
217
+ await eventually(() => !alive(child), 5_000, "the child should be gone");
218
+ });
219
+
220
+ test("a command that traps the stop signal is killed once its grace is over", async () => {
221
+ const host = await start({ sandbox: recordingSandbox(), killGraceMs: 200 });
222
+ const cwd = dirIn(host.home, "work");
223
+ const result = await host.niwa.call(procRun, { cmd: sh("trap '' TERM; while :; do sleep 1; done"), cwd, timeout: 300 });
224
+ expect(result.outcome).toBe("timed-out");
225
+ });
226
+
227
+ test("a background child left behind does not hold the run, and does not survive it", async () => {
228
+ const host = await start({ sandbox: recordingSandbox() });
229
+ const cwd = dirIn(host.home, "work");
230
+ const began = Date.now();
231
+ const result = await host.niwa.call(procRun, { cmd: sh("sleep 60 & echo $! > child.pid; echo hi"), cwd, timeout: 30_000 });
232
+ expect(result.outcome).toBe("exited");
233
+ expect(result.exit).toBe(0);
234
+ expect(Date.now() - began).toBeLessThan(10_000);
235
+ expect(result.tail).toBe("hi\n");
236
+ const child = Number(readFileSync(join(cwd, "child.pid"), "utf8"));
237
+ await eventually(() => !alive(child), 5_000, "the child should be gone");
238
+ });
239
+
240
+ test("the output is an artifact: the result and the record keep only a bounded tail", async () => {
241
+ const host = await start({ sandbox: recordingSandbox(), tailBytes: 64 });
242
+ const cwd = dirIn(host.home, "work");
243
+ const result = await host.niwa.call(procRun, { cmd: sh("i=0; while [ $i -lt 5000 ]; do echo line-$i; i=$((i+1)); done"), cwd, timeout: 20_000 });
244
+ const whole = outputOf(host, result.output);
245
+ expect(whole.startsWith("line-0\n")).toBe(true);
246
+ expect(whole.endsWith("line-4999\n")).toBe(true);
247
+ expect(result.output.size).toBe(Buffer.byteLength(whole));
248
+ expect(result.tail.length).toBeLessThanOrEqual(64);
249
+ expect(whole.endsWith(result.tail)).toBe(true);
250
+
251
+ const finished = (await host.niwa.records.read()).filter((row) => row.type === "proc.finished");
252
+ expect(finished).toHaveLength(1);
253
+ const data = finished[0]?.data as Record<string, unknown>;
254
+ expect(data["tail"]).toBe(result.tail);
255
+ expect(data).toMatchObject({ action: "proc.run", cwd: realpathSync(cwd), program: "/bin/sh", exit: 0, output: result.output });
256
+ });
257
+
258
+ test("a box that cannot run stops the call before a process exists", async () => {
259
+ const host = await start({ sandbox: absentSandbox });
260
+ const cwd = dirIn(host.home, "work");
261
+ const marker = join(cwd, "ran");
262
+ await expect(host.niwa.call(procRun, { cmd: sh(`touch ${marker}`), cwd, timeout: 10_000 })).rejects.toThrow(/sandbox nono is not available/);
263
+ await Bun.sleep(100);
264
+ expect(existsSync(marker)).toBe(false);
265
+ expect((await host.niwa.records.read()).filter((row) => row.type === "proc.finished")).toEqual([]);
266
+ });
267
+
268
+ test("a directory that is not there is refused", async () => {
269
+ const host = await start({ sandbox: recordingSandbox() });
270
+ await expect(host.niwa.call(procRun, { cmd: ["/usr/bin/true"], cwd: join(host.home, "nowhere"), timeout: 1000 })).rejects.toThrow(/does not exist/);
271
+ writeFileSync(join(host.home, "file"), "");
272
+ await expect(host.niwa.call(procRun, { cmd: ["/usr/bin/true"], cwd: join(host.home, "file"), timeout: 1000 })).rejects.toThrow(/not a directory/);
273
+ });
@@ -0,0 +1,127 @@
1
+ // Watching one started command: what is told when its output could not be kept or was cut off.
2
+ //
3
+ // What it proves:
4
+ // 1. an artifact store that fails stops the command and fails the call: it is never a result
5
+ // with an empty output and exit 0
6
+ // 2. reading that is given up on, because something the command started in another group still
7
+ // holds its pipes, is said in the result
8
+ // 3. a command whose output was all read says so
9
+
10
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { afterEach, expect, test } from "bun:test";
14
+
15
+ import type { ArtifactStore, ArtifactWriter } from "@niwa-labs/core";
16
+ import { eventually } from "@niwa-labs/testing";
17
+
18
+ import { OutputCapture } from "../src/artifact.ts";
19
+ import { launchPlain, supervise } from "../src/supervise.ts";
20
+ import { alive } from "./support.ts";
21
+
22
+ const dirs: string[] = [];
23
+ afterEach(() => {
24
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
25
+ });
26
+
27
+ function workDir(): string {
28
+ const dir = mkdtempSync(join(tmpdir(), "niwa-supervise-"));
29
+ dirs.push(dir);
30
+ return dir;
31
+ }
32
+
33
+ const ENV = { PATH: "/usr/bin:/bin" };
34
+ const TIMES = { timeout: 20_000, killGraceMs: 100, drainMs: 150 };
35
+
36
+ /** A store whose writer takes nothing, or keeps the bytes it is given. */
37
+ function store(write: (chunk: Uint8Array) => void): { store: ArtifactStore; discarded: () => boolean } {
38
+ let discarded = false;
39
+ const writer: ArtifactWriter = {
40
+ write,
41
+ finish: () => ({ digest: "sha256:0", size: 0, type: "text/plain" }),
42
+ discard: () => {
43
+ discarded = true;
44
+ },
45
+ };
46
+ return {
47
+ store: {
48
+ put: () => {
49
+ throw new Error("not used");
50
+ },
51
+ writer: () => writer,
52
+ read: () => {
53
+ throw new Error("not used");
54
+ },
55
+ },
56
+ discarded: () => discarded,
57
+ };
58
+ }
59
+
60
+ test("an artifact store that fails stops the command and fails the call", async () => {
61
+ const dir = workDir();
62
+ const kept = store(() => {
63
+ throw new Error("the disk is full");
64
+ });
65
+ const capture = new OutputCapture({ artifacts: kept.store, secrets: [], limit: 1 << 20, tailBytes: 16 });
66
+ const child = launchPlain(["/bin/sh", "-c", "echo $$ > pid; echo hi; sleep 30"], dir, ENV);
67
+ const began = Date.now();
68
+ await expect(supervise(child, capture, TIMES)).rejects.toThrow("the disk is full");
69
+ expect(Date.now() - began).toBeLessThan(10_000);
70
+ await eventually(() => existsSync(join(dir, "pid")), 2_000, "the command should have started");
71
+ const pid = Number(readFileSync(join(dir, "pid"), "utf8"));
72
+ await eventually(() => !alive(pid), 5_000, "the command should have been stopped");
73
+ });
74
+
75
+ test("output left in a pipe that something in another group still holds is said to be cut off", async () => {
76
+ const dir = workDir();
77
+ const kept = store(() => {});
78
+ const capture = new OutputCapture({ artifacts: kept.store, secrets: [], limit: 1 << 20, tailBytes: 16 });
79
+ const script = `perl -e 'use POSIX; if (!fork) { POSIX::setsid(); open(my $f, ">", "pid"); print $f $$; close $f; exec "sleep", "30" }'; echo hi`;
80
+ const child = launchPlain(["/bin/sh", "-c", script], dir, ENV);
81
+ try {
82
+ const ended = await supervise(child, capture, TIMES);
83
+ expect(ended.outcome).toBe("exited");
84
+ expect(ended.exit).toBe(0);
85
+ expect(ended.outputCut).toBe(true);
86
+ } finally {
87
+ await eventually(() => existsSync(join(dir, "pid")), 2_000, "the detached process should have started");
88
+ try {
89
+ process.kill(Number(readFileSync(join(dir, "pid"), "utf8")), "SIGKILL");
90
+ } catch {
91
+ // Already gone.
92
+ }
93
+ }
94
+ });
95
+
96
+ test("a command whose whole output was read says nothing was cut off", async () => {
97
+ const dir = workDir();
98
+ const kept = store(() => {});
99
+ const capture = new OutputCapture({ artifacts: kept.store, secrets: [], limit: 1 << 20, tailBytes: 16 });
100
+ const child = launchPlain(["/bin/sh", "-c", "echo hi; sleep 30 &"], dir, ENV);
101
+ const ended = await supervise(child, capture, TIMES);
102
+ expect(ended.exit).toBe(0);
103
+ expect(ended.outputCut).toBe(false);
104
+ });
105
+
106
+ test("the end of a command is when its process ends, not when the box has cleaned up after it", async () => {
107
+ const dir = workDir();
108
+ const options = { timeout: 300, killGraceMs: 100, drainMs: 150 };
109
+ for (const cleanup of ["slow", "failing"] as const) {
110
+ const kept = store(() => {});
111
+ const capture = new OutputCapture({ artifacts: kept.store, secrets: [], limit: 1 << 20, tailBytes: 16 });
112
+ const real = launchPlain(["/bin/sh", "-c", "echo hi"], dir, ENV);
113
+ const child = {
114
+ ...real,
115
+ ended: real.exited,
116
+ // The clean-up of the box comes after the process is gone, and takes longer than the command had.
117
+ exited: real.exited.then(async (code) => {
118
+ await Bun.sleep(600);
119
+ if (cleanup === "failing") throw new Error("the settings could not be removed");
120
+ return code;
121
+ }),
122
+ };
123
+ const ended = await supervise(child, capture, options);
124
+ expect(ended.outcome).toBe("exited");
125
+ expect(ended.exit).toBe(0);
126
+ }
127
+ });
@@ -0,0 +1,178 @@
1
+ // What the proc tests share: a sandbox that confines nothing and writes down what it was asked,
2
+ // and a host with the module installed.
3
+
4
+ import { mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ import type { Action, ActionContext, ArtifactRef, ArtifactStore, RecordType } from "@niwa-labs/core";
8
+ import type { PluginApi } from "@niwa-labs/plugin";
9
+ import { SandboxUnavailable, sandbox as sandboxHost } from "@niwa-labs/sandbox";
10
+ import type { BoxPolicy, BoxSpec, Sandbox, SandboxHost } from "@niwa-labs/sandbox";
11
+ import { createNiwa, tempHome } from "@niwa-labs/testing";
12
+
13
+ import { proc } from "../src/index.ts";
14
+ import type { ProcOptions } from "../src/index.ts";
15
+
16
+ /** The policy a sandbox that holds a run to its directory reports: the spec's places, a device and a system place to read. */
17
+ export function heldPolicy(spec: BoxSpec): BoxPolicy {
18
+ return { write: [...spec.write], devices: ["/dev/null"], read: { only: [spec.cwd, "/usr/lib"] }, net: [...spec.net] };
19
+ }
20
+
21
+ /**
22
+ * A sandbox that runs the command as it is. Every spec it is given is kept. It reports `policy`
23
+ * of the spec as what it applies: by default one that holds a run.
24
+ */
25
+ export function recordingSandbox(policy: (spec: BoxSpec) => BoxPolicy | undefined = heldPolicy): Sandbox & { readonly specs: BoxSpec[] } {
26
+ const specs: BoxSpec[] = [];
27
+ return {
28
+ specs,
29
+ name: "nono",
30
+ class: "process",
31
+ available: async () => true,
32
+ manifest: (spec) => {
33
+ const reported = policy(spec);
34
+ return { sandbox: "nono", cwd: spec.cwd, env: spec.env, ...(reported === undefined ? {} : { policy: reported }) };
35
+ },
36
+ async launch(spec, argv, options) {
37
+ specs.push(spec);
38
+ const child = Bun.spawn([...argv], {
39
+ cwd: spec.cwd,
40
+ env: { ...spec.env },
41
+ stdin: "pipe",
42
+ stdout: "pipe",
43
+ stderr: "pipe",
44
+ detached: options?.detached ?? false,
45
+ });
46
+ return {
47
+ pid: child.pid,
48
+ stdin: child.stdin,
49
+ stdout: child.stdout,
50
+ stderr: child.stderr,
51
+ exited: child.exited,
52
+ kill: (signal) => child.kill(signal),
53
+ };
54
+ },
55
+ };
56
+ }
57
+
58
+ /** A sandbox that cannot run on this machine. */
59
+ export const absentSandbox: Sandbox = {
60
+ name: "nono",
61
+ class: "process",
62
+ available: async () => false,
63
+ manifest: (spec) => ({ sandbox: "nono", cwd: spec.cwd, env: spec.env, policy: heldPolicy(spec) }),
64
+ async launch() {
65
+ throw new SandboxUnavailable("nono", "not here");
66
+ },
67
+ };
68
+
69
+ /**
70
+ * The module's options, with the sandbox a test gives as an adapter, and the host's sandbox to put
71
+ * it in (`boxes`, the catalog alone when absent).
72
+ */
73
+ export type TestProcOptions = Omit<ProcOptions, "sandbox"> & { readonly sandbox?: Sandbox; readonly boxes?: SandboxHost };
74
+
75
+ /** The options of the module from a test's: its adapter in the host's sandbox. */
76
+ export function procOptions(options: TestProcOptions): ProcOptions {
77
+ const { sandbox, boxes, ...rest } = options;
78
+ if (sandbox === undefined) return { ...rest, ...(boxes === undefined ? {} : { sandbox: boxes }) };
79
+ const host = boxes ?? sandboxHost();
80
+ return { ...rest, sandbox: { ...host, adapter: sandbox, names: host.names, install: host.install, plan: host.plan } };
81
+ }
82
+
83
+ /** A host with the proc module over a fresh home. */
84
+ export async function procHost(options: TestProcOptions = {}, at?: string) {
85
+ const home =
86
+ at === undefined
87
+ ? await tempHome()
88
+ : { path: at, cleanup: async () => rmSync(at, { recursive: true, force: true }) };
89
+ const niwa = createNiwa({ home: home.path });
90
+ niwa.use(proc(procOptions(options)));
91
+ await niwa.serve();
92
+ return {
93
+ niwa,
94
+ home: home.path,
95
+ async stop() {
96
+ await niwa.close();
97
+ await home.cleanup();
98
+ },
99
+ };
100
+ }
101
+
102
+ /** The text of an output the host keeps as an artifact. */
103
+ export function outputOf(host: { niwa: { artifacts: ArtifactStore } }, ref: ArtifactRef): string {
104
+ return new TextDecoder().decode(host.niwa.artifacts.read(ref));
105
+ }
106
+
107
+ /** A directory made inside a parent. */
108
+ export function dirIn(parent: string, ...parts: string[]): string {
109
+ const path = join(parent, ...parts);
110
+ mkdirSync(path, { recursive: true });
111
+ return path;
112
+ }
113
+
114
+ /** Every regular file under a directory, with its bytes. */
115
+ export function filesUnder(dir: string): Array<{ path: string; bytes: Buffer }> {
116
+ const found: Array<{ path: string; bytes: Buffer }> = [];
117
+ for (const name of readdirSync(dir)) {
118
+ const path = join(dir, name);
119
+ const stat = statSync(path);
120
+ if (stat.isDirectory()) found.push(...filesUnder(path));
121
+ else if (stat.isFile()) found.push({ path, bytes: readFileSync(path) });
122
+ }
123
+ return found;
124
+ }
125
+
126
+ /** Is a process alive? */
127
+ export function alive(pid: number): boolean {
128
+ try {
129
+ process.kill(pid, 0);
130
+ return true;
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * The actions of the proc module, called as the core calls them in a step: with a context of the
138
+ * test's own, so a signal can be given and the records the action writes are kept.
139
+ */
140
+ export async function procActions(options: TestProcOptions = {}) {
141
+ const home = await tempHome();
142
+ const niwa = createNiwa({ home: home.path });
143
+ const actions = new Map<string, Action<any, any>>();
144
+ const emitted: Array<{ type: string; data: Record<string, unknown> }> = [];
145
+ const api = {
146
+ declare: () => {},
147
+ home: () => home.path,
148
+ secrets: niwa.secrets,
149
+ artifacts: niwa.artifacts,
150
+ rights: () => "unlimited",
151
+ action: (found: Action<any, any>) => {
152
+ actions.set(found.name, found);
153
+ },
154
+ } as unknown as PluginApi;
155
+ proc(procOptions(options)).setup(api);
156
+ const context = (signal?: AbortSignal): ActionContext =>
157
+ ({
158
+ operationId: "op-test",
159
+ ...(signal === undefined ? {} : { signal }),
160
+ emit: async <T>(type: RecordType<T>, data: T) => {
161
+ emitted.push({ type: type.name, data: data as Record<string, unknown> });
162
+ return {} as never;
163
+ },
164
+ }) as unknown as ActionContext;
165
+ return {
166
+ home: home.path,
167
+ emitted,
168
+ async call(name: "proc.run" | "proc.exec", input: unknown, signal?: AbortSignal): Promise<any> {
169
+ const found = actions.get(name);
170
+ if (found === undefined) throw new Error(`no action ${name}`);
171
+ return await found.run(found.input.parse(input), context(signal));
172
+ },
173
+ async stop() {
174
+ await niwa.close();
175
+ await home.cleanup();
176
+ },
177
+ };
178
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": [
4
+ "src"
5
+ ]
6
+ }