diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index 13a9e89958..14aea24bd7 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -2,7 +2,7 @@ // point for the concurrent-Windows+WSL-backend feature; see the design // notes below before extending it. // -// Current state (step 3): +// Current state (step 4): // - `DesktopBackendManager.ts` no longer exposes a Context.Service. It // is a per-instance factory (`makeBackendInstance(spec)`); the pool // calls it once for the Windows primary at startup. @@ -10,6 +10,10 @@ // and the `onReady`/`onShutdown` callbacks to the window service's // `handleBackendReady` / `handleBackendNotReady`. Readiness is no // longer in `DesktopState`; the window owns its own latch. +// - The pool exposes `register(spec)` and `unregister(id)` so other +// services can attach a backend on demand. Each registered instance +// gets its own child scope so unregister can stop it cleanly without +// tearing down the whole pool. // - Consumers (window/wsl IPC, lifecycle hooks, telemetry) read the // primary instance off `pool.primary`. There is no longer a separate // `DesktopBackendManager` service in the layer graph. @@ -35,11 +39,12 @@ // 2. Drop `DesktopState.backendReady`. The window owns its own // readiness latch, driven by the primary instance's onReady / // onShutdown callbacks. -// 3. (this commit) Per-instance log routing: replace the singleton +// 3. Per-instance log routing: replace the singleton // DesktopBackendOutputLog with a factory that vends one rotating // writer per instance id (primary keeps server-child.log; others go // to server-child-.log). -// 4. Add register/unregister so WSL backend can be added on demand. +// 4. (this commit) Add register/unregister so WSL backend can be added +// on demand. No caller registers a second instance yet. // 5. Wire WSL distro startup through the pool; remove `setWslBackend` // mode-swap IPC in favor of `enableWslBackend` / `setWslDistro`. // 6. Widen `getLocalEnvironmentBootstrap` → `*Bootstraps`; frontend @@ -48,19 +53,52 @@ // "WSL backend enabled + distro" pair instead. import * as Context from "effect/Context"; +import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; +import * as SynchronizedRef from "effect/SynchronizedRef"; + +import * as FileSystem from "effect/FileSystem"; +import { HttpClient } from "effect/unstable/http"; +import { ChildProcessSpawner } from "effect/unstable/process"; import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopBackendManager from "./DesktopBackendManager.ts"; +import * as DesktopObservability from "../app/DesktopObservability.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; export type BackendInstanceId = DesktopBackendManager.BackendInstanceId; export const BackendInstanceId = DesktopBackendManager.BackendInstanceId; export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID; export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance; +export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec; + +// Caller tried to register an id that's already in the pool. The pool +// refuses overwrites so two independent orchestrators racing on the +// same id surface as a typed failure instead of one silently winning. +export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Data.TaggedError( + "DesktopBackendPoolInstanceAlreadyRegisteredError", +)<{ + readonly id: BackendInstanceId; +}> { + override get message() { + return `Backend instance "${this.id}" is already registered in the pool.`; + } +} + +// Primary instance is registered for the pool's lifetime. Unregister is +// a no-op for it today (no real callers), but if someone wires it up +// later it's a clear bug rather than something to "handle". +export class DesktopBackendPoolCannotUnregisterPrimaryError extends Data.TaggedError( + "DesktopBackendPoolCannotUnregisterPrimaryError", +)<{}> { + override get message() { + return "Refusing to unregister the primary backend from the pool."; + } +} export interface DesktopBackendPoolShape { // Look up a registered instance. None when no backend with that id is @@ -74,6 +112,23 @@ export interface DesktopBackendPoolShape { // exposed as a typed effect so consumers don't have to handle the // Option for the case that's guaranteed to be present. readonly primary: Effect.Effect; + // Build a fresh DesktopBackendInstance from `spec` and add it to the + // registry. The pool owns the instance's scope: unregister(id) or pool + // teardown closes it and runs the instance's auto-stop finalizer. The + // returned instance has not been started — callers decide when to + // start it (and can call start more than once if a retry-after-failure + // story makes sense for them). + readonly register: ( + spec: BackendInstanceSpec, + ) => Effect.Effect; + // Stop the named instance and remove it from the registry. Closing the + // instance's scope triggers its auto-stop finalizer; the registry is + // updated atomically with the scope close so subsequent get(id) calls + // observe the unregister before the underlying child process has fully + // exited. + readonly unregister: ( + id: BackendInstanceId, + ) => Effect.Effect; } export class DesktopBackendPool extends Context.Service< @@ -81,11 +136,34 @@ export class DesktopBackendPool extends Context.Service< DesktopBackendPoolShape >()("t3/desktop/BackendPool") {} +// Services required by makeBackendInstance — exported so caller +// orchestrators that build their own specs can confirm the layer graph +// satisfies them at compile time. +export type BackendInstanceFactoryRequirements = + | FileSystem.FileSystem + | ChildProcessSpawner.ChildProcessSpawner + | HttpClient.HttpClient + | DesktopObservability.DesktopBackendOutputLogFactory; + +interface RegisteredInstance { + readonly instance: DesktopBackendInstance; + // None for the primary (which lives in the pool's own layer scope and + // is never unregistered); Some for instances added via register, whose + // scope unregister closes to stop them. + readonly scope: Option.Option; +} + export const layer = Layer.effect( DesktopBackendPool, Effect.gen(function* () { const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; const desktopWindow = yield* DesktopWindow.DesktopWindow; + // Capture the services needed to build any future instance from the + // pool's layer scope. register() runs `makeBackendInstance` against + // a fresh child scope but reuses these services so the instance gets + // the same FileSystem, spawner, HTTP client and log factory the + // primary instance uses. + const factoryContext = yield* Effect.context(); const primary = yield* DesktopBackendManager.makeBackendInstance({ id: DesktopBackendManager.PRIMARY_INSTANCE_ID, @@ -99,17 +177,68 @@ export const layer = Layer.effect( onShutdown: () => desktopWindow.handleBackendNotReady, }); - const instancesRef = yield* Ref.make>( - new Map([[DesktopBackendManager.PRIMARY_INSTANCE_ID, primary]]), + const instancesRef = yield* SynchronizedRef.make< + ReadonlyMap + >( + new Map([ + [DesktopBackendManager.PRIMARY_INSTANCE_ID, { instance: primary, scope: Option.none() }], + ]), ); + const register: DesktopBackendPoolShape["register"] = (spec) => + SynchronizedRef.modifyEffect(instancesRef, (current) => { + if (current.has(spec.id)) { + return Effect.fail(new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id })); + } + return Effect.gen(function* () { + const instanceScope = yield* Scope.make("sequential"); + const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe( + Scope.provide(instanceScope), + Effect.provide(factoryContext), + ); + const next = new Map(current); + next.set(spec.id, { instance, scope: Option.some(instanceScope) }); + return [instance, next as ReadonlyMap] as const; + }); + }); + + const unregister: DesktopBackendPoolShape["unregister"] = (id) => + Effect.gen(function* () { + if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) { + return yield* new DesktopBackendPoolCannotUnregisterPrimaryError(); + } + // modifyEffect atomically pulls the entry out of the registry + // and yields the scope handle; closing the scope below runs the + // instance's auto-stop finalizer. + const removed = yield* SynchronizedRef.modifyEffect(instancesRef, (current) => { + const entry = current.get(id); + if (entry === undefined) { + return Effect.succeed([Option.none(), current] as const); + } + const next = new Map(current); + next.delete(id); + return Effect.succeed([ + entry.scope, + next as ReadonlyMap, + ] as const); + }); + yield* Option.match(removed, { + onNone: () => Effect.void, + onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore), + }); + }); + return DesktopBackendPool.of({ get: (id) => - Ref.get(instancesRef).pipe( - Effect.map((instances) => Option.fromNullishOr(instances.get(id))), + SynchronizedRef.get(instancesRef).pipe( + Effect.map((instances) => Option.fromNullishOr(instances.get(id)?.instance)), ), - list: Ref.get(instancesRef).pipe(Effect.map((instances) => Array.from(instances.values()))), + list: SynchronizedRef.get(instancesRef).pipe( + Effect.map((instances) => Array.from(instances.values(), (entry) => entry.instance)), + ), primary: Effect.succeed(primary), + register, + unregister, }); }), ); @@ -118,6 +247,9 @@ export const layer = Layer.effect( // composition without standing up the full manager. Each provided // instance is registered under its own id; the first one is also // surfaced as `primary` so callers can stub a single-instance pool. +// `register` and `unregister` are stubbed to die so tests that +// accidentally exercise pool registration fail loudly instead of +// silently noop'ing. export const layerTest = ( instances: readonly DesktopBackendInstance[], ): Layer.Layer => @@ -135,6 +267,8 @@ export const layerTest = ( get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))), list: Effect.succeed(Array.from(byId.values())), primary: Effect.succeed(primary), + register: () => Effect.die("DesktopBackendPool.layerTest does not support register"), + unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"), }); }), );