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

DesktopWslBackend.ts

268 lines11.9 KB

1// Orchestrator that keeps the WSL pool instance in sync with the user's
2// settings. `reconcile` is the single entry point — bootstrap calls it
3// once after the primary backend starts, and the wsl.ts IPC calls it
4// after persisting a `wslBackendEnabled` or `wslDistro` change. The
5// effect is idempotent and never fails: errors (WSL not available, port
6// allocation failed, register failed) get logged and reconcile returns
7// having left the pool in a consistent state (either the previous WSL
8// instance is still running, or none is).
9//
10// The instance id encodes the desired distro selection — `wsl:default`
11// when the user picked "track the WSL default" (settings.wslDistro is
12// null) and `wsl:<distro>` otherwise. Changing the distro setting
13// changes the id, so reconcile unregisters the old instance before
14// registering the new one. The label that the frontend env switcher
15// renders is derived from the same field.
16//
17// Port allocation: each WSL instance gets a freshly scanned port to
18// avoid colliding with the primary or with a previously-registered WSL
19// instance that's still tearing down. The scan only checks loopback
20// (127.0.0.1) since the WSL backend is loopback-only — the primary
21// owns LAN exposure when the user opts in.
22​
23import * as Cause from "effect/Cause";
24import * as Context from "effect/Context";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Ref from "effect/Ref";
29import * as Semaphore from "effect/Semaphore";
30​
31import * as NetService from "@t3tools/shared/Net";
32​
33import * as DesktopObservability from "../app/DesktopObservability.ts";
34import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
35import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
36import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
37import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
38import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
39​
40// Exported so callers that parse pool ids (e.g. the pickFolder IPC
41// handler in ipc/methods/window.ts) reference the same prefix this
42// module produces. Keeping it inline in two places risks silent
43// divergence if one ever gets renamed.
44export const WSL_INSTANCE_ID_PREFIX = "wsl:";
45const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`;
46const MAX_TCP_PORT = 65_535;
47​
48export class DesktopWslBackend extends Context.Service<
49 DesktopWslBackend,
50 {
51 // Bring the pool in line with the current persisted WSL settings.
52 // Idempotent. Never fails (errors are logged); callers can chain it
53 // after persisting settings without an error-handling dance.
54 readonly reconcile: Effect.Effect<void>;
55 // Reason the dual-mode WSL secondary last failed preflight (no node, wrong
56 // version, missing build tools), or None. Read by the getWslState IPC so
57 // Connections settings can show it inline. None in wsl-only mode (that path
58 // surfaces via a dialog + Windows fallback).
59 readonly lastPreflightError: Effect.Effect<Option.Option<string>>;
60 }
61>()("@t3tools/desktop/wsl/DesktopWslBackend") {}
62​
63const { logInfo: logWslBackendInfo, logWarning: logWslBackendWarning } =
64 DesktopObservability.makeComponentLogger("desktop-wsl-backend");
65​
66const resolveTargetInstanceId = (distro: string | null): DesktopBackendPool.BackendInstanceId =>
67 DesktopBackendPool.BackendInstanceId(
68 distro === null ? WSL_DEFAULT_DISTRO_ID : `${WSL_INSTANCE_ID_PREFIX}${distro}`,
69 );
70​
71const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean =>
72 id.startsWith(WSL_INSTANCE_ID_PREFIX);
73​
74const buildLabel = (distro: string | null): string =>
75 distro === null ? "WSL (default distro)" : `WSL (${distro})`;
76​
77// Loopback-only port scan starting one above the primary's port. The
78// WSL backend is reachable via 127.0.0.1 from Windows (wslhost
79// auto-forwards), so we only need to verify the IPv4 loopback can bind.
80const scanForWslPort = Effect.fn("desktop.wslBackend.scanForWslPort")(function* (
81 startPort: number,
82): Effect.fn.Return<number, NetService.NetError, NetService.NetService> {
83 const net = yield* NetService.NetService;
84 for (let port = startPort; port <= MAX_TCP_PORT; port += 1) {
85 if (yield* net.canListenOnHost(port, "127.0.0.1")) {
86 return port;
87 }
88 }
89 return yield* new NetService.NetError({
90 message: `No loopback port available for WSL backend between ${startPort} and ${MAX_TCP_PORT}.`,
91 });
92});
93​
94export const layer = Layer.effect(
95 DesktopWslBackend,
96 Effect.gen(function* () {
97 const pool = yield* DesktopBackendPool.DesktopBackendPool;
98 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
99 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
100 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
101 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
102 const net = yield* NetService.NetService;
103 // Serialize reconcile so the bootstrap fork and the IPC handlers
104 // (setWslBackendEnabled, setWslDistro) can't interleave. Without
105 // this, two reconciles could both observe "no WSL instance
106 // registered" between their pool reads and both call startNew
107 // with different distros, leaving the loser stranded.
108 const reconcileMutex = yield* Semaphore.make(1);
109​
110 // Last fatal preflight failure from the dual-mode WSL *secondary*, surfaced
111 // inline in Connections settings. The primary's failure is handled by the
112 // pool (dialog + Windows fallback) instead; here the app stays usable on
113 // Windows, so we record the reason rather than interrupting. Cleared on any
114 // reconcile state change so it reflects the current attempt.
115 const preflightErrorRef = yield* Ref.make(Option.none<string>());
116​
117 const findExistingWslInstance = pool.list.pipe(
118 Effect.map((instances) => instances.find((instance) => isWslInstanceId(instance.id))),
119 Effect.map(Option.fromNullishOr),
120 );
121​
122 const stopExisting = (id: DesktopBackendPool.BackendInstanceId) =>
123 pool.unregister(id).pipe(
124 Effect.catchTags({
125 DesktopBackendPoolCannotUnregisterPrimaryError: (cause) =>
126 // Should never happen — wsl: ids are not the primary id — but
127 // log loudly if the logic ever drifts.
128 logWslBackendWarning("refusing to unregister primary as wsl instance", {
129 id,
130 error: cause.message,
131 }),
132 }),
133 );
134​
135 const startNew = Effect.fn("desktop.wslBackend.startNew")(function* (input: {
136 readonly distro: string | null;
137 }) {
138 const primaryConfig = yield* serverExposure.backendConfig;
139 const port = yield* scanForWslPort(primaryConfig.port + 1).pipe(
140 Effect.provideService(NetService.NetService, net),
141 Effect.map((value) => Option.some(value)),
142 Effect.catch((error) =>
143 logWslBackendWarning("could not allocate port for WSL backend", {
144 error: error.message,
145 }).pipe(Effect.as(Option.none<number>())),
146 ),
147 );
148​
149 if (Option.isNone(port)) {
150 return;
151 }
152 const allocatedPort = port.value;
153​
154 const targetId = resolveTargetInstanceId(input.distro);
155 yield* logWslBackendInfo("registering WSL backend with pool", {
156 id: targetId,
157 port: allocatedPort,
158 distro: input.distro ?? null,
159 });
160​
161 const instance = yield* pool
162 .register({
163 id: targetId,
164 label: Effect.succeed(buildLabel(input.distro)),
165 configResolve: configuration.resolveWsl({ port: allocatedPort, distro: input.distro }),
166 // Dual-mode secondary: record a fatal preflight failure so Connections
167 // settings can show why the WSL backend never appeared. No dialog or
168 // fallback — Windows is the primary and keeps working.
169 onPreflightFailed: (failure) =>
170 Ref.set(preflightErrorRef, Option.some(failure.reason)).pipe(Effect.as(false)),
171 onReady: () => Ref.set(preflightErrorRef, Option.none()),
172 })
173 .pipe(
174 Effect.map((registered) => Option.some(registered)),
175 Effect.catch((error) =>
176 logWslBackendWarning("WSL backend already registered, skipping start", {
177 id: targetId,
178 error: error.message,
179 }).pipe(Effect.as(Option.none<DesktopBackendPool.DesktopBackendInstance>())),
180 ),
181 );
182​
183 yield* Option.match(instance, {
184 onNone: () => Effect.void,
185 onSome: (registered) => registered.start,
186 });
187 });
188​
189 const reconcileBody = Effect.gen(function* () {
190 const settings = yield* appSettings.get;
191 const available = yield* wslEnvironment.isAvailable;
192 const existing = yield* findExistingWslInstance;
193 const existingId = Option.map(existing, (instance) => instance.id);
194​
195 // In wsl-only mode the pool's primary IS the WSL backend (see
196 // DesktopBackendConfiguration.resolvePrimary), so the
197 // orchestrator skips registering a parallel "wsl:<distro>"
198 // secondary. Without this skip we'd spin up two WSL processes
199 // on the same distro for users who explicitly asked for one.
200 const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly;
201 const targetId = shouldRun
202 ? Option.some(resolveTargetInstanceId(settings.wslDistro))
203 : Option.none<DesktopBackendPool.BackendInstanceId>();
204​
205 // No-op if the desired state already matches what's registered.
206 if (Option.isNone(targetId) && Option.isNone(existingId)) {
207 return;
208 }
209 if (
210 Option.isSome(targetId) &&
211 Option.isSome(existing) &&
212 targetId.value === existing.value.id
213 ) {
214 const existingInstance = existing.value;
215 const snapshot = yield* existingInstance.snapshot;
216 const isIdle =
217 !snapshot.ready && Option.isNone(snapshot.activePid) && !snapshot.restartScheduled;
218 if (isIdle) {
219 yield* logWslBackendInfo("retrying idle WSL backend", { id: existingInstance.id });
220 yield* Ref.set(preflightErrorRef, Option.none());
221 yield* existingInstance.start;
222 }
223 return;
224 }
225​
226 // A real state change is happening (start, stop, or distro swap). Clear
227 // any stale secondary preflight error so it reflects this fresh attempt;
228 // onPreflightFailed re-sets it only if the new secondary exhausts retries.
229 yield* Ref.set(preflightErrorRef, Option.none());
230​
231 if (Option.isSome(existingId)) {
232 yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });
233 yield* stopExisting(existingId.value);
234 }
235​
236 if (Option.isSome(targetId)) {
237 // Pre-warm the WSL VM before registering so the readiness probe
238 // doesn't race wsl.exe's first-spawn cold start. preWarm tolerates
239 // distro=null (uses the WSL default) and is bounded by its own
240 // timeout, so it's safe to await unconditionally here.
241 yield* wslEnvironment.preWarm(settings.wslDistro);
242 yield* startNew({ distro: settings.wslDistro });
243 }
244 });
245​
246 // Top-level safety net. Every internal step today already catches
247 // its own failures (port allocation, register, preWarm), so the
248 // inferred error type is `never` and this catch is a no-op in
249 // steady state. It's here to enforce the file-header contract
250 // ("reconcile never fails; errors are logged") if a future change
251 // introduces an unhandled failure path — otherwise IPC callers
252 // like setWslBackendEnabled would surface it to the renderer as
253 // an opaque error.
254 const reconcile = reconcileMutex
255 .withPermits(1)(reconcileBody)
256 .pipe(
257 Effect.catchCause((cause) =>
258 logWslBackendWarning("reconcile failed", { cause: Cause.pretty(cause) }),
259 ),
260 Effect.withSpan("desktop.wslBackend.reconcile"),
261 );
262​
263 return DesktopWslBackend.of({
264 reconcile,
265 lastPreflightError: Ref.get(preflightErrorRef),
266 });
267 }),
268);