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

SshDeviceHost.test.ts

180 lines7.0 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 spawner = ChildProcessSpawner.make((command) =>
30 Effect.gen(function* () {
31 if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");
32 const forwarding = command.args.includes("-L");
33 (forwarding ? tunnelArgs : commandArgs).push([...command.args]);
34 if (forwarding) tunnelStdins.push(command.options.stdin);
35 let output = "";
36 let exitCode = 0;
37 if (forwarding) {
38 if (failForward) {
39 failForward = false;
40 return yield* PlatformError.systemError({
41 _tag: "AlreadyExists",
42 module: "ChildProcess",
43 method: "spawn",
44 description: "Port already bound",
45 });
46 }
47 forwards++;
48 yield* Effect.addFinalizer(() =>
49 Effect.sync(() => {
50 forwards--;
51 }),
52 );
53 } else {
54 const stdin = command.options.stdin;
55 if (
56 !stdin ||
57 typeof stdin !== "object" ||
58 !("stream" in stdin) ||
59 !Stream.isStream(stdin.stream)
60 )
61 return yield* Effect.die("Missing script");
62 const script = yield* stdin.stream.pipe(
63 Stream.decodeText(),
64 Stream.runFold(
65 () => "",
66 (a, b) => a + b,
67 ),
68 );
69 const mode = /const mode = "([^"]+)"/.exec(script)?.[1] ?? "";
70 modes.push(mode);
71 owners.push(/const owner = "([^"]+)"/.exec(script)?.[1] ?? "");
72 output = JSON.stringify({
73 nodePath: "/node",
74 platforms: [{ platform: "ios", available: true }],
75 hubPort: 1234,
76 helpers: { serveSimAxSettings: null, serveSimCli: null },
77 ...(mode === "agent-start"
78 ? { daemonPort: 1235, token: "fixture", entryPath: "/agent.mjs" }
79 : {}),
80 });
81 if (mode === "") {
82 output = `${"verbose-prefix ".repeat(400)}PANIC: emulator SDK is broken\n`;
83 exitCode = 1;
84 }
85 }
86 return ChildProcessSpawner.makeHandle({
87 pid: ChildProcessSpawner.ProcessId(123),
88 stdout: Stream.make(new TextEncoder().encode(output)),
89 stderr: Stream.empty,
90 all: Stream.empty,
91 exitCode: forwarding
92 ? Effect.never
93 : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
94 isRunning: Effect.succeed(forwarding),
95 kill: () => Effect.void,
96 stdin: Sink.drain,
97 getInputFd: () => Sink.drain,
98 getOutputFd: () => Stream.empty,
99 unref: Effect.succeed(Effect.void),
100 });
101 }),
102 );
103 const host = yield* SshDeviceHost.make(
104 { id: "test", label: "Test", target: "test.example" },
105 () =>
106 rejectConfig
107 ? Effect.fail(
108 new DeviceHost.DeviceHostError({
109 hostId: "test",
110 step: "configuring agent access",
111 cause: new Error("fixture failure"),
112 }),
113 )
114 : Effect.void,
115 ).pipe(
116 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(home, home), Net.layer)),
117 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
118 Effect.provideService(
119 HttpClient.HttpClient,
120 HttpClient.make((request) =>
121 Effect.succeed(HttpClientResponse.fromWeb(request, new Response("ok"))),
122 ),
123 ),
124 );
125 yield* host.ensureReady(() => Effect.void);
126 yield* SshDeviceHost.probe({ id: "test", label: "Test", target: "test.example" }).pipe(
127 Effect.provide(ServerConfig.layerTest(home, home)),
128 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
129 );
130 expect(new Set(owners).size).toBe(1);
131 expect(owners[0]).toMatch(/^[a-f0-9]{24}$/);
132 expect(forwards).toBe(1);
133 expect(modes.filter((mode) => mode === "start")).toHaveLength(2);
134 const ready = yield* host.current;
135 expect(ready).not.toBeNull();
136 if (ready) {
137 const failed = yield* ready.run("emulator", ["-list-avds"]);
138 expect(failed.code).toBe(1);
139 expect(failed.stdout).toMatch(/^\[truncated\]/);
140 expect(failed.stderr).toBe(failed.stdout.trim());
141 expect(failed.stderr).toMatch(/PANIC: emulator SDK is broken$/);
142 }
143 yield* host.platformAvailability("ios");
144 expect((yield* host.summary).hubInstalled).toBe(true);
145 const failed = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.result);
146 expect(failed._tag).toBe("Failure");
147 expect(forwards).toBe(0);
148 expect(modes.at(-1)).toBe("stop-agent");
149 expect(yield* host.current).toBeNull();
150 rejectConfig = false;
151 yield* host.ensureAgentReady(() => Effect.void);
152 yield* host.platformAvailability("ios");
153 expect((yield* host.summary).agentDeviceInstalled).toBe(true);
154 yield* host.stopAgent;
155 expect(forwards).toBe(1);
156 const multiplexingOff = ["ControlMaster=no", "ControlPath=none", "ControlPersist=no"];
157 expect(tunnelArgs.length).toBeGreaterThan(0);
158 for (const args of tunnelArgs) {
159 for (const option of multiplexingOff) {
160 const index = args.indexOf(option);
161 expect(index).toBeGreaterThan(0);
162 expect(args[index - 1]).toBe("-o");
163 }
164 // The tunnel lives only as long as the server holds the write end of its stdin.
165 expect(args).not.toContain("-N");
166 expect(args.slice(args.indexOf("test.example") + 1)).toEqual([
167 "sh",
168 "-c",
169 "'exec cat >/dev/null'",
170 ]);
171 }
172 expect(tunnelStdins).toEqual(tunnelArgs.map(() => "pipe"));
173 expect(commandArgs.length).toBeGreaterThan(0);
174 for (const args of commandArgs) {
175 for (const option of multiplexingOff) expect(args).not.toContain(option);
176 }
177 yield* host.stop;
178 expect(forwards).toBe(0);
179 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
180);