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

diagnosis.ts

379 lines13.1 KB

1import {
2 t3ConnectTroubleshootingUrl,
3 type T3ConnectTroubleshootingSection,
4} from "@t3tools/contracts";
5import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
6import * as DateTime from "effect/DateTime";
7​
8import type {
9 ConnectionAttemptError,
10 ConnectionFailureCause,
11 ConnectionHop,
12 SupervisorConnectionState,
13} from "./model.ts";
14​
15export type ConnectionHopResult = "ok" | "failed" | "unchecked";
16​
17export interface ConnectionDiagnosisHop {
18 readonly hop: ConnectionHop;
19 readonly label: string;
20 readonly result: ConnectionHopResult;
22​
23export interface ConnectionDiagnosis {
24 /** Names the part that failed, e.g. "Mac mini's tunnel is offline". */
25 readonly headline: string;
26 readonly hops: ReadonlyArray<ConnectionDiagnosisHop>;
27 readonly steps: ReadonlyArray<string>;
28 readonly facts: ReadonlyArray<readonly [label: string, value: string]>;
29 /** The troubleshooting guide section for this failure. Null for direct routes, except a pending T3 Connect sign-in. */
30 readonly moreInfoUrl: string | null;
32​
33export interface ConnectionDiagnosisInput {
34 readonly hostLabel: string;
35 readonly state: SupervisorConnectionState;
36 /** The environment's usual route, used when the failure does not name one. */
37 readonly via: "relay" | "direct";
38 /** The relay's last health check, which can name a cause before any connect attempt. */
39 readonly relayStatus?: Pick<
40 RelayEnvironmentStatusResponse,
41 "status" | "endpointFailure" | "endpointStatus" | "offlineReason"
42 > | null;
43 readonly clientVersion?: string | undefined;
44 readonly serverVersion?: string | null | undefined;
46​
47interface Located {
48 readonly hop: ConnectionHop;
49 readonly cause:
50 | ConnectionFailureCause
51 | "offline"
52 | "outdated"
53 | "released"
54 | "session_pending"
55 | null;
56 /** The failure named no hop, so the hops before this one were never probed. */
57 readonly guessed?: true;
59​
60const NOT_ANSWERING: ReadonlySet<ConnectionFailureCause> = new Set([
61 "origin_unreachable",
62 "invalid_response",
63]);
64​
65function locate(input: ConnectionDiagnosisInput): Located | null {
66 const failure = input.state.lastFailure;
67 if (input.state.network === "offline" || input.state.phase === "offline") {
68 return { hop: "device", cause: "offline" };
69 }
70 if (failure?._tag === "ConnectionBlockedError" && failure.serverUpdateRequired) {
71 return { hop: "server", cause: "outdated" };
72 }
73 if (failure?.reason === "session-pending") {
74 return { hop: "device", cause: "session_pending" };
75 }
76 if (failure?.hop !== undefined) {
77 return { hop: failure.hop, cause: failure.failureCause ?? null };
78 }
79 if (failure !== null) {
80 const unreachable =
81 failure.reason === "network" ||
82 failure.reason === "timeout" ||
83 failure.reason === "transport";
84 const via = failure.via ?? input.via;
85 return {
86 hop: unreachable && via === "relay" ? "tunnel" : "server",
87 cause: null,
88 guessed: true,
89 };
90 }
91 const status = input.relayStatus;
92 if (status?.status !== "offline") return null;
93 if (status.offlineReason === "tunnel_released") return { hop: "tunnel", cause: "released" };
94 const cause = status.endpointFailure ?? null;
95 return { hop: cause !== null && NOT_ANSWERING.has(cause) ? "server" : "tunnel", cause };
97​
98function headline(host: string, located: Located, failure: ConnectionAttemptError | null): string {
99 switch (located.cause) {
100 case "offline":
101 return "This device is offline";
102 case "session_pending":
103 return "This device is still loading its T3 Connect sign-in";
104 case "outdated":
105 return `${host} runs an older T3 Code`;
106 case "clock_skew":
107 return "This device's clock is off";
108 case "not_linked":
109 return `${host} is not linked to your T3 Connect account`;
110 case "relay_error":
111 return "T3 Connect returned an error";
112 case "tunnel_pending":
113 return `${host}'s tunnel is still being set up`;
114 case "tunnel_not_enabled":
115 return `T3 Connect is not turned on for ${host}`;
116 case "released":
117 case "tunnel_down":
118 return `${host}'s tunnel is offline`;
119 case "origin_unreachable":
120 return `Tunnel works, but T3 Code on ${host} did not answer`;
121 case "invalid_response":
122 return `T3 Code on ${host} sent an unexpected answer`;
123 case "dns":
124 return `${host}'s tunnel address did not resolve`;
125 case "tls":
126 return `Secure connection to ${host}'s tunnel failed`;
127 case "refused":
128 return `${host}'s tunnel refused the connection`;
129 case "timeout":
130 return `${host} did not answer in time`;
131 case "unknown":
132 case null:
133 break;
134 }
135 switch (located.hop) {
136 case "device":
137 return "This device could not prepare the connection";
138 case "relay":
139 return failure?.reason === "authentication"
140 ? "T3 Connect did not accept this device's sign-in"
141 : "This device can't reach T3 Connect";
142 case "tunnel":
143 // The relay already reached the host when this device fails on its own.
144 return failure?.reason === "network" ||
145 failure?.reason === "transport" ||
146 failure?.reason === "timeout"
147 ? `This device can't reach ${host}'s tunnel`
148 : `T3 Connect could not reach ${host}'s tunnel`;
149 case "server":
150 return failure?.reason === "authentication" || failure?.reason === "permission"
151 ? `T3 Code on ${host} did not accept this device`
152 : `T3 Code on ${host} did not answer`;
153 }
155​
156function steps(host: string, located: Located, failure: ConnectionAttemptError | null): string[] {
157 const checkHost = `On ${host}, check Settings > Sharing & access or run \`t3 connect status\`.`;
158 switch (located.cause) {
159 case "offline":
160 return ["Connect this device to the internet. T3 Code reconnects on its own."];
161 case "session_pending":
162 return [
163 "Wait a moment. T3 Code retries on its own.",
164 "If it keeps waiting, reload or restart T3 Code on this device.",
165 ];
166 case "outdated":
167 return [`Update T3 Code on ${host}.`];
168 case "clock_skew":
169 return [`Turn on automatic date and time on this device and on ${host}, then retry.`];
170 case "not_linked":
171 return [
172 "Check that this device is signed in to the same T3 Connect account as the host.",
173 `On ${host}, open Settings > Sharing & access and turn T3 Connect on.`,
174 ];
175 case "tunnel_pending":
176 return ["Wait a minute. T3 Code retries on its own.", checkHost];
177 case "relay_error":
178 return [
179 "Wait a few minutes. T3 Code retries on its own.",
180 "If it keeps failing, copy the diagnostics and report it.",
181 ];
182 case "tunnel_not_enabled":
183 return [`On ${host}, open Settings > Sharing & access and turn T3 Connect on.`];
184 case "released":
185 case "tunnel_down":
186 return [
187 `Make sure ${host} is awake and T3 Code is running on it.`,
188 checkHost,
189 `A VPN or Tailscale exit node on ${host} can block the tunnel (port 7844). Turn it off or allow the tunnel.`,
190 ];
191 case "origin_unreachable":
192 case "invalid_response":
193 return [`Open or restart T3 Code on ${host}.`, checkHost];
194 // The relay saw these on its way to the host, so the fix is on the host.
195 case "dns":
196 case "tls":
197 case "refused":
198 case "timeout":
199 case "unknown":
200 return [`Make sure ${host} is awake and online.`, checkHost];
201 case null:
202 break;
203 }
204 switch (located.hop) {
205 case "device":
206 return [
207 "Restart T3 Code on this device.",
208 `If it keeps failing, remove ${host} from this device and add it again.`,
209 ];
210 case "relay":
211 return failure?.reason === "authentication"
212 ? ["Sign out of T3 Connect and sign in again."]
213 : [
214 "Check this device's internet connection.",
215 "A VPN, firewall, or ad blocker on this device can block T3 Connect.",
216 ];
217 case "tunnel":
218 return failure?.reason === "network" ||
219 failure?.reason === "transport" ||
220 failure?.reason === "timeout"
221 ? [
222 "A VPN, firewall, or DNS filter on this device can block the tunnel.",
223 "Try another network, or add a direct route such as a Tailscale address.",
224 ]
225 : [`Make sure ${host} is awake and online.`, checkHost];
226 case "server":
227 return [
228 `Make sure T3 Code is running on ${host}.`,
229 "Retry. If it keeps failing, copy the diagnostics.",
230 ];
231 }
233​
234function helpSection(
235 located: Located,
236 failure: ConnectionAttemptError | null,
237): T3ConnectTroubleshootingSection {
238 switch (located.cause) {
239 case "offline":
240 return "this-device-cant-reach-t3-connect";
241 case "outdated":
242 return "the-host-runs-an-older-t3-code";
243 case "clock_skew":
244 return "the-clock-is-off";
245 case "session_pending":
246 case "not_linked":
247 case "tunnel_not_enabled":
248 return "sign-in-account-or-link-problems";
249 case "relay_error":
250 return "t3-connect-returned-an-error";
251 case "released":
252 case "tunnel_down":
253 case "tunnel_pending":
254 return "the-hosts-tunnel-is-offline";
255 case "origin_unreachable":
256 case "invalid_response":
257 return "the-tunnel-works-but-t3-code-does-not-answer";
258 case "dns":
259 case "tls":
260 case "refused":
261 case "timeout":
262 case "unknown":
263 return "the-t3-connect-address-does-not-resolve-or-answer";
264 case null:
265 break;
266 }
267 const onThisDevice =
268 failure?.reason === "network" ||
269 failure?.reason === "transport" ||
270 failure?.reason === "timeout";
271 switch (located.hop) {
272 case "device":
273 return "this-device-cant-reach-t3-connect";
274 case "relay":
275 return failure?.reason === "authentication"
276 ? "sign-in-account-or-link-problems"
277 : "this-device-cant-reach-t3-connect";
278 case "tunnel":
279 return onThisDevice ? "this-device-cant-reach-t3-connect" : "the-hosts-tunnel-is-offline";
280 case "server":
281 return failure?.reason === "authentication" || failure?.reason === "permission"
282 ? "sign-in-account-or-link-problems"
283 : "the-tunnel-works-but-t3-code-does-not-answer";
284 }
286​
287const HOP_ORDER = {
288 relay: ["device", "relay", "tunnel", "server"],
289 direct: ["device", "server"],
290} as const;
291​
292function hopLabel(hop: ConnectionHop, host: string): string {
293 switch (hop) {
294 case "device":
295 return "This device";
296 case "relay":
297 return "T3 Connect";
298 case "tunnel":
299 return `${host} tunnel`;
300 case "server":
301 return `T3 Code on ${host}`;
302 }
304​
305/**
306 * Turns a connection state into what failed, in order, and what to try. Returns
307 * null when nothing has failed. Web and mobile render this same model.
308 */
309export function presentConnectionDiagnosis(
310 input: ConnectionDiagnosisInput,
311): ConnectionDiagnosis | null {
312 const located = locate(input);
313 if (located === null) return null;
314 const host = input.hostLabel;
315 const failure = input.state.lastFailure;
316 const relayPath =
317 located.hop === "relay" ||
318 located.hop === "tunnel" ||
319 (failure === null && input.relayStatus?.status === "offline") ||
320 (failure?.via ?? input.via) === "relay";
321 const order: ReadonlyArray<ConnectionHop> = HOP_ORDER[relayPath ? "relay" : "direct"];
322 const failedIndex = order.indexOf(located.hop);
323 const hops = order.map((hop, index): ConnectionDiagnosisHop => ({
324 hop,
325 label: hopLabel(hop, host),
326 result:
327 index === failedIndex
328 ? "failed"
329 : index < failedIndex && located.guessed !== true
330 ? "ok"
331 : "unchecked",
332 }));
333​
334 // The relay health check only explains the state when no attempt has failed yet.
335 const httpStatus = failure !== null ? failure.httpStatus : input.relayStatus?.endpointStatus;
336 const facts: Array<readonly [string, string]> = [];
337 const add = (label: string, value: string | number | null | undefined) => {
338 if (value !== null && value !== undefined && value !== "") facts.push([label, String(value)]);
339 };
340 add("Cause", located.cause ?? failure?.reason);
341 add("HTTP status", httpStatus);
342 add("Attempts", input.state.attempt > 0 ? input.state.attempt : null);
343 add(
344 "Next retry",
345 input.state.retryAt === null
346 ? null
347 : DateTime.formatIso(DateTime.makeUnsafe(input.state.retryAt)),
348 );
349 add("Route", relayPath ? "T3 Connect" : "Direct");
350 add("App version", input.clientVersion);
351 add("Host version", input.serverVersion);
352 add("Error", failure?.detail);
353 add("Trace ID", failure?.traceId);
354​
355 return {
356 headline: headline(host, located, failure),
357 hops,
358 steps: steps(host, located, failure),
359 facts,
360 moreInfoUrl:
361 relayPath || located.cause === "session_pending"
362 ? t3ConnectTroubleshootingUrl(helpSection(located, failure))
363 : null,
364 };
366​
367const HOP_MARK = { ok: "ok", failed: "FAILED", unchecked: "not checked" } as const;
368​
369/** One plain-text block for bug reports. */
370export function connectionDiagnosisText(hostLabel: string, diagnosis: ConnectionDiagnosis): string {
371 return [
372 `T3 Code connection to ${hostLabel}: ${diagnosis.headline}`,
373 "",
374 ...diagnosis.hops.map((hop) => `${hop.label}: ${HOP_MARK[hop.result]}`),
375 "",
376 ...diagnosis.facts.map(([label, value]) => `${label}: ${value}`),
377 ...(diagnosis.moreInfoUrl ? ["", `More info: ${diagnosis.moreInfoUrl}`] : []),
378 ].join("\n");