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

DesktopBackendPool.ts

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