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

diagnosis.ts

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