Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SshDeviceHost.ts

496 lines17.3 KB

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