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

SshDeviceHost.test.ts

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