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

DesktopBackendPool.ts

412 lines16.9 KB

1import {
2 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
3 DESKTOP_UPDATE_IN_PROGRESS_TTL_MS,
4} from "@t3tools/contracts";
5import * as Context from "effect/Context";
6import * as Deferred from "effect/Deferred";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as FiberHandle from "effect/FiberHandle";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Schedule from "effect/Schedule";
15import * as Schema from "effect/Schema";
16import * as Scope from "effect/Scope";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18import * as SynchronizedRef from "effect/SynchronizedRef";
19​
20import * as FileSystem from "effect/FileSystem";
21import { HttpClient } from "effect/http";
22import { ChildProcessSpawner } from "effect/process";
23​
24import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
25import * as DesktopBackendManager from "./DesktopBackendManager.ts";
26import * as DesktopHomeOwner from "./DesktopHomeOwner.ts";
27import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
28import * as DesktopObservability from "../app/DesktopObservability.ts";
29import * as DesktopState from "../app/DesktopState.ts";
30import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
31import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
32import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
33import * as DesktopWindow from "../window/DesktopWindow.ts";
34import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
35import * as ElectronDialog from "../electron/ElectronDialog.ts";
36import * as ElectronApp from "../electron/ElectronApp.ts";
37​
38const { logWarning: logBackendPoolWarning } =
39 DesktopObservability.makeComponentLogger("desktop-backend-pool");
40​
41const decodeServerRuntime = Schema.decodeUnknownEffect(
42 Schema.fromJsonString(Schema.Struct({ pid: Schema.Number, port: Schema.Number })),
43);
44​
45export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
46export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
47export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
48export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
49export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
50​
51export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedError<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
52 "DesktopBackendPoolInstanceAlreadyRegisteredError",
53 {
54 id: Schema.String,
55 },
56) {
57 override get message() {
58 return `Backend instance "${this.id}" is already registered in the pool.`;
59 }
61​
62export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedError<DesktopBackendPoolCannotUnregisterPrimaryError>()(
63 "DesktopBackendPoolCannotUnregisterPrimaryError",
64 {},
65) {
66 override get message() {
67 return "Refusing to unregister the primary backend from the pool.";
68 }
70​
71export class DesktopBackendPool extends Context.Service<
72 DesktopBackendPool,
73 {
74 readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
75 readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
76 readonly primary: Effect.Effect<DesktopBackendInstance>;
77 readonly register: (
78 spec: BackendInstanceSpec,
79 ) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
80 readonly unregister: (
81 id: BackendInstanceId,
82 ) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
83 }
84>()("@t3tools/desktop/backend/DesktopBackendPool") {}
85​
86export type BackendInstanceFactoryRequirements =
87 | FileSystem.FileSystem
88 | ChildProcessSpawner.ChildProcessSpawner
89 | HttpClient.HttpClient
90 | DesktopObservability.DesktopBackendOutputLogFactory
91 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
92 | DesktopBrowserHost.DesktopBrowserHost
93 | DesktopWslEnvironment.DesktopWslEnvironment;
94​
95interface ActiveRegisteredInstance {
96 readonly _tag: "Active";
97 readonly instance: DesktopBackendInstance;
98 readonly scope: Option.Option<Scope.Closeable>;
100​
101interface ClosingRegisteredInstance {
102 readonly _tag: "Closing";
103 readonly done: Deferred.Deferred<void>;
105​
106type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
107​
108type RegisterAction =
109 | { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
110 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
111​
112type UnregisterAction =
113 | { readonly _tag: "Absent" }
114 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
115 | { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
116​
117export const layer = Layer.effect(
118 DesktopBackendPool,
119 Effect.gen(function* () {
120 const environment = yield* DesktopEnvironment.DesktopEnvironment;
121 const fileSystem = yield* FileSystem.FileSystem;
122 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
123 const desktopWindow = yield* DesktopWindow.DesktopWindow;
124 const electronDialog = yield* ElectronDialog.ElectronDialog;
125 const electronApp = yield* ElectronApp.ElectronApp;
126 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
127 const { primaryBackendStartup } = yield* DesktopState.DesktopState;
128 // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends.
129 const layerScope = yield* Scope.Scope;
130 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
131 const homeOwnerContext = yield* Effect.context<
132 FileSystem.FileSystem | Path.Path | DesktopEnvironment.DesktopEnvironment
133 >();
134​
135 const updateMarkerPath = environment.path.join(
136 environment.baseDir,
137 "runtime",
138 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
139 );
140 const serverRuntimePath = environment.path.join(environment.stateDir, "server-runtime.json");
141 // The server publishes its runtime after HTTP readiness. Until then an SSH launcher
142 // finds nothing to adopt, so dropping the marker earlier lets it start a competing server.
143 const releaseUpdateMarker = Effect.fn("desktop.backendPool.releaseUpdateMarker")(function* (
144 httpBaseUrl: URL,
145 pid: number,
146 ) {
147 const marker = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option);
148 if (Option.isNone(marker)) {
149 return;
150 }
151 yield* fileSystem.readFileString(serverRuntimePath).pipe(
152 Effect.flatMap(decodeServerRuntime),
153 Effect.map((runtime) => runtime.pid === pid && runtime.port === Number(httpBaseUrl.port)),
154 Effect.orElseSucceed(() => false),
155 Effect.repeat({
156 until: (published) => published,
157 schedule: Schedule.spaced(Duration.millis(100)),
158 }),
159 Effect.timeoutOption(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS)),
160 );
161 // A later update may have replaced the marker; that handoff is not ours to end.
162 const current = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option);
163 if (Option.isSome(current) && current.value === marker.value) {
164 yield* fileSystem.remove(updateMarkerPath, { force: true }).pipe(Effect.ignore);
165 }
166 });
167 // One wait at a time: each run's shutdown or readiness ends the previous run's wait.
168 const updateMarkerWait = yield* FiberHandle.make<void>();
169​
170 // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference.
171 const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
172 function* (failure: DesktopBackendManager.PreflightFailure) {
173 const { reason, fatal } = failure;
174 if (!fatal) {
175 yield* logBackendPoolWarning(
176 "primary WSL preflight retry window exhausted; using Windows for this launch",
177 { reason },
178 );
179 yield* electronDialog.showErrorBox(
180 "WSL backend is still unavailable",
181 `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
182 );
183 yield* appSettings.applyWslWindowsFallbackInMemory;
184 return true;
185 }
186​
187 yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
188 reason,
189 });
190 yield* electronDialog.showErrorBox(
191 "WSL backend couldn't start",
192 `${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Sharing & access once the WSL distro is fixed.`,
193 );
194 // Clear wslOnly too so enabling WSL cannot restore a failed mode.
195 // Keep the in-memory fallback if persistence fails.
196 yield* appSettings.applyWslWindowsFallback.pipe(
197 Effect.catch((error) =>
198 logBackendPoolWarning(
199 "failed to persist Windows fallback after WSL preflight failure",
200 {
201 error: error.message,
202 },
203 ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
204 ),
205 );
206 return true;
207 },
208 );
209​
210 const primary = yield* DesktopBackendManager.makeBackendInstance({
211 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
212 // Resolve lazily: startup loads persisted settings after pool initialization.
213 label: configuration.resolvePrimaryLabel,
214 configResolve: configuration.resolvePrimary,
215 // Absorb window errors so readiness can reset restartAttempt.
216 onReady: (httpBaseUrl, pid) =>
217 FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe(
218 Effect.andThen(desktopWindow.handleBackendReady(httpBaseUrl)),
219 // Only once the main window exists, so the recovery window never closes into nothing.
220 Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })),
221 Effect.catch((error) =>
222 logBackendPoolWarning("failed to open main window after backend readiness", {
223 error: error.message,
224 }),
225 ),
226 ),
227 onStartupFailure: (failure) =>
228 SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }),
229 onShutdown: () =>
230 FiberHandle.clear(updateMarkerWait).pipe(
231 Effect.andThen(desktopWindow.handleBackendNotReady),
232 ),
233 onPreflightFailed: handlePrimaryPreflightFailure,
234 onStateDirOwned: () =>
235 DesktopHomeOwner.readLiveHomeOwner().pipe(
236 Effect.flatMap((owner) =>
237 electronDialog.showErrorBox(
238 "This T3 home is unavailable",
239 DesktopHomeOwner.homeOwnedMessage(owner),
240 ),
241 ),
242 Effect.provideContext(homeOwnerContext),
243 Effect.andThen(electronApp.quit),
244 ),
245 });
246​
247 const instancesRef = yield* SynchronizedRef.make<
248 ReadonlyMap<BackendInstanceId, RegisteredInstance>
249 >(
250 new Map([
251 [
252 DesktopBackendManager.PRIMARY_INSTANCE_ID,
253 { _tag: "Active", instance: primary, scope: Option.none() },
254 ],
255 ]),
256 );
257​
258 const register: DesktopBackendPool["Service"]["register"] = (spec) =>
259 Effect.suspend(() =>
260 SynchronizedRef.modifyEffect(
261 instancesRef,
262 (
263 current,
264 ): Effect.Effect<
265 readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
266 DesktopBackendPoolInstanceAlreadyRegisteredError
267 > => {
268 const existing = current.get(spec.id);
269 if (existing?._tag === "Active") {
270 return Effect.fail(
271 new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
272 );
273 }
274 if (existing?._tag === "Closing") {
275 return Effect.succeed([
276 { _tag: "Wait", done: existing.done } as const,
277 current,
278 ] as const);
279 }
280 return Effect.gen(function* () {
281 // Provide the child Scope last so the captured pool Scope cannot shadow it and orphan stop/restart finalizers.
282 const instanceScope = yield* Scope.fork(layerScope, "sequential");
283 const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
284 Scope.provide(instanceScope),
285 Effect.provide(factoryContext),
286 );
287 const next = new Map(current);
288 next.set(spec.id, {
289 _tag: "Active",
290 instance,
291 scope: Option.some(instanceScope),
292 });
293 return [
294 { _tag: "Registered", instance } as const,
295 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
296 ] as const;
297 });
298 },
299 ).pipe(
300 Effect.flatMap((result) =>
301 result._tag === "Registered"
302 ? Effect.succeed(result.instance)
303 : Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
304 ),
305 ),
306 );
307​
308 const unregister: DesktopBackendPool["Service"]["unregister"] = Effect.fn(
309 "DesktopBackendPool.unregister",
310 )(function* (id) {
311 if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
312 return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
313 }
314 const done = yield* Deferred.make<void>();
315 const action = yield* SynchronizedRef.modifyEffect(
316 instancesRef,
317 (
318 current,
319 ): Effect.Effect<
320 readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
321 > => {
322 const entry = current.get(id);
323 if (entry === undefined) {
324 return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
325 }
326 if (entry._tag === "Closing") {
327 return Effect.succeed([{ _tag: "Wait", done: entry.done } as const, current] as const);
328 }
329 const next = new Map(current);
330 next.set(id, { _tag: "Closing", done });
331 return Effect.succeed([
332 { _tag: "Close", entry } as const,
333 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
334 ] as const);
335 },
336 );
337​
338 if (action._tag === "Absent") return;
339 if (action._tag === "Wait") {
340 yield* Deferred.await(action.done);
341 return;
342 }
343​
344 const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
345 const closing = current.get(id);
346 if (closing?._tag !== "Closing" || closing.done !== done) {
347 return Effect.succeed([undefined, current] as const);
348 }
349 const next = new Map(current);
350 next.delete(id);
351 return Effect.succeed([
352 undefined,
353 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
354 ] as const);
355 }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
356 yield* Option.match(action.entry.scope, {
357 onNone: () => Effect.void,
358 onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
359 }).pipe(Effect.ensuring(finish));
360 });
361​
362 return DesktopBackendPool.of({
363 get: Effect.fn("DesktopBackendPool.get")(function (id) {
364 return SynchronizedRef.get(instancesRef).pipe(
365 Effect.map((instances) => {
366 const entry = instances.get(id);
367 return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
368 }),
369 );
370 }),
371 list: SynchronizedRef.get(instancesRef).pipe(
372 Effect.map((instances) =>
373 Array.from(instances.values()).flatMap((entry) =>
374 entry._tag === "Active" ? [entry.instance] : [],
375 ),
376 ),
377 ),
378 primary: Effect.succeed(primary),
379 register,
380 unregister,
381 });
382 }),
383);
384​
385export const layerTest = (
386 instances: readonly DesktopBackendInstance[],
387): Layer.Layer<DesktopBackendPool> =>
388 Layer.effect(
389 DesktopBackendPool,
390 Effect.gen(function* () {
391 if (instances.length === 0) {
392 return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
393 }
394 const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
395 instances.map((instance) => [instance.id, instance] as const),
396 );
397 const primary = instances[0]!;
398 return DesktopBackendPool.of({
399 get: Effect.fn("DesktopBackendPool.get")(function (id) {
400 return Effect.succeed(Option.fromNullishOr(byId.get(id)));
401 }),
402 list: Effect.succeed(Array.from(byId.values())),
403 primary: Effect.succeed(primary),
404 register: Effect.fn("DesktopBackendPool.register")(function () {
405 return Effect.die("DesktopBackendPool.layerTest does not support register");
406 }),
407 unregister: Effect.fn("DesktopBackendPool.unregister")(function () {
408 return Effect.die("DesktopBackendPool.layerTest does not support unregister");
409 }),
410 });
411 }),
412 );