Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2import {
3 type DeviceHostSummary,
4 DevicePlatformAvailability,
5 type SshDeviceHostConfig,
6} from "@t3tools/contracts";
7import { runSshCommand, baseSshArgs, resolveSshCommand } from "@t3tools/ssh/command";
8import * as NetService from "@t3tools/shared/Net";
9import { waitForHttpReady } from "@t3tools/shared/httpReadiness";
10import * as Exit from "effect/Exit";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Path from "effect/Path";
14import * as Scope from "effect/Scope";
15import * as Semaphore from "effect/Semaphore";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import * as HttpClient from "effect/unstable/http/HttpClient";
19import * as ChildProcess from "effect/unstable/process/ChildProcess";
20import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
21import * as ServerConfig from "../config.ts";
22import * as DeviceHost from "./DeviceHost.ts";
23import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts";
24
25const Probe = Schema.Struct({
26 nodePath: Schema.String,
27 platforms: Schema.Array(DevicePlatformAvailability),
28});
29const Started = Schema.Struct({
30 ...Probe.fields,
31 hubPort: Schema.Int,
32 daemonPort: Schema.optionalKey(Schema.Int),
33 token: Schema.optionalKey(Schema.String),
34 entryPath: Schema.optionalKey(Schema.String),
35 helpers: Schema.Struct({
36 serveSimAxSettings: Schema.NullOr(Schema.String),
37 serveSimCli: Schema.NullOr(Schema.String),
38 }),
39});
40const decodeProbe = Schema.decodeUnknownEffect(Schema.fromJsonString(Probe));
41const decodeStarted = Schema.decodeUnknownEffect(Schema.fromJsonString(Started));
42const targetFor = (config: SshDeviceHostConfig) => ({
43 alias: config.target,
44 hostname: config.target,
45 username: null,
46 port: config.port ?? null,
47});
48const identityArgs = (config: SshDeviceHostConfig) =>
49 config.identityFile ? ["-i", config.identityFile] : [];
50const commandArgs = (script: string) => [
51 "sh",
52 "-c",
53 quoteRemoteArg(remoteDeviceEnvironment + script),
54];
55const bootstrap = (
56 config: SshDeviceHostConfig,
57 owner: string,
58 mode: "probe" | "start" | "agent-start" | "stop-agent" | "stop",
59) =>
60 runSshCommand(targetFor(config), {
61 preHostArgs: identityArgs(config),
62 remoteCommandArgs: commandArgs(
63 'command -v node >/dev/null 2>&1 || { echo "Node is missing from the non-interactive SSH PATH" >&2; exit 1; }; exec node',
64 ),
65 stdin: remoteDeviceScript(owner, mode),
66 timeoutMs: mode === "start" || mode === "agent-start" ? 1_300_000 : 45_000,
67 }).pipe(
68 Effect.mapError(
69 (cause) => new DeviceHost.DeviceHostError({ hostId: config.id, step: mode, cause }),
70 ),
71 );
72
73export const probe = Effect.fn("SshDeviceHost.probe")(function* (config: SshDeviceHostConfig) {
74 const result = yield* bootstrap(config, "probe", "probe");
75 const value = yield* decodeProbe(result.stdout.trim()).pipe(
76 Effect.mapError(
77 (cause) =>
78 new DeviceHost.DeviceHostError({ hostId: config.id, step: "reading probe result", cause }),
79 ),
80 );
81 return {
82 id: config.id,
83 label: config.label,
84 kind: "ssh",
85 hubInstalled: false,
86 agentDeviceInstalled: false,
87 platforms: value.platforms,
88 } satisfies DeviceHostSummary;
89});
90
91export const make = Effect.fn("SshDeviceHost.make")(function* (
92 config: SshDeviceHostConfig,
93 onReady: (
94 ready: DeviceHost.DeviceHostAgentReady,
95 ) => Effect.Effect<void, DeviceHost.DeviceHostError> = () => Effect.void,
96 onStatus: (
97 status: "starting" | "ready" | "failed",
98 detail?: string,
99 ) => Effect.Effect<void> = () => Effect.void,
100) {
101 const fs = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103 const server = yield* ServerConfig.ServerConfig;
104 const net = yield* NetService.NetService;
105 const http = yield* HttpClient.HttpClient;
106 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
107 const parentScope = yield* Scope.Scope;
108 const ssh = yield* resolveSshCommand;
109 const environmentId = yield* fs
110 .readFileString(server.environmentIdPath)
111 .pipe(Effect.orElseSucceed(() => server.stateDir));
112 const owner = NodeCrypto.createHash("sha256")
113 .update(`${environmentId}\0${server.stateDir}\0${config.id}`)
114 .digest("hex")
115 .slice(0, 24);
116 const provide = <A, E>(
117 effect: Effect.Effect<
118 A,
119 E,
120 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
121 >,
122 ) =>
123 effect.pipe(
124 Effect.provideService(FileSystem.FileSystem, fs),
125 Effect.provideService(Path.Path, path),
126 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
127 );
128 const lock = yield* Semaphore.make(1);
129 let stopped = false;
130 let activated = false;
131 let wantsAgent = false;
132 let ready:
133 | (DeviceHost.DeviceHostReady & {
134 agentDevice?: DeviceHost.DeviceHostAgentReady["agentDevice"];
135 })
136 | null = null;
137 let connectionScope: Scope.Closeable | null = null;
138 let summary: DeviceHostSummary = {
139 id: config.id,
140 label: config.label,
141 kind: "ssh",
142 hubInstalled: false,
143 agentDeviceInstalled: false,
144 platforms: [],
145 };
146
147 const run: DeviceHost.DeviceHostReady["run"] = (command, args, options) =>
148 provide(
149 runSshCommand(targetFor(config), {
150 preHostArgs: identityArgs(config),
151 remoteCommandArgs: commandArgs(`exec ${[command, ...args].map(quoteRemoteArg).join(" ")}`),
152 ...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
153 ...(options?.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
154 }),
155 ).pipe(
156 Effect.map((result) => ({ ...result, code: 0 })),
157 Effect.catch((error) =>
158 Effect.succeed({
159 stdout: "stdout" in error ? (error.stdout ?? "") : "",
160 stderr: error.message,
161 code: "exitCode" in error ? (error.exitCode ?? 127) : 127,
162 }),
163 ),
164 );
165
166 const connectOnce = Effect.fn("SshDeviceHost.connectOnce")(function* (): Effect.fn.Return<
167 DeviceHost.DeviceHostReady & { agentDevice?: DeviceHost.DeviceHostAgentReady["agentDevice"] },
168 DeviceHost.DeviceHostError
169 > {
170 activated = true;
171 const result = yield* provide(bootstrap(config, owner, wantsAgent ? "agent-start" : "start"));
172 yield* onStatus("starting");
173 const remote = yield* decodeStarted(result.stdout.trim()).pipe(
174 Effect.mapError(
175 (cause) =>
176 new DeviceHost.DeviceHostError({
177 hostId: config.id,
178 step: "reading host endpoints",
179 cause,
180 }),
181 ),
182 );
183 summary = {
184 ...summary,
185 platforms: remote.platforms,
186 hubInstalled: true,
187 agentDeviceInstalled: wantsAgent || summary.agentDeviceInstalled,
188 };
189 const hubPort = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
190 Effect.mapError(
191 (cause) =>
192 new DeviceHost.DeviceHostError({
193 hostId: config.id,
194 step: "reserving hub port",
195 cause,
196 }),
197 ),
198 );
199 const daemonPort = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
200 Effect.mapError(
201 (cause) =>
202 new DeviceHost.DeviceHostError({
203 hostId: config.id,
204 step: "reserving daemon port",
205 cause,
206 }),
207 ),
208 );
209 const scope = yield* Scope.make();
210 connectionScope = scope;
211 const child = yield* spawner
212 .spawn(
213 ChildProcess.make(
214 ssh,
215 [
216 ...baseSshArgs(targetFor(config), { batchMode: "yes" }),
217 ...identityArgs(config),
218 "-o",
219 "ExitOnForwardFailure=yes",
220 "-o",
221 "ServerAliveInterval=10",
222 "-o",
223 "ServerAliveCountMax=3",
224 "-N",
225 "-L",
226 `127.0.0.1:${hubPort}:127.0.0.1:${remote.hubPort}`,
227 ...(remote.daemonPort === undefined
228 ? []
229 : ["-L", `127.0.0.1:${daemonPort}:127.0.0.1:${remote.daemonPort}`]),
230 config.target,
231 ],
232 { stdin: "ignore", stdout: "ignore", stderr: "pipe" },
233 ),
234 )
235 .pipe(
236 Effect.provideService(Scope.Scope, scope),
237 Effect.mapError(
238 (cause) =>
239 new DeviceHost.DeviceHostError({ hostId: config.id, step: "forwarding ports", cause }),
240 ),
241 );
242 let stderr = "";
243 yield* child.stderr.pipe(
244 Stream.decodeText(),
245 Stream.runForEach((chunk) =>
246 Effect.sync(() => {
247 stderr = (stderr + chunk).slice(-2000);
248 }),
249 ),
250 Effect.forkIn(scope),
251 );
252 const next = {
253 nodePath: remote.nodePath,
254 hub: { origin: `http://127.0.0.1:${hubPort}` },
255 ...(remote.daemonPort !== undefined &&
256 remote.token !== undefined &&
257 remote.entryPath !== undefined
258 ? {
259 agentDevice: {
260 baseUrl: `http://127.0.0.1:${daemonPort}`,
261 token: remote.token,
262 entryPath: remote.entryPath,
263 },
264 }
265 : {}),
266 helpers: remote.helpers,
267 run,
268 };
269 for (const [baseUrl, route] of [
270 [next.hub.origin, "/readyz"],
271 ...(next.agentDevice ? [[next.agentDevice.baseUrl, "/health"]] : []),
272 ]) {
273 yield* waitForHttpReady({
274 baseUrl: baseUrl!,
275 path: route!,
276 timeoutMs: 15000,
277 makeError: () =>
278 new DeviceHost.DeviceHostError({
279 hostId: config.id,
280 step: "waiting for SSH forward",
281 cause: new Error(stderr || "Forwarded endpoint did not answer."),
282 }),
283 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
284 }
285 if (next.agentDevice) yield* onReady({ ...next, agentDevice: next.agentDevice });
286 ready = next;
287 yield* onStatus("ready");
288 // Reconnect also repairs helpers that died while SSH itself stayed connected.
289 const unhealthy = Effect.gen(function* () {
290 while (true) {
291 yield* Effect.sleep("10 seconds");
292 const alive = yield* http.get(`${next.hub.origin}/readyz`).pipe(
293 Effect.timeout("5 seconds"),
294 Effect.map((r) => r.status === 200),
295 Effect.orElseSucceed(() => false),
296 );
297 const daemonAlive = next.agentDevice
298 ? yield* http.get(`${next.agentDevice!.baseUrl}/health`).pipe(
299 Effect.timeout("5 seconds"),
300 Effect.map((r) => r.status === 200),
301 Effect.orElseSucceed(() => false),
302 )
303 : true;
304 if (!alive || !daemonAlive) return;
305 }
306 });
307 yield* Effect.gen(function* () {
308 yield* Effect.raceFirst(child.exitCode.pipe(Effect.ignore), unhealthy);
309 if (stopped || connectionScope !== scope) return;
310 ready = null;
311 yield* onStatus("starting", "Reconnecting to device host…");
312 yield* Scope.close(scope, Exit.void);
313 let delay = 1000;
314 while (true) {
315 if (stopped || connectionScope !== scope) return;
316 yield* Effect.sleep(delay);
317 const result = yield* lock
318 .withPermit(
319 Effect.suspend(() => (stopped || ready ? Effect.void : connect().pipe(Effect.asVoid))),
320 )
321 .pipe(Effect.result);
322 if (result._tag === "Success") return;
323 yield* onStatus("failed", result.failure.message);
324 if (connectionScope && connectionScope !== scope)
325 yield* Scope.close(connectionScope, Exit.void);
326 connectionScope = scope;
327 delay = Math.min(delay * 2, 30000);
328 }
329 }).pipe(Effect.forkIn(parentScope));
330 return next;
331 });
332
333 const connect = Effect.fn("SshDeviceHost.connect")(function* () {
334 for (let attempt = 0; ; attempt++) {
335 const result = yield* connectOnce().pipe(Effect.result);
336 if (result._tag === "Success") return result.success;
337 const failedScope = connectionScope;
338 connectionScope = null;
339 if (failedScope) yield* Scope.close(failedScope, Exit.void);
340 // SSH binds after the reservation is released, so a competing bind needs fresh ports.
341 if (
342 attempt >= 2 ||
343 !["forwarding ports", "waiting for SSH forward"].includes(result.failure.step)
344 )
345 return yield* result.failure;
346 }
347 });
348
349 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
350 lock.withPermit(
351 Effect.gen(function* () {
352 stopped = false;
353 if (ready) return ready;
354 summary = yield* provide(probe(config));
355 yield* onPhase("installing");
356 return yield* connect().pipe(
357 Effect.tapError(() =>
358 connectionScope ? Scope.close(connectionScope, Exit.void) : Effect.void,
359 ),
360 );
361 }),
362 );
363 const stop = lock.withPermit(
364 Effect.gen(function* () {
365 stopped = true;
366 ready = null;
367 if (connectionScope) yield* Scope.close(connectionScope, Exit.void);
368 connectionScope = null;
369 if (activated) yield* provide(bootstrap(config, owner, "stop")).pipe(Effect.ignore);
370 activated = false;
371 wantsAgent = false;
372 }),
373 );
374 const changeAgent = (enabled: boolean) =>
375 lock.withPermit(
376 Effect.gen(function* () {
377 wantsAgent = enabled;
378 if (enabled && ready?.agentDevice) return { ...ready, agentDevice: ready.agentDevice };
379 if (!enabled && !ready?.agentDevice) return null;
380 ready = null;
381 const previousScope = connectionScope;
382 connectionScope = null;
383 if (previousScope) yield* Scope.close(previousScope, Exit.void);
384 if (!enabled) yield* provide(bootstrap(config, owner, "stop-agent"));
385 return yield* connect().pipe(
386 Effect.onError(() =>
387 Effect.gen(function* () {
388 const failedScope = connectionScope;
389 connectionScope = null;
390 if (failedScope) yield* Scope.close(failedScope, Exit.void);
391 if (enabled)
392 yield* provide(bootstrap(config, owner, "stop-agent")).pipe(Effect.ignore);
393 }),
394 ),
395 );
396 }),
397 );
398 yield* Effect.addFinalizer(() => stop);
399 return {
400 id: config.id,
401 summary: Effect.sync(() => summary),
402 current: Effect.sync(() => ready),
403 ensureReady,
404 ensureAgentReady: (onPhase) =>
405 onPhase("installing").pipe(
406 Effect.flatMap(() => changeAgent(true)),
407 Effect.flatMap((value) =>
408 value?.agentDevice
409 ? Effect.succeed({ ...value, agentDevice: value.agentDevice })
410 : Effect.fail(
411 new DeviceHost.DeviceHostError({
412 hostId: config.id,
413 step: "starting agent tools",
414 cause: new Error("Daemon endpoint missing"),
415 }),
416 ),
417 ),
418 ),
419 stopAgent: changeAgent(false).pipe(Effect.asVoid, Effect.ignore),
420 stop,
421 platformAvailability: (platform) =>
422 provide(probe(config)).pipe(
423 Effect.map((value) => {
424 summary = { ...summary, platforms: value.platforms };
425 return value.platforms.find((p) => p.platform === platform)!;
426 }),
427 Effect.orElseSucceed(() => ({
428 platform,
429 available: false,
430 reason: "Cannot reach device host. Test its SSH connection in Settings.",
431 })),
432 ),
433 } satisfies DeviceHost.DeviceHost["Service"];
434});