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

sshHelper.ts

126 lines4.3 KB

1// @effect-diagnostics nodeBuiltinImport:off
2// @effect-diagnostics globalTimers:off
3// @effect-diagnostics globalDateInEffect:off
4// The helpers mirror the inline Node snippets the SSH launch script used to
5// run, byte for byte in behaviour, so they stay on plain Node APIs.
6import * as NodeFS from "node:fs";
7import * as NodeHttp from "node:http";
8import * as NodeNet from "node:net";
9​
10import * as Effect from "effect/Effect";
11import { Argument, Command } from "effect/cli";
12​
13/**
14 * Small helpers the SSH launch script needs on the remote host. The script
15 * used to run these as inline `node -` snippets; archive-distributed runtimes
16 * have no Node on the remote, so the executable provides them instead. Output
17 * and exit codes match the snippets exactly because the shell script parses
18 * them.
19 */
20​
21const tryPort = (port: number) =>
22 new Promise<number | false>((resolve) => {
23 const server = NodeNet.createServer();
24 server.unref();
25 server.once("error", () => resolve(false));
26 server.listen(port, "127.0.0.1", () => {
27 server.close((error) => resolve(error ? false : port));
28 });
29 });
30​
31/** Prints the first free loopback port from the preferred one, scanning `window` ports. */
32const pickPort = Command.make("pick-port", {
33 portFile: Argument.String("port-file"),
34 defaultPort: Argument.Int("default-port"),
35 scanWindow: Argument.Int("scan-window"),
36}).pipe(
37 Command.withHandler(({ portFile, defaultPort, scanWindow }) =>
38 Effect.promise(async () => {
39 const raw = NodeFS.existsSync(portFile) ? NodeFS.readFileSync(portFile, "utf8").trim() : "";
40 const preferred = Number.parseInt(raw, 10);
41 const start = Number.isInteger(preferred) ? preferred : defaultPort;
42 for (let port = start; port < start + scanWindow; port += 1) {
43 if (await tryPort(port)) {
44 process.stdout.write(String(port));
45 return;
46 }
47 }
48 process.exitCode = 1;
49 }),
50 ),
51);
52​
53const probe = (port: number, probeTimeoutMs: number) =>
54 new Promise<boolean>((resolve) => {
55 const request = NodeHttp.get(
56 { hostname: "127.0.0.1", port, path: "/", timeout: probeTimeoutMs },
57 (response) => {
58 response.resume();
59 response.once("end", () => {
60 const status = response.statusCode ?? 0;
61 resolve(status >= 200 && status < 300);
62 });
63 },
64 );
65 request.once("timeout", () => {
66 request.destroy();
67 resolve(false);
68 });
69 request.once("error", () => resolve(false));
70 });
71​
72/** Exits 0 once the loopback server answers, 1 when the deadline passes first. */
73const waitReady = Command.make("wait-ready", {
74 port: Argument.Int("port"),
75 timeoutMs: Argument.Int("timeout-ms"),
76 probeTimeoutMs: Argument.Int("probe-timeout-ms"),
77}).pipe(
78 Command.withHandler(({ port, timeoutMs, probeTimeoutMs }) =>
79 Effect.promise(async () => {
80 const deadline = Date.now() + timeoutMs;
81 while (Date.now() < deadline) {
82 if (await probe(port, probeTimeoutMs)) return;
83 await new Promise((resolve) => setTimeout(resolve, 100));
84 }
85 process.exitCode = 1;
86 }),
87 ),
88);
89​
90/** Prints `<pid> <port>` for a live default-home server, or exits 1. */
91const runtimePort = Command.make("runtime-port", {
92 runtimeFile: Argument.String("runtime-file"),
93}).pipe(
94 Command.withHandler(({ runtimeFile }) =>
95 Effect.sync(() => {
96 try {
97 // @effect-diagnostics-next-line preferSchemaOverJson:off - mirrors the shell snippet's loose parse.
98 const runtime = JSON.parse(NodeFS.readFileSync(runtimeFile, "utf8")) as {
99 pid?: unknown;
100 port?: unknown;
101 origin?: unknown;
102 };
103 const pid = Number(runtime.pid);
104 const port = Number(runtime.port);
105 if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port)) {
106 process.exitCode = 1;
107 return;
108 }
109 const origin = new URL(String(runtime.origin ?? ""));
110 if (origin.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(origin.hostname)) {
111 process.exitCode = 1;
112 return;
113 }
114 process.kill(pid, 0);
115 process.stdout.write(`${pid} ${port}`);
116 } catch {
117 process.exitCode = 1;
118 }
119 }),
120 ),
121);
122​
123export const sshHelperCommand = Command.make("__ssh-helper").pipe(
124 Command.unlisted,
125 Command.withSubcommands([pickPort, waitReady, runtimePort]),
126);