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

relayClient.test.ts

285 lines9.2 KB

1import { sha256 } from "@noble/hashes/sha2";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { describe, expect, it } from "@effect/vitest";
4import * as ConfigProvider from "effect/ConfigProvider";
5import * as Effect from "effect/Effect";
6import * as Encoding from "effect/Encoding";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import { HttpClient, HttpClientResponse } from "effect/unstable/http";
12import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13import { HostProcessArchitecture, HostProcessPlatform } from "./hostProcess.ts";
14​
15import {
16 RelayClientInstallError,
17 CLOUDFLARED_VERSION,
18 makeCloudflaredRelayClient,
19} from "./relayClient.ts";
20​
21// The suite runs the linux code path against the real filesystem, checking
22// POSIX exec bits that NTFS never reports; the win32 branch skips that check.
23const windowsHost = HostProcessPlatform.defaultValue() === "win32";
24​
25const hostRuntimeLayer = (env: Record<string, string> = {}) =>
26 Layer.mergeAll(
27 Layer.succeed(HostProcessPlatform, "linux"),
28 Layer.succeed(HostProcessArchitecture, "x64"),
29 ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
30 );
31​
32function makeHandle(exitCode = 0) {
33 return ChildProcessSpawner.makeHandle({
34 pid: ChildProcessSpawner.ProcessId(100),
35 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
36 isRunning: Effect.succeed(false),
37 kill: () => Effect.void,
38 unref: Effect.succeed(Effect.void),
39 stdin: Sink.drain,
40 stdout: Stream.empty,
41 stderr: Stream.empty,
42 all: Stream.empty,
43 getInputFd: () => Sink.drain,
44 getOutputFd: () => Stream.empty,
45 });
47​
48const makeHttpClientLayer = (bytes: Uint8Array) =>
49 Layer.succeed(
50 HttpClient.HttpClient,
51 HttpClient.make((request) =>
52 Effect.succeed(
53 HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)),
54 ),
55 ),
56 );
57​
58const makeSpawnerLayer = (commands: Array<string>) =>
59 Layer.succeed(
60 ChildProcessSpawner.ChildProcessSpawner,
61 ChildProcessSpawner.make((command) =>
62 Effect.sync(() => {
63 commands.push(ChildProcess.isStandardCommand(command) ? command.command : "piped-command");
64 // The pinned Windows executable rejects --version but accepts the version subcommand.
65 return makeHandle(
66 ChildProcess.isStandardCommand(command) && command.args.includes("--version") ? 1 : 0,
67 );
68 }),
69 ),
70 );
71​
72describe("RelayClient", () => {
73 it.effect.skipIf(windowsHost)(
74 "resolves explicit overrides before managed and PATH executables",
75 () =>
76 Effect.gen(function* () {
77 const fileSystem = yield* FileSystem.FileSystem;
78 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
79 prefix: "t3-cloudflared-test-",
80 });
81 const overridePath = `${baseDir}/override-cloudflared`;
82 yield* fileSystem.writeFileString(overridePath, "override");
83 yield* fileSystem.chmod(overridePath, 0o755);
84 const manager = yield* makeCloudflaredRelayClient({
85 baseDir,
86 });
87​
88 expect(
89 yield* manager.resolve.pipe(
90 Effect.provideService(
91 ConfigProvider.ConfigProvider,
92 ConfigProvider.fromEnv({
93 env: { PATH: "", T3CODE_CLOUDFLARED_PATH: overridePath },
94 }),
95 ),
96 ),
97 ).toEqual({
98 status: "available",
99 executablePath: overridePath,
100 source: "override",
101 version: CLOUDFLARED_VERSION,
102 });
103 }).pipe(
104 Effect.scoped,
105 Effect.provide(
106 Layer.mergeAll(
107 NodeServices.layer,
108 makeHttpClientLayer(new Uint8Array()),
109 makeSpawnerLayer([]),
110 hostRuntimeLayer(),
111 ),
112 ),
113 ),
114 );
115​
116 it.effect.skipIf(windowsHost)(
117 "downloads, verifies, validates, and atomically installs the managed executable",
118 () =>
119 Effect.gen(function* () {
120 const fileSystem = yield* FileSystem.FileSystem;
121 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
122 prefix: "t3-cloudflared-test-",
123 });
124 const bytes = new TextEncoder().encode("test-cloudflared-binary");
125 const manager = yield* makeCloudflaredRelayClient({
126 baseDir,
127 releaseAsset: {
128 url: "https://example.test/cloudflared",
129 sha256: Encoding.encodeHex(sha256(bytes)),
130 archive: "binary",
131 },
132 });
133​
134 const progress: Array<string> = [];
135 const installed = yield* manager.installWithProgress((event) =>
136 Effect.sync(() => {
137 if (event.type === "progress") {
138 progress.push(event.stage);
139 }
140 }),
141 );
142 const managedPath = `${baseDir}/tools/cloudflared/${CLOUDFLARED_VERSION}/linux-x64/cloudflared`;
143 expect(installed).toEqual({
144 status: "available",
145 executablePath: managedPath,
146 source: "managed",
147 version: CLOUDFLARED_VERSION,
148 });
149 expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe(
150 "test-cloudflared-binary",
151 );
152 expect(progress).toEqual([
153 "checking",
154 "waiting_for_lock",
155 "downloading",
156 "verifying",
157 "installing",
158 "validating",
159 "activating",
160 ]);
161 expect(yield* manager.resolve).toEqual(installed);
162 }).pipe(
163 Effect.scoped,
164 Effect.provide(
165 Layer.mergeAll(
166 NodeServices.layer,
167 makeHttpClientLayer(new TextEncoder().encode("test-cloudflared-binary")),
168 makeSpawnerLayer([]),
169 hostRuntimeLayer(),
170 ),
171 ),
172 ),
173 );
174​
175 it.effect("rejects downloads whose checksum does not match the pinned manifest", () =>
176 Effect.gen(function* () {
177 const fileSystem = yield* FileSystem.FileSystem;
178 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
179 prefix: "t3-cloudflared-test-",
180 });
181 const manager = yield* makeCloudflaredRelayClient({
182 baseDir,
183 releaseAsset: {
184 url: "https://example.test/cloudflared",
185 sha256: Encoding.encodeHex(sha256(new TextEncoder().encode("expected"))),
186 archive: "binary",
187 },
188 });
189​
190 const error = yield* manager.install.pipe(Effect.flip);
191 expect(error).toBeInstanceOf(RelayClientInstallError);
192 expect(error.reason).toBe("invalid_checksum");
193 }).pipe(
194 Effect.scoped,
195 Effect.provide(
196 Layer.mergeAll(
197 NodeServices.layer,
198 makeHttpClientLayer(new TextEncoder().encode("tampered")),
199 makeSpawnerLayer([]),
200 hostRuntimeLayer(),
201 ),
202 ),
203 ),
204 );
205​
206 it.effect.skipIf(windowsHost)("serializes concurrent installs within one runtime", () => {
207 const commands: Array<string> = [];
208 const bytes = new TextEncoder().encode("test-cloudflared-binary");
209 return Effect.gen(function* () {
210 const fileSystem = yield* FileSystem.FileSystem;
211 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
212 prefix: "t3-cloudflared-test-",
213 });
214 const manager = yield* makeCloudflaredRelayClient({
215 baseDir,
216 releaseAsset: {
217 url: "https://example.test/cloudflared",
218 sha256: Encoding.encodeHex(sha256(bytes)),
219 archive: "binary",
220 },
221 });
222​
223 const [first, second] = yield* Effect.all([manager.install, manager.install], {
224 concurrency: "unbounded",
225 });
226 expect(second).toEqual(first);
227 expect(commands).toHaveLength(1);
228 }).pipe(
229 Effect.scoped,
230 Effect.provide(
231 Layer.mergeAll(
232 NodeServices.layer,
233 makeHttpClientLayer(bytes),
234 makeSpawnerLayer(commands),
235 hostRuntimeLayer(),
236 ),
237 ),
238 );
239 });
240​
241 it.effect.skipIf(windowsHost)(
242 "observes PATH changes after the manager has been constructed",
243 () => {
244 const env = { PATH: "" };
245 return Effect.gen(function* () {
246 const fileSystem = yield* FileSystem.FileSystem;
247 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
248 prefix: "t3-cloudflared-test-",
249 });
250 const binDir = `${baseDir}/bin`;
251 const executablePath = `${binDir}/cloudflared`;
252 const manager = yield* makeCloudflaredRelayClient({
253 baseDir,
254 });
255​
256 expect(yield* manager.resolve).toEqual({
257 status: "missing",
258 version: CLOUDFLARED_VERSION,
259 });
260​
261 yield* fileSystem.makeDirectory(binDir);
262 yield* fileSystem.writeFileString(executablePath, "cloudflared");
263 yield* fileSystem.chmod(executablePath, 0o755);
264 env.PATH = binDir;
265​
266 expect(yield* manager.resolve).toEqual({
267 status: "available",
268 executablePath,
269 source: "path",
270 version: CLOUDFLARED_VERSION,
271 });
272 }).pipe(
273 Effect.scoped,
274 Effect.provide(
275 Layer.mergeAll(
276 NodeServices.layer,
277 makeHttpClientLayer(new Uint8Array()),
278 makeSpawnerLayer([]),
279 hostRuntimeLayer(env),
280 ),
281 ),
282 );
283 },
284 );
285});