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

SshDeviceHost.test.ts

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