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

tunnel.test.ts

801 lines31.5 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/http";
16import { ChildProcess, ChildProcessSpawner } from "effect/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 stateKey = "711bc738002d72fd";
237 const launch = SshTunnel.buildRemoteLaunchScript(ARCHIVE);
238 const devLaunch = SshTunnel.buildRemoteLaunchScript({
239 ...NODE_SCRIPT,
240 nodeEngineRange: TEST_NODE_ENGINE_RANGE,
241 });
242​
243 assert.include(
244 launch,
245 '[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
246 );
247 assert.include(launch, "RUNNER_CHANGED=1");
248 assert.include(launch, "ensure_remote_node_path()");
249 assert.include(launch, "if ! ensure_remote_node_path; then");
250 assert.include(devLaunch, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
251 assert.include(devLaunch, "does not satisfy required range ");
252 assert.include(launch, 'kill "$REMOTE_PID" 2>/dev/null || true');
253 assert.include(launch, "wait_ready");
254 assert.include(launch, '"$RUNNER_FILE" serve --host 127.0.0.1');
255 assert.include(launch, '--base-dir "$DEFAULT_SERVER_HOME"');
256 assert.notInclude(launch, "server-home");
257 assert.include(launch, "Remote T3 server did not become ready");
258 assert.include(launch, 'wait_ready "60000"');
259 assert.include(launch, 'if [ -s "$LOG_FILE" ]; then');
260 assert.include(launch, "It wrote nothing to %s");
261 assert.include(launch, "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'");
262 assert.include(
263 SshTunnel.buildRemotePairingScript(stateKey, ARCHIVE),
264 '"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
265 );
266 assert.include(
267 SshTunnel.buildRemotePairingScript(stateKey, ARCHIVE),
268 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"',
269 );
270 assert.notInclude(SshTunnel.buildRemotePairingScript(stateKey, ARCHIVE), "server-home");
271 assert.include(
272 SshTunnel.buildRemotePairingScript(stateKey, ARCHIVE),
273 "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'",
274 );
275 assert.include(
276 SshTunnel.buildRemoteStopScript(stateKey),
277 'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
278 );
279 assert.include(
280 SshTunnel.buildRemoteStopScript(stateKey),
281 'kill "$REMOTE_PID" 2>/dev/null || true',
282 );
283 assert.include(
284 SshTunnel.buildRemoteStopScript(stateKey),
285 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"',
286 );
287 assert.include(
288 launch,
289 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
290 );
291 assert.include(launch, "resolve_default_runtime_port()");
292 assert.include(launch, 'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port');
293 assert.include(launch, "if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))");
294 assert.include(launch, 'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"');
295 assert.include(launch, 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
296 assert.include(launch, 'rm -f "$PID_FILE"');
297 assert.include(launch, "printf 'external\\n' >\"$MANAGED_FILE\"");
298 assert.include(launch, 'if [ -z "$REMOTE_PORT" ]; then');
299 assert.isBelow(
300 launch.indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
301 launch.indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
302 );
303 assert.isBelow(
304 launch.indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
305 launch.indexOf('elif [ -n "$REMOTE_PID" ]'),
306 );
307 });
308​
309 it.effect("accepts launch JSON after remote shell startup noise", () => {
310 const target = {
311 alias: "devbox",
312 hostname: "devbox.example.com",
313 username: "julius",
314 port: 2222,
315 } as const;
316 const spawnedCommands: Array<ReadonlyArray<string>> = [];
317 const spawner = ChildProcessSpawner.make((command) =>
318 Effect.sync(() => {
319 spawnedCommands.push(commandArgs(command));
320 return makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n');
321 }),
322 );
323 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
324 const layerProcess = Layer.merge(NodeServices.layer, layerSpawner);
325​
326 return Effect.gen(function* () {
327 const result = yield* SshTunnel.launchOrReuseRemoteServer(target, undefined, ARCHIVE);
328 assert.equal(result.remotePort, 3774);
329 assert.deepEqual(spawnedCommands[0]?.slice(-5, -1), ["sh", "-l", "-s", "--"]);
330 }).pipe(Effect.provide(layerProcess));
331 });
332​
333 it.effect("allows cold remote launches to exceed the default SSH command timeout", () => {
334 const target = {
335 alias: "devbox",
336 hostname: "devbox.example.com",
337 username: "julius",
338 port: 2222,
339 } as const;
340 const spawner = ChildProcessSpawner.make(() =>
341 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 75_000)),
342 );
343 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
344 const layerProcess = Layer.mergeAll(NodeServices.layer, layerSpawner, TestClock.layer());
345​
346 return Effect.gen(function* () {
347 const fiber = yield* Effect.forkChild(
348 SshTunnel.launchOrReuseRemoteServer(target, undefined, NODE_SCRIPT),
349 );
350 yield* Effect.yieldNow;
351 yield* TestClock.adjust(Duration.seconds(75));
352​
353 const result = yield* Fiber.join(fiber);
354 assert.equal(result.remotePort, 3774);
355 }).pipe(Effect.provide(layerProcess));
356 });
357​
358 it.effect("gives cold archive launches a larger budget than node-script launches", () => {
359 const target = {
360 alias: "devbox",
361 hostname: "devbox.example.com",
362 username: "julius",
363 port: 2222,
364 } as const;
365 const spawner = ChildProcessSpawner.make(() =>
366 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 800_000)),
367 );
368 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
369 const layerProcess = Layer.mergeAll(NodeServices.layer, layerSpawner, TestClock.layer());
370​
371 return Effect.gen(function* () {
372 const fiber = yield* Effect.forkChild(
373 SshTunnel.launchOrReuseRemoteServer(target, undefined, ARCHIVE),
374 );
375 yield* Effect.yieldNow;
376 yield* TestClock.adjust(Duration.seconds(800));
377​
378 const result = yield* Fiber.join(fiber);
379 assert.equal(result.remotePort, 3774);
380 }).pipe(Effect.provide(layerProcess));
381 });
382​
383 it("allows the remote port picker to run without a state file path", () => {
384 assert.include(SshTunnel.REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
385 });
386​
387 it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
388 Effect.gen(function* () {
389 const fiber = yield* Effect.forkChild(
390 Effect.result(
391 SshTunnel.waitForHttpReady({
392 baseUrl: "http://127.0.0.1:41773/",
393 timeoutMs: 1_000,
394 intervalMs: 100,
395 probeTimeoutMs: 250,
396 }),
397 ),
398 );
399 yield* Effect.yieldNow;
400 yield* TestClock.adjust(Duration.millis(1_000));
401​
402 const result = yield* Fiber.join(fiber);
403​
404 assert.isTrue(Result.isFailure(result));
405 if (Result.isFailure(result)) {
406 assert.include(result.failure.message, "Timed out waiting 1000ms");
407 }
408 }).pipe(
409 Effect.provide(
410 Layer.merge(TestClock.layer(), Layer.succeed(HttpClient.HttpClient, hangingHttpClient)),
411 ),
412 ),
413 );
414​
415 it("preserves primitive readiness reason values in diagnostic output", () => {
416 assert.deepEqual(
417 SshTunnel.describeReadinessCause({
418 _tag: "HttpClientError",
419 message: "Backend readiness probe failed.",
420 reason: "authentication failed",
421 cause: "upstream closed",
422 }),
423 {
424 _tag: "HttpClientError",
425 message: "Backend readiness probe failed.",
426 reason: "authentication failed",
427 cause: "upstream closed",
428 },
429 );
430 });
431​
432 it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
433 const target = {
434 alias: "devbox",
435 hostname: "devbox.example.com",
436 username: "julius",
437 port: 2222,
438 } as const;
439 const spawner = ChildProcessSpawner.make(() =>
440 Effect.succeed(
441 makeSuccessfulProcess(`{
442 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
443 "credential": "LCL4R2TPHDKQ",
444 "scopes": ["orchestration:read"],
445 "expiresAt": "2026-04-29T01:01:20.994Z"
447​
448`),
449 ),
450 );
451 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
452 const layerProcess = Layer.merge(NodeServices.layer, layerSpawner);
453 return Effect.gen(function* () {
454 const result = yield* SshTunnel.issueRemotePairingToken(target, undefined, ARCHIVE);
455 assert.equal(result.credential, "LCL4R2TPHDKQ");
456 }).pipe(Effect.provide(layerProcess));
457 });
458​
459 it.effect("accepts pretty-printed pairing JSON after remote shell startup noise", () => {
460 const target = {
461 alias: "devbox",
462 hostname: "devbox.example.com",
463 username: "julius",
464 port: 2222,
465 } as const;
466 const spawner = ChildProcessSpawner.make(() =>
467 Effect.succeed(
468 makeSuccessfulProcess(`loaded nvm default
470 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
471 "credential": "LCL4R2TPHDKQ",
472 "scopes": ["orchestration:read"],
473 "expiresAt": "2026-04-29T01:01:20.994Z"
475​
476`),
477 ),
478 );
479 const layerSpawner = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
480 const layerProcess = Layer.merge(NodeServices.layer, layerSpawner);
481 return Effect.gen(function* () {
482 const result = yield* SshTunnel.issueRemotePairingToken(target, undefined, ARCHIVE);
483 assert.equal(result.credential, "LCL4R2TPHDKQ");
484 }).pipe(Effect.provide(layerProcess));
485 });
486​
487 it.effect.each(["successful stop", "failed stop"] as const)(
488 "closes the tunnel scope and starts fresh after a %s",
489 (mode) => {
490 const spawnedCommands: Array<ReadonlyArray<string>> = [];
491 let tunnelKillCount = 0;
492 let stopCommandCount = 0;
493 const spawner = ChildProcessSpawner.make((command) =>
494 Effect.sync(() => {
495 const args = commandArgs(command);
496 spawnedCommands.push(args);
497 if (args.includes("-N")) {
498 return makeRunningProcess(() => {
499 tunnelKillCount += 1;
500 });
501 }
502 if (args.includes("sh") && args.includes("--")) {
503 return makeSuccessfulProcess('{"remotePort":3773}\n');
504 }
505 if (args.includes("sh")) {
506 stopCommandCount += 1;
507 if (mode === "failed stop" && stopCommandCount === 1) {
508 return {
509 ...makeSuccessfulProcess(""),
510 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
511 stderr: Stream.make(
512 new TextEncoder().encode("Remote T3 server did not stop within 2 seconds.\n"),
513 ),
514 };
515 }
516 return makeSuccessfulProcess('{"stopped":true}\n');
517 }
518 return makeSuccessfulProcess("\n");
519 }),
520 );
521 const layer = Layer.mergeAll(
522 NodeServices.layer,
523 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
524 Layer.succeed(HttpClient.HttpClient, testHttpClient),
525 Layer.succeed(NetService.NetService, testNetService),
526 SshAuth.SshPasswordPrompt.disabledLayer,
527 SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
528 );
529 const target = {
530 alias: "devbox",
531 hostname: "devbox.example.com",
532 username: "julius",
533 port: 2222,
534 } as const;
535​
536 return Effect.gen(function* () {
537 const manager = yield* SshTunnel.SshEnvironmentManager;
538​
539 const first = yield* manager.ensureEnvironment(target);
540 assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
541 const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
542 assert.isDefined(firstTunnelArgs);
543 assert.include(firstTunnelArgs, "ControlMaster=no");
544 assert.include(firstTunnelArgs, "ControlPath=none");
545 assert.include(firstTunnelArgs, "ControlPersist=no");
546​
547 const disconnected = yield* Effect.result(manager.disconnectEnvironment(target));
548 if (mode === "failed stop") {
549 assert.isTrue(Result.isFailure(disconnected));
550 if (Result.isFailure(disconnected)) {
551 assert.instanceOf(disconnected.failure, SshCommandError);
552 assert.equal(
553 disconnected.failure.message,
554 "Remote T3 server did not stop within 2 seconds.",
555 );
556 }
557 } else {
558 assert.isTrue(Result.isSuccess(disconnected));
559 }
560 assert.equal(tunnelKillCount, 1);
561 assert.equal(stopCommandCount, 1);
562​
563 if (mode === "failed stop") {
564 yield* manager.disconnectEnvironment(target);
565 assert.equal(tunnelKillCount, 1);
566 assert.equal(stopCommandCount, 2);
567 }
568​
569 yield* manager.ensureEnvironment(target);
570​
571 assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
572 assert.equal(tunnelKillCount, 1);
573 }).pipe(
574 Effect.provide(layer),
575 Effect.scoped,
576 Effect.andThen(
577 Effect.sync(() => {
578 assert.equal(tunnelKillCount, 2);
579 assert.equal(stopCommandCount, mode === "failed stop" ? 3 : 2);
580 }),
581 ),
582 );
583 },
584 );
585​
586 it.effect.each(["local tunnel", "remote server"] as const)(
587 "waits for %s shutdown before reconnecting the same target",
588 (stalledStep) =>
589 Effect.gen(function* () {
590 const shutdownStarted = yield* Deferred.make<void>();
591 const finishShutdown = yield* Deferred.make<void>();
592 const reconnectsStarted = yield* Deferred.make<void>();
593 const pauseShutdown = Deferred.succeed(shutdownStarted, undefined).pipe(
594 Effect.andThen(Deferred.await(finishShutdown)),
595 );
596 let resolutions = 0;
597 let launches = 0;
598 let tunnels = 0;
599 let stops = 0;
600 let remoteRunning = false;
601 const target = { alias: "devbox", hostname: "devbox", username: null, port: null };
602 const spawner = ChildProcessSpawner.make((command) =>
603 Effect.gen(function* () {
604 const args = commandArgs(command);
605 const isTarget = args.includes(target.alias);
606 if (args.includes("-G")) {
607 if (isTarget && ++resolutions === 4) {
608 yield* Deferred.succeed(reconnectsStarted, undefined);
609 }
610 return makeSuccessfulProcess("");
611 }
612 if (args.includes("-N")) {
613 const tunnel = makeRunningProcess(() => undefined);
614 if (isTarget && ++tunnels === 1 && stalledStep === "local tunnel") {
615 return {
616 ...tunnel,
617 kill: (options?: ChildProcess.KillOptions) =>
618 pauseShutdown.pipe(Effect.andThen(tunnel.kill(options))),
619 };
620 }
621 return tunnel;
622 }
623 if (args.includes("--")) {
624 if (isTarget) {
625 launches += 1;
626 remoteRunning = true;
627 }
628 return makeSuccessfulProcess('{"remotePort":3773}\n');
629 }
630 const stop = makeSuccessfulProcess('{"stopped":true}\n');
631 if (!isTarget) return stop;
632 const pause = ++stops === 1 && stalledStep === "remote server";
633 return {
634 ...stop,
635 exitCode: (pause ? pauseShutdown : Effect.void).pipe(
636 Effect.andThen(
637 Effect.sync(() => {
638 remoteRunning = false;
639 return ChildProcessSpawner.ExitCode(0);
640 }),
641 ),
642 ),
643 };
644 }),
645 );
646 const layer = Layer.mergeAll(
647 NodeServices.layer,
648 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
649 Layer.succeed(HttpClient.HttpClient, testHttpClient),
650 Layer.succeed(NetService.NetService, testNetService),
651 SshAuth.SshPasswordPrompt.disabledLayer,
652 SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
653 );
654 yield* Effect.gen(function* () {
655 const manager = yield* SshTunnel.SshEnvironmentManager;
656 yield* manager.ensureEnvironment(target);
657 const disconnect = yield* Effect.forkChild(manager.disconnectEnvironment(target));
658 yield* Deferred.await(shutdownStarted);
659 const firstReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
660 const secondReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
661 yield* Deferred.await(reconnectsStarted);
662​
663 yield* manager.ensureEnvironment({
664 alias: "other",
665 hostname: "other",
666 username: null,
667 port: null,
668 });
669 yield* TestClock.adjust(Duration.zero);
670 const launchesBeforeShutdown = launches;
671 yield* Deferred.succeed(finishShutdown, undefined);
672 yield* Fiber.join(disconnect);
673 const first = yield* Fiber.join(firstReconnect);
674 const second = yield* Fiber.join(secondReconnect);
675​
676 assert.equal(launchesBeforeShutdown, 1);
677 assert.equal(launches, 2);
678 assert.equal(tunnels, 2);
679 assert.isTrue(remoteRunning);
680 assert.equal(first.httpBaseUrl, second.httpBaseUrl);
681 }).pipe(
682 Effect.ensuring(Deferred.succeed(finishShutdown, undefined)),
683 Effect.provide(layer),
684 Effect.scoped,
685 );
686 }),
687 );
688});
689​
690// The archive runner is generated shell; string assertions cannot prove the
691// lock excludes concurrent installers. Run the real script against a tiny
692// fake archive served from a file:// mirror.
693describe("archive runner script", () => {
694 const hostPlatform = HostProcessPlatform.defaultValue();
695 const hostArch = HostProcessArchitecture.defaultValue();
696 const windowsHost = hostPlatform === "win32";
697 const archiveVersion = "1.2.3-preview.20260911.4";
698​
699 const runRunner = (home: string, runner: string) =>
700 Effect.gen(function* () {
701 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
702 const child = yield* spawner.spawn(
703 ChildProcess.make("sh", [runner, "--version"], {
704 env: { PATH: process.env.PATH ?? "", HOME: home },
705 extendEnv: false,
706 }),
707 );
708 const [stdout, stderr, exitCode] = yield* Effect.all(
709 [
710 child.stdout.pipe(
711 Stream.decodeText(),
712 Stream.runFold(
713 () => "",
714 (acc, chunk) => acc + chunk,
715 ),
716 ),
717 child.stderr.pipe(
718 Stream.decodeText(),
719 Stream.runFold(
720 () => "",
721 (acc, chunk) => acc + chunk,
722 ),
723 ),
724 child.exitCode.pipe(Effect.map(Number)),
725 ],
726 { concurrency: "unbounded" },
727 );
728 return { stdout, stderr, exitCode };
729 });
730​
731 // A fake "executable" that answers --version, packed the way the release
732 // workflow packs the real archive: one top-level directory named after the
733 // stem, checksummed in SHA256SUMS.
734 const makeMirror = Effect.fn("makeMirror")(function* (root: string) {
735 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
736 const platform = hostPlatform === "darwin" ? "darwin" : "linux";
737 const arch = hostArch === "arm64" ? "arm64" : "x64";
738 const stem = `t3-${archiveVersion}-${platform}-${arch}`;
739 const stage = `${root}/stage/${stem}`;
740 const release = `${root}/mirror/v${archiveVersion}`;
741 const script = [
742 "set -eu",
743 `mkdir -p '${stage}' '${release}'`,
744 `printf '#!/bin/sh\\necho t3 v${archiveVersion}\\n' > '${stage}/t3'`,
745 `chmod +x '${stage}/t3'`,
746 `tar -czf '${release}/${stem}.tar.gz' -C '${root}/stage' '${stem}'`,
747 `cd '${release}' && (sha256sum '${stem}.tar.gz' 2>/dev/null || shasum -a 256 '${stem}.tar.gz') > SHA256SUMS`,
748 ].join("\n");
749 const child = yield* spawner.spawn(ChildProcess.make("sh", ["-c", script]));
750 assert.equal(Number(yield* child.exitCode), 0);
751 return `file://${root}/mirror`;
752 });
753​
754 it.effect.skipIf(windowsHost)(
755 "installs once when several launches race, and reclaims stale locks",
756 () =>
757 Effect.gen(function* () {
758 const fs = yield* FileSystem.FileSystem;
759 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-archive-runner-" });
760 const releaseBaseUrl = yield* makeMirror(root);
761 const runner = `${root}/run-t3.sh`;
762 yield* fs.writeFileString(
763 runner,
764 SshTunnel.buildRemoteT3RunnerScript({ archiveVersion, releaseBaseUrl }),
765 );
766 const home = `${root}/home`;
767 yield* fs.makeDirectory(home, { recursive: true });
768​
769 const results = yield* Effect.all(
770 [runRunner(home, runner), runRunner(home, runner), runRunner(home, runner)],
771 { concurrency: "unbounded" },
772 );
773 for (const result of results) {
774 assert.equal(result.exitCode, 0, result.stderr);
775 assert.include(result.stdout, `t3 v${archiveVersion}`);
776 }
777 const versionsDir = `${home}/.t3/runtime/versions`;
778 assert.deepEqual(yield* fs.readDirectory(versionsDir), [archiveVersion]);
779 assert.equal(
780 (yield* fs.readFileString(`${versionsDir}/${archiveVersion}/.install-complete`)).trim(),
781 archiveVersion,
782 );
783​
784 // A lock left by a crashed installer (dead pid) must not block the
785 // next launch, and neither must one that never published a pid.
786 const lock = `${versionsDir}/.${archiveVersion}.install.lock`;
787 yield* fs.remove(`${versionsDir}/${archiveVersion}`, { recursive: true });
788 yield* fs.makeDirectory(lock);
789 yield* fs.writeFileString(`${lock}/pid`, "999999\n");
790 const afterDead = yield* runRunner(home, runner);
791 assert.equal(afterDead.exitCode, 0, afterDead.stderr);
792​
793 yield* fs.remove(`${versionsDir}/${archiveVersion}`, { recursive: true });
794 yield* fs.makeDirectory(lock);
795 const afterUnowned = yield* runRunner(home, runner);
796 assert.equal(afterUnowned.exitCode, 0, afterUnowned.stderr);
797 assert.isFalse(yield* fs.exists(lock));
798 }).pipe(Effect.provide(NodeServices.layer)),
799 60_000,
800 );
801});