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

connect.test.ts

327 lines11.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as RelayClient from "@t3tools/shared/relayClient";
4import { assert, it } from "@effect/vitest";
5import * as Cause from "effect/Cause";
6import * as ConfigProvider from "effect/ConfigProvider";
7import * as Console from "effect/Console";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Logger from "effect/Logger";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as References from "effect/References";
14import * as Terminal from "effect/Terminal";
15​
16import * as BootService from "../cloud/bootService.ts";
17import {
18 acquireRelayClientForLink,
19 headlessSessionConfig,
20 reportCloudDisconnectResults,
21 reportServiceOnboarding,
22} from "./connect.ts";
23import { offerServiceDuringOnboarding, recoverServiceOnboardingOffer } from "./service.ts";
24​
25const readHeadlessSessionConfig = (env: Record<string, string>) =>
26 headlessSessionConfig.pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))));
27​
28const managedExecutable = {
29 status: "available",
30 executablePath: "/tmp/cloudflared",
31 source: "managed",
32 version: RelayClient.CLOUDFLARED_VERSION,
33} as const;
34​
35it.effect("detects headless operation from individual SSH config values", () =>
36 Effect.gen(function* () {
37 assert.isFalse(yield* readHeadlessSessionConfig({}));
38 assert.isFalse(yield* readHeadlessSessionConfig({ CI: "true" }));
39 assert.isTrue(yield* readHeadlessSessionConfig({ SSH_CONNECTION: "client server" }));
40 assert.isTrue(yield* readHeadlessSessionConfig({ SSH_TTY: "/dev/pts/1" }));
41 }),
42);
43​
44it.effect("treats cancelling optional background setup as a successful skip", () =>
45 Effect.gen(function* () {
46 const result = yield* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));
47 assert.equal(result, "skipped");
48 }),
49);
50​
51it.effect("keeps a successful connection when a remote service update is pending", () =>
52 Effect.gen(function* () {
53 const result = yield* recoverServiceOnboardingOffer(
54 Effect.fail(new BootService.BootServiceUpdatePendingError()),
55 );
56 assert.equal(result, "skipped");
57 }),
58);
59​
60it.effect("reports pending onboarding until the handed-off service is ready", () =>
61 Effect.gen(function* () {
62 const input = yield* Queue.make<Terminal.UserInput>();
63 yield* Queue.offer(input, {
64 input: Option.some("\r"),
65 key: { name: "return", ctrl: false, meta: false, shift: false },
66 });
67 const terminal = Terminal.make({
68 columns: Effect.succeed(80),
69 rows: Effect.succeed(24),
70 readInput: Effect.succeed(Queue.asDequeue(input)),
71 readLine: Effect.die("unexpected line input"),
72 display: () => Effect.void,
73 });
74 const plan = {
75 program: ["/test/t3", "__service-launcher"],
76 baseDir: "/test",
77 unitPath: "/test/t3code.service",
78 logPath: "/test/boot-service.log",
79 handedOff: true,
80 };
81 let current = false;
82 const service = BootService.BootService.of({
83 status: Effect.sync(() => ({
84 supported: true,
85 installed: true,
86 current,
87 unitPath: plan.unitPath,
88 logPath: plan.logPath,
89 })),
90 install: () => Effect.succeed(plan),
91 restart: Effect.die("unexpected restart"),
92 uninstall: Effect.die("unexpected uninstall"),
93 withStopped: () => Effect.die("unexpected maintenance"),
94 });
95 const lines: string[] = [];
96 const onboard = recoverServiceOnboardingOffer(offerServiceDuringOnboarding).pipe(
97 Effect.flatMap(reportServiceOnboarding),
98 Effect.provideService(BootService.BootService, service),
99 Effect.provideService(Terminal.Terminal, terminal),
100 Effect.provideService(HostProcess.Platform, "linux"),
101 Effect.provideService(Console.Console, {
102 ...globalThis.console,
103 log: (...args) => {
104 lines.push(args.map(String).join(" "));
105 },
106 }),
107 );
108​
109 yield* onboard;
110 const output = lines.join("\n");
111 assert.notInclude(output, "Background service ready");
112 assert.notInclude(output, "Start the server");
113 assert.include(output, "Background service restarting");
114 assert.include(output, plan.logPath);
115​
116 current = true;
117 lines.length = 0;
118 yield* onboard;
119 assert.include(lines.join("\n"), "Background service ready");
120 assert.notInclude(lines.join("\n"), "restarting");
121 }).pipe(Effect.provide(NodeServices.layer)),
122);
123​
124it.effect("does not install the relay client when the user declines the managed download", () =>
125 Effect.gen(function* () {
126 let installCalls = 0;
127 const result = yield* acquireRelayClientForLink(
128 {
129 resolve: Effect.succeed({
130 status: "missing",
131 version: RelayClient.CLOUDFLARED_VERSION,
132 }),
133 install: Effect.sync(() => {
134 installCalls += 1;
135 return managedExecutable;
136 }),
137 installWithProgress: () =>
138 Effect.sync(() => {
139 installCalls += 1;
140 return managedExecutable;
141 }),
142 pruneManagedVersions: Effect.void,
143 },
144 () => Effect.succeed(false),
145 () => Effect.void,
146 );
147​
148 assert.isTrue(Option.isNone(result));
149 assert.equal(installCalls, 0);
150 }),
151);
152​
153it.effect("installs the relay client after the user accepts the managed download", () =>
154 Effect.gen(function* () {
155 let installCalls = 0;
156 const progress: Array<string> = [];
157 const result = yield* acquireRelayClientForLink(
158 {
159 resolve: Effect.succeed({
160 status: "missing",
161 version: RelayClient.CLOUDFLARED_VERSION,
162 }),
163 install: Effect.sync(() => {
164 installCalls += 1;
165 return managedExecutable;
166 }),
167 installWithProgress: (report) =>
168 report({ type: "progress", stage: "downloading" }).pipe(
169 Effect.andThen(
170 Effect.sync(() => {
171 installCalls += 1;
172 return managedExecutable;
173 }),
174 ),
175 ),
176 pruneManagedVersions: Effect.void,
177 },
178 () => Effect.succeed(true),
179 (event) =>
180 Effect.sync(() => {
181 if (event.type === "progress") {
182 progress.push(event.stage);
183 }
184 }),
185 );
186​
187 assert.deepEqual(Option.getOrThrow(result), managedExecutable);
188 assert.equal(installCalls, 1);
189 assert.deepEqual(progress, ["downloading"]);
190 }),
191);
192​
193it.effect("reuses an available relay client executable without prompting", () =>
194 Effect.gen(function* () {
195 let promptCalls = 0;
196 const result = yield* acquireRelayClientForLink(
197 {
198 resolve: Effect.succeed(managedExecutable),
199 install: Effect.die("unexpected install"),
200 installWithProgress: () => Effect.die("unexpected install"),
201 pruneManagedVersions: Effect.void,
202 },
203 () =>
204 Effect.sync(() => {
205 promptCalls += 1;
206 return false;
207 }),
208 () => Effect.void,
209 );
210​
211 assert.deepEqual(Option.getOrThrow(result), managedExecutable);
212 assert.equal(promptCalls, 0);
213 }),
214);
215​
216it.effect("keeps disconnect causes in structured logs and out of console warnings", () => {
217 const warnings: ReadonlyArray<unknown>[] = [];
218 const logs: Readonly<Record<string, unknown>>[] = [];
219 const testConsole = {
220 ...globalThis.console,
221 warn: (...args: ReadonlyArray<unknown>) => {
222 warnings.push(args);
223 },
224 } satisfies Console.Console;
225 const logger = Logger.make(({ fiber }) => {
226 logs.push(fiber.getRef(References.CurrentLogAnnotations));
227 });
228 const liveFailure = "live unlink private diagnostic";
229 const relayFailure = "relay revoke private diagnostic";
230​
231 return reportCloudDisconnectResults({
232 clearAuthorization: true,
233 liveResult: {
234 status: "failed",
235 cause: Cause.fail(new Error(liveFailure)),
236 },
237 relayResult: Exit.failCause(Cause.die(new Error(relayFailure))),
238 }).pipe(
239 Effect.provideService(Console.Console, testConsole),
240 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
241 Effect.tap(() =>
242 Effect.sync(() => {
243 assert.lengthOf(warnings, 2);
244 const warningText = warnings.flat().map(String).join("\n");
245 assert.include(warningText, "running server could not stop its tunnel");
246 assert.include(warningText, "Could not revoke the relay-side environment record");
247 assert.notInclude(warningText, liveFailure);
248 assert.notInclude(warningText, relayFailure);
249 assert.deepEqual(
250 logs.map(({ operation, clearAuthorization }) => ({ operation, clearAuthorization })),
251 [
252 { operation: "live-server-unlink", clearAuthorization: true },
253 { operation: "relay-environment-unlink", clearAuthorization: true },
254 ],
255 );
256 const loggedCauses = logs.map((log) => String(log.cause)).join("\n");
257 assert.include(loggedCauses, liveFailure);
258 assert.include(loggedCauses, relayFailure);
259 }),
260 ),
261 );
262});
263​
264/** Captures console lines from a successful local disconnect report. */
265const captureDisconnectReport = (input: {
266 readonly clearAuthorization: boolean;
267 readonly liveResult: {
268 readonly status: "succeeded";
269 };
270 readonly relayResult: Exit.Exit<
271 { readonly status: "not-authenticated" } | { readonly status: "revoked" },
272 unknown
273 >;
274}) => {
275 const lines: Array<{ readonly stream: "log" | "warn"; readonly text: string }> = [];
276 const testConsole = {
277 ...globalThis.console,
278 log: (...args: ReadonlyArray<unknown>) => {
279 lines.push({ stream: "log", text: args.map(String).join(" ") });
280 },
281 warn: (...args: ReadonlyArray<unknown>) => {
282 lines.push({ stream: "warn", text: args.map(String).join(" ") });
283 },
284 } satisfies Console.Console;
285​
286 return reportCloudDisconnectResults(input).pipe(
287 Effect.provideService(Console.Console, testConsole),
288 Effect.provide(Logger.layer([Logger.make(() => undefined)], { mergeWithExisting: false })),
289 Effect.as(lines),
290 );
291};
292​
293it.effect("warns to deregister when unlink has no stored CLI authorization", () =>
294 Effect.gen(function* () {
295 const lines = yield* captureDisconnectReport({
296 clearAuthorization: false,
297 liveResult: { status: "succeeded" },
298 relayResult: Exit.succeed({ status: "not-authenticated" }),
299 });
300​
301 assert.deepEqual(
302 lines.map((line) => line.stream),
303 ["log", "warn"],
304 );
305 assert.equal(lines[0]?.text, "T3 Connect is disabled locally.");
306 assert.include(lines[1]?.text, "The relay-side environment record was not revoked.");
307 assert.include(lines[1]?.text, "T3 Connect page of your T3 account");
308 assert.include(lines[1]?.text, "`t3 connect login`");
309 assert.notInclude(lines.map((line) => line.text).join("\n"), "Revoked the relay-side");
310 }),
311);
312​
313it.effect("points a failed relay unlink at retry and account deregistration", () =>
314 Effect.gen(function* () {
315 const lines = yield* captureDisconnectReport({
316 clearAuthorization: false,
317 liveResult: { status: "succeeded" },
318 relayResult: Exit.fail("relay unreachable"),
319 });
320 const warning = lines.find((line) => line.stream === "warn")?.text ?? "";
321​
322 assert.equal(lines[0]?.text, "T3 Connect is disabled locally.");
323 assert.include(warning, "Run `t3 connect unlink` again when the relay is reachable");
324 assert.include(warning, "deregister it from the T3 Connect page of your T3 account");
325 assert.notInclude(warning, "relay unreachable");
326 }),
327);