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

connect.test.ts

164 lines5.8 KB

1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises the Node HTTP boundary.
2import * as NodeHttp from "node:http";
3​
4import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as NetService from "@t3tools/shared/Net";
7import * as RelayClient from "@t3tools/shared/relayClient";
8import { assert, it } from "@effect/vitest";
9import * as ConfigProvider from "effect/ConfigProvider";
10import * as Console from "effect/Console";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as TestConsole from "effect/testing/TestConsole";
16import { Command } from "effect/cli";
17​
18import { makeCli } from "../binCli.ts";
19import {
20 makePersistedServerRuntimeState,
21 persistServerRuntimeState,
22} from "../serverRuntimeState.ts";
23import { acquireRelayClientForLink } from "./connect.ts";
24​
25const managedExecutable = {
26 status: "available",
27 executablePath: "/tmp/cloudflared",
28 source: "managed",
29 version: RelayClient.CLOUDFLARED_VERSION,
30} as const;
31​
32it.effect("does not install the relay client when the user declines the managed download", () =>
33 Effect.gen(function* () {
34 let installCalls = 0;
35 const result = yield* acquireRelayClientForLink(
36 {
37 resolve: Effect.succeed({
38 status: "missing",
39 version: RelayClient.CLOUDFLARED_VERSION,
40 }),
41 install: Effect.sync(() => {
42 installCalls += 1;
43 return managedExecutable;
44 }),
45 installWithProgress: () =>
46 Effect.sync(() => {
47 installCalls += 1;
48 return managedExecutable;
49 }),
50 pruneManagedVersions: Effect.void,
51 },
52 () => Effect.succeed(false),
53 () => Effect.void,
54 );
55​
56 assert.isTrue(Option.isNone(result));
57 assert.equal(installCalls, 0);
58 }),
59);
60​
61it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
62 "t3 connect unlink",
63 (it) => {
64 const runUnlink = (recordedPid: number, options?: { readonly portFreed?: boolean }) =>
65 Effect.gen(function* () {
66 const requests: Array<string> = [];
67 const warnings: Array<string> = [];
68 const server = yield* Effect.acquireRelease(
69 Effect.callback<NodeHttp.Server>((resume) => {
70 const listening = NodeHttp.createServer((request, response) => {
71 requests.push(`${request.method} ${request.url}`);
72 response.writeHead(200, { "content-type": "application/json" });
73 response.end(JSON.stringify({ ok: true, endpointRuntimeStatus: null }));
74 });
75 listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
76 }),
77 (listening) => Effect.sync(() => listening.close()),
78 );
79 const address = server.address();
80 if (address === null || typeof address === "string") {
81 return yield* Effect.die(new Error("Expected a TCP address"));
82 }
83 if (options?.portFreed) {
84 yield* Effect.callback<void>((resume) => {
85 server.close(() => resume(Effect.void));
86 });
87 }
88​
89 const fs = yield* FileSystem.FileSystem;
90 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-unlink-test-" });
91 const state = yield* makePersistedServerRuntimeState({
92 config: { host: "127.0.0.1", devUrl: undefined },
93 port: address.port,
94 });
95 yield* persistServerRuntimeState({
96 path: `${baseDir}/userdata/server-runtime.json`,
97 state: { ...state, pid: recordedPid },
98 });
99​
100 yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([
101 "connect",
102 "unlink",
103 "--base-dir",
104 baseDir,
105 ]).pipe(
106 // TestConsole has no reader for Console.warn.
107 Effect.updateService(Console.Console, (console) => ({
108 ...console,
109 warn: (...args: ReadonlyArray<unknown>) => {
110 warnings.push(args.join(" "));
111 },
112 })),
113 );
114​
115 return { requests, warnings, printed: (yield* TestConsole.logLines).join("\n") };
116 }).pipe(
117 Effect.scoped,
118 Effect.provide(
119 Layer.mergeAll(
120 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
121 Layer.fresh(TestConsole.layer),
122 ),
123 ),
124 );
125​
126 // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it.
127 const deadPid = 4_194_305;
128​
129 it.effect("does not tell the user to restart a server that is gone", () =>
130 Effect.gen(function* () {
131 const { printed, warnings } = yield* runUnlink(deadPid, { portFreed: true });
132​
133 assert.include(printed, "T3 Connect is disabled locally.");
134 assert.notInclude(warnings.join("\n"), "Restart that server");
135 }),
136 );
137​
138 it.effect("warns that a server that is gone may have left its connector running", () =>
139 Effect.gen(function* () {
140 const { warnings } = yield* runUnlink(deadPid, { portFreed: true });
141​
142 assert.include(warnings.join("\n"), "its cloudflared process may still be running");
143 }),
144 );
145​
146 it.effect("does not send a token to whatever took over a dead server's port", () =>
147 Effect.gen(function* () {
148 const { requests } = yield* runUnlink(deadPid);
149​
150 assert.deepEqual(requests, []);
151 }),
152 );
153​
154 it.effect("asks a running server to stop its tunnel", () =>
155 Effect.gen(function* () {
156 const { requests, printed, warnings } = yield* runUnlink(process.pid);
157​
158 assert.deepEqual(requests, ["POST /api/connect/unlink"]);
159 assert.include(printed, "T3 Connect is disabled locally.");
160 assert.notInclude(warnings.join("\n"), "cloudflared process");
161 }),
162 );
163 },
164);