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