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

ConnectReachability.ts

537 lines21.9 KB

1import * as NodeNet from "node:net";
2​
3import {
4 connectReachabilityHelpUrl,
5 type EnvironmentConnectReachability,
6 formatConnectReachable,
7} from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import { SpawnExecutableResolution } from "@t3tools/shared/shell";
10import { readTailscaleExitNode, type TailscaleExitNode } from "@t3tools/tailscale";
11import * as Clock from "effect/Clock";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Ref from "effect/Ref";
19import * as Scope from "effect/Scope";
20import * as Stream from "effect/Stream";
21import * as SynchronizedRef from "effect/SynchronizedRef";
22import * as Schema from "effect/Schema";
23import { HttpClient, HttpClientResponse } from "effect/http";
24import { ChildProcessSpawner } from "effect/process";
25​
26import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
27import { CLOUD_ENDPOINT_RUNTIME_CONFIG } from "./config.ts";
28import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
29​
30// cloudflared finds the edge through the SRV record `_v2-origintunneld._tcp.argotunnel.com`,
31// which names these two hosts on port 7844. QUIC and HTTP/2 both use that port.
32const TUNNEL_EDGE_HOSTS = ["region1.v2.argotunnel.com", "region2.v2.argotunnel.com"];
33const TUNNEL_EDGE_PORT = 7844;
34const EDGE_CONNECT_TIMEOUT = Duration.seconds(5);
35const ENDPOINT_REQUEST_TIMEOUT = Duration.seconds(10);
36const ERROR_BODY_READ_TIMEOUT = Duration.seconds(2);
37// An IP literal, so the answer does not come from this machine's DNS, over HTTPS because
38// some networks intercept port 53.
39const PUBLIC_DNS_OVER_HTTPS = "https://1.1.1.1/dns-query";
40const PUBLIC_DNS_TIMEOUT = Duration.seconds(5);
41// cloudflared registers several connections within a few seconds; they are one change.
42const READINESS_CHANGE_DEBOUNCE = Duration.seconds(3);
43// Readiness changes miss failures and recoveries past cloudflared (DNS, origin, edge errors).
44const RECHECK_INTERVAL = Duration.minutes(5);
45// cloudflared can keep reporting ready connections the edge already dropped, so its
46// own readiness watch never restarts it. A 530 can also be brief, so restart only once it
47// lasts, and wait longer after each restart that did not help.
48const DEAD_CONNECTOR_RESTART_AFTER = Duration.minutes(2);
49const DEAD_CONNECTOR_RESTART_AFTER_MAX = Duration.hours(1);
50​
51export type EndpointProbe =
52 | { readonly kind: "status"; readonly status: number; readonly cloudflareError?: string }
53 | {
54 readonly kind: "dns_failed";
55 /** Whether public DNS has the name; absent when it could not be asked. */
56 readonly existsPublicly?: boolean;
57 }
58 | { readonly kind: "timeout" | "network_error" };
59​
60/** Everything one check learned. `null` means that step did not run. */
61export interface ReachabilityFacts {
62 readonly managedTunnelConfigured: boolean;
63 readonly connector: ManagedEndpointRuntime.ConnectorFacts | null;
64 readonly endpoint: EndpointProbe | null;
65 readonly edgeReachable: boolean | null;
66 readonly exitNode: TailscaleExitNode | null;
68​
69type Unreachable = Extract<EnvironmentConnectReachability, { status: "unreachable" }>;
70​
71function exitNodeHint(exitNode: TailscaleExitNode | null): string | null {
72 if (!exitNode) return null;
73 const name = exitNode.name ? ` "${exitNode.name}"` : "";
74 return `Tailscale exit node${name} is on. Traffic to Cloudflare goes through it.`;
76​
77/** Turns what one check learned into the answer every surface shows. */
78export function classifyReachability(
79 facts: ReachabilityFacts,
80 checkedAt: string,
81): EnvironmentConnectReachability {
82 const { connector, endpoint, exitNode } = facts;
83 const fail = (
84 cause: Unreachable["cause"],
85 reason: string,
86 fix: string,
87 hint: string | null = null,
88 ): Unreachable => ({ status: "unreachable", checkedAt, cause, reason, hint, fix });
89 const restart = "Restart T3 Code. If it stays, run `t3 connect` again.";
90​
91 if (!facts.managedTunnelConfigured) {
92 // A running server reads the link `t3 connect` stores only at startup.
93 return fail(
94 "not_linked",
95 "The server has not set up a T3 Connect tunnel.",
96 "Run `t3 connect`, then restart T3 Code so it applies the link.",
97 );
98 }
99 if (connector === null) {
100 return fail(
101 "connector_not_running",
102 "The tunnel client (cloudflared) is not running.",
103 "Restart T3 Code. If it stays down, check the server log for relay client errors.",
104 );
105 }
106 const status = endpoint?.kind === "status" ? endpoint.status : null;
107 if (status === 200) {
108 return {
109 status: "reachable",
110 checkedAt,
111 readyConnections: connector.readyConnections,
112 protocol: connector.protocol,
113 };
114 }
115 // The edge test is TCP only. With QUIC connections up, a 502 from a working tunnel, or
116 // DNS already failing, a failed TCP test would hide the real cause.
117 if (
118 facts.edgeReachable === false &&
119 status !== 502 &&
120 !(connector.readyConnections && connector.readyConnections > 0) &&
121 endpoint?.kind !== "dns_failed"
122 ) {
123 return fail(
124 "edge_unreachable",
125 `Cloudflare's tunnel port (${TUNNEL_EDGE_PORT}) times out from this machine.`,
126 exitNode
127 ? `tailscale set --exit-node= (or allow outbound ${TUNNEL_EDGE_PORT} on that network)`
128 : `Allow outbound TCP and UDP port ${TUNNEL_EDGE_PORT}, or turn off the VPN or firewall that blocks it.`,
129 exitNodeHint(exitNode) ?? "A VPN, proxy, or firewall may block it.",
130 );
131 }
132 if (status === 502) {
133 return fail(
134 "origin_unreachable",
135 "The tunnel is up, but it cannot reach the T3 server on this machine.",
136 "Restart T3 Code so the tunnel uses the port the server listens on.",
137 );
138 }
139 if (endpoint === null || connector.readyConnections === 0) {
140 return fail(
141 "connector_not_ready",
142 "cloudflared has not connected to Cloudflare yet.",
143 "Wait a minute. If it stays, check the network and the server log.",
144 );
145 }
146 const cloudflareError = endpoint.kind === "status" ? endpoint.cloudflareError : undefined;
147 // Cloudflare answers 530 with error 1033 when the tunnel has no live connector. Other
148 // codes, such as 1016 for a broken DNS record, are not fixed by restarting cloudflared.
149 if (status === 530 && (cloudflareError === undefined || cloudflareError === "1033")) {
150 return fail(
151 "no_connector",
152 "Cloudflare has no live connection from this machine for the tunnel.",
153 restart,
154 );
155 }
156 if (status === 530 && cloudflareError === "1016") {
157 return fail(
158 "dns_failed",
159 "The T3 Connect address no longer points to this machine's tunnel (Cloudflare error 1016). T3 Connect may have removed this environment.",
160 "Link this environment again. Turn T3 Connect off and on in Settings > Sharing & access, or run `t3 connect link` and then restart T3 Code.",
161 );
162 }
163 if (status !== null) {
164 const code = cloudflareError === undefined ? "" : ` (Cloudflare error ${cloudflareError})`;
165 return fail(
166 "unexpected_response",
167 `The T3 Connect address answered with HTTP ${status}${code}.`,
168 restart,
169 );
170 }
171 if (endpoint.kind === "dns_failed") {
172 // A lookup made before the relay published the record leaves a cached "not found"
173 // for the zone's negative TTL (30 minutes).
174 if (endpoint.existsPublicly === true) {
175 return fail(
176 "dns_failed",
177 "The T3 Connect address resolves in public DNS, but this network's DNS still has an old cached answer that it does not exist.",
178 "Wait. The cached answer usually clears within about 30 minutes.",
179 exitNodeHint(exitNode),
180 );
181 }
182 if (endpoint.existsPublicly === false) {
183 return fail(
184 "dns_failed",
185 "The T3 Connect address is missing from public DNS. The relay did not publish it.",
186 restart,
187 );
188 }
189 return fail(
190 "dns_failed",
191 "The T3 Connect address does not resolve from this machine.",
192 "Check the DNS settings on this machine or its VPN.",
193 exitNodeHint(exitNode),
194 );
195 }
196 return fail(
197 "timeout",
198 "The T3 Connect address did not answer from this machine.",
199 "Check the network, VPN, or proxy on this machine.",
200 exitNodeHint(exitNode),
201 );
203​
204/** The loud diagnosis the CLI prints and the server logs. */
205export function formatReachabilityFailure(result: Unreachable): string {
206 return [
207 "✕ T3 Connect is NOT reachable from other devices",
208 ` ${result.reason}`,
209 ...(result.hint ? [` ${result.hint}`] : []),
210 ` Fix: ${result.fix}`,
211 ` More info: ${connectReachabilityHelpUrl(result.cause)}`,
212 ].join("\n");
214​
215/** The code of a failed name lookup, or null. getaddrinfo reports more than the DNS codes, such as EBUSY. */
216function dnsLookupErrorCode(error: unknown): string | null {
217 let current = error;
218 for (let depth = 0; depth < 6 && typeof current === "object" && current !== null; depth++) {
219 const code = "code" in current && typeof current.code === "string" ? current.code : "";
220 if (("syscall" in current && current.syscall === "getaddrinfo") || DNS_ERROR_CODES.has(code)) {
221 return code;
222 }
223 current = "cause" in current ? current.cause : undefined;
224 }
225 return null;
227​
228const DNS_ERROR_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_NONAME"]);
229// Answers that the name does not exist, which a resolver may have cached. EAI_AGAIN means
230// the resolver did not answer. glibc behind systemd-resolved can report NXDOMAIN as EBUSY.
231const NOT_FOUND_CODES = new Set(["ENOTFOUND", "EAI_NONAME", "EBUSY"]);
232​
233const DnsJsonAnswer = Schema.Struct({ Status: Schema.Number });
234​
235const canOpenTcp = (host: string, port: number) =>
236 Effect.callback<boolean>((resume) => {
237 const socket = NodeNet.connect({ host, port });
238 const finish = (connected: boolean) => {
239 socket.destroy();
240 resume(Effect.succeed(connected));
241 };
242 socket.setTimeout(Duration.toMillis(EDGE_CONNECT_TIMEOUT), () => finish(false));
243 socket.once("connect", () => finish(true));
244 socket.once("error", () => finish(false));
245 return Effect.sync(() => socket.destroy());
246 });
247​
248export class ConnectReachability extends Context.Service<
249 ConnectReachability,
250 {
251 /** Runs a check now. The server also runs one when the tunnel's readiness changes. */
252 readonly check: Effect.Effect<EnvironmentConnectReachability>;
253 readonly latest: Effect.Effect<Option.Option<EnvironmentConnectReachability>>;
254 }
255>()("t3/cloud/ConnectReachability") {}
256​
257const make = Effect.gen(function* () {
258 const runtime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime;
259 const secrets = yield* ServerSecretStore.ServerSecretStore;
260 const httpClient = yield* HttpClient.HttpClient;
261 // `order` ranks checks by start, so a slow older one cannot replace a newer result.
262 const latestRef = yield* Ref.make(
263 Option.none<{ readonly order: number; readonly result: EnvironmentConnectReachability }>(),
264 );
265 const checkCounter = yield* Ref.make(0);
266 // Checks update this as they finish, even when a newer check already did. A dead streak
267 // or a restart backoff that began before a healthy check no longer counts.
268 const lastHealthyOrder = yield* Ref.make(0);
269 const deadConnectorRef = yield* SynchronizedRef.make<{
270 readonly streak: {
271 readonly pid: number;
272 readonly since: number;
273 readonly order: number;
274 } | null;
275 readonly restartAfterMillis: number;
276 readonly restartOrder: number;
277 }>({
278 streak: null,
279 restartAfterMillis: Duration.toMillis(DEAD_CONNECTOR_RESTART_AFTER),
280 restartOrder: 0,
281 });
282 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
283 const hostPlatform = yield* HostProcess.Platform;
284 const hostEnv = yield* HostProcess.Environment;
285 const resolveExecutable = yield* SpawnExecutableResolution;
286 const scope = yield* Scope.Scope;
287 // Looks up the command readTailscaleExitNode runs, so a machine without Tailscale does not
288 // log a failed spawn on every unreachable check.
289 const hasTailscaleCli = Effect.promise(async () => {
290 const command = hostPlatform === "win32" ? "tailscale.exe" : "tailscale";
291 try {
292 return (await resolveExecutable(command, hostPlatform, hostEnv)) !== undefined;
293 } catch {
294 return false;
295 }
296 });
297 const readExitNode = Effect.flatMap(hasTailscaleCli, (available) =>
298 available
299 ? readTailscaleExitNode.pipe(
300 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
301 Effect.provideService(HostProcess.Platform, hostPlatform),
302 Effect.orElseSucceed(() => null),
303 )
304 : Effect.succeed(null),
305 );
306​
307 // DNS JSON status 0 is NOERROR (the name exists, even with no A record) and 3 is NXDOMAIN.
308 const existsInPublicDns = Effect.fn("ConnectReachability.existsInPublicDns")(
309 function* (hostname: string) {
310 const response = yield* httpClient.get(PUBLIC_DNS_OVER_HTTPS, {
311 urlParams: { name: hostname, type: "A" },
312 headers: { accept: "application/dns-json" },
313 });
314 const { Status } = yield* HttpClientResponse.schemaBodyJson(DnsJsonAnswer)(response);
315 return Status === 0 ? true : Status === 3 ? false : null;
316 },
317 Effect.scoped,
318 Effect.timeoutOption(PUBLIC_DNS_TIMEOUT),
319 Effect.map(Option.getOrNull),
320 Effect.orElseSucceed(() => null),
321 );
322​
323 const probeEndpoint = Effect.fn("ConnectReachability.probeEndpoint")(
324 function* (hostname: string) {
325 const response = yield* httpClient
326 .get(`https://${hostname}/.well-known/t3/environment`, { acceptJson: true })
327 .pipe(Effect.timeoutOption(ENDPOINT_REQUEST_TIMEOUT));
328 if (Option.isNone(response)) return { kind: "timeout" } satisfies EndpointProbe;
329 const { status } = response.value;
330 if (status !== 530) return { kind: "status", status } satisfies EndpointProbe;
331 // Cloudflare's error page is HTML unless the client accepts JSON, which carries
332 // `"error_code":1033`. Clients that send no User-Agent get `error code: 1033`.
333 const body = yield* response.value.text.pipe(
334 Effect.timeoutOption(ERROR_BODY_READ_TIMEOUT),
335 Effect.orElseSucceed(() => Option.none<string>()),
336 );
337 const code = /error[_ ]code"?:\s*(\d{4})/i.exec(Option.getOrElse(body, () => ""))?.[1];
338 return (
339 code === undefined
340 ? { kind: "status", status }
341 : { kind: "status", status, cloudflareError: code }
342 ) satisfies EndpointProbe;
343 },
344 Effect.scoped,
345 (effect, hostname) =>
346 effect.pipe(
347 Effect.catch((error) => {
348 const code = dnsLookupErrorCode(error);
349 if (code === null) return Effect.succeed<EndpointProbe>({ kind: "network_error" });
350 if (!NOT_FOUND_CODES.has(code))
351 return Effect.succeed<EndpointProbe>({ kind: "dns_failed" });
352 return existsInPublicDns(hostname).pipe(
353 Effect.map((existsPublicly): EndpointProbe =>
354 existsPublicly === null
355 ? { kind: "dns_failed" }
356 : { kind: "dns_failed", existsPublicly },
357 ),
358 );
359 }),
360 ),
361 );
362​
363 const gatherFacts = Effect.gen(function* () {
364 const managedTunnelConfigured = Option.isSome(
365 yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG).pipe(Effect.orElseSucceed(Option.none)),
366 );
367 const connector = managedTunnelConfigured ? yield* runtime.inspectConnector : null;
368 const endpoint =
369 connector?.hostname && connector.readyConnections !== 0
370 ? yield* probeEndpoint(connector.hostname)
371 : null;
372 const facts: ReachabilityFacts = {
373 managedTunnelConfigured,
374 connector,
375 endpoint,
376 edgeReachable: null,
377 exitNode: null,
378 };
379 if (connector === null || (endpoint?.kind === "status" && endpoint.status === 200)) {
380 return facts;
381 }
382 // Run only the probes classifyReachability can use for this endpoint result.
383 const status = endpoint?.kind === "status" ? endpoint.status : null;
384 const needsEdgeProbe =
385 status !== 502 && (connector.readyConnections ?? 0) === 0 && endpoint?.kind !== "dns_failed";
386 const endpointUsesExitNode =
387 endpoint?.kind === "timeout" ||
388 endpoint?.kind === "network_error" ||
389 (endpoint?.kind === "dns_failed" && endpoint.existsPublicly !== false);
390 const probeEdge = Effect.forEach(
391 TUNNEL_EDGE_HOSTS,
392 (host) => canOpenTcp(host, TUNNEL_EDGE_PORT),
393 { concurrency: "unbounded" },
394 ).pipe(Effect.map((results) => results.some(Boolean)));
395 const [edgeReachable, exitNode] = yield* Effect.all(
396 [
397 needsEdgeProbe ? probeEdge : Effect.succeed(null),
398 endpointUsesExitNode ? readExitNode : Effect.succeed(null),
399 ],
400 { concurrency: 2 },
401 );
402 return {
403 ...facts,
404 edgeReachable,
405 // An unreachable edge names the exit node in its fix.
406 exitNode: endpointUsesExitNode || edgeReachable !== false ? exitNode : yield* readExitNode,
407 };
408 });
409​
410 const isLatest = (order: number) =>
411 Ref.get(latestRef).pipe(
412 Effect.map((latest) => Option.isNone(latest) || latest.value.order <= order),
413 );
414​
415 // Runs inside the check span; the runtime restart has its own. Returns the streak a dead
416 // connector just started and when to confirm it.
417 const restartDeadConnector = Effect.fnUntraced(function* (
418 facts: ReachabilityFacts,
419 result: EnvironmentConnectReachability,
420 order: number,
421 ) {
422 const now = yield* Clock.currentTimeMillis;
423 const { connector } = facts;
424 const dead =
425 result.status === "unreachable" &&
426 result.cause === "no_connector" &&
427 connector !== null &&
428 (connector.readyConnections ?? 0) > 0
429 ? connector
430 : null;
431 return yield* SynchronizedRef.modifyEffect(deadConnectorRef, (current) =>
432 Effect.gen(function* () {
433 const healthy = yield* Ref.get(lastHealthyOrder);
434 const state = {
435 streak: current.streak && current.streak.order > healthy ? current.streak : null,
436 restartAfterMillis:
437 current.restartOrder > healthy
438 ? current.restartAfterMillis
439 : Duration.toMillis(DEAD_CONNECTOR_RESTART_AFTER),
440 restartOrder: current.restartOrder,
441 };
442 if (!(yield* isLatest(order))) return [null, state] as const;
443 if (dead === null) return [null, { ...state, streak: null }] as const;
444 if (state.streak?.pid !== dead.pid) {
445 const started = { ...state, streak: { pid: dead.pid, since: now, order } };
446 return [{ order, after: Duration.millis(state.restartAfterMillis) }, started] as const;
447 }
448 if (now - state.streak.since < state.restartAfterMillis) return [null, state] as const;
449 // Checks can invalidate the streak while this request waits for the runtime's lock.
450 const streakOrder = state.streak.order;
451 const stillDead = Effect.gen(function* () {
452 if (!(yield* isLatest(order))) return false;
453 return (yield* Ref.get(lastHealthyOrder)) < streakOrder;
454 });
455 if (!(yield* runtime.restartConnector(dead.pid, stillDead))) {
456 return [null, state] as const;
457 }
458 const restarted = {
459 streak: null,
460 restartAfterMillis: Math.min(
461 state.restartAfterMillis * 2,
462 Duration.toMillis(DEAD_CONNECTOR_RESTART_AFTER_MAX),
463 ),
464 restartOrder: order,
465 };
466 return [null, restarted] as const;
467 }),
468 );
469 });
470​
471 const check: Effect.Effect<EnvironmentConnectReachability> = Effect.gen(function* () {
472 const order = yield* Ref.updateAndGet(checkCounter, (count) => count + 1);
473 const facts = yield* gatherFacts;
474 const result = classifyReachability(facts, DateTime.formatIso(yield* DateTime.now));
475 if (result.status === "reachable") {
476 yield* Ref.update(lastHealthyOrder, (healthy) => Math.max(healthy, order));
477 }
478 const previous = yield* Ref.modify(latestRef, (current) =>
479 Option.isSome(current) && current.value.order > order
480 ? [null, current]
481 : [current, Option.some({ order, result })],
482 );
483 if (previous === null) return result;
484 const started = yield* restartDeadConnector(facts, result, order);
485 // Nothing else would look again until the next periodic check.
486 if (started !== null) {
487 const confirm = SynchronizedRef.get(deadConnectorRef).pipe(
488 Effect.flatMap(({ streak }) =>
489 streak?.order === started.order ? Effect.suspend(() => check) : Effect.void,
490 ),
491 );
492 yield* Effect.sleep(started.after).pipe(Effect.andThen(confirm), Effect.forkIn(scope));
493 }
494 const changed = Option.match(previous, {
495 onNone: () => true,
496 onSome: ({ result: last }) =>
497 last.status !== result.status ||
498 (last.status === "unreachable" &&
499 result.status === "unreachable" &&
500 last.cause !== result.cause),
501 });
502 if (!changed || (result.status === "unreachable" && result.cause === "not_linked")) {
503 return result;
504 }
505 if (result.status === "unreachable") {
506 // A connector that has not connected yet is usually still starting; the
507 // runtime restarts it, and an unreachable edge is reported as its own cause.
508 const log = result.cause === "connector_not_ready" ? Effect.logWarning : Effect.logError;
509 yield* log(`\n${formatReachabilityFailure(result)}`).pipe(
510 Effect.annotateLogs({ cause: result.cause }),
511 );
512 } else {
513 yield* Effect.logInfo(
514 `T3 Connect is reachable from other devices. ${formatConnectReachable(result)}`,
515 );
516 }
517 return result;
518 }).pipe(Effect.withSpan("ConnectReachability.check"));
519​
520 yield* runtime.readinessChanged.pipe(
521 Stream.debounce(READINESS_CHANGE_DEBOUNCE),
522 Stream.runForEach(() => check),
523 Effect.forkScoped,
524 );
525 yield* Effect.sleep(RECHECK_INTERVAL).pipe(
526 Effect.andThen(check),
527 Effect.forever,
528 Effect.forkScoped,
529 );
530​
531 return ConnectReachability.of({
532 check,
533 latest: Ref.get(latestRef).pipe(Effect.map(Option.map(({ result }) => result))),
534 });
535});
536​
537export const layer = Layer.effect(ConnectReachability, make);