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

SshDeviceHost.test.ts

185 lines7.1 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 { kind: "ssh", 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({
127 kind: "ssh",
128 id: "test",
129 label: "Test",
130 target: "test.example",
131 }).pipe(
132 Effect.provide(ServerConfig.layerTest(home, home)),
133 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
134 );
135 expect(new Set(owners).size).toBe(1);
136 expect(owners[0]).toMatch(/^[a-f0-9]{24}$/);
137 expect(forwards).toBe(1);
138 expect(modes.filter((mode) => mode === "start")).toHaveLength(2);
139 const ready = yield* host.current;
140 expect(ready).not.toBeNull();
141 if (ready) {
142 const failed = yield* ready.run("emulator", ["-list-avds"]);
143 expect(failed.code).toBe(1);
144 expect(failed.stdout).toMatch(/^\[truncated\]/);
145 expect(failed.stderr).toBe(failed.stdout.trim());
146 expect(failed.stderr).toMatch(/PANIC: emulator SDK is broken$/);
147 }
148 yield* host.platformAvailability("ios");
149 expect((yield* host.summary).hubInstalled).toBe(true);
150 const failed = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.result);
151 expect(failed._tag).toBe("Failure");
152 expect(forwards).toBe(0);
153 expect(modes.at(-1)).toBe("stop-agent");
154 expect(yield* host.current).toBeNull();
155 rejectConfig = false;
156 yield* host.ensureAgentReady(() => Effect.void);
157 yield* host.platformAvailability("ios");
158 expect((yield* host.summary).agentDeviceInstalled).toBe(true);
159 yield* host.stopAgent;
160 expect(forwards).toBe(1);
161 const multiplexingOff = ["ControlMaster=no", "ControlPath=none", "ControlPersist=no"];
162 expect(tunnelArgs.length).toBeGreaterThan(0);
163 for (const args of tunnelArgs) {
164 for (const option of multiplexingOff) {
165 const index = args.indexOf(option);
166 expect(index).toBeGreaterThan(0);
167 expect(args[index - 1]).toBe("-o");
168 }
169 // The tunnel lives only as long as the server holds the write end of its stdin.
170 expect(args).not.toContain("-N");
171 expect(args.slice(args.indexOf("test.example") + 1)).toEqual([
172 "sh",
173 "-c",
174 "'exec cat >/dev/null'",
175 ]);
176 }
177 expect(tunnelStdins).toEqual(tunnelArgs.map(() => "pipe"));
178 expect(commandArgs.length).toBeGreaterThan(0);
179 for (const args of commandArgs) {
180 for (const option of multiplexingOff) expect(args).not.toContain(option);
181 }
182 yield* host.stop;
183 expect(forwards).toBe(0);
184 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
185);