Open History to see the last commit
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 {
15 buildRemoteLaunchScript,
16 buildRemoteStopScript,
17 buildRemoteT3RunnerScript,
18} from "./tunnel.ts";
19
20const Started = Schema.Struct({
21 pid: Schema.Number,
22 port: Schema.Number,
23 args: Schema.Array(Schema.String),
24});
25const decodeStarted = Schema.decodeUnknownSync(Schema.fromJsonString(Started));
26
27describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
28 "remote runner process ownership",
29 () => {
30 it.live("keeps the server PID and graceful shutdown through the node-script runner", () =>
31 Effect.gen(function* () {
32 const fs = yield* FileSystem.FileSystem;
33 const path = yield* Path.Path;
34 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
35 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-runner-" });
36 const bin = path.join(fixture, "bin");
37 const cliPath = path.join(fixture, "installed cli.mjs");
38 yield* fs.makeDirectory(bin);
39 yield* fs.symlink(process.execPath, path.join(bin, "node"));
40 yield* fs.writeFileString(
41 cliPath,
42 `#!/usr/bin/env node
43import * as net from "node:net";
44const server = net.createServer((socket) => {
45 socket.end();
46 server.close();
47});
48process.on("SIGTERM", () => server.close(() => {
49 process.stdout.write("graceful shutdown\\n");
50}));
51server.listen(Number(process.env.T3_TEST_PORT ?? 0), "127.0.0.1", () => {
52 process.stdout.write(JSON.stringify({
53 pid: process.pid,
54 port: server.address().port,
55 args: process.argv.slice(2),
56 }) + "\\n");
57});
58`,
59 );
60 yield* fs.chmod(cliPath, 0o700);
61
62 const runServer = (port = 0) =>
63 Effect.gen(function* () {
64 const child = yield* spawner.spawn(
65 ChildProcess.make("/bin/sh", ["-s", "--", "serve", "a path with spaces"], {
66 cwd: fixture,
67 env: {
68 PATH: bin,
69 T3_TEST_PORT: String(port),
70 },
71 detached: false,
72 stdin: Stream.make(
73 new TextEncoder().encode(buildRemoteT3RunnerScript({ nodeScriptPath: cliPath })),
74 ),
75 }),
76 );
77 const ready = yield* Deferred.make<typeof Started.Type>();
78 const stdout: string[] = [];
79 const output = yield* child.stdout.pipe(
80 Stream.decodeText(),
81 Stream.splitLines,
82 Stream.runForEach((line) =>
83 Effect.gen(function* () {
84 stdout.push(line);
85 if (stdout.length === 1) {
86 yield* Deferred.succeed(ready, decodeStarted(line));
87 }
88 }),
89 ),
90 Effect.forkScoped,
91 );
92 const stderr = yield* child.stderr.pipe(
93 Stream.decodeText(),
94 Stream.mkString,
95 Effect.forkScoped,
96 );
97 const receipt = yield* Effect.raceFirst(
98 Deferred.await(ready),
99 Fiber.join(output).pipe(
100 Effect.flatMap(() => Fiber.join(stderr)),
101 Effect.flatMap((message) =>
102 Effect.die(new Error(`Runner exited before listening: ${message}`)),
103 ),
104 ),
105 );
106 // A failed PID assertion must still close the owned fixture server.
107 yield* Effect.addFinalizer(() =>
108 Effect.gen(function* () {
109 if (yield* child.isRunning) {
110 yield* Effect.callback<void>((resume) => {
111 const connection = NodeNet.connect(receipt.port, "127.0.0.1");
112 connection.on("error", () => undefined);
113 connection.once("close", () => resume(Effect.void));
114 return Effect.sync(() => connection.destroy());
115 });
116 yield* child.exitCode;
117 }
118 }).pipe(Effect.orDie),
119 );
120 assert.equal(receipt.pid, child.pid);
121 assert.deepEqual(receipt.args, ["serve", "a path with spaces"]);
122 yield* child.kill({ killSignal: "SIGTERM" });
123 assert.equal(yield* child.exitCode, 0);
124 yield* Fiber.join(output);
125 assert.include(stdout, "graceful shutdown");
126 return receipt.port;
127 }).pipe(Effect.scoped);
128
129 const port = yield* runServer();
130 assert.equal(yield* runServer(port), port);
131 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
132 );
133 },
134);
135
136describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
137 "remote reconnect process ownership",
138 () => {
139 it.live.each(["managed", "external", "missing-pid"] as const)(
140 "reuses the same %s server published in the runtime file",
141 (serverKind) =>
142 Effect.gen(function* () {
143 const fs = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
146 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-reconnect-" });
147 const runner = { nodeScriptPath: path.join(fixture, "unused-cli.mjs") };
148 const child = yield* spawner.spawn(
149 ChildProcess.make(
150 process.execPath,
151 [
152 "--input-type=module",
153 "-e",
154 `import * as http from "node:http";
155import * as fs from "node:fs";
156const server = http.createServer((_request, response) => response.end("ready"));
157process.on("SIGTERM", () => fs.writeFileSync("stopped", "SIGTERM"));
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 ],
163 { cwd: fixture, detached: false },
164 ),
165 );
166 yield* Effect.addFinalizer(() =>
167 child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore),
168 );
169 const started = decodeStarted(
170 yield* child.stdout.pipe(
171 Stream.decodeText(),
172 Stream.splitLines,
173 Stream.take(1),
174 Stream.mkString,
175 ),
176 );
177 yield* fs.makeDirectory(path.join(fixture, "userdata"));
178 yield* fs.writeFileString(
179 path.join(fixture, "userdata", "server-runtime.json"),
180 `{"pid":${started.pid},"port":${started.port},"origin":"http://127.0.0.1:${started.port}"}`,
181 );
182 yield* fs.writeFileString(
183 path.join(fixture, "run-t3.sh"),
184 `${buildRemoteT3RunnerScript(runner)}\n`,
185 );
186 yield* fs.writeFileString(path.join(fixture, "port"), `${started.port}\n`);
187 yield* fs.writeFileString(
188 path.join(fixture, "managed"),
189 `${serverKind === "external" ? "external" : "managed"}\n`,
190 );
191 if (serverKind === "managed") {
192 yield* fs.writeFileString(path.join(fixture, "pid"), `${started.pid}\n`);
193 }
194 // Redirect state discovery and ownership files to this fixture only.
195 const script = buildRemoteLaunchScript(runner)
196 .replace(/^STATE_DIR=.*$/mu, 'STATE_DIR="$T3_TEST_STATE_DIR"')
197 .replace(/^DEFAULT_SERVER_HOME=.*$/mu, 'DEFAULT_SERVER_HOME="$T3_TEST_STATE_DIR"');
198 const launch = yield* spawner.spawn(
199 ChildProcess.make("/bin/sh", ["-s", "--", "fixture"], {
200 cwd: fixture,
201 env: { T3_TEST_STATE_DIR: fixture },
202 extendEnv: true,
203 stdin: Stream.make(new TextEncoder().encode(script)),
204 }),
205 );
206 const result = yield* Effect.all(
207 {
208 stdout: launch.stdout.pipe(Stream.decodeText(), Stream.mkString),
209 stderr: launch.stderr.pipe(Stream.decodeText(), Stream.mkString),
210 exitCode: launch.exitCode,
211 },
212 { concurrency: "unbounded" },
213 );
214 assert.equal(result.exitCode, 0, result.stderr);
215 assert.isFalse(yield* fs.exists(path.join(fixture, "stopped")));
216 assert.isTrue(yield* child.isRunning);
217 const expectedKind = serverKind === "missing-pid" ? "external" : serverKind;
218 assert.equal(
219 result.stdout,
220 `{"remotePort":${started.port},"serverKind":"${expectedKind}"}\n`,
221 );
222 assert.equal(
223 yield* fs.readFileString(path.join(fixture, "managed")),
224 `${expectedKind}\n`,
225 );
226 if (serverKind === "managed") {
227 assert.equal(yield* fs.readFileString(path.join(fixture, "pid")), `${started.pid}\n`);
228 } else {
229 assert.isFalse(yield* fs.exists(path.join(fixture, "pid")));
230 }
231 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
232 );
233 },
234);
235
236describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
237 "remote stop process ownership",
238 () => {
239 it.live.each(["graceful", "timeout", "external"] as const)(
240 "confirms the stop result for a %s server",
241 (mode) =>
242 Effect.gen(function* () {
243 const fs = yield* FileSystem.FileSystem;
244 const path = yield* Path.Path;
245 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
246 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-stop-" });
247 const signalPath = path.join(fixture, "signals");
248 const child = yield* spawner.spawn(
249 ChildProcess.make(
250 process.execPath,
251 [
252 "--input-type=module",
253 "-e",
254 `import * as fs from "node:fs";
255import * as net from "node:net";
256const server = net.createServer((socket) => socket.end());
257let signals = 0;
258process.on("SIGTERM", () => {
259 fs.writeFileSync(process.argv[2], String(++signals));
260 if (process.argv[1] !== "timeout" || signals > 1) server.close();
261});
262server.listen(0, "127.0.0.1", () => {
263 process.stdout.write(JSON.stringify({ pid: process.pid, port: server.address().port, args: [] }) + "\\n");
264});
265`,
266 mode,
267 signalPath,
268 ],
269 { cwd: fixture, detached: false },
270 ),
271 );
272 // A failed assertion must still stop this captured fixture process.
273 yield* Effect.addFinalizer(() =>
274 child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore),
275 );
276 const started = decodeStarted(
277 yield* child.stdout.pipe(
278 Stream.decodeText(),
279 Stream.splitLines,
280 Stream.take(1),
281 Stream.mkString,
282 ),
283 );
284 assert.equal(started.pid, child.pid);
285 const savedState = {
286 pid: `${child.pid}\n`,
287 port: `${started.port}\n`,
288 managed: mode === "external" ? "external\n" : "managed\n",
289 };
290 for (const [name, contents] of Object.entries(savedState)) {
291 yield* fs.writeFileString(path.join(fixture, name), contents);
292 }
293 const script = buildRemoteStopScript({
294 alias: "fixture",
295 hostname: "fixture",
296 username: null,
297 port: null,
298 });
299 // Redirect only the state directory. Never use the developer's SSH state.
300 const isolatedScript = script.replace(
301 /^STATE_DIR=.*$/mu,
302 'STATE_DIR="$T3_TEST_STATE_DIR"',
303 );
304 assert.notEqual(isolatedScript, script);
305 const runStop = Effect.fn("test.remoteStop")(function* () {
306 const stop = yield* spawner.spawn(
307 ChildProcess.make("/bin/sh", ["-s"], {
308 cwd: fixture,
309 env: { T3_TEST_STATE_DIR: fixture },
310 stdin: Stream.make(new TextEncoder().encode(isolatedScript)),
311 }),
312 );
313 return yield* Effect.all(
314 {
315 stdout: stop.stdout.pipe(Stream.decodeText(), Stream.mkString),
316 stderr: stop.stderr.pipe(Stream.decodeText(), Stream.mkString),
317 exitCode: stop.exitCode,
318 },
319 { concurrency: "unbounded" },
320 );
321 }, Effect.scoped);
322 let result = yield* runStop();
323 if (mode !== "graceful") {
324 assert.isTrue(yield* child.isRunning);
325 yield* Effect.callback<void, Error>((resume) => {
326 const connection = NodeNet.connect(started.port, "127.0.0.1");
327 connection.once("error", (error) => resume(Effect.fail(error)));
328 connection.once("close", () => resume(Effect.void));
329 return Effect.sync(() => connection.destroy());
330 });
331 }
332 if (mode === "timeout") {
333 assert.equal(result.exitCode, 1);
334 assert.equal(result.stdout, "");
335 assert.include(result.stderr, "did not stop within 2 seconds");
336 assert.equal(yield* fs.readFileString(signalPath), "1");
337 for (const [name, contents] of Object.entries(savedState)) {
338 assert.equal(yield* fs.readFileString(path.join(fixture, name)), contents);
339 }
340 result = yield* runStop();
341 }
342 assert.equal(result.exitCode, 0);
343 assert.equal(result.stdout, '{"stopped":true}\n');
344 assert.equal(result.stderr, "");
345 for (const name of Object.keys(savedState)) {
346 assert.isFalse(yield* fs.exists(path.join(fixture, name)));
347 }
348 if (mode === "external") {
349 assert.isFalse(yield* fs.exists(signalPath));
350 } else {
351 assert.equal(yield* child.exitCode, 0);
352 assert.equal(yield* fs.readFileString(signalPath), mode === "timeout" ? "2" : "1");
353 }
354 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
355 );
356 },
357);