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

sshDeviceScript.test.ts

267 lines14.8 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 await NodeFSP.writeFile(
60 NodePath.join(bin, "emulator"),
61 "#!/bin/sh\nprintf 'emulated webcam<N> none\\n' >&2\n",
62 { mode: 0o755 },
63 );
64 const root = NodePath.join(home, ".t3/device");
65 const hubDir = NodePath.join(root, `tools/expo-device-hub@${DEVICE_HUB_VERSION}`);
66 const agentDir = NodePath.join(root, `tools/agent-device@${AGENT_DEVICE_VERSION}`);
67 const hub = NodePath.join(hubDir, "node_modules/expo-device-hub/dist/server/cli.mjs");
68 const agent = NodePath.join(agentDir, "node_modules/agent-device/bin/agent-device.mjs");
69 await NodeFSP.mkdir(NodePath.join(hubDir, "node_modules/expo-device-hub/dist/server"), {
70 recursive: true,
71 });
72 await NodeFSP.mkdir(NodePath.join(agentDir, "node_modules/agent-device/bin"), {
73 recursive: true,
74 });
75 await NodeFSP.writeFile(NodePath.join(hubDir, ".install-complete"), DEVICE_HUB_VERSION);
76 await NodeFSP.writeFile(NodePath.join(agentDir, ".install-complete"), AGENT_DEVICE_VERSION);
77 await NodeFSP.writeFile(
78 hub,
79 `import http from 'node:http'; import fs from 'node:fs';
80if(fs.existsSync('fail-start-once')) {fs.unlinkSync('fail-start-once');process.exit(1);}
81const args=process.argv.slice(2); fs.writeFileSync('hub-args.json',JSON.stringify(args)); fs.writeFileSync('hub-camera-args',process.env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_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');`,
82 );
83 await NodeFSP.writeFile(
84 agent,
85 `import fs from 'node:fs'; import path from 'node:path'; import http from 'node:http'; import {spawn} from 'node:child_process';
86const args=process.argv.slice(2);
87const state=process.env.AGENT_DEVICE_STATE_DIR || args[args.indexOf('--state-dir')+1];
88const file=path.join(state,'daemon.json');
89if(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 {} }
90else 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?.();}); }
91else { 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(); }
92`,
93 );
94 await NodeFSP.copyFile(agent, NodePath.join(NodePath.dirname(agent), "daemon.mjs"));
95 const nextHubVersion = DEVICE_HUB_VERSION + "-upgrade";
96 const nextAgentVersion = AGENT_DEVICE_VERSION + "-upgrade";
97 // Each owner stands in for a host on a different platform.
98 const hostPlatforms: Record<string, NodeJS.Platform> = { one: "linux", two: "darwin" };
99 const hubArgs = async (owner: string): Promise<ReadonlyArray<string>> =>
100 JSON.parse(
101 await NodeFSP.readFile(NodePath.join(root, `hosts/${owner}/hub-args.json`), "utf8"),
102 );
103 let invocation = 0;
104 const invoke = async (
105 owner: string,
106 mode: "probe" | "start" | "agent-start" | "stop-agent" | "stop",
107 upgraded = false,
108 ) => {
109 const file = NodePath.join(home, `${owner}-${mode}-${invocation++}.cjs`);
110 await NodeFSP.writeFile(
111 file,
112 `Object.defineProperty(process, 'platform', { value: ${JSON.stringify(hostPlatforms[owner])} });\n` +
113 `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` +
114 remoteDeviceScript(owner, mode)
115 .replace(DEVICE_HUB_VERSION, upgraded ? nextHubVersion : DEVICE_HUB_VERSION)
116 .replace(AGENT_DEVICE_VERSION, upgraded ? nextAgentVersion : AGENT_DEVICE_VERSION),
117 );
118 const result = await exec(process.execPath, [file], {
119 env: {
120 ...process.env,
121 HOME: home,
122 PATH: `${bin}:${process.env.PATH}`,
123 SERVE_EMU_FFMPEG: NodePath.join(home, "missing-ffmpeg"),
124 ANDROID_HOME: "",
125 EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: "-memory 4096",
126 },
127 });
128 return result.stdout ? JSON.parse(result.stdout) : null;
129 };
130 const inventory = await invoke("one", "probe");
131 expect(inventory.tools.hub.installedVersions).toEqual([DEVICE_HUB_VERSION]);
132 expect(inventory.tools.hub.runningVersion).toBeNull();
133 expect(inventory.tools.agent.installedVersions).toEqual([AGENT_DEVICE_VERSION]);
134 await expect(NodeFSP.stat(NodePath.join(root, "hosts/one/hub.json"))).rejects.toThrow();
135 const template = NodePath.join(home, "hub-template");
136 await NodeFSP.cp(hubDir, template, { recursive: true });
137 await NodeFSP.rm(NodePath.join(hubDir, ".install-complete"));
138 const installLock = hubDir + ".lock";
139 await NodeFSP.symlink("2147483647:exited-installer", installLock);
140 await NodeFSP.writeFile(
141 NodePath.join(bin, "npm"),
142 `#!${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});`,
143 { mode: 0o755 },
144 );
145 await NodeFSP.mkdir(NodePath.join(root, "hosts/one"), { recursive: true });
146 await NodeFSP.writeFile(NodePath.join(root, "hosts/one/fail-start-once"), "");
147 await NodeFSP.writeFile(NodePath.join(root, "tools/.maintenance-lock"), "blocked");
148 await NodeFSP.writeFile(NodePath.join(root, "tools/.users"), "unwritable lease directory");
149 try {
150 const [manual, concurrent] = await Promise.all([
151 invoke("one", "start"),
152 invoke("one", "start"),
153 ]);
154 expect(concurrent.hubPort).toBe(manual.hubPort);
155 expect(manual.daemonPort).toBeUndefined();
156 expect((await hubArgs("one")).slice(-2)).toEqual(["--platform", "android"]);
157 expect(
158 await NodeFSP.readFile(NodePath.join(root, "hosts/one/hub-camera-args"), "utf8"),
159 ).toBe("-camera-front emulated -camera-back emulated -memory 4096");
160 // A hub started before discovery was filtered has no recorded platform.
161 const hubFile = NodePath.join(root, "hosts/one/hub.json");
162 const { platform: _platform, ...unfilteredHub } = JSON.parse(
163 await NodeFSP.readFile(hubFile, "utf8"),
164 );
165 await NodeFSP.writeFile(hubFile, JSON.stringify(unfilteredHub));
166 const filtered = await invoke("one", "start");
167 expect(filtered.hubPort).not.toBe(manual.hubPort);
168 expect(await NodeFSP.readFile(NodePath.join(home, "stops"), "utf8")).toContain(
169 `${unfilteredHub.pid}\n`,
170 );
171 expect((await invoke("one", "start")).hubPort).toBe(filtered.hubPort);
172 await expect(
173 NodeFSP.stat(NodePath.join(root, "hosts/one/daemon.json")),
174 ).rejects.toThrow();
175 const [first, concurrentAgent] = await Promise.all([
176 invoke("one", "agent-start"),
177 invoke("one", "agent-start"),
178 ]);
179 expect(concurrentAgent.hubPort).toBe(first.hubPort);
180 expect(concurrentAgent.daemonPort).toBe(first.daemonPort);
181 const running = await invoke("one", "probe");
182 expect(running.tools.hub.runningVersion).toBe(DEVICE_HUB_VERSION);
183 expect(running.tools.agent.runningVersion).toBe(AGENT_DEVICE_VERSION);
184 const second = await invoke("two", "agent-start");
185 const reused = await invoke("one", "agent-start");
186 expect(reused.hubPort).toBe(first.hubPort);
187 expect(await hubArgs("two")).not.toContain("--platform");
188 expect((await invoke("two", "start")).hubPort).toBe(second.hubPort);
189 expect(reused.daemonPort).toBe(first.daemonPort);
190 expect(second.hubPort).not.toBe(first.hubPort);
191 expect(second.daemonPort).not.toBe(first.daemonPort);
192 const firstHub = JSON.parse(
193 await NodeFSP.readFile(NodePath.join(root, "hosts/one/hub.json"), "utf8"),
194 );
195 const secondHub = JSON.parse(
196 await NodeFSP.readFile(NodePath.join(root, "hosts/two/hub.json"), "utf8"),
197 );
198 await NodeFSP.writeFile(NodePath.join(root, `hosts/one/unhealthy-${firstHub.pid}`), "");
199 let repaired = await invoke("one", "agent-start");
200 expect(repaired.hubPort).not.toBe(first.hubPort);
201 const stopped = (await NodeFSP.readFile(NodePath.join(home, "stops"), "utf8"))
202 .trim()
203 .split("\n");
204 expect(stopped).toContain(String(firstHub.pid));
205 expect(stopped).not.toContain(String(secondHub.pid));
206 const previousDaemon = JSON.parse(
207 await NodeFSP.readFile(NodePath.join(root, "hosts/one/daemon.json"), "utf8"),
208 );
209 for (const [source, name, version] of [
210 [hubDir, "expo-device-hub", nextHubVersion],
211 [agentDir, "agent-device", nextAgentVersion],
212 ]) {
213 const destination = NodePath.join(root, `tools/${name}@${version}`);
214 await NodeFSP.cp(source!, destination, { recursive: true });
215 await NodeFSP.writeFile(NodePath.join(destination, ".install-complete"), version!);
216 }
217 const upgraded = await invoke("one", "agent-start", true);
218 expect(upgraded.entryPath).toContain(nextAgentVersion);
219 const upgradedHub = JSON.parse(
220 await NodeFSP.readFile(NodePath.join(root, "hosts/one/hub.json"), "utf8"),
221 );
222 expect(upgradedHub.entryPath).toContain(nextHubVersion);
223 const upgradedDaemon = JSON.parse(
224 await NodeFSP.readFile(NodePath.join(root, "hosts/one/daemon.json"), "utf8"),
225 );
226 expect(upgradedDaemon.pid).not.toBe(previousDaemon.pid);
227 expect(await invoke("one", "agent-start", true)).toEqual(upgraded);
228 await NodeFSP.writeFile(
229 NodePath.join(root, `hosts/one/unhealthy-agent-${upgradedDaemon.pid}`),
230 "",
231 );
232 repaired = await invoke("one", "agent-start", true);
233 expect(
234 await NodeFSP.readFile(NodePath.join(root, "hosts/one/stopped-agent"), "utf8"),
235 ).toBe(String(upgradedDaemon.pid));
236 expect(repaired.daemonPort).not.toBe(upgraded.daemonPort);
237 const originalScript = remoteDeviceScript("one", "stop-agent");
238 const upgradedStop = NodePath.join(home, "upgraded-stop.cjs");
239 await NodeFSP.writeFile(
240 upgradedStop,
241 originalScript.replace(AGENT_DEVICE_VERSION, "999.0.0"),
242 );
243 await exec(process.execPath, [upgradedStop], {
244 env: { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}` },
245 });
246 const daemon = JSON.parse(
247 await NodeFSP.readFile(NodePath.join(root, "hosts/one/daemon.json"), "utf8"),
248 );
249 expect(
250 await NodeFSP.readFile(NodePath.join(root, "hosts/one/stopped-agent"), "utf8"),
251 ).toBe(String(daemon.pid));
252 expect((await fetch(`http://127.0.0.1:${repaired.hubPort}/readyz`)).ok).toBe(true);
253 await invoke("one", "stop");
254 expect((await fetch(`http://127.0.0.1:${second.hubPort}/readyz`)).ok).toBe(true);
255 expect(
256 JSON.parse(await NodeFSP.readFile(NodePath.join(root, "hosts/two/hub.json"), "utf8"))
257 .owner,
258 ).toBe("two");
259 } finally {
260 await invoke("one", "stop").catch(() => {});
261 await invoke("two", "stop").catch(() => {});
262 await NodeFSP.rm(home, { recursive: true, force: true });
263 }
264 });
265 }),
266 );
267});