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

SshDeviceHost.test.ts

504 lines19.0 KB

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 TestClock from "effect/testing/TestClock";
15import * as ServerConfig from "../config.ts";
16import * as DeviceHost from "./DeviceHost.ts";
17import * as SshDeviceHost from "./SshDeviceHost.ts";
18​
19it.effect("preserves installed status after probes and cleans failed agent activation", () =>
20 Effect.gen(function* () {
21 const fs = yield* FileSystem.FileSystem;
22 const home = yield* fs.makeTempDirectoryScoped();
23 const modes: string[] = [];
24 const owners: string[] = [];
25 const tunnelArgs: string[][] = [];
26 const tunnelStdins: unknown[] = [];
27 const commandArgs: string[][] = [];
28 let forwards = 0;
29 let failForward = true;
30 let rejectConfig = true;
31 const releases: Array<string | undefined> = [];
32 const spawner = ChildProcessSpawner.make((command) =>
33 Effect.gen(function* () {
34 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
35 const forwarding = command.args.includes("-L");
36 (forwarding ? tunnelArgs : commandArgs).push(command.args.map(String));
37 if (forwarding) tunnelStdins.push(command.options.stdin);
38 let output = "";
39 let exitCode = 0;
40 if (forwarding) {
41 if (failForward) {
42 failForward = false;
43 return yield* PlatformError.systemError({
44 _tag: "AlreadyExists",
45 module: "ChildProcess",
46 method: "spawn",
47 description: "Port already bound",
48 });
49 }
50 forwards++;
51 yield* Effect.addFinalizer(() =>
52 Effect.sync(() => {
53 forwards--;
54 }),
55 );
56 } else {
57 const stdin = command.options.stdin;
58 if (
59 !stdin ||
60 typeof stdin !== "object" ||
61 !("stream" in stdin) ||
62 !Stream.isStream(stdin.stream)
63 )
64 return yield* Effect.die("Missing script");
65 const script = yield* stdin.stream.pipe(
66 Stream.decodeText(),
67 Stream.runFold(
68 () => "",
69 (a, b) => a + b,
70 ),
71 );
72 const mode = /const mode = "([^"]+)"/.exec(script)?.[1] ?? "";
73 modes.push(mode);
74 owners.push(/const owner = "([^"]+)"/.exec(script)?.[1] ?? "");
75 output = JSON.stringify({
76 nodePath: "/node",
77 platforms: [{ platform: "ios", available: true }],
78 hubPort: 1234,
79 helpers: { serveSimAxSettings: null, serveSimCli: null },
80 ...(mode === "agent-start"
81 ? { daemonPort: 1235, token: "fixture", entryPath: "/agent.mjs" }
82 : {}),
83 });
84 if (mode === "") {
85 output = `${"verbose-prefix ".repeat(400)}PANIC: emulator SDK is broken\n`;
86 exitCode = 1;
87 }
88 }
89 return ChildProcessSpawner.makeHandle({
90 pid: ChildProcessSpawner.ProcessId(123),
91 stdout: Stream.make(new TextEncoder().encode(output)),
92 stderr: Stream.empty,
93 all: Stream.empty,
94 exitCode: forwarding
95 ? Effect.never
96 : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
97 isRunning: Effect.succeed(forwarding),
98 kill: () => Effect.void,
99 stdin: Sink.drain,
100 getInputFd: () => Sink.drain,
101 getOutputFd: () => Stream.empty,
102 unref: Effect.succeed(Effect.void),
103 });
104 }),
105 );
106 const host = yield* SshDeviceHost.make(
107 { kind: "ssh", id: "test", label: "Test", target: "test.example" },
108 () =>
109 rejectConfig
110 ? Effect.fail(
111 new DeviceHost.DeviceHostError({
112 hostId: "test",
113 step: "configuring agent access",
114 cause: new Error("fixture failure"),
115 }),
116 )
117 : Effect.void,
118 ).pipe(
119 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
120 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
121 Effect.provideService(
122 HttpClient.HttpClient,
123 HttpClient.make((request) =>
124 Effect.sync(() => {
125 if (!request.url.endsWith("/rpc"))
126 return HttpClientResponse.fromWeb(request, new Response("ok"));
127 releases.push(request.headers.authorization);
128 return HttpClientResponse.fromWeb(request, Response.json({ result: { ok: true } }));
129 }),
130 ),
131 ),
132 );
133 yield* host.ensureReady(() => Effect.void);
134 yield* SshDeviceHost.probe({
135 kind: "ssh",
136 id: "test",
137 label: "Test",
138 target: "test.example",
139 }).pipe(
140 Effect.provide(ServerConfig.layerTest(home, home)),
141 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
142 );
143 expect(new Set(owners).size).toBe(1);
144 expect(owners[0]).toMatch(/^[a-f0-9]{24}$/);
145 expect(forwards).toBe(1);
146 expect(modes.filter((mode) => mode === "start")).toHaveLength(2);
147 const ready = yield* host.current;
148 expect(ready).not.toBeNull();
149 if (ready) {
150 const failed = yield* ready.run("emulator", ["-list-avds"]);
151 expect(failed.code).toBe(1);
152 expect(failed.stdout).toMatch(/^\[truncated\]/);
153 expect(failed.stderr).toBe(failed.stdout.trim());
154 expect(failed.stderr).toMatch(/PANIC: emulator SDK is broken$/);
155 }
156 yield* host.platformAvailability("ios");
157 expect((yield* host.summary).hubInstalled).toBe(true);
158 const failed = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.result);
159 expect(failed._tag).toBe("Failure");
160 expect(forwards).toBe(0);
161 expect(modes.at(-1)).toBe("stop-agent");
162 expect(yield* host.current).toBeNull();
163 rejectConfig = false;
164 yield* host.ensureAgentReady(() => Effect.void);
165 yield* host.platformAvailability("ios");
166 expect((yield* host.summary).agentDeviceInstalled).toBe(true);
167 // Close releases agent sessions through the forwarded daemon.
168 const agentReady = yield* host.current;
169 yield* agentReady!.releaseAgentSession!("t3-session", "device");
170 expect(releases).toEqual(["Bearer fixture"]);
171 yield* host.stopAgent;
172 expect(forwards).toBe(1);
173 const multiplexingOff = ["ControlMaster=no", "ControlPath=none", "ControlPersist=no"];
174 expect(tunnelArgs.length).toBeGreaterThan(0);
175 for (const args of tunnelArgs) {
176 for (const option of multiplexingOff) {
177 const index = args.indexOf(option);
178 expect(index).toBeGreaterThan(0);
179 expect(args[index - 1]).toBe("-o");
180 }
181 // The tunnel lives only as long as the server holds the write end of its stdin.
182 expect(args).not.toContain("-N");
183 expect(args.slice(args.indexOf("test.example") + 1)).toEqual([
184 "sh",
185 "-c",
186 "'exec cat >/dev/null'",
187 ]);
188 }
189 expect(tunnelStdins).toEqual(tunnelArgs.map(() => "pipe"));
190 expect(commandArgs.length).toBeGreaterThan(0);
191 for (const args of commandArgs) {
192 for (const option of multiplexingOff) expect(args).not.toContain(option);
193 }
194 yield* host.stop;
195 expect(forwards).toBe(0);
196 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
197);
198​
199it.effect("lists Android devices without probing the host again once it reports Android", () =>
200 Effect.gen(function* () {
201 const fs = yield* FileSystem.FileSystem;
202 const home = yield* fs.makeTempDirectoryScoped();
203 const modes: string[] = [];
204 let androidInstalled = false;
205 const spawner = ChildProcessSpawner.make((command) =>
206 Effect.gen(function* () {
207 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
208 const forwarding = command.args.includes("-L");
209 let output = "";
210 if (!forwarding) {
211 const stdin = command.options.stdin;
212 const script =
213 stdin && typeof stdin === "object" && "stream" in stdin && Stream.isStream(stdin.stream)
214 ? yield* stdin.stream.pipe(
215 Stream.decodeText(),
216 Stream.runFold(
217 () => "",
218 (a, b) => a + b,
219 ),
220 )
221 : "";
222 const mode = /const mode = "([^"]+)"/.exec(script)?.[1] ?? "";
223 modes.push(mode);
224 output =
225 mode === ""
226 ? "Pixel_8\n"
227 : JSON.stringify({
228 nodePath: "/node",
229 platforms: [
230 { platform: "ios", available: true },
231 { platform: "android", available: androidInstalled },
232 ],
233 hubPort: 1234,
234 helpers: { serveSimAxSettings: null, serveSimCli: null },
235 });
236 }
237 return ChildProcessSpawner.makeHandle({
238 pid: ChildProcessSpawner.ProcessId(123),
239 stdout: Stream.make(new TextEncoder().encode(output)),
240 stderr: Stream.empty,
241 all: Stream.empty,
242 exitCode: forwarding ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(0)),
243 isRunning: Effect.succeed(forwarding),
244 kill: () => Effect.void,
245 stdin: Sink.drain,
246 getInputFd: () => Sink.drain,
247 getOutputFd: () => Stream.empty,
248 unref: Effect.succeed(Effect.void),
249 });
250 }),
251 );
252 const host = yield* SshDeviceHost.make({
253 kind: "ssh",
254 id: "test",
255 label: "Test",
256 target: "test.example",
257 }).pipe(
258 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
259 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
260 Effect.provideService(
261 HttpClient.HttpClient,
262 HttpClient.make((request) =>
263 Effect.succeed(
264 HttpClientResponse.fromWeb(
265 request,
266 new Response(
267 request.url.endsWith("/api/devices")
268 ? JSON.stringify({ simulators: [], emulators: [] })
269 : "ok",
270 ),
271 ),
272 ),
273 ),
274 ),
275 );
276 const ready = yield* host.ensureReady(() => Effect.void);
277 const androidNames = ready.devices.list.pipe(
278 Effect.map((list) =>
279 list.devices.filter((device) => device.platform === "android").map((device) => device.name),
280 ),
281 );
282​
283 modes.splice(0);
284​
285 expect(yield* androidNames).toEqual([]);
286 expect(modes.splice(0)).toEqual(["probe"]);
287 expect(yield* androidNames).toEqual([]);
288 expect(modes.splice(0)).toEqual(["probe"]);
289​
290 // The SDK appears after connecting, so the next listing still probes the host.
291 androidInstalled = true;
292 expect(yield* androidNames).toEqual(["Pixel_8"]);
293 expect(modes.splice(0)).toEqual(["probe", ""]);
294​
295 // Android is now known to be available, so listing only runs `emulator -list-avds`.
296 expect(yield* androidNames).toEqual(["Pixel_8"]);
297 expect(modes.splice(0)).toEqual([""]);
298​
299 androidInstalled = false;
300 expect((yield* host.platformAvailability("android")).available).toBe(false);
301 expect(modes.splice(0)).toEqual(["probe"]);
302 expect(yield* androidNames).toEqual([]);
303 expect(modes.splice(0)).toEqual(["probe"]);
304​
305 androidInstalled = true;
306 yield* host.inspect;
307 expect(modes.splice(0)).toEqual(["probe"]);
308 expect(yield* androidNames).toEqual(["Pixel_8"]);
309 expect(modes.splice(0)).toEqual([""]);
310 yield* host.stop;
311 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
312);
313​
314it.effect(
315 "keeps the SSH forward through slow health probes and reconnects once the hub stays down",
316 () =>
317 Effect.gen(function* () {
318 const fs = yield* FileSystem.FileSystem;
319 const home = yield* fs.makeTempDirectoryScoped();
320 let forwardSpawns = 0;
321 let hubAnswers = true;
322 const spawner = ChildProcessSpawner.make((command) =>
323 Effect.gen(function* () {
324 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
325 const forwarding = command.args.includes("-L");
326 // A fresh forward reaches a working hub again.
327 if (forwarding && ++forwardSpawns > 1) hubAnswers = true;
328 const output = JSON.stringify({
329 nodePath: "/node",
330 platforms: [{ platform: "ios", available: true }],
331 hubPort: 1234,
332 helpers: { serveSimAxSettings: null, serveSimCli: null },
333 });
334 return ChildProcessSpawner.makeHandle({
335 pid: ChildProcessSpawner.ProcessId(123),
336 stdout: Stream.make(new TextEncoder().encode(output)),
337 stderr: Stream.empty,
338 all: Stream.empty,
339 exitCode: forwarding ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(0)),
340 isRunning: Effect.succeed(forwarding),
341 kill: () => Effect.void,
342 stdin: Sink.drain,
343 getInputFd: () => Sink.drain,
344 getOutputFd: () => Stream.empty,
345 unref: Effect.succeed(Effect.void),
346 });
347 }),
348 );
349 const host = yield* SshDeviceHost.make({
350 kind: "ssh",
351 id: "test",
352 label: "Test",
353 target: "test.example",
354 }).pipe(
355 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
356 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
357 Effect.provideService(
358 HttpClient.HttpClient,
359 HttpClient.make((request) =>
360 hubAnswers
361 ? Effect.succeed(HttpClientResponse.fromWeb(request, new Response("ok")))
362 : Effect.never,
363 ),
364 ),
365 );
366 yield* host.ensureReady(() => Effect.void);
367 expect(forwardSpawns).toBe(1);
368​
369 // A loaded host can miss a probe or two without being gone; the forward stays up.
370 hubAnswers = false;
371 yield* TestClock.adjust("30 seconds");
372 hubAnswers = true;
373 yield* TestClock.adjust("2 minutes");
374 expect(forwardSpawns).toBe(1);
375​
376 // A hub that keeps missing probes is still replaced.
377 hubAnswers = false;
378 // Recovery reset the miss count, so two new misses do not reconnect yet.
379 yield* TestClock.adjust("30 seconds");
380 expect(forwardSpawns).toBe(1);
381 yield* TestClock.adjust("30 seconds");
382 expect(forwardSpawns).toBe(2);
383 yield* host.stop;
384 }).pipe(
385 Effect.scoped,
386 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, TestClock.layer())),
387 ),
388);
389​
390it.effect.each([
391 {
392 name: "a Windows PowerShell login shell",
393 exitCode: 1,
394 stderr: "sh : The term 'sh' is not recognized as the name of a cmdlet\r\n",
395 shellEcho: "%OS%\r\nWindows_NT\r\n",
396 nodePlatform: null,
397 windows: true,
398 },
399 {
400 name: "a Windows cmd login shell",
401 exitCode: 1,
402 stderr: "'sh' is not recognized as an internal or external command,\r\n",
403 shellEcho: "Windows_NT $env:OS\r\n",
404 nodePlatform: null,
405 windows: true,
406 },
407 {
408 name: "a Windows cmd login shell returning 9009",
409 exitCode: 9009,
410 stderr: "'sh' is not recognized as an internal or external command,\r\n",
411 shellEcho: "Windows_NT $env:OS\r\n",
412 nodePlatform: null,
413 windows: true,
414 },
415 {
416 name: "a Windows Git Bash login shell without a spawnable npm",
417 exitCode: 1,
418 stderr: "npm is missing from the non-interactive SSH PATH\n",
419 shellEcho: "%OS% :OS\n",
420 nodePlatform: "win32",
421 windows: true,
422 },
423 {
424 name: "a Linux host without npm",
425 exitCode: 1,
426 stderr: "npm is missing from the non-interactive SSH PATH\n",
427 shellEcho: "%OS% :OS\n",
428 nodePlatform: "linux",
429 windows: false,
430 },
431 {
432 name: "a POSIX host without Node",
433 exitCode: 1,
434 stderr: "Node is missing from the non-interactive SSH PATH\n",
435 shellEcho: "%OS% :OS\n",
436 nodePlatform: null,
437 windows: false,
438 },
439 {
440 name: "a connection failure",
441 exitCode: 255,
442 stderr: "Connection refused\n",
443 shellEcho: "Windows_NT\n",
444 nodePlatform: "win32",
445 windows: false,
446 },
447])(
448 "probe failure on $name keeps the SSH cause",
449 ({ exitCode, stderr, shellEcho, nodePlatform, windows }) =>
450 Effect.gen(function* () {
451 const fs = yield* FileSystem.FileSystem;
452 const home = yield* fs.makeTempDirectoryScoped();
453 const shellChecks: string[] = [];
454 const spawner = ChildProcessSpawner.make((command) =>
455 Effect.gen(function* () {
456 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
457 const remote = command.args.slice(command.args.indexOf("test.example") + 1).join(" ");
458 const shellCheck = remote === "echo %OS% $env:OS";
459 const platformCheck = remote === "node -p process.platform";
460 if (shellCheck || platformCheck) shellChecks.push(remote);
461 return ChildProcessSpawner.makeHandle({
462 pid: ChildProcessSpawner.ProcessId(123),
463 stdout: Stream.make(
464 new TextEncoder().encode(
465 shellCheck ? shellEcho : platformCheck ? `${nodePlatform ?? ""}\n` : "",
466 ),
467 ),
468 stderr: Stream.make(
469 new TextEncoder().encode(shellCheck || platformCheck ? "" : stderr),
470 ),
471 all: Stream.empty,
472 exitCode: Effect.succeed(
473 ChildProcessSpawner.ExitCode(
474 shellCheck ? 0 : platformCheck ? (nodePlatform === null ? 1 : 0) : exitCode,
475 ),
476 ),
477 isRunning: Effect.succeed(false),
478 kill: () => Effect.void,
479 stdin: Sink.drain,
480 getInputFd: () => Sink.drain,
481 getOutputFd: () => Stream.empty,
482 unref: Effect.succeed(Effect.void),
483 });
484 }),
485 );
486 const failure = yield* SshDeviceHost.probe({
487 kind: "ssh",
488 id: "test",
489 label: "Test",
490 target: "test.example",
491 }).pipe(
492 Effect.provide(ServerConfig.layerTest(home, home)),
493 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
494 Effect.flip,
495 );
496 expect(failure).toMatchObject({ _tag: "DeviceHostError", step: "probe" });
497 const sshFailure = { _tag: "SshCommandError", exitCode, stderr };
498 expect(failure.cause).toMatchObject(
499 windows ? { _tag: "SshWindowsHostError", cause: sshFailure } : sshFailure,
500 );
501 // A transport failure has no remote shell to ask.
502 if (exitCode === 255) expect(shellChecks).toEqual([]);
503 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
504);