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

portForwards.ts

174 lines6.8 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 allowsPreviewTunnel,
4 type DesktopPortForward,
5 type EnvironmentId,
6} from "@t3tools/contracts";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Queue from "effect/Queue";
11import * as Schedule from "effect/Schedule";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import * as AsyncResult from "effect/reactivity/AsyncResult";
15import { Atom } from "effect/reactivity";
16import { msg } from "gt-react";
17​
18import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
19​
20import { tunnelsEnvironmentLoopback } from "../browser/browserTargetResolver";
21import { m } from "../i18n/messages";
22import { environmentAtomList } from "./environmentAtomList";
23import { environmentSession } from "./session";
24​
25const EMPTY_FORWARDS: ReadonlyArray<DesktopPortForward> = [];
26​
27const previewBridge = () =>
28 typeof window === "undefined" ? undefined : window.desktopBridge?.preview;
29​
30/** Ports of other environments the desktop app forwards to this machine; empty elsewhere. */
31const portForwardsAtom = Atom.make(
32 Stream.callback<ReadonlyArray<DesktopPortForward>>((queue) =>
33 Effect.gen(function* () {
34 const bridge = previewBridge();
35 if (!bridge) return yield* Effect.never;
36 let changed = false;
37 yield* Effect.acquireRelease(
38 Effect.sync(() =>
39 bridge.onPortForwards((forwards) => {
40 changed = true;
41 Queue.offerUnsafe(queue, forwards);
42 }),
43 ),
44 (unsubscribe) => Effect.sync(unsubscribe),
45 );
46 const initial = yield* Effect.promise(() => bridge.listPortForwards());
47 if (!changed) Queue.offerUnsafe(queue, initial);
48 return yield* Effect.never;
49 }),
50 ),
51 { initialValue: EMPTY_FORWARDS },
52).pipe(Atom.keepAlive, Atom.withLabel("desktop:port-forwards"));
53​
54export function usePortForwards(): ReadonlyArray<DesktopPortForward> {
55 return AsyncResult.getOrElse(useAtomValue(portForwardsAtom), () => EMPTY_FORWARDS);
57​
58/** Only the desktop app forwards, and only from environments whose tunnel it may use. */
59export const canForwardPorts = (environment: {
60 readonly entry: { readonly target: ConnectionTarget };
61 readonly serverConfig: Parameters<typeof allowsPreviewTunnel>[0] | null;
62}): boolean =>
63 previewBridge() !== undefined &&
64 tunnelsEnvironmentLoopback(environment.entry.target) &&
65 environment.serverConfig !== null &&
66 allowsPreviewTunnel(environment.serverConfig);
67​
68/**
69 * Whether the environment runs on another machine. A saved route can still lead back to this
70 * computer (its own Tailscale address, a relay), where a forward would only loop.
71 */
72export type ForwardLocality = "remote" | "local" | "pending" | "unknown";
73​
74class PortForwardLocalityError extends Schema.TaggedError<PortForwardLocalityError>()(
75 "PortForwardLocalityError",
76 { environmentId: Schema.String, cause: Schema.Defect() },
77) {
78 override get message(): string {
79 return m(msg("Could not tell whether this environment runs on this computer."));
80 }
82​
83// A probe can fail while the environment is briefly unreachable (a reconnect race); retry it.
84const LOCALITY_RETRY_SCHEDULE = Schedule.exponential("1 second").pipe(
85 Schedule.modifyDelay(({ duration }) =>
86 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
87 ),
88);
89​
90const localityResultAtom = Atom.family((environmentId: EnvironmentId) =>
91 Atom.make((get) => {
92 // Each established connection probes anew, so a failed probe never outlives a reconnect.
93 const connection = AsyncResult.getOrElse(
94 get(environmentSession.transportSessionAtom(environmentId)),
95 () => Option.none(),
96 );
97 const bridge = previewBridge();
98 if (Option.isNone(connection) || bridge === undefined) return Effect.never;
99 return Effect.tryPromise({
100 try: () => bridge.sharesLoopback(environmentId),
101 catch: (cause) => new PortForwardLocalityError({ environmentId, cause }),
102 }).pipe(
103 Effect.retry(LOCALITY_RETRY_SCHEDULE),
104 Effect.map((shares): ForwardLocality => (shares ? "local" : "remote")),
105 );
106 }).pipe(
107 Atom.setIdleTTL(10 * 60_000),
108 Atom.withLabel(`desktop:port-forward-locality-probe:${environmentId}`),
109 ),
110);
111​
112const localityAtom = Atom.family((environmentId: EnvironmentId) =>
113 Atom.make((get): ForwardLocality => {
114 const result = get(localityResultAtom(environmentId));
115 if (AsyncResult.isSuccess(result)) return result.value;
116 return AsyncResult.isFailure(result) ? "unknown" : "pending";
117 }).pipe(Atom.withLabel(`desktop:port-forward-locality:${environmentId}`)),
118);
119​
120const NO_LOCALITY = Atom.make<ForwardLocality>("unknown").pipe(
121 Atom.withLabel("desktop:port-forward-locality:none"),
122);
123​
124/** Pass `null` for an environment the desktop doesn't tunnel to; that one never probes. */
125export function useForwardLocality(environmentId: EnvironmentId | null): ForwardLocality {
126 return useAtomValue(environmentId === null ? NO_LOCALITY : localityAtom(environmentId));
128​
129export const forwardLocalitiesAtom = environmentAtomList(
130 "desktop:port-forward-localities",
131 localityAtom,
132);
133​
134export const findPortForward = (
135 forwards: ReadonlyArray<DesktopPortForward>,
136 environmentId: EnvironmentId,
137 remotePort: number,
138) =>
139 forwards.find(
140 (forward) => forward.environmentId === environmentId && forward.remotePort === remotePort,
141 );
142​
143export function forwardPort(environmentId: EnvironmentId, remotePort: number) {
144 const bridge = previewBridge();
145 if (!bridge) return Promise.reject(new Error(m(msg("Port forwarding needs the desktop app."))));
146 return bridge.forwardPort(environmentId, remotePort).catch((error: unknown) => {
147 // Electron flattens main-process errors into "Error invoking remote method '…': Tag: text".
148 const raw = error instanceof Error ? error.message : String(error);
149 throw new Error(
150 raw.includes("LoopbackTunnelSameMachineError")
151 ? m(
152 msg("This environment runs on this computer, so localhost:{port} already reaches it.", {
153 port: remotePort,
154 }),
155 )
156 : raw.includes("LoopbackTunnelUnavailableError")
157 ? m(msg("This environment can't be reached right now. Try again once it reconnects."))
158 : raw.replace(/^Error invoking remote method '[^']*':\s*(\w+Error:\s*)?/u, ""),
159 { cause: error },
160 );
161 });
163​
164export function stopPortForward(environmentId: EnvironmentId, remotePort: number) {
165 return previewBridge()?.stopPortForward(environmentId, remotePort) ?? Promise.resolve();
167​
168/** `url` with its host and port moved to the forward's end on this machine. */
169export function forwardedUrl(forward: DesktopPortForward, url?: string): string {
170 const local = new URL(url ?? "http://localhost/");
171 local.hostname = "localhost";
172 local.port = String(forward.localPort);
173 return local.toString();