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

tunnel.test.ts

401 lines15.2 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as NetService from "@t3tools/shared/Net";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
8import * as Result from "effect/Result";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import { TestClock } from "effect/testing";
12import { HttpClient, HttpClientResponse } from "effect/unstable/http";
13import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
14​
15import { SshPasswordPrompt } from "./auth.ts";
16import {
17 buildRemoteLaunchScript,
18 buildRemotePairingScript,
19 buildRemoteStopScript,
20 buildRemoteT3RunnerScript,
21 describeReadinessCause,
22 issueRemotePairingToken,
23 launchOrReuseRemoteServer,
24 REMOTE_PICK_PORT_SCRIPT,
25 SshEnvironmentManager,
26 waitForHttpReady,
27} from "./tunnel.ts";
28​
29const TEST_NODE_ENGINE_RANGE = "^22.16 || ^23.11 || >=24.10";
30​
31const makeSuccessfulProcess = (stdout: string) => {
32 const stdoutStream = Stream.make(new TextEncoder().encode(stdout));
33 return ChildProcessSpawner.makeHandle({
34 pid: ChildProcessSpawner.ProcessId(123),
35 stdout: stdoutStream,
36 stderr: Stream.empty,
37 all: stdoutStream,
38 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
39 isRunning: Effect.succeed(false),
40 kill: () => Effect.void,
41 stdin: Sink.drain,
42 getInputFd: () => Sink.drain,
43 getOutputFd: () => Stream.empty,
44 unref: Effect.succeed(Effect.void),
45 });
46};
47​
48const makeRunningProcess = (onKill: () => void) => {
49 let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null;
50 return ChildProcessSpawner.makeHandle({
51 pid: ChildProcessSpawner.ProcessId(123),
52 stdout: Stream.empty,
53 stderr: Stream.empty,
54 all: Stream.empty,
55 exitCode: Effect.callback<ChildProcessSpawner.ExitCode>((resume) => {
56 finish = (exitCode) => resume(Effect.succeed(exitCode));
57 return Effect.sync(() => {
58 finish = null;
59 });
60 }),
61 isRunning: Effect.succeed(true),
62 kill: () =>
63 Effect.sync(() => {
64 onKill();
65 finish?.(ChildProcessSpawner.ExitCode(143));
66 }),
67 stdin: Sink.drain,
68 getInputFd: () => Sink.drain,
69 getOutputFd: () => Stream.empty,
70 unref: Effect.succeed(Effect.void),
71 });
72};
73​
74const testHttpClient = HttpClient.make((request) =>
75 Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))),
76);
77​
78const hangingHttpClient = HttpClient.make(() => Effect.never);
79​
80const testNetService = NetService.NetService.of({
81 canListenOnHost: () => Effect.succeed(true),
82 isPortAvailableOnLoopback: () => Effect.succeed(true),
83 hasListenerOnHost: () => Effect.succeed(false),
84 reserveLoopbackPort: () => Effect.succeed(41_773),
85 findAvailablePort: (preferred) => Effect.succeed(preferred),
86});
87​
88function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
89 return command._tag === "StandardCommand" ? command.args : [];
91​
92describe("ssh tunnel scripts", () => {
93 it("builds the remote t3 runner with npx and npm fallbacks", () => {
94 const script = buildRemoteT3RunnerScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE });
95​
96 assert.include(script, "T3_NODE_SCRIPT_PATH=''");
97 assert.include(script, 'exec t3 "$@"');
98 assert.include(script, "exec npx --yes 't3@latest' \"$@\"");
99 assert.include(script, "exec npm exec --yes 't3@latest' -- \"$@\"");
100 assert.include(script, "could not install 't3@latest'");
101 assert.include(script, 'prepend_path_if_dir "$HOME/.local/bin"');
102 assert.include(script, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
103 assert.include(script, "remote_node_satisfies_engine()");
104 assert.include(script, "function satisfiesSemverRange");
105 assert.include(script, "satisfiesSemverRange(rawVersion, range)");
106 assert.include(script, 'prepend_path_if_dir "$VOLTA_HOME/bin"');
107 assert.include(script, 'prepend_path_if_dir "$HOME/.asdf/shims"');
108 assert.include(script, 'prepend_path_if_dir "$HOME/.local/share/mise/shims"');
109 assert.include(script, 'eval "$(fnm env --shell bash)"');
110 assert.include(script, "fnm use --silent-if-unchanged");
111 assert.include(script, "fnm use default");
112 assert.include(script, 'prepend_path_if_dir "$HOME/.nodenv/shims"');
113 assert.include(script, 'NVM_DIR="$HOME/.nvm"');
114 assert.include(script, "nvm use --silent default");
115 assert.include(script, 'for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin');
116 assert.notInclude(script, "ensure $NVM_DIR/nvm.sh is available");
117 });
118​
119 it("does not hard-code a remote node engine range", () => {
120 const script = buildRemoteT3RunnerScript();
121​
122 assert.include(script, "T3_NODE_ENGINE_RANGE=''");
123 assert.notInclude(script, TEST_NODE_ENGINE_RANGE);
124 });
125​
126 it("shell-quotes package specs in the remote t3 runner", () => {
127 const script = buildRemoteT3RunnerScript({
128 packageSpec: "t3@nightly; touch /tmp/t3-owned",
129 });
130​
131 assert.include(script, "exec npx --yes 't3@nightly; touch /tmp/t3-owned' \"$@\"");
132 assert.include(script, "exec npm exec --yes 't3@nightly; touch /tmp/t3-owned' -- \"$@\"");
133 assert.notInclude(script, "exec npx --yes t3@nightly; touch /tmp/t3-owned");
134 });
135​
136 it("builds the remote t3 runner with a node script override", () => {
137 const script = buildRemoteT3RunnerScript({
138 nodeScriptPath: "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs",
139 });
140​
141 assert.include(
142 script,
143 "T3_NODE_SCRIPT_PATH='/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs'",
144 );
145 assert.include(script, 'exec node "$T3_NODE_SCRIPT_PATH" "$@"');
146 });
147​
148 it("uses the remote t3 runner for launch and pairing scripts", () => {
149 const target = {
150 alias: "devbox",
151 hostname: "devbox.example.com",
152 username: "julius",
153 port: 2222,
154 } as const;
155​
156 assert.include(
157 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
158 '[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
159 );
160 assert.include(buildRemoteLaunchScript(), "RUNNER_CHANGED=1");
161 assert.include(buildRemoteLaunchScript(), "ensure_remote_node_path()");
162 assert.include(buildRemoteLaunchScript(), "if ! ensure_remote_node_path; then");
163 assert.include(
164 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
165 `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`,
166 );
167 assert.include(
168 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
169 "does not satisfy required range ",
170 );
171 assert.include(buildRemoteLaunchScript(), 'kill "$REMOTE_PID" 2>/dev/null || true');
172 assert.include(buildRemoteLaunchScript(), "wait_ready");
173 assert.include(buildRemoteLaunchScript(), '"$RUNNER_FILE" serve --host 127.0.0.1');
174 assert.include(buildRemoteLaunchScript(), '--base-dir "$DEFAULT_SERVER_HOME"');
175 assert.notInclude(buildRemoteLaunchScript(), "server-home");
176 assert.include(buildRemoteLaunchScript(), "Remote T3 server did not become ready");
177 assert.include(buildRemoteLaunchScript({ packageSpec: "t3@nightly" }), "t3@nightly");
178 assert.include(
179 buildRemotePairingScript(target),
180 '"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
181 );
182 assert.include(buildRemotePairingScript(target), 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"');
183 assert.notInclude(buildRemotePairingScript(target), "server-home");
184 assert.include(buildRemotePairingScript(target, { packageSpec: "t3@nightly" }), "t3@nightly");
185 assert.include(
186 buildRemoteStopScript(target),
187 'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
188 );
189 assert.include(buildRemoteStopScript(target), 'kill "$REMOTE_PID" 2>/dev/null || true');
190 assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
191 assert.include(
192 buildRemoteLaunchScript(),
193 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
194 );
195 assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()");
196 assert.include(
197 buildRemoteLaunchScript(),
198 'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port',
199 );
200 assert.include(
201 buildRemoteLaunchScript(),
202 "if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))",
203 );
204 assert.include(buildRemoteLaunchScript(), 'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"');
205 assert.include(buildRemoteLaunchScript(), 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
206 assert.include(buildRemoteLaunchScript(), 'rm -f "$PID_FILE"');
207 assert.include(buildRemoteLaunchScript(), "printf 'external\\n' >\"$MANAGED_FILE\"");
208 assert.include(buildRemoteLaunchScript(), 'if [ -z "$REMOTE_PORT" ]; then');
209 assert.isBelow(
210 buildRemoteLaunchScript().indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
211 buildRemoteLaunchScript().indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
212 );
213 assert.isBelow(
214 buildRemoteLaunchScript().indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
215 buildRemoteLaunchScript().indexOf('elif [ -n "$REMOTE_PID" ]'),
216 );
217 });
218​
219 it.effect("accepts launch JSON after remote shell startup noise", () => {
220 const target = {
221 alias: "devbox",
222 hostname: "devbox.example.com",
223 username: "julius",
224 port: 2222,
225 } as const;
226 const spawner = ChildProcessSpawner.make(() =>
227 Effect.succeed(makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n')),
228 );
229 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
230 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
231​
232 return Effect.gen(function* () {
233 const result = yield* launchOrReuseRemoteServer(target);
234 assert.equal(result.remotePort, 3774);
235 }).pipe(Effect.provide(processLayer));
236 });
237​
238 it("allows the remote port picker to run without a state file path", () => {
239 assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
240 });
241​
242 it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
243 Effect.gen(function* () {
244 const fiber = yield* Effect.forkChild(
245 Effect.result(
246 waitForHttpReady({
247 baseUrl: "http://127.0.0.1:41773/",
248 timeoutMs: 1_000,
249 intervalMs: 100,
250 probeTimeoutMs: 250,
251 }),
252 ),
253 );
254 yield* Effect.yieldNow;
255 yield* TestClock.adjust(Duration.millis(1_000));
256​
257 const result = yield* Fiber.join(fiber);
258​
259 assert.isTrue(Result.isFailure(result));
260 if (Result.isFailure(result)) {
261 assert.include(result.failure.message, "Timed out waiting 1000ms");
262 }
263 }).pipe(
264 Effect.provide(
265 Layer.merge(TestClock.layer(), Layer.succeed(HttpClient.HttpClient, hangingHttpClient)),
266 ),
267 ),
268 );
269​
270 it("preserves primitive readiness reason values in diagnostic output", () => {
271 assert.deepEqual(
272 describeReadinessCause({
273 _tag: "HttpClientError",
274 message: "Backend readiness probe failed.",
275 reason: "authentication failed",
276 cause: "upstream closed",
277 }),
278 {
279 _tag: "HttpClientError",
280 message: "Backend readiness probe failed.",
281 reason: "authentication failed",
282 cause: "upstream closed",
283 },
284 );
285 });
286​
287 it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
288 const target = {
289 alias: "devbox",
290 hostname: "devbox.example.com",
291 username: "julius",
292 port: 2222,
293 } as const;
294 const spawner = ChildProcessSpawner.make(() =>
295 Effect.succeed(
296 makeSuccessfulProcess(`{
297 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
298 "credential": "LCL4R2TPHDKQ",
299 "scopes": ["orchestration:read"],
300 "expiresAt": "2026-04-29T01:01:20.994Z"
302​
303`),
304 ),
305 );
306 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
307 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
308 return Effect.gen(function* () {
309 const result = yield* issueRemotePairingToken(target);
310 assert.equal(result.credential, "LCL4R2TPHDKQ");
311 }).pipe(Effect.provide(processLayer));
312 });
313​
314 it.effect("accepts pretty-printed pairing JSON after remote shell startup noise", () => {
315 const target = {
316 alias: "devbox",
317 hostname: "devbox.example.com",
318 username: "julius",
319 port: 2222,
320 } as const;
321 const spawner = ChildProcessSpawner.make(() =>
322 Effect.succeed(
323 makeSuccessfulProcess(`loaded nvm default
325 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
326 "credential": "LCL4R2TPHDKQ",
327 "scopes": ["orchestration:read"],
328 "expiresAt": "2026-04-29T01:01:20.994Z"
330​
331`),
332 ),
333 );
334 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
335 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
336 return Effect.gen(function* () {
337 const result = yield* issueRemotePairingToken(target);
338 assert.equal(result.credential, "LCL4R2TPHDKQ");
339 }).pipe(Effect.provide(processLayer));
340 });
341​
342 it.effect("closes the tunnel scope and starts fresh after disconnect", () => {
343 const spawnedCommands: Array<ReadonlyArray<string>> = [];
344 let tunnelKillCount = 0;
345 let stopCommandCount = 0;
346 const spawner = ChildProcessSpawner.make((command) =>
347 Effect.sync(() => {
348 const args = commandArgs(command);
349 spawnedCommands.push(args);
350 if (args.includes("-N")) {
351 return makeRunningProcess(() => {
352 tunnelKillCount += 1;
353 });
354 }
355 if (args.includes("sh") && args.includes("--")) {
356 return makeSuccessfulProcess('{"remotePort":3773}\n');
357 }
358 if (args.includes("sh")) {
359 stopCommandCount += 1;
360 return makeSuccessfulProcess('{"stopped":true}\n');
361 }
362 return makeSuccessfulProcess("\n");
363 }),
364 );
365 const layer = Layer.mergeAll(
366 NodeServices.layer,
367 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
368 Layer.succeed(HttpClient.HttpClient, testHttpClient),
369 Layer.succeed(NetService.NetService, testNetService),
370 SshPasswordPrompt.disabledLayer,
371 SshEnvironmentManager.layer(),
372 );
373 const target = {
374 alias: "devbox",
375 hostname: "devbox.example.com",
376 username: "julius",
377 port: 2222,
378 } as const;
379​
380 return Effect.gen(function* () {
381 const manager = yield* SshEnvironmentManager;
382​
383 const first = yield* manager.ensureEnvironment(target);
384 assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
385 const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
386 assert.isDefined(firstTunnelArgs);
387 assert.include(firstTunnelArgs, "ControlMaster=no");
388 assert.include(firstTunnelArgs, "ControlPath=none");
389 assert.include(firstTunnelArgs, "ControlPersist=no");
390​
391 yield* manager.disconnectEnvironment(target);
392 assert.equal(tunnelKillCount, 1);
393 assert.equal(stopCommandCount, 1);
394​
395 yield* manager.ensureEnvironment(target);
396​
397 assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
398 assert.equal(tunnelKillCount, 1);
399 }).pipe(Effect.provide(layer), Effect.scoped);
400 });
401});