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 // Match the hub cwd so relative executables and PATH entries resolve identically.
176 remoteCommandArgs: commandArgs(
177 `cd "$HOME/.t3/device/hosts/${owner}" && exec ${[command, ...args].map(quoteRemoteArg).join(" ")}`,
178 ),
179 keepErrorOutputTail: true,
180 ...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
181 ...(options?.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
182 }),
183 ).pipe(
184 Effect.map((result) => ({ ...result, code: 0 })),
185 Effect.catch((error) =>
186 Effect.succeed({
187 stdout: "stdout" in error ? (error.stdout ?? "") : "",
188 stderr: error.message,
189 code: "exitCode" in error ? (error.exitCode ?? 127) : 127,
190 }),
191 ),
192 );
193
194 const connectOnce = Effect.fn("SshDeviceHost.connectOnce")(function* (): Effect.fn.Return<
195 DeviceHost.DeviceHostReady & { agentDevice?: DeviceHost.DeviceHostAgentReady["agentDevice"] },
196 DeviceHost.DeviceHostError
197 > {
198 activated = true;
199 const result = yield* provide(bootstrap(config, owner, wantsAgent ? "agent-start" : "start"));
200 yield* onStatus("starting");
201 const remote = yield* decodeStarted(result.stdout.trim()).pipe(
202 Effect.mapError(
203 (cause) =>
204 new DeviceHost.DeviceHostError({
205 hostId: config.id,
206 step: "reading host endpoints",
207 cause,
208 }),
209 ),
210 );
211 summary = {
212 ...summary,
213 platforms: remote.platforms,
214 tools: remote.tools,
215 hubInstalled: true,
216 agentDeviceInstalled: wantsAgent || summary.agentDeviceInstalled,
217 };
218 const hubPort = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
219 Effect.mapError(
220 (cause) =>
221 new DeviceHost.DeviceHostError({
222 hostId: config.id,
223 step: "reserving hub port",
224 cause,
225 }),
226 ),
227 );
228 const daemonPort = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
229 Effect.mapError(
230 (cause) =>
231 new DeviceHost.DeviceHostError({
232 hostId: config.id,
233 step: "reserving daemon port",
234 cause,
235 }),
236 ),
237 );
238 const scope = yield* Scope.make();
239 connectionScope = scope;
240 const child = yield* spawner
241 .spawn(
242 ChildProcess.make(
243 ssh,
244 [
245 ...baseSshArgs(targetFor(config), { batchMode: "yes" }),
246 ...identityArgs(config),
247 "-o",
248 "ExitOnForwardFailure=yes",
249 // A multiplexed client hands its -L forwards to the control master and exits,
250 // so the tunnel must own its own connection.
251 "-o",
252 "ControlMaster=no",
253 "-o",
254 "ControlPath=none",
255 "-o",
256 "ControlPersist=no",
257 "-o",
258 "ServerAliveInterval=10",
259 "-o",
260 "ServerAliveCountMax=3",
261 "-T",
262 "-L",
263 `127.0.0.1:${hubPort}:127.0.0.1:${remote.hubPort}`,
264 ...(remote.daemonPort === undefined
265 ? []
266 : ["-L", `127.0.0.1:${daemonPort}:127.0.0.1:${remote.daemonPort}`]),
267 config.target,
268 // The server holds the only write end of this stdin, so when it exits for any
269 // reason the remote `cat` sees EOF and ssh exits once its forwarded connections
270 // close, instead of being orphaned.
271 "sh",
272 "-c",
273 quoteRemoteArg("exec cat >/dev/null"),
274 ],
275 { stdin: "pipe", stdout: "ignore", stderr: "pipe" },
276 ),
277 )
278 .pipe(
279 Effect.provideService(Scope.Scope, scope),
280 Effect.mapError(
281 (cause) =>
282 new DeviceHost.DeviceHostError({ hostId: config.id, step: "forwarding ports", cause }),
283 ),
284 );
285 let stderr = "";
286 yield* child.stderr.pipe(
287 Stream.decodeText(),
288 Stream.runForEach((chunk) =>
289 Effect.sync(() => {
290 stderr = (stderr + chunk).slice(-2000);
291 }),
292 ),
293 Effect.forkIn(scope),
294 );
295 const next = {
296 nodePath: remote.nodePath,
297 hub: { origin: `http://127.0.0.1:${hubPort}` },
298 ...(remote.daemonPort !== undefined &&
299 remote.token !== undefined &&
300 remote.entryPath !== undefined
301 ? {
302 agentDevice: {
303 baseUrl: `http://127.0.0.1:${daemonPort}`,
304 token: remote.token,
305 entryPath: remote.entryPath,
306 },
307 }
308 : {}),
309 helpers: remote.helpers,
310 run,
311 };
312 for (const [baseUrl, route] of [
313 [next.hub.origin, "/readyz"],
314 ...(next.agentDevice ? [[next.agentDevice.baseUrl, "/health"]] : []),
315 ]) {
316 yield* waitForHttpReady({
317 baseUrl: baseUrl!,
318 path: route!,
319 timeoutMs: 15000,
320 makeError: () =>
321 new DeviceHost.DeviceHostError({
322 hostId: config.id,
323 step: "waiting for SSH forward",
324 cause: new Error(stderr || "Forwarded endpoint did not answer."),
325 }),
326 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
327 }
328 if (next.agentDevice) yield* onReady({ ...next, agentDevice: next.agentDevice });
329 ready = next;
330 yield* onStatus("ready");
331 // Reconnect also repairs helpers that died while SSH itself stayed connected.
332 const unhealthy = Effect.gen(function* () {
333 while (true) {
334 yield* Effect.sleep("10 seconds");
335 const alive = yield* http.get(`${next.hub.origin}/readyz`).pipe(
336 Effect.timeout("5 seconds"),
337 Effect.map((r) => r.status === 200),
338 Effect.orElseSucceed(() => false),
339 );
340 const daemonAlive = next.agentDevice
341 ? yield* http.get(`${next.agentDevice!.baseUrl}/health`).pipe(
342 Effect.timeout("5 seconds"),
343 Effect.map((r) => r.status === 200),
344 Effect.orElseSucceed(() => false),
345 )
346 : true;
347 if (!alive || !daemonAlive) return;
348 }
349 });
350 yield* Effect.gen(function* () {
351 yield* Effect.raceFirst(child.exitCode.pipe(Effect.ignore), unhealthy);
352 if (stopped || connectionScope !== scope) return;
353 ready = null;
354 yield* onStatus("starting", "Reconnecting to device host…");
355 yield* Scope.close(scope, Exit.void);
356 let delay = 1000;
357 while (true) {
358 if (stopped || connectionScope !== scope) return;
359 yield* Effect.sleep(delay);
360 const result = yield* lock
361 .withPermit(
362 Effect.suspend(() => (stopped || ready ? Effect.void : connect().pipe(Effect.asVoid))),
363 )
364 .pipe(Effect.result);
365 if (result._tag === "Success") return;
366 yield* onStatus("failed", result.failure.message);
367 if (connectionScope && connectionScope !== scope)
368 yield* Scope.close(connectionScope, Exit.void);
369 connectionScope = scope;
370 delay = Math.min(delay * 2, 30000);
371 }
372 }).pipe(Effect.forkIn(parentScope));
373 return next;
374 });
375
376 const connect = Effect.fn("SshDeviceHost.connect")(function* () {
377 for (let attempt = 0; ; attempt++) {
378 const result = yield* connectOnce().pipe(Effect.result);
379 if (result._tag === "Success") return result.success;
380 const failedScope = connectionScope;
381 connectionScope = null;
382 if (failedScope) yield* Scope.close(failedScope, Exit.void);
383 // SSH binds after the reservation is released, so a competing bind needs fresh ports.
384 if (
385 attempt >= 2 ||
386 !["forwarding ports", "waiting for SSH forward"].includes(result.failure.step)
387 )
388 return yield* result.failure;
389 }
390 });
391
392 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
393 lock.withPermit(
394 Effect.gen(function* () {
395 stopped = false;
396 if (ready) return ready;
397 summary = yield* provide(probe(config, owner));
398 yield* onPhase(
399 summary.hubInstalled ? "starting" : "installing",
400 summary.hubInstalled
401 ? undefined
402 : deviceToolInstallMessage("device hub", summary.tools?.hub),
403 );
404 return yield* connect().pipe(
405 Effect.tapError(() =>
406 connectionScope ? Scope.close(connectionScope, Exit.void) : Effect.void,
407 ),
408 );
409 }),
410 );
411 const stop = lock.withPermit(
412 Effect.gen(function* () {
413 stopped = true;
414 ready = null;
415 if (connectionScope) yield* Scope.close(connectionScope, Exit.void);
416 connectionScope = null;
417 if (activated) yield* provide(bootstrap(config, owner, "stop")).pipe(Effect.ignore);
418 activated = false;
419 wantsAgent = false;
420 }),
421 );
422 const changeAgent = (enabled: boolean) =>
423 lock.withPermit(
424 Effect.gen(function* () {
425 wantsAgent = enabled;
426 if (enabled && ready?.agentDevice) return { ...ready, agentDevice: ready.agentDevice };
427 if (!enabled && !ready?.agentDevice) return null;
428 ready = null;
429 const previousScope = connectionScope;
430 connectionScope = null;
431 if (previousScope) yield* Scope.close(previousScope, Exit.void);
432 if (!enabled) yield* provide(bootstrap(config, owner, "stop-agent"));
433 return yield* connect().pipe(
434 Effect.onError(() =>
435 Effect.gen(function* () {
436 const failedScope = connectionScope;
437 connectionScope = null;
438 if (failedScope) yield* Scope.close(failedScope, Exit.void);
439 if (enabled)
440 yield* provide(bootstrap(config, owner, "stop-agent")).pipe(Effect.ignore);
441 }),
442 ),
443 );
444 }),
445 );
446 yield* Effect.addFinalizer(() => stop);
447 return {
448 id: config.id,
449 summary: Effect.sync(() => summary),
450 inspect: provide(probe(config, owner)).pipe(
451 Effect.tap((value) =>
452 Effect.sync(() => {
453 summary = value;
454 }),
455 ),
456 ),
457 current: Effect.sync(() => ready),
458 ensureReady,
459 ensureAgentReady: (onPhase) =>
460 ensureReady(onPhase).pipe(
461 Effect.flatMap(() =>
462 onPhase(
463 summary.agentDeviceInstalled ? "starting" : "installing",
464 summary.agentDeviceInstalled
465 ? undefined
466 : deviceToolInstallMessage("agent tools", summary.tools?.agent),
467 ),
468 ),
469 Effect.flatMap(() => changeAgent(true)),
470 Effect.flatMap((value) =>
471 value?.agentDevice
472 ? Effect.succeed({ ...value, agentDevice: value.agentDevice })
473 : Effect.fail(
474 new DeviceHost.DeviceHostError({
475 hostId: config.id,
476 step: "starting agent tools",
477 cause: new Error("Daemon endpoint missing"),
478 }),
479 ),
480 ),
481 ),
482 stopAgent: changeAgent(false).pipe(Effect.asVoid, Effect.ignore),
483 stop,
484 platformAvailability: (platform) =>
485 provide(probe(config, owner)).pipe(
486 Effect.map((value) => {
487 summary = { ...summary, platforms: value.platforms };
488 return value.platforms.find((p) => p.platform === platform)!;
489 }),
490 Effect.orElseSucceed(() => ({
491 platform,
492 available: false,
493 reason: "Cannot reach device host. Test its SSH connection in Settings.",
494 })),
495 ),
496 } satisfies DeviceHost.DeviceHost["Service"];
497});