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

DesktopBackendPool.ts

349 lines14.3 KB

1import * as Context from "effect/Context";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as Scope from "effect/Scope";
9import * as SynchronizedRef from "effect/SynchronizedRef";
10​
11import * as FileSystem from "effect/FileSystem";
12import { HttpClient } from "effect/http";
13import { ChildProcessSpawner } from "effect/process";
14​
15import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
16import * as DesktopBackendManager from "./DesktopBackendManager.ts";
17import * as DesktopObservability from "../app/DesktopObservability.ts";
18import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
19import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
20import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
21import * as DesktopWindow from "../window/DesktopWindow.ts";
22import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
23import * as ElectronDialog from "../electron/ElectronDialog.ts";
24import * as ElectronApp from "../electron/ElectronApp.ts";
25​
26const { logWarning: logBackendPoolWarning } =
27 DesktopObservability.makeComponentLogger("desktop-backend-pool");
28​
29export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
30export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
31export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
32export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
33export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
34​
35export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedError<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
36 "DesktopBackendPoolInstanceAlreadyRegisteredError",
37 {
38 id: Schema.String,
39 },
40) {
41 override get message() {
42 return `Backend instance "${this.id}" is already registered in the pool.`;
43 }
45​
46export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedError<DesktopBackendPoolCannotUnregisterPrimaryError>()(
47 "DesktopBackendPoolCannotUnregisterPrimaryError",
48 {},
49) {
50 override get message() {
51 return "Refusing to unregister the primary backend from the pool.";
52 }
54​
55export class DesktopBackendPool extends Context.Service<
56 DesktopBackendPool,
57 {
58 readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
59 readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
60 readonly primary: Effect.Effect<DesktopBackendInstance>;
61 readonly register: (
62 spec: BackendInstanceSpec,
63 ) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
64 readonly unregister: (
65 id: BackendInstanceId,
66 ) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
67 }
68>()("@t3tools/desktop/backend/DesktopBackendPool") {}
69​
70export type BackendInstanceFactoryRequirements =
71 | FileSystem.FileSystem
72 | ChildProcessSpawner.ChildProcessSpawner
73 | HttpClient.HttpClient
74 | DesktopObservability.DesktopBackendOutputLogFactory
75 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
76 | DesktopBrowserHost.DesktopBrowserHost
77 | DesktopWslEnvironment.DesktopWslEnvironment;
78​
79interface ActiveRegisteredInstance {
80 readonly _tag: "Active";
81 readonly instance: DesktopBackendInstance;
82 readonly scope: Option.Option<Scope.Closeable>;
84​
85interface ClosingRegisteredInstance {
86 readonly _tag: "Closing";
87 readonly done: Deferred.Deferred<void>;
89​
90type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
91​
92type RegisterAction =
93 | { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
94 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
95​
96type UnregisterAction =
97 | { readonly _tag: "Absent" }
98 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
99 | { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
100​
101export const layer = Layer.effect(
102 DesktopBackendPool,
103 Effect.gen(function* () {
104 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
105 const desktopWindow = yield* DesktopWindow.DesktopWindow;
106 const electronDialog = yield* ElectronDialog.ElectronDialog;
107 const electronApp = yield* ElectronApp.ElectronApp;
108 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
109 // Without this, instance scopes are orphaned: they only close via explicit unregister() calls,
110 // so on app shutdown the WSL backend child process gets hard-killed by the OS instead of
111 // receiving the graceful SIGTERM + grace period the instance's stop finalizer would otherwise
112 // run.
113 const layerScope = yield* Scope.Scope;
114 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
115​
116 // Fatal configuration failures persist the Windows fallback. Bounded
117 // transport failures use an in-memory fallback for this launch so the app
118 // opens without overwriting the user's WSL preference.
119 const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
120 function* (failure: DesktopBackendManager.PreflightFailure) {
121 const { reason, fatal } = failure;
122 if (!fatal) {
123 yield* logBackendPoolWarning(
124 "primary WSL preflight retry window exhausted; using Windows for this launch",
125 { reason },
126 );
127 yield* electronDialog.showErrorBox(
128 "WSL backend is still unavailable",
129 `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
130 );
131 yield* appSettings.applyWslWindowsFallbackInMemory;
132 return true;
133 }
134​
135 yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
136 reason,
137 });
138 yield* electronDialog.showErrorBox(
139 "WSL backend couldn't start",
140 `${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`,
141 );
142 // Clearing wslBackendEnabled alone would leave a stale wslOnly:true that silently re-traps
143 // the user in wsl-only mode the next time they enable WSL. If the persisted write fails,
144 // keep this process recoverable by applying the fallback to in-memory settings.
145 yield* appSettings.applyWslWindowsFallback.pipe(
146 Effect.catch((error) =>
147 logBackendPoolWarning(
148 "failed to persist Windows fallback after WSL preflight failure",
149 {
150 error: error.message,
151 },
152 ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
153 ),
154 );
155 return true;
156 },
157 );
158​
159 const primary = yield* DesktopBackendManager.makeBackendInstance({
160 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
161 // Keep this lazy. The pool layer is initialized before startup loads
162 // persisted desktop settings, so resolving the primary label here would
163 // permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
164 // primaries as Windows.
165 label: configuration.resolvePrimaryLabel,
166 configResolve: configuration.resolvePrimary,
167 // Window creation errors propagating out of handleBackendReady must not block the readiness
168 // callback (that would prevent restartAttempt from being reset), so we absorb them here.
169 onReady: (httpBaseUrl) =>
170 desktopWindow.handleBackendReady(httpBaseUrl).pipe(
171 Effect.catch((error) =>
172 logBackendPoolWarning("failed to open main window after backend readiness", {
173 error: error.message,
174 }),
175 ),
176 ),
177 onShutdown: () => desktopWindow.handleBackendNotReady,
178 onPreflightFailed: handlePrimaryPreflightFailure,
179 onStateDirOwned: () =>
180 electronDialog
181 .showErrorBox(
182 "This T3 home is unavailable",
183 "Another T3 Code server, such as the background service, is using this data directory. Stop that server and reopen T3 Code, or set a separate T3CODE_HOME and pair with the running server.",
184 )
185 .pipe(Effect.andThen(electronApp.quit)),
186 });
187​
188 const instancesRef = yield* SynchronizedRef.make<
189 ReadonlyMap<BackendInstanceId, RegisteredInstance>
190 >(
191 new Map([
192 [
193 DesktopBackendManager.PRIMARY_INSTANCE_ID,
194 { _tag: "Active", instance: primary, scope: Option.none() },
195 ],
196 ]),
197 );
198​
199 const register: DesktopBackendPool["Service"]["register"] = (spec) =>
200 Effect.suspend(() =>
201 SynchronizedRef.modifyEffect(
202 instancesRef,
203 (
204 current,
205 ): Effect.Effect<
206 readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
207 DesktopBackendPoolInstanceAlreadyRegisteredError
208 > => {
209 const existing = current.get(spec.id);
210 if (existing?._tag === "Active") {
211 return Effect.fail(
212 new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
213 );
214 }
215 if (existing?._tag === "Closing") {
216 return Effect.succeed([
217 { _tag: "Wait", done: existing.done } as const,
218 current,
219 ] as const);
220 }
221 return Effect.gen(function* () {
222 // Provide the captured factory services first, then the child scope
223 // last so instance finalizers are owned by the unregisterable scope.
224 const instanceScope = yield* Scope.fork(layerScope, "sequential");
225 const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
226 Effect.provide(factoryContext),
227 Scope.provide(instanceScope),
228 );
229 const next = new Map(current);
230 next.set(spec.id, {
231 _tag: "Active",
232 instance,
233 scope: Option.some(instanceScope),
234 });
235 return [
236 { _tag: "Registered", instance } as const,
237 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
238 ] as const;
239 });
240 },
241 ).pipe(
242 Effect.flatMap((result) =>
243 result._tag === "Registered"
244 ? Effect.succeed(result.instance)
245 : Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
246 ),
247 ),
248 );
249​
250 const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
251 Effect.gen(function* () {
252 if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
253 return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
254 }
255 const done = yield* Deferred.make<void>();
256 const action = yield* SynchronizedRef.modifyEffect(
257 instancesRef,
258 (
259 current,
260 ): Effect.Effect<
261 readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
262 > => {
263 const entry = current.get(id);
264 if (entry === undefined) {
265 return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
266 }
267 if (entry._tag === "Closing") {
268 return Effect.succeed([
269 { _tag: "Wait", done: entry.done } as const,
270 current,
271 ] as const);
272 }
273 const next = new Map(current);
274 next.set(id, { _tag: "Closing", done });
275 return Effect.succeed([
276 { _tag: "Close", entry } as const,
277 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
278 ] as const);
279 },
280 );
281​
282 if (action._tag === "Absent") return;
283 if (action._tag === "Wait") {
284 yield* Deferred.await(action.done);
285 return;
286 }
287​
288 const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
289 const closing = current.get(id);
290 if (closing?._tag !== "Closing" || closing.done !== done) {
291 return Effect.succeed([undefined, current] as const);
292 }
293 const next = new Map(current);
294 next.delete(id);
295 return Effect.succeed([
296 undefined,
297 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
298 ] as const);
299 }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
300 yield* Option.match(action.entry.scope, {
301 onNone: () => Effect.void,
302 onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
303 }).pipe(Effect.ensuring(finish));
304 });
305​
306 return DesktopBackendPool.of({
307 get: (id) =>
308 SynchronizedRef.get(instancesRef).pipe(
309 Effect.map((instances) => {
310 const entry = instances.get(id);
311 return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
312 }),
313 ),
314 list: SynchronizedRef.get(instancesRef).pipe(
315 Effect.map((instances) =>
316 Array.from(instances.values()).flatMap((entry) =>
317 entry._tag === "Active" ? [entry.instance] : [],
318 ),
319 ),
320 ),
321 primary: Effect.succeed(primary),
322 register,
323 unregister,
324 });
325 }),
326);
327​
328export const layerTest = (
329 instances: readonly DesktopBackendInstance[],
330): Layer.Layer<DesktopBackendPool> =>
331 Layer.effect(
332 DesktopBackendPool,
333 Effect.gen(function* () {
334 if (instances.length === 0) {
335 return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
336 }
337 const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
338 instances.map((instance) => [instance.id, instance] as const),
339 );
340 const primary = instances[0]!;
341 return DesktopBackendPool.of({
342 get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
343 list: Effect.succeed(Array.from(byId.values())),
344 primary: Effect.succeed(primary),
345 register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
346 unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
347 });
348 }),
349 );