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