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

runnerProcess.test.ts

253 lines9.8 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as HostProcess 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/process";
12import * as NodeNet from "node:net";
13​
14import { remoteStateKey } from "./command.ts";
15import { buildRemoteStopScript, buildRemoteT3RunnerScript } from "./tunnel.ts";
16​
17const Started = Schema.Struct({
18 pid: Schema.Number,
19 port: Schema.Number,
20 args: Schema.Array(Schema.String),
21});
22const decodeStarted = Schema.decodeUnknownSync(Schema.fromJsonString(Started));
23​
24describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
25 "remote runner process ownership",
26 () => {
27 it.live("keeps the server PID and graceful shutdown through the node-script runner", () =>
28 Effect.gen(function* () {
29 const fs = yield* FileSystem.FileSystem;
30 const path = yield* Path.Path;
31 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
32 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-runner-" });
33 const bin = path.join(fixture, "bin");
34 const cliPath = path.join(fixture, "installed cli.mjs");
35 yield* fs.makeDirectory(bin);
36 yield* fs.symlink(process.execPath, path.join(bin, "node"));
37 yield* fs.writeFileString(
38 cliPath,
39 `#!/usr/bin/env node
40import * as net from "node:net";
41const server = net.createServer((socket) => {
42 socket.end();
43 server.close();
44});
45process.on("SIGTERM", () => server.close(() => {
46 process.stdout.write("graceful shutdown\\n");
47}));
48server.listen(Number(process.env.T3_TEST_PORT ?? 0), "127.0.0.1", () => {
49 process.stdout.write(JSON.stringify({
50 pid: process.pid,
51 port: server.address().port,
52 args: process.argv.slice(2),
53 }) + "\\n");
54});
55`,
56 );
57 yield* fs.chmod(cliPath, 0o700);
58​
59 const runServer = (port = 0) =>
60 Effect.gen(function* () {
61 const child = yield* spawner.spawn(
62 ChildProcess.make("/bin/sh", ["-s", "--", "serve", "a path with spaces"], {
63 cwd: fixture,
64 env: {
65 PATH: bin,
66 T3_TEST_PORT: String(port),
67 },
68 detached: false,
69 stdin: Stream.make(
70 new TextEncoder().encode(buildRemoteT3RunnerScript({ nodeScriptPath: cliPath })),
71 ),
72 }),
73 );
74 const ready = yield* Deferred.make<typeof Started.Type>();
75 const stdout: string[] = [];
76 const output = yield* child.stdout.pipe(
77 Stream.decodeText(),
78 Stream.splitLines,
79 Stream.runForEach((line) =>
80 Effect.gen(function* () {
81 stdout.push(line);
82 if (stdout.length === 1) {
83 yield* Deferred.succeed(ready, decodeStarted(line));
84 }
85 }),
86 ),
87 Effect.forkScoped,
88 );
89 const stderr = yield* child.stderr.pipe(
90 Stream.decodeText(),
91 Stream.mkString,
92 Effect.forkScoped,
93 );
94 const receipt = yield* Effect.raceFirst(
95 Deferred.await(ready),
96 Fiber.join(output).pipe(
97 Effect.flatMap(() => Fiber.join(stderr)),
98 Effect.flatMap((message) =>
99 Effect.die(new Error(`Runner exited before listening: ${message}`)),
100 ),
101 ),
102 );
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(HostProcess.Platform.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 yield* Effect.addFinalizer(() =>
169 child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore),
170 );
171 const started = decodeStarted(
172 yield* child.stdout.pipe(
173 Stream.decodeText(),
174 Stream.splitLines,
175 Stream.take(1),
176 Stream.mkString,
177 ),
178 );
179 assert.equal(started.pid, child.pid);
180 const savedState = {
181 pid: `${child.pid}\n`,
182 port: `${started.port}\n`,
183 managed: mode === "external" ? "external\n" : "managed\n",
184 };
185 for (const [name, contents] of Object.entries(savedState)) {
186 yield* fs.writeFileString(path.join(fixture, name), contents);
187 }
188 const script = buildRemoteStopScript(
189 yield* remoteStateKey({
190 alias: "fixture",
191 hostname: "fixture",
192 username: null,
193 port: null,
194 }),
195 );
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);