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 "-N",
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 ],
265 { stdin: "ignore", stdout: "ignore", stderr: "pipe" },
266 ),
267 )
268 .pipe(
269 Effect.provideService(Scope.Scope, scope),
270 Effect.mapError(
271 (cause) =>
272 new DeviceHost.DeviceHostError({ hostId: config.id, step: "forwarding ports", cause }),
273 ),
274 );
275 let stderr = "";
276 yield* child.stderr.pipe(
277 Stream.decodeText(),
278 Stream.runForEach((chunk) =>
279 Effect.sync(() => {
280 stderr = (stderr + chunk).slice(-2000);
281 }),
282 ),
283 Effect.forkIn(scope),
284 );
285 const next = {
286 nodePath: remote.nodePath,
287 hub: { origin: `http://127.0.0.1:${hubPort}` },
288 ...(remote.daemonPort !== undefined &&
289 remote.token !== undefined &&
290 remote.entryPath !== undefined
291 ? {
292 agentDevice: {
293 baseUrl: `http://127.0.0.1:${daemonPort}`,
294 token: remote.token,
295 entryPath: remote.entryPath,
296 },
297 }
298 : {}),
299 helpers: remote.helpers,
300 run,
301 };
302 for (const [baseUrl, route] of [
303 [next.hub.origin, "/readyz"],
304 ...(next.agentDevice ? [[next.agentDevice.baseUrl, "/health"]] : []),
305 ]) {
306 yield* waitForHttpReady({
307 baseUrl: baseUrl!,
308 path: route!,
309 timeoutMs: 15000,
310 makeError: () =>
311 new DeviceHost.DeviceHostError({
312 hostId: config.id,
313 step: "waiting for SSH forward",
314 cause: new Error(stderr || "Forwarded endpoint did not answer."),
315 }),
316 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
317 }
318 if (next.agentDevice) yield* onReady({ ...next, agentDevice: next.agentDevice });
319 ready = next;
320 yield* onStatus("ready");
321 // Reconnect also repairs helpers that died while SSH itself stayed connected.
322 const unhealthy = Effect.gen(function* () {
323 while (true) {
324 yield* Effect.sleep("10 seconds");
325 const alive = yield* http.get(`${next.hub.origin}/readyz`).pipe(
326 Effect.timeout("5 seconds"),
327 Effect.map((r) => r.status === 200),
328 Effect.orElseSucceed(() => false),
329 );
330 const daemonAlive = next.agentDevice
331 ? yield* http.get(`${next.agentDevice!.baseUrl}/health`).pipe(
332 Effect.timeout("5 seconds"),
333 Effect.map((r) => r.status === 200),
334 Effect.orElseSucceed(() => false),
335 )
336 : true;
337 if (!alive || !daemonAlive) return;
338 }
339 });
340 yield* Effect.gen(function* () {
341 yield* Effect.raceFirst(child.exitCode.pipe(Effect.ignore), unhealthy);
342 if (stopped || connectionScope !== scope) return;
343 ready = null;
344 yield* onStatus("starting", "Reconnecting to device host…");
345 yield* Scope.close(scope, Exit.void);
346 let delay = 1000;
347 while (true) {
348 if (stopped || connectionScope !== scope) return;
349 yield* Effect.sleep(delay);
350 const result = yield* lock
351 .withPermit(
352 Effect.suspend(() => (stopped || ready ? Effect.void : connect().pipe(Effect.asVoid))),
353 )
354 .pipe(Effect.result);
355 if (result._tag === "Success") return;
356 yield* onStatus("failed", result.failure.message);
357 if (connectionScope && connectionScope !== scope)
358 yield* Scope.close(connectionScope, Exit.void);
359 connectionScope = scope;
360 delay = Math.min(delay * 2, 30000);
361 }
362 }).pipe(Effect.forkIn(parentScope));
363 return next;
364 });
365
366 const connect = Effect.fn("SshDeviceHost.connect")(function* () {
367 for (let attempt = 0; ; attempt++) {
368 const result = yield* connectOnce().pipe(Effect.result);
369 if (result._tag === "Success") return result.success;
370 const failedScope = connectionScope;
371 connectionScope = null;
372 if (failedScope) yield* Scope.close(failedScope, Exit.void);
373 // SSH binds after the reservation is released, so a competing bind needs fresh ports.
374 if (
375 attempt >= 2 ||
376 !["forwarding ports", "waiting for SSH forward"].includes(result.failure.step)
377 )
378 return yield* result.failure;
379 }
380 });
381
382 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
383 lock.withPermit(
384 Effect.gen(function* () {
385 stopped = false;
386 if (ready) return ready;
387 summary = yield* provide(probe(config, owner));
388 yield* onPhase(
389 summary.hubInstalled ? "starting" : "installing",
390 summary.hubInstalled
391 ? undefined
392 : deviceToolInstallMessage("device hub", summary.tools?.hub),
393 );
394 return yield* connect().pipe(
395 Effect.tapError(() =>
396 connectionScope ? Scope.close(connectionScope, Exit.void) : Effect.void,
397 ),
398 );
399 }),
400 );
401 const stop = lock.withPermit(
402 Effect.gen(function* () {
403 stopped = true;
404 ready = null;
405 if (connectionScope) yield* Scope.close(connectionScope, Exit.void);
406 connectionScope = null;
407 if (activated) yield* provide(bootstrap(config, owner, "stop")).pipe(Effect.ignore);
408 activated = false;
409 wantsAgent = false;
410 }),
411 );
412 const changeAgent = (enabled: boolean) =>
413 lock.withPermit(
414 Effect.gen(function* () {
415 wantsAgent = enabled;
416 if (enabled && ready?.agentDevice) return { ...ready, agentDevice: ready.agentDevice };
417 if (!enabled && !ready?.agentDevice) return null;
418 ready = null;
419 const previousScope = connectionScope;
420 connectionScope = null;
421 if (previousScope) yield* Scope.close(previousScope, Exit.void);
422 if (!enabled) yield* provide(bootstrap(config, owner, "stop-agent"));
423 return yield* connect().pipe(
424 Effect.onError(() =>
425 Effect.gen(function* () {
426 const failedScope = connectionScope;
427 connectionScope = null;
428 if (failedScope) yield* Scope.close(failedScope, Exit.void);
429 if (enabled)
430 yield* provide(bootstrap(config, owner, "stop-agent")).pipe(Effect.ignore);
431 }),
432 ),
433 );
434 }),
435 );
436 yield* Effect.addFinalizer(() => stop);
437 return {
438 id: config.id,
439 summary: Effect.sync(() => summary),
440 inspect: provide(probe(config, owner)).pipe(
441 Effect.tap((value) =>
442 Effect.sync(() => {
443 summary = value;
444 }),
445 ),
446 ),
447 current: Effect.sync(() => ready),
448 ensureReady,
449 ensureAgentReady: (onPhase) =>
450 ensureReady(onPhase).pipe(
451 Effect.flatMap(() =>
452 onPhase(
453 summary.agentDeviceInstalled ? "starting" : "installing",
454 summary.agentDeviceInstalled
455 ? undefined
456 : deviceToolInstallMessage("agent tools", summary.tools?.agent),
457 ),
458 ),
459 Effect.flatMap(() => changeAgent(true)),
460 Effect.flatMap((value) =>
461 value?.agentDevice
462 ? Effect.succeed({ ...value, agentDevice: value.agentDevice })
463 : Effect.fail(
464 new DeviceHost.DeviceHostError({
465 hostId: config.id,
466 step: "starting agent tools",
467 cause: new Error("Daemon endpoint missing"),
468 }),
469 ),
470 ),
471 ),
472 stopAgent: changeAgent(false).pipe(Effect.asVoid, Effect.ignore),
473 stop,
474 platformAvailability: (platform) =>
475 provide(probe(config, owner)).pipe(
476 Effect.map((value) => {
477 summary = { ...summary, platforms: value.platforms };
478 return value.platforms.find((p) => p.platform === platform)!;
479 }),
480 Effect.orElseSucceed(() => ({
481 platform,
482 available: false,
483 reason: "Cannot reach device host. Test its SSH connection in Settings.",
484 })),
485 ),
486 } satisfies DeviceHost.DeviceHost["Service"];
487});