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 stop process ownership",
138 () => {
139 it.live.each(["graceful", "timeout", "external"] as const)(
140 "confirms the stop result for a %s server",
141 (mode) =>
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-stop-" });
147 const signalPath = path.join(fixture, "signals");
148 const child = yield* spawner.spawn(
149 ChildProcess.make(
150 process.execPath,
151 [
152 "--input-type=module",
153 "-e",
154 `import * as fs from "node:fs";
155import * as net from "node:net";
156const server = net.createServer((socket) => socket.end());
157let signals = 0;
158process.on("SIGTERM", () => {
159 fs.writeFileSync(process.argv[2], String(++signals));
160 if (process.argv[1] !== "timeout" || signals > 1) server.close();
161});
162server.listen(0, "127.0.0.1", () => {
163 process.stdout.write(JSON.stringify({ pid: process.pid, port: server.address().port, args: [] }) + "\\n");
164});
165`,
166 mode,
167 signalPath,
168 ],
169 { cwd: fixture, detached: false },
170 ),
171 );
172 // A failed assertion must still stop this captured fixture process.
173 yield* Effect.addFinalizer(() =>
174 child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore),
175 );
176 const started = decodeStarted(
177 yield* child.stdout.pipe(
178 Stream.decodeText(),
179 Stream.splitLines,
180 Stream.take(1),
181 Stream.mkString,
182 ),
183 );
184 assert.equal(started.pid, child.pid);
185 const savedState = {
186 pid: `${child.pid}\n`,
187 port: `${started.port}\n`,
188 managed: mode === "external" ? "external\n" : "managed\n",
189 };
190 for (const [name, contents] of Object.entries(savedState)) {
191 yield* fs.writeFileString(path.join(fixture, name), contents);
192 }
193 const script = buildRemoteStopScript({
194 alias: "fixture",
195 hostname: "fixture",
196 username: null,
197 port: null,
198 });
199 // Redirect only the state directory. Never use the developer's SSH state.
200 const isolatedScript = script.replace(
201 /^STATE_DIR=.*$/mu,
202 'STATE_DIR="$T3_TEST_STATE_DIR"',
203 );
204 assert.notEqual(isolatedScript, script);
205 const runStop = Effect.fn("test.remoteStop")(function* () {
206 const stop = yield* spawner.spawn(
207 ChildProcess.make("/bin/sh", ["-s"], {
208 cwd: fixture,
209 env: { T3_TEST_STATE_DIR: fixture },
210 stdin: Stream.make(new TextEncoder().encode(isolatedScript)),
211 }),
212 );
213 return yield* Effect.all(
214 {
215 stdout: stop.stdout.pipe(Stream.decodeText(), Stream.mkString),
216 stderr: stop.stderr.pipe(Stream.decodeText(), Stream.mkString),
217 exitCode: stop.exitCode,
218 },
219 { concurrency: "unbounded" },
220 );
221 }, Effect.scoped);
222 let result = yield* runStop();
223 if (mode !== "graceful") {
224 assert.isTrue(yield* child.isRunning);
225 yield* Effect.callback<void, Error>((resume) => {
226 const connection = NodeNet.connect(started.port, "127.0.0.1");
227 connection.once("error", (error) => resume(Effect.fail(error)));
228 connection.once("close", () => resume(Effect.void));
229 return Effect.sync(() => connection.destroy());
230 });
231 }
232 if (mode === "timeout") {
233 assert.equal(result.exitCode, 1);
234 assert.equal(result.stdout, "");
235 assert.include(result.stderr, "did not stop within 2 seconds");
236 assert.equal(yield* fs.readFileString(signalPath), "1");
237 for (const [name, contents] of Object.entries(savedState)) {
238 assert.equal(yield* fs.readFileString(path.join(fixture, name)), contents);
239 }
240 result = yield* runStop();
241 }
242 assert.equal(result.exitCode, 0);
243 assert.equal(result.stdout, '{"stopped":true}\n');
244 assert.equal(result.stderr, "");
245 for (const name of Object.keys(savedState)) {
246 assert.isFalse(yield* fs.exists(path.join(fixture, name)));
247 }
248 if (mode === "external") {
249 assert.isFalse(yield* fs.exists(signalPath));
250 } else {
251 assert.equal(yield* child.exitCode, 0);
252 assert.equal(yield* fs.readFileString(signalPath), mode === "timeout" ? "2" : "1");
253 }
254 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
255 );
256 },
257);
258
259const LaunchResult = Schema.Struct({
260 remotePort: Schema.Number,
261 serverKind: Schema.Literals(["external", "managed"]),
262});
263const decodeLaunchResult = Schema.decodeUnknownSync(Schema.fromJsonString(LaunchResult));
264
265// Stands in for `t3 serve`: answers the readiness probe and records itself in
266// the home's server-runtime.json, as every real server does.
267const FAKE_SERVER = `import * as fs from "node:fs";
268import * as http from "node:http";
269const flag = (name) => process.argv[process.argv.indexOf(name) + 1];
270const port = flag("--port");
271const home = flag("--base-dir");
272const runtimePath = home + "/userdata/server-runtime.json";
273const server = http.createServer((_request, response) => response.end("ok"));
274process.on("SIGTERM", () => {
275 fs.rmSync(runtimePath, { force: true });
276 process.exit(0);
277});
278server.listen(Number(port), "127.0.0.1", () => {
279 fs.mkdirSync(home + "/userdata", { recursive: true });
280 fs.writeFileSync(runtimePath, JSON.stringify({
281 version: 1,
282 pid: process.pid,
283 port: Number(port),
284 origin: "http://127.0.0.1:" + port,
285 }));
286 process.stdout.write("recorded\\n");
287});
288`;
289
290describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
291 "remote launch server reuse",
292 () => {
293 it.live("keeps its own managed server and hands off to a different one", () =>
294 Effect.gen(function* () {
295 const fs = yield* FileSystem.FileSystem;
296 const path = yield* Path.Path;
297 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
298 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launch-" });
299 const home = path.join(fixture, "home");
300 const bin = path.join(fixture, "bin");
301 const cliPath = path.join(fixture, "server.mjs");
302 const stateDir = path.join(home, ".t3", "ssh-launch", "fixture");
303 yield* fs.makeDirectory(bin);
304 yield* fs.makeDirectory(stateDir, { recursive: true });
305 yield* fs.symlink(process.execPath, path.join(bin, "node"));
306 yield* fs.writeFileString(cliPath, FAKE_SERVER);
307
308 const freePort = Effect.callback<number>((resume) => {
309 const probe = NodeNet.createServer();
310 probe.listen(0, "127.0.0.1", () => {
311 const { port } = probe.address() as NodeNet.AddressInfo;
312 probe.close(() => resume(Effect.succeed(port)));
313 });
314 });
315 // Seed the preferred port so the launch never scans the real 3773.
316 yield* fs.writeFileString(path.join(stateDir, "port"), `${yield* freePort}\n`);
317
318 const serverPids: number[] = [];
319 // Launched servers outlive the script, so stop each captured PID.
320 yield* Effect.addFinalizer(() =>
321 Effect.forEach(serverPids, (pid) =>
322 Effect.try(() => process.kill(pid, "SIGKILL")).pipe(Effect.ignore),
323 ),
324 );
325 const accepts = (port: number) =>
326 Effect.callback<boolean>((resume) => {
327 const connection = NodeNet.connect(port, "127.0.0.1");
328 connection.once("connect", () => resume(Effect.succeed(true)));
329 connection.once("error", () => resume(Effect.succeed(false)));
330 return Effect.sync(() => connection.destroy());
331 });
332
333 const launch = Effect.fn("test.remoteLaunch")(function* () {
334 const child = yield* spawner.spawn(
335 ChildProcess.make("/bin/sh", ["-s", "--", "fixture"], {
336 cwd: fixture,
337 env: { HOME: home, PATH: `${bin}:/usr/bin:/bin` },
338 stdin: Stream.make(
339 new TextEncoder().encode(buildRemoteLaunchScript({ nodeScriptPath: cliPath })),
340 ),
341 }),
342 );
343 const result = yield* Effect.all(
344 {
345 stdout: child.stdout.pipe(Stream.decodeText(), Stream.mkString),
346 stderr: child.stderr.pipe(Stream.decodeText(), Stream.mkString),
347 exitCode: child.exitCode,
348 },
349 { concurrency: "unbounded" },
350 );
351 assert.equal(result.exitCode, 0, result.stderr);
352 const pidText = yield* fs
353 .readFileString(path.join(stateDir, "pid"))
354 .pipe(Effect.orElseSucceed(() => ""));
355 const pid = Number.parseInt(pidText, 10);
356 if (Number.isInteger(pid)) serverPids.push(pid);
357 return { ...decodeLaunchResult(result.stdout.trim()), pid };
358 }, Effect.scoped);
359
360 const first = yield* launch();
361 assert.equal(first.serverKind, "managed");
362 const second = yield* launch();
363 assert.deepEqual(second, first);
364
365 // A different server in the default home is still adopted.
366 const externalPort = yield* freePort;
367 const external = yield* spawner.spawn(
368 ChildProcess.make(
369 process.execPath,
370 [cliPath, "--port", String(externalPort), "--base-dir", path.join(home, ".t3")],
371 { cwd: fixture, detached: false },
372 ),
373 );
374 yield* Effect.addFinalizer(() =>
375 external.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore),
376 );
377 // It has written server-runtime.json once it reports in.
378 yield* external.stdout.pipe(
379 Stream.decodeText(),
380 Stream.splitLines,
381 Stream.take(1),
382 Stream.runDrain,
383 );
384 const handedOff = yield* launch();
385 assert.equal(handedOff.serverKind, "external");
386 assert.equal(handedOff.remotePort, externalPort);
387 assert.isFalse(yield* accepts(first.remotePort));
388 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
389 );
390 },
391);