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

ConnectReachability.ts

431 lines17.0 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 Clock from "effect/Clock";
10import * as Context from "effect/Context";
11import * as DateTime from "effect/DateTime";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Ref from "effect/Ref";
17import * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19import * as SynchronizedRef from "effect/SynchronizedRef";
20import { HttpClient } from "effect/http";
21import { ChildProcessSpawner } from "effect/process";
22​
23import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
24import { CLOUD_ENDPOINT_RUNTIME_CONFIG } from "./config.ts";
25import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
26​
27// cloudflared finds the edge through the SRV record `_v2-origintunneld._tcp.argotunnel.com`,
28// which names these two hosts on port 7844. QUIC and HTTP/2 both use that port.
29const TUNNEL_EDGE_HOSTS = ["region1.v2.argotunnel.com", "region2.v2.argotunnel.com"];
30const TUNNEL_EDGE_PORT = 7844;
31const EDGE_CONNECT_TIMEOUT = Duration.seconds(5);
32const ENDPOINT_REQUEST_TIMEOUT = Duration.seconds(10);
33const ERROR_BODY_READ_TIMEOUT = Duration.seconds(2);
34// cloudflared registers several connections within a few seconds; they are one change.
35const READINESS_CHANGE_DEBOUNCE = Duration.seconds(3);
36// Readiness changes miss failures and recoveries past cloudflared (DNS, origin, edge errors).
37const RECHECK_INTERVAL = Duration.minutes(5);
38// cloudflared can keep reporting ready connections the edge already dropped, so its
39// own readiness watch never restarts it. A 530 can also be brief, so restart only once it
40// lasts, and wait longer after each restart that did not help.
41const DEAD_CONNECTOR_RESTART_AFTER = Duration.minutes(2);
42const DEAD_CONNECTOR_RESTART_AFTER_MAX = Duration.hours(1);
43​
44export type EndpointProbe =
45 | { readonly kind: "status"; readonly status: number; readonly cloudflareError?: string }
46 | { readonly kind: "dns_failed" | "timeout" | "network_error" };
47​
48/** Everything one check learned. `null` means that step did not run. */
49export interface ReachabilityFacts {
50 readonly managedTunnelConfigured: boolean;
51 readonly connector: ManagedEndpointRuntime.ConnectorFacts | null;
52 readonly endpoint: EndpointProbe | null;
53 readonly edgeReachable: boolean | null;
54 readonly exitNode: TailscaleExitNode | null;
56​
57type Unreachable = Extract<EnvironmentConnectReachability, { status: "unreachable" }>;
58​
59function exitNodeHint(exitNode: TailscaleExitNode | null): string | null {
60 if (!exitNode) return null;
61 const name = exitNode.name ? ` "${exitNode.name}"` : "";
62 return `Tailscale exit node${name} is on. Traffic to Cloudflare goes through it.`;
64​
65/** Turns what one check learned into the answer every surface shows. */
66export function classifyReachability(
67 facts: ReachabilityFacts,
68 checkedAt: string,
69): EnvironmentConnectReachability {
70 const { connector, endpoint, exitNode } = facts;
71 const fail = (
72 cause: Unreachable["cause"],
73 reason: string,
74 fix: string,
75 hint: string | null = null,
76 ): Unreachable => ({ status: "unreachable", checkedAt, cause, reason, hint, fix });
77 const restart = "Restart T3 Code. If it stays, run `t3 connect` again.";
78​
79 if (!facts.managedTunnelConfigured) {
80 return fail(
81 "not_linked",
82 "The server has not set up a T3 Connect tunnel.",
83 "Run `t3 connect`, then restart the server (`t3 service restart`) so it applies the link.",
84 );
85 }
86 if (connector === null) {
87 return fail(
88 "connector_not_running",
89 "The tunnel client (cloudflared) is not running.",
90 "Restart T3 Code. If it stays down, check the server log for relay client errors.",
91 );
92 }
93 const status = endpoint?.kind === "status" ? endpoint.status : null;
94 if (status === 200) {
95 return {
96 status: "reachable",
97 checkedAt,
98 readyConnections: connector.readyConnections,
99 protocol: connector.protocol,
100 };
101 }
102 // The edge test is TCP only. With QUIC connections up, a 502 from a working tunnel, or
103 // DNS already failing, a failed TCP test would hide the real cause.
104 if (
105 facts.edgeReachable === false &&
106 status !== 502 &&
107 !(connector.readyConnections && connector.readyConnections > 0) &&
108 endpoint?.kind !== "dns_failed"
109 ) {
110 return fail(
111 "edge_unreachable",
112 `Cloudflare's tunnel port (${TUNNEL_EDGE_PORT}) times out from this machine.`,
113 exitNode
114 ? `tailscale set --exit-node= (or allow outbound ${TUNNEL_EDGE_PORT} on that network)`
115 : `Allow outbound TCP and UDP port ${TUNNEL_EDGE_PORT}, or turn off the VPN or firewall that blocks it.`,
116 exitNodeHint(exitNode) ?? "A VPN, proxy, or firewall may block it.",
117 );
118 }
119 if (status === 502) {
120 return fail(
121 "origin_unreachable",
122 "The tunnel is up, but it cannot reach the T3 server on this machine.",
123 "Restart T3 Code so the tunnel uses the port the server listens on.",
124 );
125 }
126 if (endpoint === null || connector.readyConnections === 0) {
127 return fail(
128 "connector_not_ready",
129 "cloudflared has not connected to Cloudflare yet.",
130 "Wait a minute. If it stays, check the network and the server log.",
131 );
132 }
133 const cloudflareError = endpoint.kind === "status" ? endpoint.cloudflareError : undefined;
134 // Cloudflare answers 530 with error 1033 when the tunnel has no live connector. Other
135 // codes, such as 1016 for a broken DNS record, are not fixed by restarting cloudflared.
136 if (status === 530 && (cloudflareError === undefined || cloudflareError === "1033")) {
137 return fail(
138 "no_connector",
139 "Cloudflare has no live connection from this machine for the tunnel.",
140 restart,
141 );
142 }
143 if (status !== null) {
144 const code = cloudflareError === undefined ? "" : ` (Cloudflare error ${cloudflareError})`;
145 return fail(
146 "unexpected_response",
147 `The T3 Connect address answered with HTTP ${status}${code}.`,
148 restart,
149 );
150 }
151 return endpoint.kind === "dns_failed"
152 ? fail(
153 "dns_failed",
154 "The T3 Connect address does not resolve from this machine.",
155 "Check the DNS settings on this machine or its VPN.",
156 exitNodeHint(exitNode),
157 )
158 : fail(
159 "timeout",
160 "The T3 Connect address did not answer from this machine.",
161 "Check the network, VPN, or proxy on this machine.",
162 exitNodeHint(exitNode),
163 );
165​
166/** The loud diagnosis the CLI prints and the server logs. */
167export function formatReachabilityFailure(result: Unreachable): string {
168 return [
169 "✕ T3 Connect is NOT reachable from other devices",
170 ` ${result.reason}`,
171 ...(result.hint ? [` ${result.hint}`] : []),
172 ` Fix: ${result.fix}`,
173 ` More info: ${connectReachabilityHelpUrl(result.cause)}`,
174 ].join("\n");
176​
177function hasErrorCode(error: unknown, codes: ReadonlySet<string>): boolean {
178 let current = error;
179 for (let depth = 0; depth < 6 && typeof current === "object" && current !== null; depth++) {
180 if ("code" in current && typeof current.code === "string" && codes.has(current.code)) {
181 return true;
182 }
183 current = "cause" in current ? current.cause : undefined;
184 }
185 return false;
187​
188const DNS_ERROR_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_NONAME"]);
189​
190const canOpenTcp = (host: string, port: number) =>
191 Effect.callback<boolean>((resume) => {
192 const socket = NodeNet.connect({ host, port });
193 const finish = (connected: boolean) => {
194 socket.destroy();
195 resume(Effect.succeed(connected));
196 };
197 socket.setTimeout(Duration.toMillis(EDGE_CONNECT_TIMEOUT), () => finish(false));
198 socket.once("connect", () => finish(true));
199 socket.once("error", () => finish(false));
200 return Effect.sync(() => socket.destroy());
201 });
202​
203export class ConnectReachability extends Context.Service<
204 ConnectReachability,
205 {
206 /** Runs a check now. The server also runs one when the tunnel's readiness changes. */
207 readonly check: Effect.Effect<EnvironmentConnectReachability>;
208 readonly latest: Effect.Effect<Option.Option<EnvironmentConnectReachability>>;
209 }
210>()("t3/cloud/ConnectReachability") {}
211​
212const make = Effect.gen(function* () {
213 const runtime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime;
214 const secrets = yield* ServerSecretStore.ServerSecretStore;
215 const httpClient = yield* HttpClient.HttpClient;
216 // `order` ranks checks by start, so a slow older one cannot replace a newer result.
217 const latestRef = yield* Ref.make(
218 Option.none<{ readonly order: number; readonly result: EnvironmentConnectReachability }>(),
219 );
220 const checkCounter = yield* Ref.make(0);
221 // Checks update this as they finish, even when a newer check already did. A dead streak
222 // or a restart backoff that began before a healthy check no longer counts.
223 const lastHealthyOrder = yield* Ref.make(0);
224 const deadConnectorRef = yield* SynchronizedRef.make<{
225 readonly streak: {
226 readonly pid: number;
227 readonly since: number;
228 readonly order: number;
229 } | null;
230 readonly restartAfterMillis: number;
231 readonly restartOrder: number;
232 }>({
233 streak: null,
234 restartAfterMillis: Duration.toMillis(DEAD_CONNECTOR_RESTART_AFTER),
235 restartOrder: 0,
236 });
237 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
238 const scope = yield* Scope.Scope;
239 const readExitNode = readTailscaleExitNode.pipe(
240 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
241 Effect.orElseSucceed(() => null),
242 );
243​
244 const probeEndpoint = Effect.fn("ConnectReachability.probeEndpoint")(
245 function* (hostname: string) {
246 const response = yield* httpClient
247 .get(`https://${hostname}/.well-known/t3/environment`, { acceptJson: true })
248 .pipe(Effect.timeoutOption(ENDPOINT_REQUEST_TIMEOUT));
249 if (Option.isNone(response)) return { kind: "timeout" } satisfies EndpointProbe;
250 const { status } = response.value;
251 if (status !== 530) return { kind: "status", status } satisfies EndpointProbe;
252 // Cloudflare's error page is HTML unless the client accepts JSON, which carries
253 // `"error_code":1033`. Clients that send no User-Agent get `error code: 1033`.
254 const body = yield* response.value.text.pipe(
255 Effect.timeoutOption(ERROR_BODY_READ_TIMEOUT),
256 Effect.orElseSucceed(() => Option.none<string>()),
257 );
258 const code = /error[_ ]code"?:\s*(\d{4})/i.exec(Option.getOrElse(body, () => ""))?.[1];
259 return (
260 code === undefined
261 ? { kind: "status", status }
262 : { kind: "status", status, cloudflareError: code }
263 ) satisfies EndpointProbe;
264 },
265 Effect.scoped,
266 Effect.catch((error) =>
267 Effect.succeed<EndpointProbe>({
268 kind: hasErrorCode(error, DNS_ERROR_CODES) ? "dns_failed" : "network_error",
269 }),
270 ),
271 );
272​
273 const gatherFacts = Effect.gen(function* () {
274 const managedTunnelConfigured = Option.isSome(
275 yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG).pipe(Effect.orElseSucceed(Option.none)),
276 );
277 const connector = managedTunnelConfigured ? yield* runtime.inspectConnector : null;
278 const endpoint =
279 connector?.hostname && connector.readyConnections !== 0
280 ? yield* probeEndpoint(connector.hostname)
281 : null;
282 const facts: ReachabilityFacts = {
283 managedTunnelConfigured,
284 connector,
285 endpoint,
286 edgeReachable: null,
287 exitNode: null,
288 };
289 if (connector === null || (endpoint?.kind === "status" && endpoint.status === 200)) {
290 return facts;
291 }
292 const [edgeResults, exitNode] = yield* Effect.all(
293 [
294 Effect.forEach(TUNNEL_EDGE_HOSTS, (host) => canOpenTcp(host, TUNNEL_EDGE_PORT), {
295 concurrency: "unbounded",
296 }),
297 readExitNode,
298 ],
299 { concurrency: 2 },
300 );
301 return { ...facts, edgeReachable: edgeResults.some(Boolean), exitNode };
302 });
303​
304 const isLatest = (order: number) =>
305 Ref.get(latestRef).pipe(
306 Effect.map((latest) => Option.isNone(latest) || latest.value.order <= order),
307 );
308​
309 // Runs inside the check span; the runtime restart has its own. Returns the streak a dead
310 // connector just started and when to confirm it.
311 const restartDeadConnector = Effect.fnUntraced(function* (
312 facts: ReachabilityFacts,
313 result: EnvironmentConnectReachability,
314 order: number,
315 ) {
316 const now = yield* Clock.currentTimeMillis;
317 const { connector } = facts;
318 const dead =
319 result.status === "unreachable" &&
320 result.cause === "no_connector" &&
321 connector !== null &&
322 (connector.readyConnections ?? 0) > 0
323 ? connector
324 : null;
325 return yield* SynchronizedRef.modifyEffect(deadConnectorRef, (current) =>
326 Effect.gen(function* () {
327 const healthy = yield* Ref.get(lastHealthyOrder);
328 const state = {
329 streak: current.streak && current.streak.order > healthy ? current.streak : null,
330 restartAfterMillis:
331 current.restartOrder > healthy
332 ? current.restartAfterMillis
333 : Duration.toMillis(DEAD_CONNECTOR_RESTART_AFTER),
334 restartOrder: current.restartOrder,
335 };
336 if (!(yield* isLatest(order))) return [null, state] as const;
337 if (dead === null) return [null, { ...state, streak: null }] as const;
338 if (state.streak?.pid !== dead.pid) {
339 const started = { ...state, streak: { pid: dead.pid, since: now, order } };
340 return [{ order, after: Duration.millis(state.restartAfterMillis) }, started] as const;
341 }
342 if (now - state.streak.since < state.restartAfterMillis) return [null, state] as const;
343 // Checks can invalidate the streak while this request waits for the runtime's lock.
344 const streakOrder = state.streak.order;
345 const stillDead = Effect.gen(function* () {
346 if (!(yield* isLatest(order))) return false;
347 return (yield* Ref.get(lastHealthyOrder)) < streakOrder;
348 });
349 if (!(yield* runtime.restartConnector(dead.pid, stillDead))) {
350 return [null, state] as const;
351 }
352 const restarted = {
353 streak: null,
354 restartAfterMillis: Math.min(
355 state.restartAfterMillis * 2,
356 Duration.toMillis(DEAD_CONNECTOR_RESTART_AFTER_MAX),
357 ),
358 restartOrder: order,
359 };
360 return [null, restarted] as const;
361 }),
362 );
363 });
364​
365 const check: Effect.Effect<EnvironmentConnectReachability> = Effect.gen(function* () {
366 const order = yield* Ref.updateAndGet(checkCounter, (count) => count + 1);
367 const facts = yield* gatherFacts;
368 const result = classifyReachability(facts, DateTime.formatIso(yield* DateTime.now));
369 if (result.status === "reachable") {
370 yield* Ref.update(lastHealthyOrder, (healthy) => Math.max(healthy, order));
371 }
372 const previous = yield* Ref.modify(latestRef, (current) =>
373 Option.isSome(current) && current.value.order > order
374 ? [null, current]
375 : [current, Option.some({ order, result })],
376 );
377 if (previous === null) return result;
378 const started = yield* restartDeadConnector(facts, result, order);
379 // Nothing else would look again until the next periodic check.
380 if (started !== null) {
381 const confirm = SynchronizedRef.get(deadConnectorRef).pipe(
382 Effect.flatMap(({ streak }) =>
383 streak?.order === started.order ? Effect.suspend(() => check) : Effect.void,
384 ),
385 );
386 yield* Effect.sleep(started.after).pipe(Effect.andThen(confirm), Effect.forkIn(scope));
387 }
388 const changed = Option.match(previous, {
389 onNone: () => true,
390 onSome: ({ result: last }) =>
391 last.status !== result.status ||
392 (last.status === "unreachable" &&
393 result.status === "unreachable" &&
394 last.cause !== result.cause),
395 });
396 if (!changed || (result.status === "unreachable" && result.cause === "not_linked")) {
397 return result;
398 }
399 if (result.status === "unreachable") {
400 // A connector that has not connected yet is usually still starting; the
401 // runtime restarts it, and an unreachable edge is reported as its own cause.
402 const log = result.cause === "connector_not_ready" ? Effect.logWarning : Effect.logError;
403 yield* log(`\n${formatReachabilityFailure(result)}`).pipe(
404 Effect.annotateLogs({ cause: result.cause }),
405 );
406 } else {
407 yield* Effect.logInfo(
408 `T3 Connect is reachable from other devices. ${formatConnectReachable(result)}`,
409 );
410 }
411 return result;
412 }).pipe(Effect.withSpan("ConnectReachability.check"));
413​
414 yield* runtime.readinessChanged.pipe(
415 Stream.debounce(READINESS_CHANGE_DEBOUNCE),
416 Stream.runForEach(() => check),
417 Effect.forkScoped,
418 );
419 yield* Effect.sleep(RECHECK_INTERVAL).pipe(
420 Effect.andThen(check),
421 Effect.forever,
422 Effect.forkScoped,
423 );
424​
425 return ConnectReachability.of({
426 check,
427 latest: Ref.get(latestRef).pipe(Effect.map(Option.map(({ result }) => result))),
428 });
429});
430​
431export const layer = Layer.effect(ConnectReachability, make);