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