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