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