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

DesktopBackendPool.ts

336 lines13.7 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 // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends.
110 const layerScope = yield* Scope.Scope;
111 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
112​
113 // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference.
114 const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
115 function* (failure: DesktopBackendManager.PreflightFailure) {
116 const { reason, fatal } = failure;
117 if (!fatal) {
118 yield* logBackendPoolWarning(
119 "primary WSL preflight retry window exhausted; using Windows for this launch",
120 { reason },
121 );
122 yield* electronDialog.showErrorBox(
123 "WSL backend is still unavailable",
124 `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
125 );
126 yield* appSettings.applyWslWindowsFallbackInMemory;
127 return true;
128 }
129​
130 yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
131 reason,
132 });
133 yield* electronDialog.showErrorBox(
134 "WSL backend couldn't start",
135 `${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.`,
136 );
137 // Clear wslOnly too so enabling WSL cannot restore a failed mode.
138 // Keep the in-memory fallback if persistence fails.
139 yield* appSettings.applyWslWindowsFallback.pipe(
140 Effect.catch((error) =>
141 logBackendPoolWarning(
142 "failed to persist Windows fallback after WSL preflight failure",
143 {
144 error: error.message,
145 },
146 ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
147 ),
148 );
149 return true;
150 },
151 );
152​
153 const primary = yield* DesktopBackendManager.makeBackendInstance({
154 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
155 // Resolve lazily: startup loads persisted settings after pool initialization.
156 label: configuration.resolvePrimaryLabel,
157 configResolve: configuration.resolvePrimary,
158 // Absorb window errors so readiness can reset restartAttempt.
159 onReady: (httpBaseUrl) =>
160 desktopWindow.handleBackendReady(httpBaseUrl).pipe(
161 Effect.catch((error) =>
162 logBackendPoolWarning("failed to open main window after backend readiness", {
163 error: error.message,
164 }),
165 ),
166 ),
167 onShutdown: () => desktopWindow.handleBackendNotReady,
168 onPreflightFailed: handlePrimaryPreflightFailure,
169 onStateDirOwned: () =>
170 electronDialog
171 .showErrorBox(
172 "This T3 home is unavailable",
173 "Another T3 Code server, such as the background service, is using this data directory, or an older background service is set up for it. Stop that server or try `t3 update`. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command. Then reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.",
174 )
175 .pipe(Effect.andThen(electronApp.quit)),
176 });
177​
178 const instancesRef = yield* SynchronizedRef.make<
179 ReadonlyMap<BackendInstanceId, RegisteredInstance>
180 >(
181 new Map([
182 [
183 DesktopBackendManager.PRIMARY_INSTANCE_ID,
184 { _tag: "Active", instance: primary, scope: Option.none() },
185 ],
186 ]),
187 );
188​
189 const register: DesktopBackendPool["Service"]["register"] = (spec) =>
190 Effect.suspend(() =>
191 SynchronizedRef.modifyEffect(
192 instancesRef,
193 (
194 current,
195 ): Effect.Effect<
196 readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
197 DesktopBackendPoolInstanceAlreadyRegisteredError
198 > => {
199 const existing = current.get(spec.id);
200 if (existing?._tag === "Active") {
201 return Effect.fail(
202 new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
203 );
204 }
205 if (existing?._tag === "Closing") {
206 return Effect.succeed([
207 { _tag: "Wait", done: existing.done } as const,
208 current,
209 ] as const);
210 }
211 return Effect.gen(function* () {
212 // Provide the child Scope last so the captured pool Scope cannot shadow it and orphan stop/restart finalizers.
213 const instanceScope = yield* Scope.fork(layerScope, "sequential");
214 const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
215 Scope.provide(instanceScope),
216 Effect.provide(factoryContext),
217 );
218 const next = new Map(current);
219 next.set(spec.id, {
220 _tag: "Active",
221 instance,
222 scope: Option.some(instanceScope),
223 });
224 return [
225 { _tag: "Registered", instance } as const,
226 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
227 ] as const;
228 });
229 },
230 ).pipe(
231 Effect.flatMap((result) =>
232 result._tag === "Registered"
233 ? Effect.succeed(result.instance)
234 : Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
235 ),
236 ),
237 );
238​
239 const unregister: DesktopBackendPool["Service"]["unregister"] = Effect.fn(
240 "DesktopBackendPool.unregister",
241 )(function* (id) {
242 if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
243 return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
244 }
245 const done = yield* Deferred.make<void>();
246 const action = yield* SynchronizedRef.modifyEffect(
247 instancesRef,
248 (
249 current,
250 ): Effect.Effect<
251 readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
252 > => {
253 const entry = current.get(id);
254 if (entry === undefined) {
255 return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
256 }
257 if (entry._tag === "Closing") {
258 return Effect.succeed([{ _tag: "Wait", done: entry.done } as const, current] as const);
259 }
260 const next = new Map(current);
261 next.set(id, { _tag: "Closing", done });
262 return Effect.succeed([
263 { _tag: "Close", entry } as const,
264 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
265 ] as const);
266 },
267 );
268​
269 if (action._tag === "Absent") return;
270 if (action._tag === "Wait") {
271 yield* Deferred.await(action.done);
272 return;
273 }
274​
275 const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
276 const closing = current.get(id);
277 if (closing?._tag !== "Closing" || closing.done !== done) {
278 return Effect.succeed([undefined, current] as const);
279 }
280 const next = new Map(current);
281 next.delete(id);
282 return Effect.succeed([
283 undefined,
284 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
285 ] as const);
286 }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
287 yield* Option.match(action.entry.scope, {
288 onNone: () => Effect.void,
289 onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
290 }).pipe(Effect.ensuring(finish));
291 });
292​
293 return DesktopBackendPool.of({
294 get: (id) =>
295 SynchronizedRef.get(instancesRef).pipe(
296 Effect.map((instances) => {
297 const entry = instances.get(id);
298 return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
299 }),
300 ),
301 list: SynchronizedRef.get(instancesRef).pipe(
302 Effect.map((instances) =>
303 Array.from(instances.values()).flatMap((entry) =>
304 entry._tag === "Active" ? [entry.instance] : [],
305 ),
306 ),
307 ),
308 primary: Effect.succeed(primary),
309 register,
310 unregister,
311 });
312 }),
313);
314​
315export const layerTest = (
316 instances: readonly DesktopBackendInstance[],
317): Layer.Layer<DesktopBackendPool> =>
318 Layer.effect(
319 DesktopBackendPool,
320 Effect.gen(function* () {
321 if (instances.length === 0) {
322 return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
323 }
324 const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
325 instances.map((instance) => [instance.id, instance] as const),
326 );
327 const primary = instances[0]!;
328 return DesktopBackendPool.of({
329 get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
330 list: Effect.succeed(Array.from(byId.values())),
331 primary: Effect.succeed(primary),
332 register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
333 unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
334 });
335 }),
336 );