Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Executes the generated remote launcher in an isolated shell with fake commands and clock.
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4import * as NodeURL from "node:url";
5import * as NodeChildProcess from "node:child_process";
6import * as NodeSqlite from "node:sqlite";
7import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import { ChildProcessSpawner } from "effect/process";
14import { launchOrReuseRemoteServer, type RemoteT3RunnerOptions } from "./tunnel.ts";
15
16// Capture exactly the script sent over SSH, then run it with fake remote commands.
17export const captureLauncherFor = Effect.fn("test.captureLauncher")(function* (
18 runner: RemoteT3RunnerOptions,
19) {
20 let script = "";
21 const spawner = ChildProcessSpawner.make((command) =>
22 Effect.gen(function* () {
23 if (command._tag === "StandardCommand") {
24 const stdin = command.options.stdin;
25 if (typeof stdin === "object" && "stream" in stdin && Stream.isStream(stdin.stream)) {
26 script = yield* stdin.stream.pipe(Stream.decodeText(), Stream.mkString);
27 }
28 }
29 return ChildProcessSpawner.makeHandle({
30 pid: ChildProcessSpawner.ProcessId(123),
31 stdout: Stream.make(new TextEncoder().encode('{"remotePort":3773}\n')),
32 stderr: Stream.empty,
33 all: Stream.empty,
34 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
35 exitStatus: Effect.succeed({ _tag: "Exited", code: 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 );
45 yield* launchOrReuseRemoteServer(
46 { alias: "test", hostname: "test.invalid", username: null, port: null },
47 undefined,
48 runner,
49 ).pipe(
50 Effect.provide(
51 Layer.mergeAll(
52 NodeServices.layer,
53 NodeCrypto.layer,
54 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
55 ),
56 ),
57 );
58 return script;
59});
60
61export const captureLauncher = captureLauncherFor({ nodeScriptPath: "/fake/server.ts" });
62
63function holdLock(path: string) {
64 const db = new NodeSqlite.DatabaseSync(path);
65 db.exec("BEGIN EXCLUSIVE;");
66 return { [Symbol.dispose]: () => db.close() };
67}
68
69export function runLauncher(
70 script: string,
71 options: {
72 readonly marker?: unknown;
73 readonly archive?: boolean;
74 readonly clearMarkerOnReady?: boolean;
75 readonly recordedKind?: "managed" | "external";
76 readonly clockJump?: number;
77 readonly readyAt?: number;
78 readonly initialPort?: number;
79 // A boot service between two servers holds the home with no runtime record yet.
80 readonly serviceServing?: boolean;
81 readonly allowFailure?: boolean;
82 // The desktop publishes runtime and removes the marker right after the first runtime read.
83 readonly publishAfterFirstRuntimeRead?: boolean;
84 },
85) {
86 const root = NodeURL.fileURLToPath(new URL("../../../", import.meta.url));
87 const home = NodeFS.mkdtempSync(NodePath.join(root, "packages/ssh/.ssh-launcher-test-"));
88 try {
89 const bin = NodePath.join(home, "bin");
90 const runtime = NodePath.join(home, ".t3/runtime");
91 NodeFS.mkdirSync(bin);
92 NodeFS.mkdirSync(runtime, { recursive: true });
93 const markerPath = NodePath.join(runtime, "desktop-update-in-progress");
94 if (options.marker)
95 NodeFS.writeFileSync(
96 markerPath,
97 typeof options.marker === "string" ? options.marker : JSON.stringify(options.marker),
98 );
99 NodeFS.writeFileSync(NodePath.join(home, "clock"), "0");
100 NodeFS.writeFileSync(NodePath.join(home, "events"), "");
101 const executable = (name: string, body: string) =>
102 NodeFS.writeFileSync(NodePath.join(bin, name), `#!/bin/sh\nset -eu\n${body}\n`, {
103 mode: 0o755,
104 });
105 NodeFS.writeFileSync(
106 NodePath.join(home, "clock.cjs"),
107 `
108const fs = require('node:fs');
109Date.now = () => Number(fs.readFileSync(process.env.HOME + '/clock', 'utf8'));
110`,
111 );
112 executable(
113 options.archive ? "test-node" : "node",
114 `
115case "\${2:-}" in
116 */server-runtime.json)
117 # A started server publishes its runtime record, which the launch waits for.
118 # The fake nohup runs in the background, so wait for it instead of racing it.
119 if [ -e "$HOME/picked-port" ]; then
120 while [ ! -e "$HOME/started-server" ]; do /bin/sleep 0.01; done
121 fi
122 if [ -e "$HOME/started-server" ]; then
123 printf 'record %s\\n' "$(cat "$HOME/clock")" >> "$HOME/events"
124 printf '%s 5999' "$(cat "$HOME/started-server")"
125 exit 0
126 fi
127 NOW="$(cat "$HOME/clock")"
128 printf 'runtime %s\\n' "$NOW" >> "$HOME/events"
129 if [ "$NOW" -ge "$TEST_READY_AT" ] || [ -e "$2" ]; then printf '%s %s' "$TEST_SERVER_PID" 4888
130 elif [ "$TEST_PUBLISH_AFTER_FIRST_READ" = 1 ]; then
131 mkdir -p "\${2%/*}"
132 printf '{}' > "$2"
133 rm -f "$HOME/.t3/runtime/desktop-update-in-progress"
134 exit 1
135 elif [ -n "$TEST_INITIAL_PORT" ]; then printf '%s %s' "$TEST_SERVER_PID" "$TEST_INITIAL_PORT"
136 else exit 1; fi ;;
137 */port)
138 printf 'start %s\\n' "$(cat "$HOME/clock")" >> "$HOME/events"
139 touch "$HOME/picked-port"
140 printf 5999 ;;
141 [0-9]*)
142 NOW="$(cat "$HOME/clock")"
143 printf 'probe %s %s\\n' "$2" "$NOW" >> "$HOME/events"
144 [ "$2" = 5999 ] || { [ "$2" = 4888 ] && { [ "$NOW" -ge "$TEST_READY_AT" ] || [ -e "$HOME/.t3/userdata/server-runtime.json" ]; }; } ;;
145 */desktop-update-in-progress)
146 printf 'marker %s\\n' "$(cat "$HOME/clock")" >> "$HOME/events"
147 exec "$TEST_REAL_NODE" --require "$HOME/clock.cjs" "$@" ;;
148 *) exec "$TEST_REAL_NODE" --require "$HOME/clock.cjs" "$@" ;;
149esac`,
150 );
151 executable(
152 "sleep",
153 `awk -v seconds="$1" '{ printf "%.0f", $1 + seconds * 1000 }' "$HOME/clock" > "$HOME/clock.next"
154mv "$HOME/clock.next" "$HOME/clock"
155if [ "$TEST_CLEAR_MARKER" = 1 ] && [ "$(cat "$HOME/clock")" -ge "$TEST_READY_AT" ]; then
156 rm -f "$HOME/.t3/runtime/desktop-update-in-progress"
157fi
158if [ -n "$TEST_CLOCK_JUMP" ] && [ ! -e "$HOME/jumped" ]; then
159 printf '%s' "$TEST_CLOCK_JUMP" > "$HOME/clock"
160 touch "$HOME/jumped"
161fi`,
162 );
163 executable("nohup", 'printf "%s" "$$" > "$HOME/started-server"');
164 // The test process stands in for a recorded server; report the serve command it would run.
165 executable(
166 "ps",
167 `if [ "$*" = "-ww -o args= -p $TEST_SERVER_PID" ]; then
168 printf '/bin/sh %s/.t3/ssh-launch/test-target/run-t3.sh serve --host 127.0.0.1 --port 5999\\n' "$HOME"
169 exit 0
170fi
171PATH=/usr/bin:/bin exec ps "$@"`,
172 );
173 if (options.recordedKind) {
174 const state = NodePath.join(home, ".t3/ssh-launch/test-target");
175 NodeFS.mkdirSync(state, { recursive: true });
176 NodeFS.writeFileSync(NodePath.join(state, "pid"), String(process.pid));
177 NodeFS.writeFileSync(NodePath.join(state, "port"), "5999");
178 NodeFS.writeFileSync(NodePath.join(state, "managed"), options.recordedKind);
179 const runner = script.split("cat >\"$RUNNER_NEXT\" <<'SH'\n")[1]?.split("\nSH\n")[0];
180 if (!runner) throw new Error("runner missing");
181 NodeFS.writeFileSync(NodePath.join(state, "run-t3.sh"), runner + "\n");
182 }
183 if (options.archive) {
184 executable("node", 'printf "unexpected host node invocation\\n" >&2; exit 1');
185 const version = NodePath.join(home, ".t3/runtime/versions/1.2.3");
186 NodeFS.mkdirSync(version, { recursive: true });
187 NodeFS.writeFileSync(NodePath.join(version, ".install-complete"), "1.2.3");
188 NodeFS.writeFileSync(
189 NodePath.join(home, "helper.ts"),
190 `
191import * as Effect from "effect/Effect";
192import * as NodeServices from "@effect/platform-node/NodeServices";
193import { Command } from "effect/cli";
194import { sshHelperCommand } from ${JSON.stringify(NodePath.join(root, "apps/server/src/cli/sshHelper.ts"))};
195await Effect.runPromise(Command.runWith(sshHelperCommand, { version: "1.2.3" })(process.argv.slice(2)).pipe(Effect.provide(NodeServices.layer)));
196`,
197 );
198 NodeFS.writeFileSync(
199 NodePath.join(version, "t3"),
200 `#!/bin/sh
201set -eu
202if [ "$1" = --version ]; then printf 1.2.3; exit; fi
203[ "$1" = __ssh-helper ]
204case "$2" in
205 update-remaining) printf 'marker %s\\n' "$(cat "$HOME/clock")" >> "$HOME/events"; exec "$TEST_REAL_NODE" --require "$HOME/clock.cjs" "$HOME/helper.ts" "$2" "$3" ;;
206 home-owned) exec "$TEST_REAL_NODE" "$HOME/helper.ts" "$2" "$3" ;;
207 runtime-port | pick-port | wait-ready) exec "$HOME/bin/test-node" - "$3" ;;
208 *) exit 1 ;;
209esac
210`,
211 { mode: 0o755 },
212 );
213 }
214 using _serving = options.serviceServing
215 ? holdLock(NodePath.join(runtime, "service-serving.lock"))
216 : undefined;
217 const result = NodeChildProcess.spawnSync("/bin/sh", ["-s", "--", "test-target"], {
218 input: `kill() {
219 if [ "$1" = -0 ]; then command kill "$@"; else
220 printf 'kill %s\\n' "$*" >> "$HOME/events"
221 return 1
222 fi
223}
224${script}`,
225 encoding: "utf8",
226 timeout: 30_000,
227 env: {
228 ...process.env,
229 HOME: home,
230 PATH: `${bin}:/usr/bin:/bin`,
231 TEST_REAL_NODE: process.execPath,
232 TEST_CLEAR_MARKER: options.clearMarkerOnReady ? "1" : "0",
233 TEST_CLOCK_JUMP: options.clockJump === undefined ? "" : String(options.clockJump),
234 TEST_SERVER_PID: String(process.pid),
235 TEST_READY_AT: String(options.readyAt ?? 1_000_000),
236 TEST_INITIAL_PORT: options.initialPort === undefined ? "" : String(options.initialPort),
237 TEST_PUBLISH_AFTER_FIRST_READ: options.publishAfterFirstRuntimeRead ? "1" : "0",
238 },
239 });
240 if (result.error || (result.status !== 0 && !options.allowFailure))
241 throw new Error(
242 `launcher failed: ${result.error ?? result.status}\n${result.stderr}\n${result.stdout}\n${NodeFS.readFileSync(NodePath.join(home, "events"), "utf8")}`,
243 );
244 return {
245 status: result.status,
246 stderr: result.stderr,
247 output: result.status === 0 ? JSON.parse(result.stdout.trim()) : undefined,
248 events: NodeFS.readFileSync(NodePath.join(home, "events"), "utf8").trim().split("\n"),
249 now: Number(NodeFS.readFileSync(NodePath.join(home, "clock"), "utf8")),
250 markerExists: NodeFS.existsSync(markerPath),
251 };
252 } finally {
253 NodeFS.rmSync(home, { recursive: true, force: true });
254 }
255}