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 // A multiplexed client hands its -L forwards to the control master and exits,
266 // so the tunnel must own its own 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 androidAvailable: platformAvailability("android").pipe(
321 Effect.map((availability) => availability.available),
322 ),
323 }),
324 ...(remote.daemonPort !== undefined &&
325 remote.token !== undefined &&
326 remote.entryPath !== undefined
327 ? {
328 agentDevice: {
329 baseUrl: `http://127.0.0.1:${daemonPort}`,
330 token: remote.token,
331 entryPath: remote.entryPath,
332 },
333 }
334 : {}),
335 helpers: remote.helpers,
336 run,
337 };
338 for (const [baseUrl, route] of [
339 [next.hub.origin, "/readyz"],
340 ...(next.agentDevice ? [[next.agentDevice.baseUrl, "/health"]] : []),
341 ]) {
342 yield* waitForHttpReady({
343 baseUrl: baseUrl!,
344 path: route!,
345 timeoutMs: 15000,
346 makeError: () =>
347 new DeviceHost.DeviceHostError({
348 hostId: config.id,
349 step: "waiting for SSH forward",
350 cause: new Error(stderr || "Forwarded endpoint did not answer."),
351 }),
352 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
353 }
354 if (next.agentDevice) yield* onReady({ ...next, agentDevice: next.agentDevice });
355 ready = next;
356 yield* onStatus("ready");
357 // Reconnect also repairs helpers that died while SSH itself stayed connected.
358 const unhealthy = Effect.gen(function* () {
359 while (true) {
360 yield* Effect.sleep("10 seconds");
361 const alive = yield* http.get(`${next.hub.origin}/readyz`).pipe(
362 Effect.timeout("5 seconds"),
363 Effect.map((r) => r.status === 200),
364 Effect.orElseSucceed(() => false),
365 );
366 const daemonAlive = next.agentDevice
367 ? yield* http.get(`${next.agentDevice!.baseUrl}/health`).pipe(
368 Effect.timeout("5 seconds"),
369 Effect.map((r) => r.status === 200),
370 Effect.orElseSucceed(() => false),
371 )
372 : true;
373 if (!alive || !daemonAlive) return;
374 }
375 });
376 yield* Effect.gen(function* () {
377 yield* Effect.raceFirst(child.exitCode.pipe(Effect.ignore), unhealthy);
378 if (stopped || connectionScope !== scope) return;
379 ready = null;
380 yield* onStatus("starting", "Reconnecting to device host…");
381 yield* Scope.close(scope, Exit.void);
382 let delay = 1000;
383 while (true) {
384 if (stopped || connectionScope !== scope) return;
385 yield* Effect.sleep(delay);
386 const result = yield* lock
387 .withPermit(
388 Effect.suspend(() => (stopped || ready ? Effect.void : connect().pipe(Effect.asVoid))),
389 )
390 .pipe(Effect.result);
391 if (result._tag === "Success") return;
392 yield* onStatus("failed", result.failure.message);
393 if (connectionScope && connectionScope !== scope)
394 yield* Scope.close(connectionScope, Exit.void);
395 connectionScope = scope;
396 delay = Math.min(delay * 2, 30000);
397 }
398 }).pipe(Effect.forkIn(parentScope));
399 return next;
400 });
401
402 const connect = Effect.fn("SshDeviceHost.connect")(function* () {
403 for (let attempt = 0; ; attempt++) {
404 const result = yield* connectOnce().pipe(Effect.result);
405 if (result._tag === "Success") return result.success;
406 const failedScope = connectionScope;
407 connectionScope = null;
408 if (failedScope) yield* Scope.close(failedScope, Exit.void);
409 // SSH binds after the reservation is released, so a competing bind needs fresh ports.
410 if (
411 attempt >= 2 ||
412 !["forwarding ports", "waiting for SSH forward"].includes(result.failure.step)
413 )
414 return yield* result.failure;
415 }
416 });
417
418 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
419 lock.withPermit(
420 Effect.gen(function* () {
421 stopped = false;
422 if (ready) return ready;
423 summary = yield* provide(probe(config, owner));
424 yield* onPhase(
425 summary.hubInstalled ? "starting" : "installing",
426 summary.hubInstalled
427 ? undefined
428 : deviceToolInstallMessage("device hub", summary.tools?.hub),
429 );
430 return yield* connect().pipe(
431 Effect.tapError(() =>
432 connectionScope ? Scope.close(connectionScope, Exit.void) : Effect.void,
433 ),
434 );
435 }),
436 );
437 const stop = lock.withPermit(
438 Effect.gen(function* () {
439 stopped = true;
440 ready = null;
441 if (connectionScope) yield* Scope.close(connectionScope, Exit.void);
442 connectionScope = null;
443 if (activated) yield* provide(bootstrap(config, owner, "stop")).pipe(Effect.ignore);
444 activated = false;
445 wantsAgent = false;
446 }),
447 );
448 const changeAgent = (enabled: boolean) =>
449 lock.withPermit(
450 Effect.gen(function* () {
451 wantsAgent = enabled;
452 if (enabled && ready?.agentDevice) return { ...ready, agentDevice: ready.agentDevice };
453 if (!enabled && !ready?.agentDevice) return null;
454 ready = null;
455 const previousScope = connectionScope;
456 connectionScope = null;
457 if (previousScope) yield* Scope.close(previousScope, Exit.void);
458 if (!enabled) yield* provide(bootstrap(config, owner, "stop-agent"));
459 return yield* connect().pipe(
460 Effect.onError(() =>
461 Effect.gen(function* () {
462 const failedScope = connectionScope;
463 connectionScope = null;
464 if (failedScope) yield* Scope.close(failedScope, Exit.void);
465 if (enabled)
466 yield* provide(bootstrap(config, owner, "stop-agent")).pipe(Effect.ignore);
467 }),
468 ),
469 );
470 }),
471 );
472 yield* Effect.addFinalizer(() => stop);
473 return {
474 id: config.id,
475 label: config.label,
476 summary: Effect.sync(() => summary),
477 inspect: provide(probe(config, owner)).pipe(
478 Effect.tap((value) =>
479 Effect.sync(() => {
480 summary = value;
481 }),
482 ),
483 ),
484 current: Effect.sync(() => ready),
485 ensureReady,
486 ensureAgentReady: (onPhase) =>
487 ensureReady(onPhase).pipe(
488 Effect.flatMap(() =>
489 onPhase(
490 summary.agentDeviceInstalled ? "starting" : "installing",
491 summary.agentDeviceInstalled
492 ? undefined
493 : deviceToolInstallMessage("agent tools", summary.tools?.agent),
494 ),
495 ),
496 Effect.flatMap(() => changeAgent(true)),
497 Effect.flatMap((value) =>
498 value?.agentDevice
499 ? Effect.succeed({ ...value, agentDevice: value.agentDevice })
500 : Effect.fail(
501 new DeviceHost.DeviceHostError({
502 hostId: config.id,
503 step: "starting agent tools",
504 cause: new Error("Daemon endpoint missing"),
505 }),
506 ),
507 ),
508 ),
509 stopAgent: changeAgent(false).pipe(Effect.asVoid, Effect.ignore),
510 stop,
511 platformAvailability,
512 } satisfies DeviceHost.DeviceHost["Service"];
513});