Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { 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 REMOTE_PICK_PORT_SCRIPT,
24 SshEnvironmentManager,
25 waitForHttpReady,
26} from "./tunnel.ts";
27
28const makeSuccessfulProcess = (stdout: string) => {
29 const stdoutStream = Stream.make(new TextEncoder().encode(stdout));
30 return ChildProcessSpawner.makeHandle({
31 pid: ChildProcessSpawner.ProcessId(123),
32 stdout: stdoutStream,
33 stderr: Stream.empty,
34 all: stdoutStream,
35 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
36 isRunning: Effect.succeed(false),
37 kill: () => Effect.void,
38 stdin: Sink.drain,
39 getInputFd: () => Sink.drain,
40 getOutputFd: () => Stream.empty,
41 unref: Effect.succeed(Effect.void),
42 });
43};
44
45const makeRunningProcess = (onKill: () => void) => {
46 let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null;
47 return ChildProcessSpawner.makeHandle({
48 pid: ChildProcessSpawner.ProcessId(123),
49 stdout: Stream.empty,
50 stderr: Stream.empty,
51 all: Stream.empty,
52 exitCode: Effect.callback<ChildProcessSpawner.ExitCode>((resume) => {
53 finish = (exitCode) => resume(Effect.succeed(exitCode));
54 return Effect.sync(() => {
55 finish = null;
56 });
57 }),
58 isRunning: Effect.succeed(true),
59 kill: () =>
60 Effect.sync(() => {
61 onKill();
62 finish?.(ChildProcessSpawner.ExitCode(143));
63 }),
64 stdin: Sink.drain,
65 getInputFd: () => Sink.drain,
66 getOutputFd: () => Stream.empty,
67 unref: Effect.succeed(Effect.void),
68 });
69};
70
71const testHttpClient = HttpClient.make((request) =>
72 Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))),
73);
74
75const hangingHttpClient = HttpClient.make(() => Effect.never);
76
77const testNetService = NetService.of({
78 canListenOnHost: () => Effect.succeed(true),
79 isPortAvailableOnLoopback: () => Effect.succeed(true),
80 reserveLoopbackPort: () => Effect.succeed(41_773),
81 findAvailablePort: (preferred) => Effect.succeed(preferred),
82});
83
84function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
85 return command._tag === "StandardCommand" ? command.args : [];
86}
87
88describe("ssh tunnel scripts", () => {
89 it("builds the remote t3 runner with npx and npm fallbacks", () => {
90 const script = buildRemoteT3RunnerScript();
91
92 assert.include(script, "T3_NODE_SCRIPT_PATH=''");
93 assert.include(script, 'exec t3 "$@"');
94 assert.include(script, "exec npx --yes 't3@latest' \"$@\"");
95 assert.include(script, "exec npm exec --yes 't3@latest' -- \"$@\"");
96 assert.include(script, "could not install 't3@latest'");
97 });
98
99 it("shell-quotes package specs in the remote t3 runner", () => {
100 const script = buildRemoteT3RunnerScript({
101 packageSpec: "t3@nightly; touch /tmp/t3-owned",
102 });
103
104 assert.include(script, "exec npx --yes 't3@nightly; touch /tmp/t3-owned' \"$@\"");
105 assert.include(script, "exec npm exec --yes 't3@nightly; touch /tmp/t3-owned' -- \"$@\"");
106 assert.notInclude(script, "exec npx --yes t3@nightly; touch /tmp/t3-owned");
107 });
108
109 it("builds the remote t3 runner with a node script override", () => {
110 const script = buildRemoteT3RunnerScript({
111 nodeScriptPath: "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs",
112 });
113
114 assert.include(
115 script,
116 "T3_NODE_SCRIPT_PATH='/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs'",
117 );
118 assert.include(script, 'exec node "$T3_NODE_SCRIPT_PATH" "$@"');
119 });
120
121 it("uses the remote t3 runner for launch and pairing scripts", () => {
122 const target = {
123 alias: "devbox",
124 hostname: "devbox.example.com",
125 username: "julius",
126 port: 2222,
127 } as const;
128
129 assert.include(
130 buildRemoteLaunchScript(),
131 '[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
132 );
133 assert.include(buildRemoteLaunchScript(), "RUNNER_CHANGED=1");
134 assert.include(buildRemoteLaunchScript(), 'kill "$REMOTE_PID" 2>/dev/null || true');
135 assert.include(buildRemoteLaunchScript(), "wait_ready");
136 assert.include(buildRemoteLaunchScript(), '"$RUNNER_FILE" serve --host 127.0.0.1');
137 assert.include(buildRemoteLaunchScript(), '--base-dir "$DEFAULT_SERVER_HOME"');
138 assert.notInclude(buildRemoteLaunchScript(), "server-home");
139 assert.include(buildRemoteLaunchScript(), "Remote T3 server did not become ready");
140 assert.include(buildRemoteLaunchScript({ packageSpec: "t3@nightly" }), "t3@nightly");
141 assert.include(
142 buildRemotePairingScript(target),
143 '"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
144 );
145 assert.include(buildRemotePairingScript(target), 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"');
146 assert.notInclude(buildRemotePairingScript(target), "server-home");
147 assert.include(buildRemotePairingScript(target, { packageSpec: "t3@nightly" }), "t3@nightly");
148 assert.include(
149 buildRemoteStopScript(target),
150 'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
151 );
152 assert.include(buildRemoteStopScript(target), 'kill "$REMOTE_PID" 2>/dev/null || true');
153 assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
154 assert.include(
155 buildRemoteLaunchScript(),
156 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
157 );
158 assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()");
159 assert.include(buildRemoteLaunchScript(), "printf 'external\\n' >\"$MANAGED_FILE\"");
160 assert.isBelow(
161 buildRemoteLaunchScript().indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
162 buildRemoteLaunchScript().indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
163 );
164 assert.isBelow(
165 buildRemoteLaunchScript().indexOf('DEFAULT_REMOTE_PORT="$(resolve_default_runtime_port'),
166 buildRemoteLaunchScript().indexOf('elif [ -n "$REMOTE_PID" ]'),
167 );
168 });
169
170 it("allows the remote port picker to run without a state file path", () => {
171 assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
172 });
173
174 it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
175 Effect.gen(function* () {
176 const fiber = yield* Effect.forkChild(
177 Effect.result(
178 waitForHttpReady({
179 baseUrl: "http://127.0.0.1:41773/",
180 timeoutMs: 1_000,
181 intervalMs: 100,
182 probeTimeoutMs: 250,
183 }),
184 ),
185 );
186 yield* Effect.yieldNow;
187 yield* TestClock.adjust(Duration.millis(1_000));
188
189 const result = yield* Fiber.join(fiber);
190
191 assert.isTrue(Result.isFailure(result));
192 if (Result.isFailure(result)) {
193 assert.include(result.failure.message, "Timed out waiting 1000ms");
194 }
195 }).pipe(
196 Effect.provide(
197 Layer.merge(TestClock.layer(), Layer.succeed(HttpClient.HttpClient, hangingHttpClient)),
198 ),
199 ),
200 );
201
202 it("preserves primitive readiness reason values in diagnostic output", () => {
203 assert.deepEqual(
204 describeReadinessCause({
205 _tag: "HttpClientError",
206 message: "Backend readiness probe failed.",
207 reason: "authentication failed",
208 cause: "upstream closed",
209 }),
210 {
211 _tag: "HttpClientError",
212 message: "Backend readiness probe failed.",
213 reason: "authentication failed",
214 cause: "upstream closed",
215 },
216 );
217 });
218
219 it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
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(
228 makeSuccessfulProcess(`{
229 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
230 "credential": "LCL4R2TPHDKQ",
231 "role": "client",
232 "expiresAt": "2026-04-29T01:01:20.994Z"
233}
234
235`),
236 ),
237 );
238 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
239 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
240 return Effect.gen(function* () {
241 const result = yield* issueRemotePairingToken(target);
242 assert.equal(result.credential, "LCL4R2TPHDKQ");
243 }).pipe(Effect.provide(processLayer));
244 });
245
246 it.effect("closes the tunnel scope and starts fresh after disconnect", () => {
247 const spawnedCommands: Array<ReadonlyArray<string>> = [];
248 let tunnelKillCount = 0;
249 let stopCommandCount = 0;
250 const spawner = ChildProcessSpawner.make((command) =>
251 Effect.sync(() => {
252 const args = commandArgs(command);
253 spawnedCommands.push(args);
254 if (args.includes("-N")) {
255 return makeRunningProcess(() => {
256 tunnelKillCount += 1;
257 });
258 }
259 if (args.includes("sh") && args.includes("--")) {
260 return makeSuccessfulProcess('{"remotePort":3773}\n');
261 }
262 if (args.includes("sh")) {
263 stopCommandCount += 1;
264 return makeSuccessfulProcess('{"stopped":true}\n');
265 }
266 return makeSuccessfulProcess("\n");
267 }),
268 );
269 const layer = Layer.mergeAll(
270 NodeServices.layer,
271 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
272 Layer.succeed(HttpClient.HttpClient, testHttpClient),
273 Layer.succeed(NetService, testNetService),
274 SshPasswordPrompt.disabledLayer,
275 SshEnvironmentManager.layer(),
276 );
277 const target = {
278 alias: "devbox",
279 hostname: "devbox.example.com",
280 username: "julius",
281 port: 2222,
282 } as const;
283
284 return Effect.gen(function* () {
285 const manager = yield* SshEnvironmentManager;
286
287 const first = yield* manager.ensureEnvironment(target);
288 assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
289
290 yield* manager.disconnectEnvironment(target);
291 assert.equal(tunnelKillCount, 1);
292 assert.equal(stopCommandCount, 1);
293
294 yield* manager.ensureEnvironment(target);
295
296 assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
297 assert.equal(tunnelKillCount, 1);
298 }).pipe(Effect.provide(layer), Effect.scoped);
299 });
300});