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

dev-share.ts

214 lines7.4 KB

1/** Vite proxies the backend, so only the web port needs a share mapping. */
2​
3import {
4 buildTailscaleHttpsBaseUrl,
5 disableTailscaleServe,
6 ensureTailscaleServe,
7 readTailscaleServeRootHolder,
8 readTailscaleStatus,
9 type TailscaleCommandError,
10 type TailscaleServeHttpsDisabledError,
11 type TailscaleStderrDiagnostic,
12} from "@t3tools/tailscale";
13import * as Effect from "effect/Effect";
14import * as Schema from "effect/Schema";
15import type { ChildProcessSpawner } from "effect/process";
16​
17/** Log fixed diagnostics; tailscale stderr can contain auth keys and node names. */
18const DIAGNOSTIC_EXPLANATIONS: Record<TailscaleStderrDiagnostic, string | undefined> = {
19 "no-existing-handler": "no mapping existed for that port",
20 "not-logged-in": "this machine is not logged into a tailnet — run `tailscale up`",
21 "not-running": "Tailscale is not running; start it and try again",
22 "permission-denied": "permission denied — `tailscale serve` may need elevated privileges",
23 "unsupported-target": "this Tailscale install can only proxy to localhost",
24 unknown: undefined,
25};
26​
27const explainCommandFailure = (
28 error: TailscaleCommandError | TailscaleServeHttpsDisabledError,
29): string | undefined =>
30 error._tag === "TailscaleServeHttpsDisabledError"
31 ? "HTTPS is not enabled on this tailnet — enable HTTPS certificates at https://login.tailscale.com/admin/dns"
32 : error._tag === "TailscaleCommandExitError" && error.stderrDiagnostic !== undefined
33 ? (DIAGNOSTIC_EXPLANATIONS[error.stderrDiagnostic] ?? "run the command by hand to see why")
34 : undefined;
35​
36export class TailscaleUnavailableError extends Schema.TaggedError<TailscaleUnavailableError>()(
37 "TailscaleUnavailableError",
38 { cause: Schema.Defect() },
39) {
40 override get message(): string {
41 return "could not talk to tailscale";
42 }
43​
44 get hint(): string {
45 return "Is Tailscale installed and tailscaled running? Try `tailscale status` — or drop --share and open the printed localhost URL.";
46 }
48​
49export class TailnetNameMissingError extends Schema.TaggedError<TailnetNameMissingError>()(
50 "TailnetNameMissingError",
51 {},
52) {
53 override get message(): string {
54 return "this machine has no tailnet DNS name";
55 }
56​
57 get hint(): string {
58 return "Run `tailscale up` and make sure MagicDNS is enabled.";
59 }
61​
62export class DevServeFailedError extends Schema.TaggedError<DevServeFailedError>()(
63 "DevServeFailedError",
64 {
65 stage: Schema.Literals(["read-existing", "clear-existing", "serve"]),
66 webPort: Schema.Number,
67 explanation: Schema.optional(Schema.String),
68 cause: Schema.optional(Schema.Defect()),
69 },
70) {
71 override get message(): string {
72 const port = String(this.webPort);
73 const base =
74 this.stage === "read-existing"
75 ? `could not read the existing mapping for port ${port}, so it was left alone`
76 : this.stage === "clear-existing"
77 ? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} --set-path=/ off\` and retry`
78 : `could not serve port ${port} on the tailnet (it is no longer served; any previous mapping for it was cleared before this attempt)`;
79 return this.explanation ? `${base}: ${this.explanation}` : base;
80 }
81​
82 get hint(): undefined {
83 return undefined;
84 }
86​
87export class DevServePortTakenError extends Schema.TaggedError<DevServePortTakenError>()(
88 "DevServePortTakenError",
89 { webPort: Schema.Number },
90) {
91 override get message(): string {
92 return `tailnet port ${String(this.webPort)} already serves another running server, so it was left alone`;
93 }
94​
95 get hint(): string {
96 return `Pick another port with T3CODE_PORT_OFFSET, or remove that mapping with \`tailscale serve --https=${String(this.webPort)} --set-path=/ off\` if nothing needs it.`;
97 }
99​
100export type DevShareError =
101 | TailscaleUnavailableError
102 | TailnetNameMissingError
103 | DevServeFailedError
104 | DevServePortTakenError;
105​
106/** Finalizer cleanup must be uninterruptible or cancellation can leave stale mappings. */
107export const unshareDevServer = (
108 webPort: number,
109): Effect.Effect<
110 {
111 readonly cleared: boolean;
112 readonly explanation?: string | undefined;
113 readonly cause?: TailscaleCommandError | undefined;
114 },
115 never,
116 ChildProcessSpawner.ChildProcessSpawner
117> =>
118 disableTailscaleServe({ servePort: webPort }).pipe(
119 Effect.as({ cleared: true } as const),
120 Effect.catch((error: TailscaleCommandError) =>
121 Effect.succeed(
122 error._tag === "TailscaleCommandExitError" &&
123 error.stderrDiagnostic === "no-existing-handler"
124 ? ({ cleared: true } as const)
125 : ({
126 cleared: false,
127 ...(explainCommandFailure(error) !== undefined
128 ? { explanation: explainCommandFailure(error) }
129 : {}),
130 cause: error,
131 } as const),
132 ),
133 ),
134 Effect.uninterruptible,
135 );
136​
137export interface DevShareResult {
138 readonly url: string;
139 readonly host: string;
141​
142/**
143 * Publishes `webPort` on the tailnet. The tailnet port always matches the web
144 * port so the URL is stable; `localTarget` points it at the backend instead
145 * when the backend serves a built client (`--built`).
146 */
147export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (input: {
148 readonly webPort: number;
149 readonly localTarget?: { readonly port: number; readonly host: string };
150}) {
151 const status = yield* readTailscaleStatus.pipe(
152 Effect.mapError((error) => new TailscaleUnavailableError({ cause: error })),
153 );
154 if (status.magicDnsName === null) {
155 return yield* new TailnetNameMissingError();
156 }
157​
158 const target = input.localTarget ?? { port: input.webPort, host: "localhost" };
159 // A mapping left by an earlier run, or one dialing a dead loopback port, is safe to replace.
160 const holder = yield* readTailscaleServeRootHolder(input.webPort, {
161 port: target.port,
162 host: target.host.replace(/^\[|\]$/gu, ""),
163 }).pipe(
164 Effect.mapError((error) => {
165 const explanation =
166 error._tag === "TailscaleStatusParseError" ? undefined : explainCommandFailure(error);
167 return new DevServeFailedError({
168 stage: "read-existing",
169 webPort: input.webPort,
170 ...(explanation !== undefined ? { explanation } : {}),
171 cause: error,
172 });
173 }),
174 );
175 if (holder === "other") {
176 return yield* new DevServePortTakenError({ webPort: input.webPort });
177 }
178​
179 const cleared = yield* unshareDevServer(input.webPort);
180 if (!cleared.cleared) {
181 // Refuse stale routes: the page could load while /ws and /api still point at a dead backend.
182 return yield* new DevServeFailedError({
183 stage: "clear-existing",
184 webPort: input.webPort,
185 ...(cleared.explanation !== undefined ? { explanation: cleared.explanation } : {}),
186 ...(cleared.cause !== undefined ? { cause: cleared.cause } : {}),
187 });
188 }
189​
190 // Vite's localhost can bind only ::1; a 127.0.0.1 proxy target would return 502.
191 yield* ensureTailscaleServe({
192 localPort: target.port,
193 servePort: input.webPort,
194 localHost: target.host,
195 }).pipe(
196 Effect.mapError((error) => {
197 const explanation = explainCommandFailure(error);
198 return new DevServeFailedError({
199 stage: "serve",
200 webPort: input.webPort,
201 ...(explanation !== undefined ? { explanation } : {}),
202 cause: error,
203 });
204 }),
205 );
206​
207 return {
208 url: buildTailscaleHttpsBaseUrl({
209 magicDnsName: status.magicDnsName,
210 servePort: input.webPort,
211 }),
212 host: status.magicDnsName,
213 } satisfies DevShareResult;
214});