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

ConnectReachability.ts

312 lines11.6 KB

1import * as NodeNet from "node:net";
2​
3import {
4 connectReachabilityHelpUrl,
5 type EnvironmentConnectReachability,
6 formatConnectReachable,
7} from "@t3tools/contracts";
8import { readTailscaleExitNode, type TailscaleExitNode } from "@t3tools/tailscale";
9import * as Context from "effect/Context";
10import * as DateTime from "effect/DateTime";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Ref from "effect/Ref";
16import * as Stream from "effect/Stream";
17import { HttpClient } from "effect/http";
18import { ChildProcessSpawner } from "effect/process";
19​
20import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
21import { CLOUD_ENDPOINT_RUNTIME_CONFIG } from "./config.ts";
22import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
23​
24// cloudflared finds the edge through the SRV record `_v2-origintunneld._tcp.argotunnel.com`,
25// which names these two hosts on port 7844. QUIC and HTTP/2 both use that port.
26const TUNNEL_EDGE_HOSTS = ["region1.v2.argotunnel.com", "region2.v2.argotunnel.com"];
27const TUNNEL_EDGE_PORT = 7844;
28const EDGE_CONNECT_TIMEOUT = Duration.seconds(5);
29const ENDPOINT_REQUEST_TIMEOUT = Duration.seconds(10);
30// cloudflared registers several connections within a few seconds; they are one change.
31const READINESS_CHANGE_DEBOUNCE = Duration.seconds(3);
32// Readiness changes miss failures and recoveries past cloudflared (DNS, origin, edge errors).
33const RECHECK_INTERVAL = Duration.minutes(5);
34​
35export type EndpointProbe =
36 | { readonly kind: "status"; readonly status: number }
37 | { readonly kind: "dns_failed" | "timeout" | "network_error" };
38​
39/** Everything one check learned. `null` means that step did not run. */
40export interface ReachabilityFacts {
41 readonly managedTunnelConfigured: boolean;
42 readonly connector: ManagedEndpointRuntime.ConnectorFacts | null;
43 readonly endpoint: EndpointProbe | null;
44 readonly edgeReachable: boolean | null;
45 readonly exitNode: TailscaleExitNode | null;
47​
48type Unreachable = Extract<EnvironmentConnectReachability, { status: "unreachable" }>;
49​
50function exitNodeHint(exitNode: TailscaleExitNode | null): string | null {
51 if (!exitNode) return null;
52 const name = exitNode.name ? ` "${exitNode.name}"` : "";
53 return `Tailscale exit node${name} is on. Traffic to Cloudflare goes through it.`;
55​
56/** Turns what one check learned into the answer every surface shows. */
57export function classifyReachability(
58 facts: ReachabilityFacts,
59 checkedAt: string,
60): EnvironmentConnectReachability {
61 const { connector, endpoint, exitNode } = facts;
62 const fail = (
63 cause: Unreachable["cause"],
64 reason: string,
65 fix: string,
66 hint: string | null = null,
67 ): Unreachable => ({ status: "unreachable", checkedAt, cause, reason, hint, fix });
68 const restart = "Restart T3 Code. If it stays, run `t3 connect` again.";
69​
70 if (!facts.managedTunnelConfigured) {
71 return fail(
72 "not_linked",
73 "The server has not set up a T3 Connect tunnel.",
74 "Run `t3 connect`, then restart the server (`t3 service restart`) so it applies the link.",
75 );
76 }
77 if (connector === null) {
78 return fail(
79 "connector_not_running",
80 "The tunnel client (cloudflared) is not running.",
81 "Restart T3 Code. If it stays down, check the server log for relay client errors.",
82 );
83 }
84 const status = endpoint?.kind === "status" ? endpoint.status : null;
85 if (status === 200) {
86 return {
87 status: "reachable",
88 checkedAt,
89 readyConnections: connector.readyConnections,
90 protocol: connector.protocol,
91 };
92 }
93 // The edge test is TCP only. With QUIC connections up, a 502 from a working tunnel, or
94 // DNS already failing, a failed TCP test would hide the real cause.
95 if (
96 facts.edgeReachable === false &&
97 status !== 502 &&
98 !(connector.readyConnections && connector.readyConnections > 0) &&
99 endpoint?.kind !== "dns_failed"
100 ) {
101 return fail(
102 "edge_unreachable",
103 `Cloudflare's tunnel port (${TUNNEL_EDGE_PORT}) times out from this machine.`,
104 exitNode
105 ? `tailscale set --exit-node= (or allow outbound ${TUNNEL_EDGE_PORT} on that network)`
106 : `Allow outbound TCP and UDP port ${TUNNEL_EDGE_PORT}, or turn off the VPN or firewall that blocks it.`,
107 exitNodeHint(exitNode) ?? "A VPN, proxy, or firewall may block it.",
108 );
109 }
110 if (status === 502) {
111 return fail(
112 "origin_unreachable",
113 "The tunnel is up, but it cannot reach the T3 server on this machine.",
114 "Restart T3 Code so the tunnel uses the port the server listens on.",
115 );
116 }
117 if (endpoint === null || connector.readyConnections === 0) {
118 return fail(
119 "connector_not_ready",
120 "cloudflared has not connected to Cloudflare yet.",
121 "Wait a minute. If it stays, check the network and the server log.",
122 );
123 }
124 // Cloudflare answers 530 (error 1033) when the tunnel has no live connector.
125 if (status === 530) {
126 return fail(
127 "no_connector",
128 "Cloudflare has no live connection from this machine for the tunnel.",
129 restart,
130 );
131 }
132 if (status !== null) {
133 return fail(
134 "unexpected_response",
135 `The T3 Connect address answered with HTTP ${status}.`,
136 restart,
137 );
138 }
139 return endpoint.kind === "dns_failed"
140 ? fail(
141 "dns_failed",
142 "The T3 Connect address does not resolve from this machine.",
143 "Check the DNS settings on this machine or its VPN.",
144 exitNodeHint(exitNode),
145 )
146 : fail(
147 "timeout",
148 "The T3 Connect address did not answer from this machine.",
149 "Check the network, VPN, or proxy on this machine.",
150 exitNodeHint(exitNode),
151 );
153​
154/** The loud diagnosis the CLI prints and the server logs. */
155export function formatReachabilityFailure(result: Unreachable): string {
156 return [
157 "✕ T3 Connect is NOT reachable from other devices",
158 ` ${result.reason}`,
159 ...(result.hint ? [` ${result.hint}`] : []),
160 ` Fix: ${result.fix}`,
161 ` More info: ${connectReachabilityHelpUrl(result.cause)}`,
162 ].join("\n");
164​
165function hasErrorCode(error: unknown, codes: ReadonlySet<string>): boolean {
166 let current = error;
167 for (let depth = 0; depth < 6 && typeof current === "object" && current !== null; depth++) {
168 if ("code" in current && typeof current.code === "string" && codes.has(current.code)) {
169 return true;
170 }
171 current = "cause" in current ? current.cause : undefined;
172 }
173 return false;
175​
176const DNS_ERROR_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_NONAME"]);
177​
178const canOpenTcp = (host: string, port: number) =>
179 Effect.callback<boolean>((resume) => {
180 const socket = NodeNet.connect({ host, port });
181 const finish = (connected: boolean) => {
182 socket.destroy();
183 resume(Effect.succeed(connected));
184 };
185 socket.setTimeout(Duration.toMillis(EDGE_CONNECT_TIMEOUT), () => finish(false));
186 socket.once("connect", () => finish(true));
187 socket.once("error", () => finish(false));
188 return Effect.sync(() => socket.destroy());
189 });
190​
191export class ConnectReachability extends Context.Service<
192 ConnectReachability,
193 {
194 /** Runs a check now. The server also runs one when the tunnel's readiness changes. */
195 readonly check: Effect.Effect<EnvironmentConnectReachability>;
196 readonly latest: Effect.Effect<Option.Option<EnvironmentConnectReachability>>;
197 }
198>()("t3/cloud/ConnectReachability") {}
199​
200const make = Effect.gen(function* () {
201 const runtime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime;
202 const secrets = yield* ServerSecretStore.ServerSecretStore;
203 const httpClient = yield* HttpClient.HttpClient;
204 // `order` ranks checks by start, so a slow older one cannot replace a newer result.
205 const latestRef = yield* Ref.make(
206 Option.none<{ readonly order: number; readonly result: EnvironmentConnectReachability }>(),
207 );
208 const checkCounter = yield* Ref.make(0);
209 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
210 const readExitNode = readTailscaleExitNode.pipe(
211 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
212 Effect.orElseSucceed(() => null),
213 );
214​
215 const probeEndpoint = (hostname: string) =>
216 httpClient.get(`https://${hostname}/.well-known/t3/environment`).pipe(
217 Effect.map((response): EndpointProbe => ({ kind: "status", status: response.status })),
218 Effect.scoped,
219 Effect.timeoutOption(ENDPOINT_REQUEST_TIMEOUT),
220 Effect.map(Option.getOrElse((): EndpointProbe => ({ kind: "timeout" }))),
221 Effect.catch((error) =>
222 Effect.succeed<EndpointProbe>({
223 kind: hasErrorCode(error, DNS_ERROR_CODES) ? "dns_failed" : "network_error",
224 }),
225 ),
226 );
227​
228 const gatherFacts = Effect.gen(function* () {
229 const managedTunnelConfigured = Option.isSome(
230 yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG).pipe(Effect.orElseSucceed(Option.none)),
231 );
232 const connector = managedTunnelConfigured ? yield* runtime.inspectConnector : null;
233 const endpoint =
234 connector?.hostname && connector.readyConnections !== 0
235 ? yield* probeEndpoint(connector.hostname)
236 : null;
237 const facts: ReachabilityFacts = {
238 managedTunnelConfigured,
239 connector,
240 endpoint,
241 edgeReachable: null,
242 exitNode: null,
243 };
244 if (connector === null || (endpoint?.kind === "status" && endpoint.status === 200)) {
245 return facts;
246 }
247 const [edgeResults, exitNode] = yield* Effect.all(
248 [
249 Effect.forEach(TUNNEL_EDGE_HOSTS, (host) => canOpenTcp(host, TUNNEL_EDGE_PORT), {
250 concurrency: "unbounded",
251 }),
252 readExitNode,
253 ],
254 { concurrency: 2 },
255 );
256 return { ...facts, edgeReachable: edgeResults.some(Boolean), exitNode };
257 });
258​
259 const check = Effect.gen(function* () {
260 const order = yield* Ref.updateAndGet(checkCounter, (count) => count + 1);
261 const facts = yield* gatherFacts;
262 const result = classifyReachability(facts, DateTime.formatIso(yield* DateTime.now));
263 const previous = yield* Ref.modify(latestRef, (current) =>
264 Option.isSome(current) && current.value.order > order
265 ? [null, current]
266 : [current, Option.some({ order, result })],
267 );
268 if (previous === null) return result;
269 const changed = Option.match(previous, {
270 onNone: () => true,
271 onSome: ({ result: last }) =>
272 last.status !== result.status ||
273 (last.status === "unreachable" &&
274 result.status === "unreachable" &&
275 last.cause !== result.cause),
276 });
277 if (!changed || (result.status === "unreachable" && result.cause === "not_linked")) {
278 return result;
279 }
280 if (result.status === "unreachable") {
281 // A connector that has not connected yet is usually still starting; the
282 // runtime restarts it, and an unreachable edge is reported as its own cause.
283 const log = result.cause === "connector_not_ready" ? Effect.logWarning : Effect.logError;
284 yield* log(`\n${formatReachabilityFailure(result)}`).pipe(
285 Effect.annotateLogs({ cause: result.cause }),
286 );
287 } else {
288 yield* Effect.logInfo(
289 `T3 Connect is reachable from other devices. ${formatConnectReachable(result)}`,
290 );
291 }
292 return result;
293 }).pipe(Effect.withSpan("ConnectReachability.check"));
294​
295 yield* runtime.readinessChanged.pipe(
296 Stream.debounce(READINESS_CHANGE_DEBOUNCE),
297 Stream.runForEach(() => check),
298 Effect.forkScoped,
299 );
300 yield* Effect.sleep(RECHECK_INTERVAL).pipe(
301 Effect.andThen(check),
302 Effect.forever,
303 Effect.forkScoped,
304 );
305​
306 return ConnectReachability.of({
307 check,
308 latest: Ref.get(latestRef).pipe(Effect.map(Option.map(({ result }) => result))),
309 });
310});
311​
312export const layer = Layer.effect(ConnectReachability, make);