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

ConnectReachability.ts

313 lines11.7 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 // A running server reads the link `t3 connect` stores only at startup.
72 return fail(
73 "not_linked",
74 "The server has not set up a T3 Connect tunnel.",
75 "Run `t3 connect`, then restart T3 Code so it applies the link.",
76 );
77 }
78 if (connector === null) {
79 return fail(
80 "connector_not_running",
81 "The tunnel client (cloudflared) is not running.",
82 "Restart T3 Code. If it stays down, check the server log for relay client errors.",
83 );
84 }
85 const status = endpoint?.kind === "status" ? endpoint.status : null;
86 if (status === 200) {
87 return {
88 status: "reachable",
89 checkedAt,
90 readyConnections: connector.readyConnections,
91 protocol: connector.protocol,
92 };
93 }
94 // The edge test is TCP only. With QUIC connections up, a 502 from a working tunnel, or
95 // DNS already failing, a failed TCP test would hide the real cause.
96 if (
97 facts.edgeReachable === false &&
98 status !== 502 &&
99 !(connector.readyConnections && connector.readyConnections > 0) &&
100 endpoint?.kind !== "dns_failed"
101 ) {
102 return fail(
103 "edge_unreachable",
104 `Cloudflare's tunnel port (${TUNNEL_EDGE_PORT}) times out from this machine.`,
105 exitNode
106 ? `tailscale set --exit-node= (or allow outbound ${TUNNEL_EDGE_PORT} on that network)`
107 : `Allow outbound TCP and UDP port ${TUNNEL_EDGE_PORT}, or turn off the VPN or firewall that blocks it.`,
108 exitNodeHint(exitNode) ?? "A VPN, proxy, or firewall may block it.",
109 );
110 }
111 if (status === 502) {
112 return fail(
113 "origin_unreachable",
114 "The tunnel is up, but it cannot reach the T3 server on this machine.",
115 "Restart T3 Code so the tunnel uses the port the server listens on.",
116 );
117 }
118 if (endpoint === null || connector.readyConnections === 0) {
119 return fail(
120 "connector_not_ready",
121 "cloudflared has not connected to Cloudflare yet.",
122 "Wait a minute. If it stays, check the network and the server log.",
123 );
124 }
125 // Cloudflare answers 530 (error 1033) when the tunnel has no live connector.
126 if (status === 530) {
127 return fail(
128 "no_connector",
129 "Cloudflare has no live connection from this machine for the tunnel.",
130 restart,
131 );
132 }
133 if (status !== null) {
134 return fail(
135 "unexpected_response",
136 `The T3 Connect address answered with HTTP ${status}.`,
137 restart,
138 );
139 }
140 return endpoint.kind === "dns_failed"
141 ? fail(
142 "dns_failed",
143 "The T3 Connect address does not resolve from this machine.",
144 "Check the DNS settings on this machine or its VPN.",
145 exitNodeHint(exitNode),
146 )
147 : fail(
148 "timeout",
149 "The T3 Connect address did not answer from this machine.",
150 "Check the network, VPN, or proxy on this machine.",
151 exitNodeHint(exitNode),
152 );
154​
155/** The loud diagnosis the CLI prints and the server logs. */
156export function formatReachabilityFailure(result: Unreachable): string {
157 return [
158 "✕ T3 Connect is NOT reachable from other devices",
159 ` ${result.reason}`,
160 ...(result.hint ? [` ${result.hint}`] : []),
161 ` Fix: ${result.fix}`,
162 ` More info: ${connectReachabilityHelpUrl(result.cause)}`,
163 ].join("\n");
165​
166function hasErrorCode(error: unknown, codes: ReadonlySet<string>): boolean {
167 let current = error;
168 for (let depth = 0; depth < 6 && typeof current === "object" && current !== null; depth++) {
169 if ("code" in current && typeof current.code === "string" && codes.has(current.code)) {
170 return true;
171 }
172 current = "cause" in current ? current.cause : undefined;
173 }
174 return false;
176​
177const DNS_ERROR_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_NONAME"]);
178​
179const canOpenTcp = (host: string, port: number) =>
180 Effect.callback<boolean>((resume) => {
181 const socket = NodeNet.connect({ host, port });
182 const finish = (connected: boolean) => {
183 socket.destroy();
184 resume(Effect.succeed(connected));
185 };
186 socket.setTimeout(Duration.toMillis(EDGE_CONNECT_TIMEOUT), () => finish(false));
187 socket.once("connect", () => finish(true));
188 socket.once("error", () => finish(false));
189 return Effect.sync(() => socket.destroy());
190 });
191​
192export class ConnectReachability extends Context.Service<
193 ConnectReachability,
194 {
195 /** Runs a check now. The server also runs one when the tunnel's readiness changes. */
196 readonly check: Effect.Effect<EnvironmentConnectReachability>;
197 readonly latest: Effect.Effect<Option.Option<EnvironmentConnectReachability>>;
198 }
199>()("t3/cloud/ConnectReachability") {}
200​
201const make = Effect.gen(function* () {
202 const runtime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime;
203 const secrets = yield* ServerSecretStore.ServerSecretStore;
204 const httpClient = yield* HttpClient.HttpClient;
205 // `order` ranks checks by start, so a slow older one cannot replace a newer result.
206 const latestRef = yield* Ref.make(
207 Option.none<{ readonly order: number; readonly result: EnvironmentConnectReachability }>(),
208 );
209 const checkCounter = yield* Ref.make(0);
210 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
211 const readExitNode = readTailscaleExitNode.pipe(
212 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
213 Effect.orElseSucceed(() => null),
214 );
215​
216 const probeEndpoint = (hostname: string) =>
217 httpClient.get(`https://${hostname}/.well-known/t3/environment`).pipe(
218 Effect.map((response): EndpointProbe => ({ kind: "status", status: response.status })),
219 Effect.scoped,
220 Effect.timeoutOption(ENDPOINT_REQUEST_TIMEOUT),
221 Effect.map(Option.getOrElse((): EndpointProbe => ({ kind: "timeout" }))),
222 Effect.catch((error) =>
223 Effect.succeed<EndpointProbe>({
224 kind: hasErrorCode(error, DNS_ERROR_CODES) ? "dns_failed" : "network_error",
225 }),
226 ),
227 );
228​
229 const gatherFacts = Effect.gen(function* () {
230 const managedTunnelConfigured = Option.isSome(
231 yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG).pipe(Effect.orElseSucceed(Option.none)),
232 );
233 const connector = managedTunnelConfigured ? yield* runtime.inspectConnector : null;
234 const endpoint =
235 connector?.hostname && connector.readyConnections !== 0
236 ? yield* probeEndpoint(connector.hostname)
237 : null;
238 const facts: ReachabilityFacts = {
239 managedTunnelConfigured,
240 connector,
241 endpoint,
242 edgeReachable: null,
243 exitNode: null,
244 };
245 if (connector === null || (endpoint?.kind === "status" && endpoint.status === 200)) {
246 return facts;
247 }
248 const [edgeResults, exitNode] = yield* Effect.all(
249 [
250 Effect.forEach(TUNNEL_EDGE_HOSTS, (host) => canOpenTcp(host, TUNNEL_EDGE_PORT), {
251 concurrency: "unbounded",
252 }),
253 readExitNode,
254 ],
255 { concurrency: 2 },
256 );
257 return { ...facts, edgeReachable: edgeResults.some(Boolean), exitNode };
258 });
259​
260 const check = Effect.gen(function* () {
261 const order = yield* Ref.updateAndGet(checkCounter, (count) => count + 1);
262 const facts = yield* gatherFacts;
263 const result = classifyReachability(facts, DateTime.formatIso(yield* DateTime.now));
264 const previous = yield* Ref.modify(latestRef, (current) =>
265 Option.isSome(current) && current.value.order > order
266 ? [null, current]
267 : [current, Option.some({ order, result })],
268 );
269 if (previous === null) return result;
270 const changed = Option.match(previous, {
271 onNone: () => true,
272 onSome: ({ result: last }) =>
273 last.status !== result.status ||
274 (last.status === "unreachable" &&
275 result.status === "unreachable" &&
276 last.cause !== result.cause),
277 });
278 if (!changed || (result.status === "unreachable" && result.cause === "not_linked")) {
279 return result;
280 }
281 if (result.status === "unreachable") {
282 // A connector that has not connected yet is usually still starting; the
283 // runtime restarts it, and an unreachable edge is reported as its own cause.
284 const log = result.cause === "connector_not_ready" ? Effect.logWarning : Effect.logError;
285 yield* log(`\n${formatReachabilityFailure(result)}`).pipe(
286 Effect.annotateLogs({ cause: result.cause }),
287 );
288 } else {
289 yield* Effect.logInfo(
290 `T3 Connect is reachable from other devices. ${formatConnectReachable(result)}`,
291 );
292 }
293 return result;
294 }).pipe(Effect.withSpan("ConnectReachability.check"));
295​
296 yield* runtime.readinessChanged.pipe(
297 Stream.debounce(READINESS_CHANGE_DEBOUNCE),
298 Stream.runForEach(() => check),
299 Effect.forkScoped,
300 );
301 yield* Effect.sleep(RECHECK_INTERVAL).pipe(
302 Effect.andThen(check),
303 Effect.forever,
304 Effect.forkScoped,
305 );
306​
307 return ConnectReachability.of({
308 check,
309 latest: Ref.get(latestRef).pipe(Effect.map(Option.map(({ result }) => result))),
310 });
311});
312​
313export const layer = Layer.effect(ConnectReachability, make);