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

tunnel.test.ts

806 lines31.6 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as NetService from "@t3tools/shared/Net";
4import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Result from "effect/Result";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import { TestClock } from "effect/testing";
15import { HttpClient, HttpClientResponse } from "effect/unstable/http";
16import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
17​
18import * as SshAuth from "./auth.ts";
19import { SshCommandError } from "./errors.ts";
20import * as SshTunnel from "./tunnel.ts";
21​
22const TEST_NODE_ENGINE_RANGE = "^22.16 || ^23.11 || >=24.10";
23​
24const makeSuccessfulProcess = (stdout: string) => {
25 const stdoutStream = Stream.make(new TextEncoder().encode(stdout));
26 return ChildProcessSpawner.makeHandle({
27 pid: ChildProcessSpawner.ProcessId(123),
28 stdout: stdoutStream,
29 stderr: Stream.empty,
30 all: stdoutStream,
31 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
32 isRunning: Effect.succeed(false),
33 kill: () => Effect.void,
34 stdin: Sink.drain,
35 getInputFd: () => Sink.drain,
36 getOutputFd: () => Stream.empty,
37 unref: Effect.succeed(Effect.void),
38 });
39};
40​
41const makeDelayedSuccessfulProcess = (stdout: string, delayMs: number) => {
42 const process = makeSuccessfulProcess(stdout);
43 return {
44 ...process,
45 exitCode: Effect.sleep(Duration.millis(delayMs)).pipe(
46 Effect.as(ChildProcessSpawner.ExitCode(0)),
47 ),
48 };
49};
50​
51const makeRunningProcess = (onKill: () => void) => {
52 let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null;
53 return ChildProcessSpawner.makeHandle({
54 pid: ChildProcessSpawner.ProcessId(123),
55 stdout: Stream.empty,
56 stderr: Stream.empty,
57 all: Stream.empty,
58 exitCode: Effect.callback<ChildProcessSpawner.ExitCode>((resume) => {
59 finish = (exitCode) => resume(Effect.succeed(exitCode));
60 return Effect.sync(() => {
61 finish = null;
62 });
63 }),
64 isRunning: Effect.succeed(true),
65 kill: () =>
66 Effect.sync(() => {
67 onKill();
68 finish?.(ChildProcessSpawner.ExitCode(143));
69 }),
70 stdin: Sink.drain,
71 getInputFd: () => Sink.drain,
72 getOutputFd: () => Stream.empty,
73 unref: Effect.succeed(Effect.void),
74 });
75};
76​
77const testHttpClient = HttpClient.make((request) =>
78 Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))),
79);
80​
81const hangingHttpClient = HttpClient.make(() => Effect.never);
82​
83const testNetService = NetService.NetService.of({
84 canListenOnHost: () => Effect.succeed(true),
85 isPortAvailableOnLoopback: () => Effect.succeed(true),
86 hasListenerOnHost: () => Effect.succeed(false),
87 reserveLoopbackPort: () => Effect.succeed(41_773),
88 findAvailablePort: (preferred) => Effect.succeed(preferred),
89});
90​
91function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
92 return command._tag === "StandardCommand" ? command.args : [];
94​
95const ARCHIVE = { archiveVersion: "1.2.3-preview.20260911.4" } as const;
96const NODE_SCRIPT = {
97 nodeScriptPath: "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs",
98} as const;
99​
100describe("ssh tunnel scripts", () => {
101 it("installs and runs the release archive without Node, npm, or npx", () => {
102 const script = SshTunnel.buildRemoteT3RunnerScript(ARCHIVE);
103​
104 assert.include(script, "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'");
105 assert.include(script, "T3_NODE_SCRIPT_PATH=''");
106 assert.include(
107 script,
108 "T3_RELEASE_BASE_URL='https://github.com/pingdotgg/t3code/releases/download'",
109 );
110 assert.include(script, 'T3_RUNTIME_DIR="$HOME/.t3/runtime/versions/$T3_ARCHIVE_VERSION"');
111 assert.include(script, 'T3_ARCHIVE="t3-$T3_ARCHIVE_VERSION-$T3_PLATFORM-$T3_ARCH.tar.gz"');
112 assert.include(script, "SHA256SUMS");
113 assert.include(script, 'exec "$T3_RUNTIME_DIR/t3" "$@"');
114 assert.notInclude(script, "npx");
115 assert.notInclude(script, "npm exec");
116 assert.notInclude(script, "t3@latest");
117 assert.notInclude(script, 'exec t3 "$@"');
118 // Concurrent launches serialize on a per-version mkdir lock and recheck
119 // the completion marker after acquiring it.
120 assert.include(
121 script,
122 'T3_LOCK="$HOME/.t3/runtime/versions/.$T3_ARCHIVE_VERSION.install.lock"',
123 );
124 // mkdir is the exclusive create; the pid follows atomically. A dead owner
125 // is reclaimed at once, a never-published owner after a short grace.
126 assert.include(script, 'while ! mkdir "$T3_LOCK" 2>/dev/null; do');
127 assert.include(script, 'mv "$T3_LOCK/pid.tmp" "$T3_LOCK/pid"');
128 assert.include(script, 'if ! kill -0 "$T3_LOCK_OWNER" 2>/dev/null; then');
129 assert.include(script, 'if [ "$T3_LOCK_UNOWNED" -ge 5 ]; then');
130 assert.include(script, 'if [ "$T3_LOCK_WAITED" -ge 360 ]; then');
131 assert.include(script, '"$T3_STAGING/SHA256SUMS" 30');
132 assert.include(script, '"$T3_STAGING/$T3_ARCHIVE" 240');
133 assert.notInclude(script, "T3_LOCK_CANDIDATE");
134 assert.notInclude(script, "-mmin");
135 assert.equal(script.split("if ! t3_runtime_ready; then").length - 1, 2);
136 assert.isBelow(
137 script.indexOf('"$T3_STAGING/t3" --version'),
138 script.indexOf('> "$T3_STAGING/.install-complete"'),
139 );
140 // Node discovery is defined for the dev path but only ever invoked inside
141 // the node-script branch, which the archive path skips entirely.
142 assert.equal(script.split("ensure_remote_node_path || true").length - 1, 1);
143 assert.isBelow(
144 script.indexOf("ensure_remote_node_path || true"),
145 script.indexOf('exec node "$T3_NODE_SCRIPT_PATH" "$@"'),
146 );
147 assert.isBelow(
148 script.indexOf('exec node "$T3_NODE_SCRIPT_PATH" "$@"'),
149 script.indexOf("T3_ARCHIVE_VERSION="),
150 );
151​
152 const launch = SshTunnel.buildRemoteLaunchScript({
153 ...ARCHIVE,
154 releaseBaseUrl: "https://mirror.example/t3/",
155 });
156 assert.include(launch, "T3_ARCHIVE_MODE=1");
157 assert.include(launch, "T3_RELEASE_BASE_URL='https://mirror.example/t3'");
158 assert.include(launch, '"$RUNNER_FILE" __ssh-helper pick-port "$PORT_FILE"');
159 assert.include(launch, '"$RUNNER_FILE" __ssh-helper wait-ready "$REMOTE_PORT"');
160 assert.include(launch, '"$RUNNER_FILE" __ssh-helper runtime-port "$DEFAULT_RUNTIME_FILE"');
161 assert.include(SshTunnel.buildRemoteLaunchScript(NODE_SCRIPT), "T3_ARCHIVE_MODE=0");
162 });
163​
164 it("rejects archive versions that are not a single exact version segment", () => {
165 for (const archiveVersion of [
166 "../other",
167 "1.2.3/evil",
168 "1.2.3\\evil",
169 "1.2.3-preview.1 x",
170 "1.2.3-preview.1\nrm -rf /",
171 "v1.2.3",
172 ]) {
173 assert.throws(
174 () => SshTunnel.buildRemoteT3RunnerScript({ archiveVersion }),
175 SshTunnel.SshInvalidArchiveVersionError,
176 undefined,
177 archiveVersion,
178 );
179 }
180 assert.include(
181 SshTunnel.buildRemoteT3RunnerScript(ARCHIVE),
182 "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'",
183 );
184 });
185​
186 it("refuses to build a runner with neither an archive version nor a node script", () => {
187 for (const input of [undefined, {}, { archiveVersion: " " }, { nodeScriptPath: null }]) {
188 assert.throws(
189 () => SshTunnel.buildRemoteT3RunnerScript(input),
190 SshTunnel.SshMissingRunnerError,
191 );
192 }
193 assert.throws(() => SshTunnel.buildRemoteLaunchScript(), SshTunnel.SshMissingRunnerError);
194 });
195​
196 it("does not hard-code a remote node engine range", () => {
197 const script = SshTunnel.buildRemoteT3RunnerScript(NODE_SCRIPT);
198​
199 assert.include(script, "T3_NODE_ENGINE_RANGE=''");
200 assert.notInclude(script, TEST_NODE_ENGINE_RANGE);
201 });
202​
203 it("builds the remote t3 runner with a node script override", () => {
204 const script = SshTunnel.buildRemoteT3RunnerScript({
205 ...NODE_SCRIPT,
206 nodeEngineRange: TEST_NODE_ENGINE_RANGE,
207 });
208​
209 assert.include(
210 script,
211 "T3_NODE_SCRIPT_PATH='/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs'",
212 );
213 assert.include(script, 'exec node "$T3_NODE_SCRIPT_PATH" "$@"');
214 assert.include(script, "T3_ARCHIVE_VERSION=''");
215 assert.include(script, 'prepend_path_if_dir "$HOME/.local/bin"');
216 assert.include(script, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
217 assert.include(script, "remote_node_satisfies_engine()");
218 assert.include(script, "function satisfiesSemverRange");
219 assert.include(script, "satisfiesSemverRange(rawVersion, range)");
220 assert.include(script, 'prepend_path_if_dir "/home/linuxbrew/.linuxbrew/bin"');
221 assert.include(script, 'prepend_path_if_dir "$VOLTA_HOME/bin"');
222 assert.include(script, 'prepend_path_if_dir "$HOME/.asdf/shims"');
223 assert.include(script, 'prepend_path_if_dir "$HOME/.local/share/mise/shims"');
224 assert.include(script, 'eval "$(fnm env --shell bash)"');
225 assert.include(script, "fnm use --silent-if-unchanged");
226 assert.include(script, "fnm use default");
227 assert.include(script, 'prepend_path_if_dir "$HOME/.nodenv/shims"');
228 assert.include(script, 'NVM_DIR="$HOME/.nvm"');
229 assert.include(script, "nvm use --silent default");
230 assert.include(script, 'for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin');
231 assert.notInclude(script, "ensure $NVM_DIR/nvm.sh is available");
232 assert.notInclude(script, "npx");
233 });
234​
235 it("uses the remote t3 runner for launch and pairing scripts", () => {
236 const target = {
237 alias: "devbox",
238 hostname: "devbox.example.com",
239 username: "julius",
240 port: 2222,
241 } as const;
242 const launch = SshTunnel.buildRemoteLaunchScript(ARCHIVE);
243 const devLaunch = SshTunnel.buildRemoteLaunchScript({
244 ...NODE_SCRIPT,
245 nodeEngineRange: TEST_NODE_ENGINE_RANGE,
246 });
247​
248 assert.include(
249 launch,
250 '[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
251 );
252 assert.include(launch, "RUNNER_CHANGED=1");
253 assert.include(launch, "ensure_remote_node_path()");
254 assert.include(launch, "if ! ensure_remote_node_path; then");
255 assert.include(devLaunch, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
256 assert.include(devLaunch, "does not satisfy required range ");
257 assert.include(launch, 'kill "$REMOTE_PID" 2>/dev/null || true');
258 assert.include(launch, "wait_ready");
259 assert.include(launch, '"$RUNNER_FILE" serve --host 127.0.0.1');
260 assert.include(launch, '--base-dir "$DEFAULT_SERVER_HOME"');
261 assert.notInclude(launch, "server-home");
262 assert.include(launch, "Remote T3 server did not become ready");
263 assert.include(launch, 'wait_ready "60000"');
264 assert.include(launch, 'if [ -s "$LOG_FILE" ]; then');
265 assert.include(launch, "It wrote nothing to %s");
266 assert.include(launch, "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'");
267 assert.include(
268 SshTunnel.buildRemotePairingScript(target, ARCHIVE),
269 '"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
270 );
271 assert.include(
272 SshTunnel.buildRemotePairingScript(target, ARCHIVE),
273 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"',
274 );
275 assert.notInclude(SshTunnel.buildRemotePairingScript(target, ARCHIVE), "server-home");
276 assert.include(
277 SshTunnel.buildRemotePairingScript(target, ARCHIVE),
278 "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'",
279 );
280 assert.include(
281 SshTunnel.buildRemoteStopScript(target),
282 'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
283 );
284 assert.include(
285 SshTunnel.buildRemoteStopScript(target),
286 'kill "$REMOTE_PID" 2>/dev/null || true',
287 );
288 assert.include(
289 SshTunnel.buildRemoteStopScript(target),
290 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"',
291 );
292 assert.include(
293 launch,
294 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
295 );
296 assert.include(launch, "resolve_default_runtime_port()");
297 assert.include(launch, 'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port');
298 assert.include(launch, "if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))");
299 assert.include(launch, 'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"');
300 assert.include(launch, 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
301 assert.include(launch, 'rm -f "$PID_FILE"');
302 assert.include(launch, "printf 'external\\n' >\"$MANAGED_FILE\"");
303 assert.include(launch, 'if [ -z "$REMOTE_PORT" ]; then');
304 assert.isBelow(
305 launch.indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
306 launch.indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
307 );
308 assert.isBelow(
309 launch.indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
310 launch.indexOf('elif [ -n "$REMOTE_PID" ]'),
311 );
312 });
313​
314 it.effect("accepts launch 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 spawnedCommands: Array<ReadonlyArray<string>> = [];
322 const spawner = ChildProcessSpawner.make((command) =>
323 Effect.sync(() => {
324 spawnedCommands.push(commandArgs(command));
325 return makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n');
326 }),
327 );
328 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
329 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
330​
331 return Effect.gen(function* () {
332 const result = yield* SshTunnel.launchOrReuseRemoteServer(target, undefined, ARCHIVE);
333 assert.equal(result.remotePort, 3774);
334 assert.deepEqual(spawnedCommands[0]?.slice(-5, -1), ["sh", "-l", "-s", "--"]);
335 }).pipe(Effect.provide(processLayer));
336 });
337​
338 it.effect("allows cold remote launches to exceed the default SSH command timeout", () => {
339 const target = {
340 alias: "devbox",
341 hostname: "devbox.example.com",
342 username: "julius",
343 port: 2222,
344 } as const;
345 const spawner = ChildProcessSpawner.make(() =>
346 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 75_000)),
347 );
348 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
349 const processLayer = Layer.mergeAll(NodeServices.layer, spawnerLayer, TestClock.layer());
350​
351 return Effect.gen(function* () {
352 const fiber = yield* Effect.forkChild(
353 SshTunnel.launchOrReuseRemoteServer(target, undefined, NODE_SCRIPT),
354 );
355 yield* Effect.yieldNow;
356 yield* TestClock.adjust(Duration.seconds(75));
357​
358 const result = yield* Fiber.join(fiber);
359 assert.equal(result.remotePort, 3774);
360 }).pipe(Effect.provide(processLayer));
361 });
362​
363 it.effect("gives cold archive launches a larger budget than node-script launches", () => {
364 const target = {
365 alias: "devbox",
366 hostname: "devbox.example.com",
367 username: "julius",
368 port: 2222,
369 } as const;
370 const spawner = ChildProcessSpawner.make(() =>
371 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 800_000)),
372 );
373 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
374 const processLayer = Layer.mergeAll(NodeServices.layer, spawnerLayer, TestClock.layer());
375​
376 return Effect.gen(function* () {
377 const fiber = yield* Effect.forkChild(
378 SshTunnel.launchOrReuseRemoteServer(target, undefined, ARCHIVE),
379 );
380 yield* Effect.yieldNow;
381 yield* TestClock.adjust(Duration.seconds(800));
382​
383 const result = yield* Fiber.join(fiber);
384 assert.equal(result.remotePort, 3774);
385 }).pipe(Effect.provide(processLayer));
386 });
387​
388 it("allows the remote port picker to run without a state file path", () => {
389 assert.include(SshTunnel.REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
390 });
391​
392 it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
393 Effect.gen(function* () {
394 const fiber = yield* Effect.forkChild(
395 Effect.result(
396 SshTunnel.waitForHttpReady({
397 baseUrl: "http://127.0.0.1:41773/",
398 timeoutMs: 1_000,
399 intervalMs: 100,
400 probeTimeoutMs: 250,
401 }),
402 ),
403 );
404 yield* Effect.yieldNow;
405 yield* TestClock.adjust(Duration.millis(1_000));
406​
407 const result = yield* Fiber.join(fiber);
408​
409 assert.isTrue(Result.isFailure(result));
410 if (Result.isFailure(result)) {
411 assert.include(result.failure.message, "Timed out waiting 1000ms");
412 }
413 }).pipe(
414 Effect.provide(
415 Layer.merge(TestClock.layer(), Layer.succeed(HttpClient.HttpClient, hangingHttpClient)),
416 ),
417 ),
418 );
419​
420 it("preserves primitive readiness reason values in diagnostic output", () => {
421 assert.deepEqual(
422 SshTunnel.describeReadinessCause({
423 _tag: "HttpClientError",
424 message: "Backend readiness probe failed.",
425 reason: "authentication failed",
426 cause: "upstream closed",
427 }),
428 {
429 _tag: "HttpClientError",
430 message: "Backend readiness probe failed.",
431 reason: "authentication failed",
432 cause: "upstream closed",
433 },
434 );
435 });
436​
437 it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
438 const target = {
439 alias: "devbox",
440 hostname: "devbox.example.com",
441 username: "julius",
442 port: 2222,
443 } as const;
444 const spawner = ChildProcessSpawner.make(() =>
445 Effect.succeed(
446 makeSuccessfulProcess(`{
447 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
448 "credential": "LCL4R2TPHDKQ",
449 "scopes": ["orchestration:read"],
450 "expiresAt": "2026-04-29T01:01:20.994Z"
452​
453`),
454 ),
455 );
456 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
457 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
458 return Effect.gen(function* () {
459 const result = yield* SshTunnel.issueRemotePairingToken(target, undefined, ARCHIVE);
460 assert.equal(result.credential, "LCL4R2TPHDKQ");
461 }).pipe(Effect.provide(processLayer));
462 });
463​
464 it.effect("accepts pretty-printed pairing JSON after remote shell startup noise", () => {
465 const target = {
466 alias: "devbox",
467 hostname: "devbox.example.com",
468 username: "julius",
469 port: 2222,
470 } as const;
471 const spawner = ChildProcessSpawner.make(() =>
472 Effect.succeed(
473 makeSuccessfulProcess(`loaded nvm default
475 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
476 "credential": "LCL4R2TPHDKQ",
477 "scopes": ["orchestration:read"],
478 "expiresAt": "2026-04-29T01:01:20.994Z"
480​
481`),
482 ),
483 );
484 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
485 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
486 return Effect.gen(function* () {
487 const result = yield* SshTunnel.issueRemotePairingToken(target, undefined, ARCHIVE);
488 assert.equal(result.credential, "LCL4R2TPHDKQ");
489 }).pipe(Effect.provide(processLayer));
490 });
491​
492 it.effect.each(["successful stop", "failed stop"] as const)(
493 "closes the tunnel scope and starts fresh after a %s",
494 (mode) => {
495 const spawnedCommands: Array<ReadonlyArray<string>> = [];
496 let tunnelKillCount = 0;
497 let stopCommandCount = 0;
498 const spawner = ChildProcessSpawner.make((command) =>
499 Effect.sync(() => {
500 const args = commandArgs(command);
501 spawnedCommands.push(args);
502 if (args.includes("-N")) {
503 return makeRunningProcess(() => {
504 tunnelKillCount += 1;
505 });
506 }
507 if (args.includes("sh") && args.includes("--")) {
508 return makeSuccessfulProcess('{"remotePort":3773}\n');
509 }
510 if (args.includes("sh")) {
511 stopCommandCount += 1;
512 if (mode === "failed stop" && stopCommandCount === 1) {
513 return {
514 ...makeSuccessfulProcess(""),
515 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
516 stderr: Stream.make(
517 new TextEncoder().encode("Remote T3 server did not stop within 2 seconds.\n"),
518 ),
519 };
520 }
521 return makeSuccessfulProcess('{"stopped":true}\n');
522 }
523 return makeSuccessfulProcess("\n");
524 }),
525 );
526 const layer = Layer.mergeAll(
527 NodeServices.layer,
528 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
529 Layer.succeed(HttpClient.HttpClient, testHttpClient),
530 Layer.succeed(NetService.NetService, testNetService),
531 SshAuth.SshPasswordPrompt.disabledLayer,
532 SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
533 );
534 const target = {
535 alias: "devbox",
536 hostname: "devbox.example.com",
537 username: "julius",
538 port: 2222,
539 } as const;
540​
541 return Effect.gen(function* () {
542 const manager = yield* SshTunnel.SshEnvironmentManager;
543​
544 const first = yield* manager.ensureEnvironment(target);
545 assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
546 const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
547 assert.isDefined(firstTunnelArgs);
548 assert.include(firstTunnelArgs, "ControlMaster=no");
549 assert.include(firstTunnelArgs, "ControlPath=none");
550 assert.include(firstTunnelArgs, "ControlPersist=no");
551​
552 const disconnected = yield* Effect.result(manager.disconnectEnvironment(target));
553 if (mode === "failed stop") {
554 assert.isTrue(Result.isFailure(disconnected));
555 if (Result.isFailure(disconnected)) {
556 assert.instanceOf(disconnected.failure, SshCommandError);
557 assert.equal(
558 disconnected.failure.message,
559 "Remote T3 server did not stop within 2 seconds.",
560 );
561 }
562 } else {
563 assert.isTrue(Result.isSuccess(disconnected));
564 }
565 assert.equal(tunnelKillCount, 1);
566 assert.equal(stopCommandCount, 1);
567​
568 if (mode === "failed stop") {
569 yield* manager.disconnectEnvironment(target);
570 assert.equal(tunnelKillCount, 1);
571 assert.equal(stopCommandCount, 2);
572 }
573​
574 yield* manager.ensureEnvironment(target);
575​
576 assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
577 assert.equal(tunnelKillCount, 1);
578 }).pipe(
579 Effect.provide(layer),
580 Effect.scoped,
581 Effect.andThen(
582 Effect.sync(() => {
583 assert.equal(tunnelKillCount, 2);
584 assert.equal(stopCommandCount, mode === "failed stop" ? 3 : 2);
585 }),
586 ),
587 );
588 },
589 );
590​
591 it.effect.each(["local tunnel", "remote server"] as const)(
592 "waits for %s shutdown before reconnecting the same target",
593 (stalledStep) =>
594 Effect.gen(function* () {
595 const shutdownStarted = yield* Deferred.make<void>();
596 const finishShutdown = yield* Deferred.make<void>();
597 const reconnectsStarted = yield* Deferred.make<void>();
598 const pauseShutdown = Deferred.succeed(shutdownStarted, undefined).pipe(
599 Effect.andThen(Deferred.await(finishShutdown)),
600 );
601 let resolutions = 0;
602 let launches = 0;
603 let tunnels = 0;
604 let stops = 0;
605 let remoteRunning = false;
606 const target = { alias: "devbox", hostname: "devbox", username: null, port: null };
607 const spawner = ChildProcessSpawner.make((command) =>
608 Effect.gen(function* () {
609 const args = commandArgs(command);
610 const isTarget = args.includes(target.alias);
611 if (args.includes("-G")) {
612 if (isTarget && ++resolutions === 4) {
613 yield* Deferred.succeed(reconnectsStarted, undefined);
614 }
615 return makeSuccessfulProcess("");
616 }
617 if (args.includes("-N")) {
618 const tunnel = makeRunningProcess(() => undefined);
619 if (isTarget && ++tunnels === 1 && stalledStep === "local tunnel") {
620 return {
621 ...tunnel,
622 kill: (options?: ChildProcess.KillOptions) =>
623 pauseShutdown.pipe(Effect.andThen(tunnel.kill(options))),
624 };
625 }
626 return tunnel;
627 }
628 if (args.includes("--")) {
629 if (isTarget) {
630 launches += 1;
631 remoteRunning = true;
632 }
633 return makeSuccessfulProcess('{"remotePort":3773}\n');
634 }
635 const stop = makeSuccessfulProcess('{"stopped":true}\n');
636 if (!isTarget) return stop;
637 const pause = ++stops === 1 && stalledStep === "remote server";
638 return {
639 ...stop,
640 exitCode: (pause ? pauseShutdown : Effect.void).pipe(
641 Effect.andThen(
642 Effect.sync(() => {
643 remoteRunning = false;
644 return ChildProcessSpawner.ExitCode(0);
645 }),
646 ),
647 ),
648 };
649 }),
650 );
651 const layer = Layer.mergeAll(
652 NodeServices.layer,
653 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
654 Layer.succeed(HttpClient.HttpClient, testHttpClient),
655 Layer.succeed(NetService.NetService, testNetService),
656 SshAuth.SshPasswordPrompt.disabledLayer,
657 SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
658 );
659 yield* Effect.gen(function* () {
660 const manager = yield* SshTunnel.SshEnvironmentManager;
661 yield* manager.ensureEnvironment(target);
662 const disconnect = yield* Effect.forkChild(manager.disconnectEnvironment(target));
663 yield* Deferred.await(shutdownStarted);
664 const firstReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
665 const secondReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
666 yield* Deferred.await(reconnectsStarted);
667​
668 yield* manager.ensureEnvironment({
669 alias: "other",
670 hostname: "other",
671 username: null,
672 port: null,
673 });
674 yield* TestClock.adjust(Duration.zero);
675 const launchesBeforeShutdown = launches;
676 yield* Deferred.succeed(finishShutdown, undefined);
677 yield* Fiber.join(disconnect);
678 const first = yield* Fiber.join(firstReconnect);
679 const second = yield* Fiber.join(secondReconnect);
680​
681 assert.equal(launchesBeforeShutdown, 1);
682 assert.equal(launches, 2);
683 assert.equal(tunnels, 2);
684 assert.isTrue(remoteRunning);
685 assert.equal(first.httpBaseUrl, second.httpBaseUrl);
686 }).pipe(
687 Effect.ensuring(Deferred.succeed(finishShutdown, undefined)),
688 Effect.provide(layer),
689 Effect.scoped,
690 );
691 }),
692 );
693});
694​
695// The archive runner is generated shell; string assertions cannot prove the
696// lock excludes concurrent installers. Run the real script against a tiny
697// fake archive served from a file:// mirror.
698describe("archive runner script", () => {
699 const hostPlatform = HostProcessPlatform.defaultValue();
700 const hostArch = HostProcessArchitecture.defaultValue();
701 const windowsHost = hostPlatform === "win32";
702 const archiveVersion = "1.2.3-preview.20260911.4";
703​
704 const runRunner = (home: string, runner: string) =>
705 Effect.gen(function* () {
706 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
707 const child = yield* spawner.spawn(
708 ChildProcess.make("sh", [runner, "--version"], {
709 env: { PATH: process.env.PATH ?? "", HOME: home },
710 extendEnv: false,
711 }),
712 );
713 const [stdout, stderr, exitCode] = yield* Effect.all(
714 [
715 child.stdout.pipe(
716 Stream.decodeText(),
717 Stream.runFold(
718 () => "",
719 (acc, chunk) => acc + chunk,
720 ),
721 ),
722 child.stderr.pipe(
723 Stream.decodeText(),
724 Stream.runFold(
725 () => "",
726 (acc, chunk) => acc + chunk,
727 ),
728 ),
729 child.exitCode.pipe(Effect.map(Number)),
730 ],
731 { concurrency: "unbounded" },
732 );
733 return { stdout, stderr, exitCode };
734 });
735​
736 // A fake "executable" that answers --version, packed the way the release
737 // workflow packs the real archive: one top-level directory named after the
738 // stem, checksummed in SHA256SUMS.
739 const makeMirror = Effect.fn("makeMirror")(function* (root: string) {
740 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
741 const platform = hostPlatform === "darwin" ? "darwin" : "linux";
742 const arch = hostArch === "arm64" ? "arm64" : "x64";
743 const stem = `t3-${archiveVersion}-${platform}-${arch}`;
744 const stage = `${root}/stage/${stem}`;
745 const release = `${root}/mirror/v${archiveVersion}`;
746 const script = [
747 "set -eu",
748 `mkdir -p '${stage}' '${release}'`,
749 `printf '#!/bin/sh\\necho t3 v${archiveVersion}\\n' > '${stage}/t3'`,
750 `chmod +x '${stage}/t3'`,
751 `tar -czf '${release}/${stem}.tar.gz' -C '${root}/stage' '${stem}'`,
752 `cd '${release}' && (sha256sum '${stem}.tar.gz' 2>/dev/null || shasum -a 256 '${stem}.tar.gz') > SHA256SUMS`,
753 ].join("\n");
754 const child = yield* spawner.spawn(ChildProcess.make("sh", ["-c", script]));
755 assert.equal(Number(yield* child.exitCode), 0);
756 return `file://${root}/mirror`;
757 });
758​
759 it.effect.skipIf(windowsHost)(
760 "installs once when several launches race, and reclaims stale locks",
761 () =>
762 Effect.gen(function* () {
763 const fs = yield* FileSystem.FileSystem;
764 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-archive-runner-" });
765 const releaseBaseUrl = yield* makeMirror(root);
766 const runner = `${root}/run-t3.sh`;
767 yield* fs.writeFileString(
768 runner,
769 SshTunnel.buildRemoteT3RunnerScript({ archiveVersion, releaseBaseUrl }),
770 );
771 const home = `${root}/home`;
772 yield* fs.makeDirectory(home, { recursive: true });
773​
774 const results = yield* Effect.all(
775 [runRunner(home, runner), runRunner(home, runner), runRunner(home, runner)],
776 { concurrency: "unbounded" },
777 );
778 for (const result of results) {
779 assert.equal(result.exitCode, 0, result.stderr);
780 assert.include(result.stdout, `t3 v${archiveVersion}`);
781 }
782 const versionsDir = `${home}/.t3/runtime/versions`;
783 assert.deepEqual(yield* fs.readDirectory(versionsDir), [archiveVersion]);
784 assert.equal(
785 (yield* fs.readFileString(`${versionsDir}/${archiveVersion}/.install-complete`)).trim(),
786 archiveVersion,
787 );
788​
789 // A lock left by a crashed installer (dead pid) must not block the
790 // next launch, and neither must one that never published a pid.
791 const lock = `${versionsDir}/.${archiveVersion}.install.lock`;
792 yield* fs.remove(`${versionsDir}/${archiveVersion}`, { recursive: true });
793 yield* fs.makeDirectory(lock);
794 yield* fs.writeFileString(`${lock}/pid`, "999999\n");
795 const afterDead = yield* runRunner(home, runner);
796 assert.equal(afterDead.exitCode, 0, afterDead.stderr);
797​
798 yield* fs.remove(`${versionsDir}/${archiveVersion}`, { recursive: true });
799 yield* fs.makeDirectory(lock);
800 const afterUnowned = yield* runRunner(home, runner);
801 assert.equal(afterUnowned.exitCode, 0, afterUnowned.stderr);
802 assert.isFalse(yield* fs.exists(lock));
803 }).pipe(Effect.provide(NodeServices.layer)),
804 60_000,
805 );
806});