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

SshDeviceHost.test.ts

310 lines11.8 KB

1import { expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Net from "@t3tools/shared/Net";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as PlatformError from "effect/PlatformError";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as HttpClient from "effect/http/HttpClient";
11import * as HttpClientResponse from "effect/http/HttpClientResponse";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13import * as ServerConfig from "../config.ts";
14import * as DeviceHost from "./DeviceHost.ts";
15import * as SshDeviceHost from "./SshDeviceHost.ts";
16​
17it.effect("preserves installed status after probes and cleans failed agent activation", () =>
18 Effect.gen(function* () {
19 const fs = yield* FileSystem.FileSystem;
20 const home = yield* fs.makeTempDirectoryScoped();
21 const modes: string[] = [];
22 const owners: string[] = [];
23 const tunnelArgs: string[][] = [];
24 const tunnelStdins: unknown[] = [];
25 const commandArgs: string[][] = [];
26 let forwards = 0;
27 let failForward = true;
28 let rejectConfig = true;
29 const releases: Array<string | undefined> = [];
30 const spawner = ChildProcessSpawner.make((command) =>
31 Effect.gen(function* () {
32 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
33 const forwarding = command.args.includes("-L");
34 (forwarding ? tunnelArgs : commandArgs).push([...command.args]);
35 if (forwarding) tunnelStdins.push(command.options.stdin);
36 let output = "";
37 let exitCode = 0;
38 if (forwarding) {
39 if (failForward) {
40 failForward = false;
41 return yield* PlatformError.systemError({
42 _tag: "AlreadyExists",
43 module: "ChildProcess",
44 method: "spawn",
45 description: "Port already bound",
46 });
47 }
48 forwards++;
49 yield* Effect.addFinalizer(() =>
50 Effect.sync(() => {
51 forwards--;
52 }),
53 );
54 } else {
55 const stdin = command.options.stdin;
56 if (
57 !stdin ||
58 typeof stdin !== "object" ||
59 !("stream" in stdin) ||
60 !Stream.isStream(stdin.stream)
61 )
62 return yield* Effect.die("Missing script");
63 const script = yield* stdin.stream.pipe(
64 Stream.decodeText(),
65 Stream.runFold(
66 () => "",
67 (a, b) => a + b,
68 ),
69 );
70 const mode = /const mode = "([^"]+)"/.exec(script)?.[1] ?? "";
71 modes.push(mode);
72 owners.push(/const owner = "([^"]+)"/.exec(script)?.[1] ?? "");
73 output = JSON.stringify({
74 nodePath: "/node",
75 platforms: [{ platform: "ios", available: true }],
76 hubPort: 1234,
77 helpers: { serveSimAxSettings: null, serveSimCli: null },
78 ...(mode === "agent-start"
79 ? { daemonPort: 1235, token: "fixture", entryPath: "/agent.mjs" }
80 : {}),
81 });
82 if (mode === "") {
83 output = `${"verbose-prefix ".repeat(400)}PANIC: emulator SDK is broken\n`;
84 exitCode = 1;
85 }
86 }
87 return ChildProcessSpawner.makeHandle({
88 pid: ChildProcessSpawner.ProcessId(123),
89 stdout: Stream.make(new TextEncoder().encode(output)),
90 stderr: Stream.empty,
91 all: Stream.empty,
92 exitCode: forwarding
93 ? Effect.never
94 : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
95 isRunning: Effect.succeed(forwarding),
96 kill: () => Effect.void,
97 stdin: Sink.drain,
98 getInputFd: () => Sink.drain,
99 getOutputFd: () => Stream.empty,
100 unref: Effect.succeed(Effect.void),
101 });
102 }),
103 );
104 const host = yield* SshDeviceHost.make(
105 { kind: "ssh", id: "test", label: "Test", target: "test.example" },
106 () =>
107 rejectConfig
108 ? Effect.fail(
109 new DeviceHost.DeviceHostError({
110 hostId: "test",
111 step: "configuring agent access",
112 cause: new Error("fixture failure"),
113 }),
114 )
115 : Effect.void,
116 ).pipe(
117 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
118 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
119 Effect.provideService(
120 HttpClient.HttpClient,
121 HttpClient.make((request) =>
122 Effect.sync(() => {
123 if (!request.url.endsWith("/rpc"))
124 return HttpClientResponse.fromWeb(request, new Response("ok"));
125 releases.push(request.headers.authorization);
126 return HttpClientResponse.fromWeb(request, Response.json({ result: { ok: true } }));
127 }),
128 ),
129 ),
130 );
131 yield* host.ensureReady(() => Effect.void);
132 yield* SshDeviceHost.probe({
133 kind: "ssh",
134 id: "test",
135 label: "Test",
136 target: "test.example",
137 }).pipe(
138 Effect.provide(ServerConfig.layerTest(home, home)),
139 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
140 );
141 expect(new Set(owners).size).toBe(1);
142 expect(owners[0]).toMatch(/^[a-f0-9]{24}$/);
143 expect(forwards).toBe(1);
144 expect(modes.filter((mode) => mode === "start")).toHaveLength(2);
145 const ready = yield* host.current;
146 expect(ready).not.toBeNull();
147 if (ready) {
148 const failed = yield* ready.run("emulator", ["-list-avds"]);
149 expect(failed.code).toBe(1);
150 expect(failed.stdout).toMatch(/^\[truncated\]/);
151 expect(failed.stderr).toBe(failed.stdout.trim());
152 expect(failed.stderr).toMatch(/PANIC: emulator SDK is broken$/);
153 }
154 yield* host.platformAvailability("ios");
155 expect((yield* host.summary).hubInstalled).toBe(true);
156 const failed = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.result);
157 expect(failed._tag).toBe("Failure");
158 expect(forwards).toBe(0);
159 expect(modes.at(-1)).toBe("stop-agent");
160 expect(yield* host.current).toBeNull();
161 rejectConfig = false;
162 yield* host.ensureAgentReady(() => Effect.void);
163 yield* host.platformAvailability("ios");
164 expect((yield* host.summary).agentDeviceInstalled).toBe(true);
165 // Close releases agent sessions through the forwarded daemon.
166 const agentReady = yield* host.current;
167 yield* agentReady!.releaseAgentSession!("t3-session", "device");
168 expect(releases).toEqual(["Bearer fixture"]);
169 yield* host.stopAgent;
170 expect(forwards).toBe(1);
171 const multiplexingOff = ["ControlMaster=no", "ControlPath=none", "ControlPersist=no"];
172 expect(tunnelArgs.length).toBeGreaterThan(0);
173 for (const args of tunnelArgs) {
174 for (const option of multiplexingOff) {
175 const index = args.indexOf(option);
176 expect(index).toBeGreaterThan(0);
177 expect(args[index - 1]).toBe("-o");
178 }
179 // The tunnel lives only as long as the server holds the write end of its stdin.
180 expect(args).not.toContain("-N");
181 expect(args.slice(args.indexOf("test.example") + 1)).toEqual([
182 "sh",
183 "-c",
184 "'exec cat >/dev/null'",
185 ]);
186 }
187 expect(tunnelStdins).toEqual(tunnelArgs.map(() => "pipe"));
188 expect(commandArgs.length).toBeGreaterThan(0);
189 for (const args of commandArgs) {
190 for (const option of multiplexingOff) expect(args).not.toContain(option);
191 }
192 yield* host.stop;
193 expect(forwards).toBe(0);
194 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
195);
196​
197it.effect("lists Android devices without probing the host again once it reports Android", () =>
198 Effect.gen(function* () {
199 const fs = yield* FileSystem.FileSystem;
200 const home = yield* fs.makeTempDirectoryScoped();
201 const modes: string[] = [];
202 let androidInstalled = false;
203 const spawner = ChildProcessSpawner.make((command) =>
204 Effect.gen(function* () {
205 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
206 const forwarding = command.args.includes("-L");
207 let output = "";
208 if (!forwarding) {
209 const stdin = command.options.stdin;
210 const script =
211 stdin && typeof stdin === "object" && "stream" in stdin && Stream.isStream(stdin.stream)
212 ? yield* stdin.stream.pipe(
213 Stream.decodeText(),
214 Stream.runFold(
215 () => "",
216 (a, b) => a + b,
217 ),
218 )
219 : "";
220 const mode = /const mode = "([^"]+)"/.exec(script)?.[1] ?? "";
221 modes.push(mode);
222 output =
223 mode === ""
224 ? "Pixel_8\n"
225 : JSON.stringify({
226 nodePath: "/node",
227 platforms: [
228 { platform: "ios", available: true },
229 { platform: "android", available: androidInstalled },
230 ],
231 hubPort: 1234,
232 helpers: { serveSimAxSettings: null, serveSimCli: null },
233 });
234 }
235 return ChildProcessSpawner.makeHandle({
236 pid: ChildProcessSpawner.ProcessId(123),
237 stdout: Stream.make(new TextEncoder().encode(output)),
238 stderr: Stream.empty,
239 all: Stream.empty,
240 exitCode: forwarding ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(0)),
241 isRunning: Effect.succeed(forwarding),
242 kill: () => Effect.void,
243 stdin: Sink.drain,
244 getInputFd: () => Sink.drain,
245 getOutputFd: () => Stream.empty,
246 unref: Effect.succeed(Effect.void),
247 });
248 }),
249 );
250 const host = yield* SshDeviceHost.make({
251 kind: "ssh",
252 id: "test",
253 label: "Test",
254 target: "test.example",
255 }).pipe(
256 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
257 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
258 Effect.provideService(
259 HttpClient.HttpClient,
260 HttpClient.make((request) =>
261 Effect.succeed(
262 HttpClientResponse.fromWeb(
263 request,
264 new Response(
265 request.url.endsWith("/api/devices")
266 ? JSON.stringify({ simulators: [], emulators: [] })
267 : "ok",
268 ),
269 ),
270 ),
271 ),
272 ),
273 );
274 const ready = yield* host.ensureReady(() => Effect.void);
275 const androidNames = ready.devices.list.pipe(
276 Effect.map((list) =>
277 list.devices.filter((device) => device.platform === "android").map((device) => device.name),
278 ),
279 );
280​
281 modes.splice(0);
282​
283 expect(yield* androidNames).toEqual([]);
284 expect(modes.splice(0)).toEqual(["probe"]);
285 expect(yield* androidNames).toEqual([]);
286 expect(modes.splice(0)).toEqual(["probe"]);
287​
288 // The SDK appears after connecting, so the next listing still probes the host.
289 androidInstalled = true;
290 expect(yield* androidNames).toEqual(["Pixel_8"]);
291 expect(modes.splice(0)).toEqual(["probe", ""]);
292​
293 // Android is now known to be available, so listing only runs `emulator -list-avds`.
294 expect(yield* androidNames).toEqual(["Pixel_8"]);
295 expect(modes.splice(0)).toEqual([""]);
296​
297 androidInstalled = false;
298 expect((yield* host.platformAvailability("android")).available).toBe(false);
299 expect(modes.splice(0)).toEqual(["probe"]);
300 expect(yield* androidNames).toEqual([]);
301 expect(modes.splice(0)).toEqual(["probe"]);
302​
303 androidInstalled = true;
304 yield* host.inspect;
305 expect(modes.splice(0)).toEqual(["probe"]);
306 expect(yield* androidNames).toEqual(["Pixel_8"]);
307 expect(modes.splice(0)).toEqual([""]);
308 yield* host.stop;
309 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
310);