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