Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

runnerProcess.test.ts

253 lines9.9 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
12import * as NodeNet from "node:net";
13​
14import { buildRemoteStopScript, buildRemoteT3RunnerScript } from "./tunnel.ts";
15​
16const Started = Schema.Struct({
17 pid: Schema.Number,
18 port: Schema.Number,
19 args: Schema.Array(Schema.String),
20});
21const decodeStarted = Schema.decodeUnknownSync(Schema.fromJsonString(Started));
22​
23describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
24 "remote runner process ownership",
25 () => {
26 it.live("keeps the server PID and graceful shutdown through the node-script runner", () =>
27 Effect.gen(function* () {
28 const fs = yield* FileSystem.FileSystem;
29 const path = yield* Path.Path;
30 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
31 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-runner-" });
32 const bin = path.join(fixture, "bin");
33 const cliPath = path.join(fixture, "installed cli.mjs");
34 yield* fs.makeDirectory(bin);
35 yield* fs.symlink(process.execPath, path.join(bin, "node"));
36 yield* fs.writeFileString(
37 cliPath,
38 `#!/usr/bin/env node
39import * as net from "node:net";
40const server = net.createServer((socket) => {
41 socket.end();
42 server.close();
43});
44process.on("SIGTERM", () => server.close(() => {
45 process.stdout.write("graceful shutdown\\n");
46}));
47server.listen(Number(process.env.T3_TEST_PORT ?? 0), "127.0.0.1", () => {
48 process.stdout.write(JSON.stringify({
49 pid: process.pid,
50 port: server.address().port,
51 args: process.argv.slice(2),
52 }) + "\\n");
53});
54`,
55 );
56 yield* fs.chmod(cliPath, 0o700);
57​
58 const runServer = (port = 0) =>
59 Effect.gen(function* () {
60 const child = yield* spawner.spawn(
61 ChildProcess.make("/bin/sh", ["-s", "--", "serve", "a path with spaces"], {
62 cwd: fixture,
63 env: {
64 PATH: bin,
65 T3_TEST_PORT: String(port),
66 },
67 detached: false,
68 stdin: Stream.make(
69 new TextEncoder().encode(buildRemoteT3RunnerScript({ nodeScriptPath: cliPath })),
70 ),
71 }),
72 );
73 const ready = yield* Deferred.make<typeof Started.Type>();
74 const stdout: string[] = [];
75 const output = yield* child.stdout.pipe(
76 Stream.decodeText(),
77 Stream.splitLines,
78 Stream.runForEach((line) =>
79 Effect.gen(function* () {
80 stdout.push(line);
81 if (stdout.length === 1) {
82 yield* Deferred.succeed(ready, decodeStarted(line));
83 }
84 }),
85 ),
86 Effect.forkScoped,
87 );
88 const stderr = yield* child.stderr.pipe(
89 Stream.decodeText(),
90 Stream.mkString,
91 Effect.forkScoped,
92 );
93 const receipt = yield* Effect.raceFirst(
94 Deferred.await(ready),
95 Fiber.join(output).pipe(
96 Effect.flatMap(() => Fiber.join(stderr)),
97 Effect.flatMap((message) =>
98 Effect.die(new Error(`Runner exited before listening: ${message}`)),
99 ),
100 ),
101 );
102 // A failed PID assertion must still close the owned fixture server.
103 yield* Effect.addFinalizer(() =>
104 Effect.gen(function* () {
105 if (yield* child.isRunning) {
106 yield* Effect.callback<void>((resume) => {
107 const connection = NodeNet.connect(receipt.port, "127.0.0.1");
108 connection.on("error", () => undefined);
109 connection.once("close", () => resume(Effect.void));
110 return Effect.sync(() => connection.destroy());
111 });
112 yield* child.exitCode;
113 }
114 }).pipe(Effect.orDie),
115 );
116 assert.equal(receipt.pid, child.pid);
117 assert.deepEqual(receipt.args, ["serve", "a path with spaces"]);
118 yield* child.kill({ killSignal: "SIGTERM" });
119 assert.equal(yield* child.exitCode, 0);
120 yield* Fiber.join(output);
121 assert.include(stdout, "graceful shutdown");
122 return receipt.port;
123 }).pipe(Effect.scoped);
124​
125 const port = yield* runServer();
126 assert.equal(yield* runServer(port), port);
127 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
128 );
129 },
130);
131​
132describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
133 "remote stop process ownership",
134 () => {
135 it.live.each(["graceful", "timeout", "external"] as const)(
136 "confirms the stop result for a %s server",
137 (mode) =>
138 Effect.gen(function* () {
139 const fs = yield* FileSystem.FileSystem;
140 const path = yield* Path.Path;
141 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
142 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-stop-" });
143 const signalPath = path.join(fixture, "signals");
144 const child = yield* spawner.spawn(
145 ChildProcess.make(
146 process.execPath,
147 [
148 "--input-type=module",
149 "-e",
150 `import * as fs from "node:fs";
151import * as net from "node:net";
152const server = net.createServer((socket) => socket.end());
153let signals = 0;
154process.on("SIGTERM", () => {
155 fs.writeFileSync(process.argv[2], String(++signals));
156 if (process.argv[1] !== "timeout" || signals > 1) server.close();
157});
158server.listen(0, "127.0.0.1", () => {
159 process.stdout.write(JSON.stringify({ pid: process.pid, port: server.address().port, args: [] }) + "\\n");
160});
161`,
162 mode,
163 signalPath,
164 ],
165 { cwd: fixture, detached: false },
166 ),
167 );
168 // A failed assertion must still stop this captured fixture process.
169 yield* Effect.addFinalizer(() =>
170 child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore),
171 );
172 const started = decodeStarted(
173 yield* child.stdout.pipe(
174 Stream.decodeText(),
175 Stream.splitLines,
176 Stream.take(1),
177 Stream.mkString,
178 ),
179 );
180 assert.equal(started.pid, child.pid);
181 const savedState = {
182 pid: `${child.pid}\n`,
183 port: `${started.port}\n`,
184 managed: mode === "external" ? "external\n" : "managed\n",
185 };
186 for (const [name, contents] of Object.entries(savedState)) {
187 yield* fs.writeFileString(path.join(fixture, name), contents);
188 }
189 const script = buildRemoteStopScript({
190 alias: "fixture",
191 hostname: "fixture",
192 username: null,
193 port: null,
194 });
195 // Redirect only the state directory. Never use the developer's SSH state.
196 const isolatedScript = script.replace(
197 /^STATE_DIR=.*$/mu,
198 'STATE_DIR="$T3_TEST_STATE_DIR"',
199 );
200 assert.notEqual(isolatedScript, script);
201 const runStop = Effect.fn("test.remoteStop")(function* () {
202 const stop = yield* spawner.spawn(
203 ChildProcess.make("/bin/sh", ["-s"], {
204 cwd: fixture,
205 env: { T3_TEST_STATE_DIR: fixture },
206 stdin: Stream.make(new TextEncoder().encode(isolatedScript)),
207 }),
208 );
209 return yield* Effect.all(
210 {
211 stdout: stop.stdout.pipe(Stream.decodeText(), Stream.mkString),
212 stderr: stop.stderr.pipe(Stream.decodeText(), Stream.mkString),
213 exitCode: stop.exitCode,
214 },
215 { concurrency: "unbounded" },
216 );
217 }, Effect.scoped);
218 let result = yield* runStop();
219 if (mode !== "graceful") {
220 assert.isTrue(yield* child.isRunning);
221 yield* Effect.callback<void, Error>((resume) => {
222 const connection = NodeNet.connect(started.port, "127.0.0.1");
223 connection.once("error", (error) => resume(Effect.fail(error)));
224 connection.once("close", () => resume(Effect.void));
225 return Effect.sync(() => connection.destroy());
226 });
227 }
228 if (mode === "timeout") {
229 assert.equal(result.exitCode, 1);
230 assert.equal(result.stdout, "");
231 assert.include(result.stderr, "did not stop within 2 seconds");
232 assert.equal(yield* fs.readFileString(signalPath), "1");
233 for (const [name, contents] of Object.entries(savedState)) {
234 assert.equal(yield* fs.readFileString(path.join(fixture, name)), contents);
235 }
236 result = yield* runStop();
237 }
238 assert.equal(result.exitCode, 0);
239 assert.equal(result.stdout, '{"stopped":true}\n');
240 assert.equal(result.stderr, "");
241 for (const name of Object.keys(savedState)) {
242 assert.isFalse(yield* fs.exists(path.join(fixture, name)));
243 }
244 if (mode === "external") {
245 assert.isFalse(yield* fs.exists(signalPath));
246 } else {
247 assert.equal(yield* child.exitCode, 0);
248 assert.equal(yield* fs.readFileString(signalPath), mode === "timeout" ? "2" : "1");
249 }
250 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
251 );
252 },
253);