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

DesktopBackendPool.ts

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