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