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

DesktopWslBackend.ts

234 lines9.6 KB

1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";
7import * as Semaphore from "effect/Semaphore";
8​
9import * as NetService from "@t3tools/shared/Net";
10​
11import * as DesktopObservability from "../app/DesktopObservability.ts";
12import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
13import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
14import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
15import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
16import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
17​
18// Exported so callers that parse pool ids (e.g. the pickFolder IPC handler in
19// ipc/methods/window.ts) reference the same prefix this module produces.
20export const WSL_INSTANCE_ID_PREFIX = "wsl:";
21const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`;
22const MAX_TCP_PORT = 65_535;
23​
24export class DesktopWslBackend extends Context.Service<
25 DesktopWslBackend,
26 {
27 readonly reconcile: Effect.Effect<void>;
28 readonly lastPreflightError: Effect.Effect<Option.Option<string>>;
29 }
30>()("@t3tools/desktop/wsl/DesktopWslBackend") {}
31​
32const { logInfo: logWslBackendInfo, logWarning: logWslBackendWarning } =
33 DesktopObservability.makeComponentLogger("desktop-wsl-backend");
34​
35const resolveTargetInstanceId = (distro: string | null): DesktopBackendPool.BackendInstanceId =>
36 DesktopBackendPool.BackendInstanceId(
37 distro === null ? WSL_DEFAULT_DISTRO_ID : `${WSL_INSTANCE_ID_PREFIX}${distro}`,
38 );
39​
40const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean =>
41 id.startsWith(WSL_INSTANCE_ID_PREFIX);
42​
43const buildLabel = (distro: string | null): string =>
44 distro === null ? "WSL (default distro)" : `WSL (${distro})`;
45​
46// Loopback-only port scan starting one above the primary's port. The
47// WSL backend is reachable via 127.0.0.1 from Windows (wslhost
48// auto-forwards), so we only need to verify the IPv4 loopback can bind.
49const scanForWslPort = Effect.fn("desktop.wslBackend.scanForWslPort")(function* (
50 startPort: number,
51): Effect.fn.Return<number, NetService.NetError, NetService.NetService> {
52 const net = yield* NetService.NetService;
53 for (let port = startPort; port <= MAX_TCP_PORT; port += 1) {
54 if (yield* net.canListenOnHost(port, "127.0.0.1")) {
55 return port;
56 }
57 }
58 return yield* new NetService.NetError({
59 message: `No loopback port available for WSL backend between ${startPort} and ${MAX_TCP_PORT}.`,
60 });
61});
62​
63export const layer = Layer.effect(
64 DesktopWslBackend,
65 Effect.gen(function* () {
66 const pool = yield* DesktopBackendPool.DesktopBackendPool;
67 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
68 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
69 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
70 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
71 const net = yield* NetService.NetService;
72 // Serialize reconcile so the bootstrap fork and the IPC handlers
73 // (setWslBackendEnabled, setWslDistro) can't interleave. Without
74 // this, two reconciles could both observe "no WSL instance
75 // registered" between their pool reads and both call startNew
76 // with different distros, leaving the loser stranded.
77 const reconcileMutex = yield* Semaphore.make(1);
78​
79 const preflightErrorRef = yield* Ref.make(Option.none<string>());
80 const ownershipRefusedRef = yield* Ref.make(
81 Option.none<DesktopBackendPool.BackendInstanceId>(),
82 );
83​
84 const findExistingWslInstance = pool.list.pipe(
85 Effect.map((instances) => instances.find((instance) => isWslInstanceId(instance.id))),
86 Effect.map(Option.fromNullishOr),
87 );
88​
89 const stopExisting = (id: DesktopBackendPool.BackendInstanceId) =>
90 pool.unregister(id).pipe(
91 Effect.catchTags({
92 DesktopBackendPoolCannotUnregisterPrimaryError: (cause) =>
93 logWslBackendWarning("refusing to unregister primary as wsl instance", {
94 id,
95 error: cause.message,
96 }),
97 }),
98 );
99​
100 const startNew = Effect.fn("desktop.wslBackend.startNew")(function* (input: {
101 readonly distro: string | null;
102 }) {
103 const primaryConfig = yield* serverExposure.backendConfig;
104 const port = yield* scanForWslPort(primaryConfig.port + 1).pipe(
105 Effect.provideService(NetService.NetService, net),
106 Effect.asSome,
107 Effect.catch((error) =>
108 logWslBackendWarning("could not allocate port for WSL backend", {
109 error: error.message,
110 }).pipe(Effect.as(Option.none<number>())),
111 ),
112 );
113​
114 if (Option.isNone(port)) {
115 return;
116 }
117 const allocatedPort = port.value;
118​
119 const targetId = resolveTargetInstanceId(input.distro);
120 yield* logWslBackendInfo("registering WSL backend with pool", {
121 id: targetId,
122 port: allocatedPort,
123 distro: input.distro ?? null,
124 });
125​
126 const instance = yield* pool
127 .register({
128 id: targetId,
129 label: Effect.succeed(buildLabel(input.distro)),
130 configResolve: configuration.resolveWsl({ port: allocatedPort, distro: input.distro }),
131 onPreflightFailed: (failure) =>
132 Ref.set(preflightErrorRef, Option.some(failure.reason)).pipe(Effect.as(false)),
133 onStateDirOwned: () =>
134 Ref.set(ownershipRefusedRef, Option.some(targetId)).pipe(
135 Effect.andThen(
136 Ref.set(
137 preflightErrorRef,
138 Option.some(
139 "Another T3 Code server is using this distro's T3 home, or an older background service is set up for it. Stop that server or pair with it, or try `t3 update` in the distro. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI in the distro. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command.",
140 ),
141 ),
142 ),
143 ),
144 onReady: () =>
145 Ref.set(ownershipRefusedRef, Option.none()).pipe(
146 Effect.andThen(Ref.set(preflightErrorRef, Option.none())),
147 ),
148 })
149 .pipe(
150 Effect.asSome,
151 Effect.catch((error) =>
152 logWslBackendWarning("WSL backend already registered, skipping start", {
153 id: targetId,
154 error: error.message,
155 }).pipe(Effect.as(Option.none<DesktopBackendPool.DesktopBackendInstance>())),
156 ),
157 );
158​
159 yield* Option.match(instance, {
160 onNone: () => Effect.void,
161 onSome: (registered) => registered.start,
162 });
163 });
164​
165 const reconcileBody = Effect.gen(function* () {
166 const settings = yield* appSettings.get;
167 if (!settings.localEnvironmentEnabled) return;
168 const available = yield* wslEnvironment.isAvailable;
169 const existing = yield* findExistingWslInstance;
170 const existingId = Option.map(existing, (instance) => instance.id);
171​
172 // In wsl-only mode the pool's primary IS the WSL backend (see
173 // DesktopBackendConfiguration.resolvePrimary), so the
174 // orchestrator skips registering a parallel "wsl:<distro>"
175 // secondary. Without this skip we'd spin up two WSL processes
176 // on the same distro for users who explicitly asked for one.
177 const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly;
178 const targetId = shouldRun
179 ? Option.some(resolveTargetInstanceId(settings.wslDistro))
180 : Option.none<DesktopBackendPool.BackendInstanceId>();
181​
182 if (Option.isNone(targetId) && Option.isNone(existingId)) {
183 return;
184 }
185 if (
186 Option.isSome(targetId) &&
187 Option.isSome(existing) &&
188 targetId.value === existing.value.id
189 ) {
190 const existingInstance = existing.value;
191 const snapshot = yield* existingInstance.snapshot;
192 const isIdle =
193 !snapshot.ready && Option.isNone(snapshot.activePid) && !snapshot.restartScheduled;
194 if (isIdle) {
195 const refused = yield* Ref.get(ownershipRefusedRef);
196 if (Option.isSome(refused) && refused.value === existingInstance.id) return;
197 yield* logWslBackendInfo("retrying idle WSL backend", { id: existingInstance.id });
198 yield* Ref.set(preflightErrorRef, Option.none());
199 yield* existingInstance.start;
200 }
201 return;
202 }
203​
204 yield* Ref.set(preflightErrorRef, Option.none());
205 yield* Ref.set(ownershipRefusedRef, Option.none());
206​
207 if (Option.isSome(existingId)) {
208 yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });
209 yield* stopExisting(existingId.value);
210 }
211​
212 if (Option.isSome(targetId)) {
213 // Pre-warm the WSL VM before registering so the readiness probe doesn't
214 // race wsl.exe's first-spawn cold start.
215 yield* wslEnvironment.preWarm(settings.wslDistro);
216 yield* startNew({ distro: settings.wslDistro });
217 }
218 });
219​
220 const reconcile = reconcileMutex
221 .withPermits(1)(reconcileBody)
222 .pipe(
223 Effect.catchCause((cause) =>
224 logWslBackendWarning("reconcile failed", { cause: Cause.pretty(cause) }),
225 ),
226 Effect.withSpan("desktop.wslBackend.reconcile"),
227 );
228​
229 return DesktopWslBackend.of({
230 reconcile,
231 lastPreflightError: Ref.get(preflightErrorRef),
232 });
233 }),
234);