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

dev-share.ts

170 lines5.7 KB

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