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

tailscaleServe.ts

139 lines5.0 KB

1/**
2 * Ownership rules for the Tailscale Serve mapping a server publishes.
3 *
4 * The mapping is tailnet-wide state keyed only by HTTPS port, so every server
5 * that starts with `tailscaleServeEnabled` competes for the same slot — a
6 * second desktop instance lands on the next free backend port and would
7 * otherwise repoint the tailnet URL away from the healthy first one. The rule
8 * is therefore: claim the mapping when it is free, ours, or stale, and never
9 * when it still reaches a live server.
10 */
11import {
12 disableTailscaleServe,
13 ensureTailscaleServe,
14 readTailscaleServeTarget,
15 type TailscaleServeTarget,
16} from "@t3tools/tailscale";
17import * as Effect from "effect/Effect";
18import { HttpClient } from "effect/unstable/http";
19import { ChildProcessSpawner } from "effect/unstable/process";
20​
21import { probeEnvironmentDescriptor } from "./environmentProbe.ts";
22import { formatHostForUrl, isLoopbackHost } from "./startupAccess.ts";
23​
24/** A mapping this server wrote, and is therefore allowed to remove again. */
25export interface OwnedTailscaleServeMapping {
26 readonly servePort: number;
27 readonly localPort: number;
29​
30// The server always publishes itself on loopback, so a loopback target on our
31// port is our own mapping - persisted by tailscale across a restart, or just
32// written by us.
33const isOwnMapping = (target: TailscaleServeTarget, localPort: number): boolean =>
34 target.localPort === localPort && isLoopbackHost(target.localHost);
35​
36const targetOrigin = (target: TailscaleServeTarget): string =>
37 `http://${formatHostForUrl(target.localHost)}:${String(target.localPort)}`;
38​
39/**
40 * Points the serve mapping at this server unless something live already holds
41 * it. Returns the mapping to remove on shutdown, or null when this server does
42 * not own one.
43 */
44export const acquireTailscaleServe = Effect.fn("server.tailscaleServe.acquire")(function* (input: {
45 readonly localPort: number;
46 readonly servePort: number;
47}): Effect.fn.Return<
48 OwnedTailscaleServeMapping | null,
49 never,
50 ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
51> {
52 const { localPort, servePort } = input;
53 const existing = yield* readTailscaleServeTarget({ servePort }).pipe(
54 // An unreadable mapping is treated as unclaimed, which is what this did
55 // before there was a check at all.
56 Effect.catch((cause) =>
57 Effect.logWarning("Could not read the Tailscale Serve mapping; treating it as unclaimed", {
58 cause,
59 servePort,
60 }).pipe(Effect.as(null)),
61 ),
62 );
63​
64 if (existing !== null) {
65 if (isOwnMapping(existing, localPort)) {
66 yield* Effect.logInfo("Tailscale Serve already maps to this server", {
67 localPort,
68 servePort,
69 });
70 return { localPort, servePort };
71 }
72 const occupant = yield* probeEnvironmentDescriptor(targetOrigin(existing));
73 if (occupant._tag !== "unreachable") {
74 yield* Effect.logWarning(
75 "Tailscale Serve already fronts a live server on another port; leaving it in place",
76 {
77 localPort,
78 servePort,
79 existingLocalPort: existing.localPort,
80 ...(occupant._tag === "descriptor"
81 ? { existingEnvironmentId: occupant.descriptor.environmentId }
82 : {}),
83 },
84 );
85 return null;
86 }
87 yield* Effect.logInfo("Reclaiming a Tailscale Serve mapping whose target is gone", {
88 localPort,
89 servePort,
90 staleLocalPort: existing.localPort,
91 });
92 }
93​
94 return yield* ensureTailscaleServe({ localPort, servePort, localHost: "127.0.0.1" }).pipe(
95 Effect.as({ localPort, servePort }),
96 Effect.tap(() => Effect.logInfo("Tailscale Serve configured", { localPort, servePort })),
97 Effect.catch((cause) =>
98 Effect.logWarning("Failed to configure Tailscale Serve", {
99 cause,
100 localPort,
101 servePort,
102 }).pipe(Effect.as(null)),
103 ),
104 );
105});
106​
107/**
108 * Removes the mapping on shutdown, but only while it still points at us: a
109 * server that started later may have taken it over legitimately, and tearing
110 * that down would strand the tailnet URL.
111 */
112export const releaseTailscaleServe = (
113 owned: OwnedTailscaleServeMapping | null,
114): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
115 if (owned === null) {
116 return Effect.void;
117 }
118 return Effect.gen(function* () {
119 const current = yield* readTailscaleServeTarget({ servePort: owned.servePort }).pipe(
120 Effect.orElseSucceed(() => null),
121 );
122 if (current !== null && !isOwnMapping(current, owned.localPort)) {
123 yield* Effect.logInfo("Tailscale Serve now points elsewhere; leaving it in place", {
124 servePort: owned.servePort,
125 currentLocalPort: current.localPort,
126 });
127 return;
128 }
129 yield* disableTailscaleServe({ servePort: owned.servePort }).pipe(
130 Effect.tap(() => Effect.logInfo("Tailscale Serve disabled", { servePort: owned.servePort })),
131 Effect.catch((cause) =>
132 Effect.logWarning("Failed to disable Tailscale Serve", {
133 cause,
134 servePort: owned.servePort,
135 }),
136 ),
137 );
138 });
139};