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