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

sshDeviceScript.test.ts

252 lines14.1 KB

1// @effect-diagnostics nodeBuiltinImport:off globalFetchInEffect:off - verifies generated remote scripts using real shell and Node processes.
2import * as Effect from "effect/Effect";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import { describe, expect, it } from "@effect/vitest";
5import * as NodeChildProcess from "node:child_process";
6import * as NodeFSP from "node:fs/promises";
7import * as NodeOS from "node:os";
8import * as NodePath from "node:path";
9import * as NodeUtil from "node:util";
10import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts";
11import { AGENT_DEVICE_VERSION, DEVICE_HUB_VERSION } from "./DeviceToolchain.ts";
12​
13const exec = NodeUtil.promisify(NodeChildProcess.execFile);
14​
15it.effect("finds Android Studio Java for a non-interactive SSH session", () =>
16 Effect.gen(function* () {
17 if ((yield* HostProcess.Platform) === "win32") return;
18 yield* Effect.promise(async () => {
19 const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-ssh-java-"));
20 try {
21 const javaHome = NodePath.join(home, ".local/opt/android-studio/jbr");
22 await NodeFSP.mkdir(NodePath.join(javaHome, "bin"), { recursive: true });
23 await NodeFSP.writeFile(
24 NodePath.join(javaHome, "bin/java"),
25 "#!/bin/sh\necho test-java\n",
26 { mode: 0o755 },
27 );
28 const result = await exec("/bin/sh", ["-c", `${remoteDeviceEnvironment}\njava`], {
29 env: { HOME: home, PATH: "/nonexistent", JAVA_HOME: "" },
30 });
31 expect(result.stdout.trim()).toBe("test-java");
32 } finally {
33 await NodeFSP.rm(home, { recursive: true, force: true });
34 }
35 });
36 }),
37);
38​
39it.effect("preserves shell metacharacters and newlines in remote arguments", () =>
40 Effect.gen(function* () {
41 if ((yield* HostProcess.Platform) === "win32") return;
42 yield* Effect.promise(async () => {
43 const value = "quotes ' \" ; $(echo expanded) $HOME\nnext line";
44 const result = await exec("sh", ["-c", `printf %s ${quoteRemoteArg(value)}`]);
45 expect(result.stdout).toBe(value);
46 });
47 }),
48);
49​
50describe("remote helper lifecycle", () => {
51 it.effect("reuses its own healthy helpers and stops only its own runtime", () =>
52 Effect.gen(function* () {
53 if ((yield* HostProcess.Platform) === "win32") return;
54 yield* Effect.promise(async () => {
55 const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-remote-script-"));
56 const bin = NodePath.join(home, "bin");
57 await NodeFSP.mkdir(bin);
58 await NodeFSP.writeFile(NodePath.join(bin, "adb"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
59 const root = NodePath.join(home, ".t3/device");
60 const hubDir = NodePath.join(root, `tools/expo-device-hub@${DEVICE_HUB_VERSION}`);
61 const agentDir = NodePath.join(root, `tools/agent-device@${AGENT_DEVICE_VERSION}`);
62 const hub = NodePath.join(hubDir, "node_modules/expo-device-hub/dist/server/cli.mjs");
63 const agent = NodePath.join(agentDir, "node_modules/agent-device/bin/agent-device.mjs");
64 await NodeFSP.mkdir(NodePath.join(hubDir, "node_modules/expo-device-hub/dist/server"), {
65 recursive: true,
66 });
67 await NodeFSP.mkdir(NodePath.join(agentDir, "node_modules/agent-device/bin"), {
68 recursive: true,
69 });
70 await NodeFSP.writeFile(NodePath.join(hubDir, ".install-complete"), DEVICE_HUB_VERSION);
71 await NodeFSP.writeFile(NodePath.join(agentDir, ".install-complete"), AGENT_DEVICE_VERSION);
72 await NodeFSP.writeFile(
73 hub,
74 `import http from 'node:http'; import fs from 'node:fs';
75if(fs.existsSync('fail-start-once')) {fs.unlinkSync('fail-start-once');process.exit(1);}
76const args=process.argv.slice(2); fs.writeFileSync('hub-args.json',JSON.stringify(args)); http.createServer((req,res)=>{res.statusCode=fs.existsSync('unhealthy-'+process.pid)?503:200;res.end('ok');}).listen(Number(args[args.indexOf('--port')+1]),'127.0.0.1');`,
77 );
78 await NodeFSP.writeFile(
79 agent,
80 `import fs from 'node:fs'; import path from 'node:path'; import http from 'node:http'; import {spawn} from 'node:child_process';
81const args=process.argv.slice(2);
82const state=process.env.AGENT_DEVICE_STATE_DIR || args[args.indexOf('--state-dir')+1];
83const file=path.join(state,'daemon.json');
84if(args[0]==='daemon') { const data=JSON.parse(fs.readFileSync(file,'utf8')); fs.writeFileSync(path.join(state,'stopped-agent'),String(data.pid)); try {process.kill(data.pid,'SIGTERM')} catch {} }
85else if(args[0]==='serve') { const server=http.createServer((req,res)=>{res.statusCode=fs.existsSync(path.join(state,'unhealthy-agent-'+process.pid))?503:200;res.end('ok');}); server.listen(0,'127.0.0.1',()=>{fs.writeFileSync(file,JSON.stringify({httpPort:server.address().port,pid:process.pid,token:'test'}));process.send?.('ready');process.disconnect?.();}); }
86else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1]),'daemon.mjs'),'serve'],{detached:true,stdio:['ignore','ignore','ignore','ipc'],env:process.env});await new Promise((resolve,reject)=>{child.once('message',resolve);child.once('error',reject);});child.unref(); }
87`,
88 );
89 await NodeFSP.copyFile(agent, NodePath.join(NodePath.dirname(agent), "daemon.mjs"));
90 const nextHubVersion = DEVICE_HUB_VERSION + "-upgrade";
91 const nextAgentVersion = AGENT_DEVICE_VERSION + "-upgrade";
92 // Each owner stands in for a host on a different platform.
93 const hostPlatforms: Record<string, NodeJS.Platform> = { one: "linux", two: "darwin" };
94 const hubArgs = async (owner: string): Promise<ReadonlyArray<string>> =>
95 JSON.parse(
96 await NodeFSP.readFile(NodePath.join(root, `hosts/${owner}/hub-args.json`), "utf8"),
97 );
98 let invocation = 0;
99 const invoke = async (
100 owner: string,
101 mode: "probe" | "start" | "agent-start" | "stop-agent" | "stop",
102 upgraded = false,
103 ) => {
104 const file = NodePath.join(home, `${owner}-${mode}-${invocation++}.cjs`);
105 await NodeFSP.writeFile(
106 file,
107 `Object.defineProperty(process, 'platform', { value: ${JSON.stringify(hostPlatforms[owner])} });\n` +
108 `const originalKill = process.kill; process.kill = (pid, signal) => { if (signal === 'SIGTERM') require('node:fs').appendFileSync(${JSON.stringify(NodePath.join(home, "stops"))}, pid+'\\n'); return originalKill(pid, signal); };\n` +
109 remoteDeviceScript(owner, mode)
110 .replace(DEVICE_HUB_VERSION, upgraded ? nextHubVersion : DEVICE_HUB_VERSION)
111 .replace(AGENT_DEVICE_VERSION, upgraded ? nextAgentVersion : AGENT_DEVICE_VERSION),
112 );
113 const result = await exec(process.execPath, [file], {
114 env: { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}` },
115 });
116 return result.stdout ? JSON.parse(result.stdout) : null;
117 };
118 const inventory = await invoke("one", "probe");
119 expect(inventory.tools.hub.installedVersions).toEqual([DEVICE_HUB_VERSION]);
120 expect(inventory.tools.hub.runningVersion).toBeNull();
121 expect(inventory.tools.agent.installedVersions).toEqual([AGENT_DEVICE_VERSION]);
122 await expect(NodeFSP.stat(NodePath.join(root, "hosts/one/hub.json"))).rejects.toThrow();
123 const template = NodePath.join(home, "hub-template");
124 await NodeFSP.cp(hubDir, template, { recursive: true });
125 await NodeFSP.rm(NodePath.join(hubDir, ".install-complete"));
126 const installLock = hubDir + ".lock";
127 await NodeFSP.symlink("2147483647:exited-installer", installLock);
128 await NodeFSP.writeFile(
129 NodePath.join(bin, "npm"),
130 `#!${process.execPath}\nconst fs=require('node:fs');const args=process.argv.slice(2);if(args[0]==='--version'){console.log('10.0.0');process.exit(0);}fs.cpSync(${JSON.stringify(template)},args[args.indexOf('--prefix')+1],{recursive:true});`,
131 { mode: 0o755 },
132 );
133 await NodeFSP.mkdir(NodePath.join(root, "hosts/one"), { recursive: true });
134 await NodeFSP.writeFile(NodePath.join(root, "hosts/one/fail-start-once"), "");
135 await NodeFSP.writeFile(NodePath.join(root, "tools/.maintenance-lock"), "blocked");
136 await NodeFSP.writeFile(NodePath.join(root, "tools/.users"), "unwritable lease directory");
137 try {
138 const [manual, concurrent] = await Promise.all([
139 invoke("one", "start"),
140 invoke("one", "start"),
141 ]);
142 expect(concurrent.hubPort).toBe(manual.hubPort);
143 expect(manual.daemonPort).toBeUndefined();
144 expect((await hubArgs("one")).slice(-2)).toEqual(["--platform", "android"]);
145 // A hub started before discovery was filtered has no recorded platform.
146 const hubFile = NodePath.join(root, "hosts/one/hub.json");
147 const { platform: _platform, ...unfilteredHub } = JSON.parse(
148 await NodeFSP.readFile(hubFile, "utf8"),
149 );
150 await NodeFSP.writeFile(hubFile, JSON.stringify(unfilteredHub));
151 const filtered = await invoke("one", "start");
152 expect(filtered.hubPort).not.toBe(manual.hubPort);
153 expect(await NodeFSP.readFile(NodePath.join(home, "stops"), "utf8")).toContain(
154 `${unfilteredHub.pid}\n`,
155 );
156 expect((await invoke("one", "start")).hubPort).toBe(filtered.hubPort);
157 await expect(
158 NodeFSP.stat(NodePath.join(root, "hosts/one/daemon.json")),
159 ).rejects.toThrow();
160 const [first, concurrentAgent] = await Promise.all([
161 invoke("one", "agent-start"),
162 invoke("one", "agent-start"),
163 ]);
164 expect(concurrentAgent.hubPort).toBe(first.hubPort);
165 expect(concurrentAgent.daemonPort).toBe(first.daemonPort);
166 const running = await invoke("one", "probe");
167 expect(running.tools.hub.runningVersion).toBe(DEVICE_HUB_VERSION);
168 expect(running.tools.agent.runningVersion).toBe(AGENT_DEVICE_VERSION);
169 const second = await invoke("two", "agent-start");
170 const reused = await invoke("one", "agent-start");
171 expect(reused.hubPort).toBe(first.hubPort);
172 expect(await hubArgs("two")).not.toContain("--platform");
173 expect((await invoke("two", "start")).hubPort).toBe(second.hubPort);
174 expect(reused.daemonPort).toBe(first.daemonPort);
175 expect(second.hubPort).not.toBe(first.hubPort);
176 expect(second.daemonPort).not.toBe(first.daemonPort);
177 const firstHub = JSON.parse(
178 await NodeFSP.readFile(NodePath.join(root, "hosts/one/hub.json"), "utf8"),
179 );
180 const secondHub = JSON.parse(
181 await NodeFSP.readFile(NodePath.join(root, "hosts/two/hub.json"), "utf8"),
182 );
183 await NodeFSP.writeFile(NodePath.join(root, `hosts/one/unhealthy-${firstHub.pid}`), "");
184 let repaired = await invoke("one", "agent-start");
185 expect(repaired.hubPort).not.toBe(first.hubPort);
186 const stopped = (await NodeFSP.readFile(NodePath.join(home, "stops"), "utf8"))
187 .trim()
188 .split("\n");
189 expect(stopped).toContain(String(firstHub.pid));
190 expect(stopped).not.toContain(String(secondHub.pid));
191 const previousDaemon = JSON.parse(
192 await NodeFSP.readFile(NodePath.join(root, "hosts/one/daemon.json"), "utf8"),
193 );
194 for (const [source, name, version] of [
195 [hubDir, "expo-device-hub", nextHubVersion],
196 [agentDir, "agent-device", nextAgentVersion],
197 ]) {
198 const destination = NodePath.join(root, `tools/${name}@${version}`);
199 await NodeFSP.cp(source!, destination, { recursive: true });
200 await NodeFSP.writeFile(NodePath.join(destination, ".install-complete"), version!);
201 }
202 const upgraded = await invoke("one", "agent-start", true);
203 expect(upgraded.entryPath).toContain(nextAgentVersion);
204 const upgradedHub = JSON.parse(
205 await NodeFSP.readFile(NodePath.join(root, "hosts/one/hub.json"), "utf8"),
206 );
207 expect(upgradedHub.entryPath).toContain(nextHubVersion);
208 const upgradedDaemon = JSON.parse(
209 await NodeFSP.readFile(NodePath.join(root, "hosts/one/daemon.json"), "utf8"),
210 );
211 expect(upgradedDaemon.pid).not.toBe(previousDaemon.pid);
212 expect(await invoke("one", "agent-start", true)).toEqual(upgraded);
213 await NodeFSP.writeFile(
214 NodePath.join(root, `hosts/one/unhealthy-agent-${upgradedDaemon.pid}`),
215 "",
216 );
217 repaired = await invoke("one", "agent-start", true);
218 expect(
219 await NodeFSP.readFile(NodePath.join(root, "hosts/one/stopped-agent"), "utf8"),
220 ).toBe(String(upgradedDaemon.pid));
221 expect(repaired.daemonPort).not.toBe(upgraded.daemonPort);
222 const originalScript = remoteDeviceScript("one", "stop-agent");
223 const upgradedStop = NodePath.join(home, "upgraded-stop.cjs");
224 await NodeFSP.writeFile(
225 upgradedStop,
226 originalScript.replace(AGENT_DEVICE_VERSION, "999.0.0"),
227 );
228 await exec(process.execPath, [upgradedStop], {
229 env: { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}` },
230 });
231 const daemon = JSON.parse(
232 await NodeFSP.readFile(NodePath.join(root, "hosts/one/daemon.json"), "utf8"),
233 );
234 expect(
235 await NodeFSP.readFile(NodePath.join(root, "hosts/one/stopped-agent"), "utf8"),
236 ).toBe(String(daemon.pid));
237 expect((await fetch(`http://127.0.0.1:${repaired.hubPort}/readyz`)).ok).toBe(true);
238 await invoke("one", "stop");
239 expect((await fetch(`http://127.0.0.1:${second.hubPort}/readyz`)).ok).toBe(true);
240 expect(
241 JSON.parse(await NodeFSP.readFile(NodePath.join(root, "hosts/two/hub.json"), "utf8"))
242 .owner,
243 ).toBe("two");
244 } finally {
245 await invoke("one", "stop").catch(() => {});
246 await invoke("two", "stop").catch(() => {});
247 await NodeFSP.rm(home, { recursive: true, force: true });
248 }
249 });
250 }),
251 );
252});