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

DesktopBackendManager.ts

1,141 lines41.3 KB

1// Per-instance backend factory. Replaces the legacy singleton
2// `DesktopBackendManager` Context.Service: each call to
3// `makeBackendInstance(spec)` constructs an isolated backend lifecycle —
4// its own state Ref, mutex, restart loop, and active child process. The
5// returned `DesktopBackendInstance` exposes start/stop/snapshot/wait
6// methods that operate on that single backend.
7//
8// The pool layer (`DesktopBackendPool.ts`) calls this factory once per
9// backend it wants to run. Today that's the Windows primary; follow-up
10// commits add a second call for the WSL instance.
11//
12// Singleton couplings that the legacy service held inline are now
13// parameterized via the spec:
14// - configResolve replaces the legacy `DesktopBackendConfiguration.resolve`
15// so each instance can resolve its own start config — the primary wires
16// `configuration.resolvePrimary`, the WSL orchestrator wires a
17// `configuration.resolveWsl({ port, distro })` closure.
18// - onReady / onShutdown drive UI side effects (window auto-open,
19// readiness latch) only for instances that want them — the primary's
20// spec passes the window's handleBackendReady/handleBackendNotReady,
21// other pool instances pass nothing.
22// - log writes go through a per-instance writer that the factory
23// pulls from `DesktopBackendOutputLogFactory.forInstance(spec.id)`,
24// so each instance lands in its own rotating file.
25​
26import * as Brand from "effect/Brand";
27import * as Cause from "effect/Cause";
28import * as Duration from "effect/Duration";
29import * as Effect from "effect/Effect";
30import * as Exit from "effect/Exit";
31import * as Fiber from "effect/Fiber";
32import * as FileSystem from "effect/FileSystem";
33import * as Option from "effect/Option";
34import * as PlatformError from "effect/PlatformError";
35import * as Ref from "effect/Ref";
36import * as Schedule from "effect/Schedule";
37import * as Schema from "effect/Schema";
38import * as Semaphore from "effect/Semaphore";
39import * as Scope from "effect/Scope";
40import * as Stream from "effect/Stream";
41import { HttpClient } from "effect/unstable/http";
42import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
43​
44import {
45 DesktopBackendBootstrap,
46 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
47 PRIMARY_LOCAL_ENVIRONMENT_ID,
48 DesktopTelemetryControlMessage,
49 type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
50} from "@t3tools/contracts";
51import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
52​
53import * as DesktopObservability from "../app/DesktopObservability.ts";
54import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
55​
56const INITIAL_RESTART_DELAY = Duration.millis(500);
57const MAX_RESTART_DELAY = Duration.seconds(10);
58// After this many consecutive fatal preflight failures, stop the silent
59// restart loop and surface the reason via onPreflightFailed. Transient
60// failures may instead provide their own larger retryLimit when they should
61// self-heal for a while but must not leave the app connecting forever.
62const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
63const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
64const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
65const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
66const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
67const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
68const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
69const { logWarning: logBackendProcessWarning } =
70 DesktopObservability.makeComponentLogger("desktop-backend-process");
71​
72type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
73​
74type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
75​
76export type BackendProcessOutputStream = "stdout" | "stderr";
77​
78export interface BackendProcessContext {
79 readonly executablePath: string;
80 readonly entryPath: string;
81 readonly cwd: string;
82 readonly httpBaseUrl: URL;
84​
85export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
86​
87export interface DesktopBackendStartConfig extends BackendProcessContext {
88 readonly args: ReadonlyArray<string>;
89 readonly env: Record<string, string | undefined>;
90 // When true the spawner merges the desktop process.env on top of `env`;
91 // when false `env` is passed verbatim. WSL mode opts out so a leaking
92 // T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3.
93 readonly extendEnv: boolean;
94 readonly bootstrap: DesktopBackendBootstrapValue;
95 readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
96 readonly httpBaseUrl: URL;
97 readonly captureOutput: boolean;
98 readonly preflightFailure: Option.Option<PreflightFailure>;
99 // Present for a WSL run after the configured/default distro has been
100 // resolved to the concrete distro passed to wsl.exe.
101 readonly runningDistro?: string;
103​
104// A preflight failure records whether it is fatal. Transient failures (WSL
105// cold-starting, wslpath while the VM boots) keep retrying so the backend can
106// self-heal; fatal ones (no node, wrong version, missing build tools) are
107// surfaced via onPreflightFailed and stop the restart loop after
108// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
109export interface PreflightFailure {
110 readonly reason: string;
111 readonly fatal: boolean;
112 readonly retryLimit?: number;
114​
115interface BackendProcessExit {
116 readonly code: Option.Option<number>;
117 readonly reason: string;
119​
120const backendProcessContextSchema = {
121 executablePath: Schema.String,
122 entryPath: Schema.String,
123 cwd: Schema.String,
124 httpBaseUrl: Schema.URL,
125};
126​
127export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
128 "BackendReadinessTimeoutError",
129 {
130 ...backendProcessContextSchema,
131 readinessUrl: Schema.URL,
132 timeoutMs: Schema.Number,
133 cause: Schema.Defect(),
134 },
135) {
136 override get message(): string {
137 return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
138 }
140​
141export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
142 "BackendProcessBootstrapEncodeError",
143 {
144 ...backendProcessContextSchema,
145 cause: Schema.Defect(),
146 },
147) {
148 override get message(): string {
149 return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
150 }
152​
153export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
154 "BackendProcessSpawnError",
155 {
156 ...backendProcessContextSchema,
157 cause: Schema.Defect(),
158 },
159) {
160 override get message(): string {
161 return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
162 }
164​
165export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
166 "BackendProcessOutputReadError",
167 {
168 ...backendProcessContextSchema,
169 pid: Schema.Number,
170 streamName: Schema.Literals(["stdout", "stderr"]),
171 cause: Schema.Defect(),
172 },
173) {
174 override get message(): string {
175 return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
176 }
178​
179export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
180 "BackendProcessOutputHandlingError",
181 {
182 ...backendProcessContextSchema,
183 pid: Schema.Number,
184 streamName: Schema.Literals(["stdout", "stderr"]),
185 chunkByteLength: Schema.Number,
186 cause: Schema.Defect(),
187 },
188) {
189 override get message(): string {
190 return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
191 }
193​
194export type BackendProcessOutputError =
195 | BackendProcessOutputReadError
196 | BackendProcessOutputHandlingError;
197​
198export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
199 "BackendProcessExitStatusError",
200 {
201 ...backendProcessContextSchema,
202 pid: Schema.Number,
203 cause: Schema.Defect(),
204 },
205) {
206 override get message(): string {
207 return `Failed to read the exit status of desktop backend process ${this.pid}.`;
208 }
210​
211export const BackendProcessError = Schema.Union([
212 BackendProcessBootstrapEncodeError,
213 BackendProcessSpawnError,
214 BackendProcessExitStatusError,
215]);
216export type BackendProcessError = typeof BackendProcessError.Type;
217​
218interface RunBackendProcessOptions extends DesktopBackendStartConfig {
219 readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
220 readonly onDesktopTelemetryControl?: (
221 message: DesktopTelemetryControlMessageValue,
222 ) => Effect.Effect<void>;
223 readonly readinessTimeout?: Duration.Duration;
224 readonly outputDrainTimeout?: Duration.Duration;
225 readonly onStarted?: (pid: number) => Effect.Effect<void>;
226 readonly onExitObserved?: () => Effect.Effect<void>;
227 readonly onReady?: () => Effect.Effect<void>;
228 readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
229 readonly onOutput?: (
230 streamName: BackendProcessOutputStream,
231 chunk: Uint8Array,
232 ) => Effect.Effect<void, Error>;
233 readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
235​
236export interface DesktopBackendSnapshot {
237 readonly desiredRunning: boolean;
238 readonly ready: boolean;
239 readonly activePid: Option.Option<number>;
240 readonly restartAttempt: number;
241 readonly restartScheduled: boolean;
243​
244// Opaque identifier for one backend process inside the pool. Today only
245// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
246// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
247// these map 1:1 with environment ids on the frontend; keeping them
248// desktop-local for now avoids leaking the contracts dependency.
249export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
250export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
251​
252export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
253 PRIMARY_LOCAL_ENVIRONMENT_ID,
254);
255​
256// One pooled backend instance. Same lifecycle surface as the legacy
257// `DesktopBackendManagerShape`; the id and label give the pool registry
258// + UI something to route on.
259export interface DesktopBackendInstance {
260 readonly id: BackendInstanceId;
261 readonly label: Effect.Effect<string>;
262 readonly start: Effect.Effect<void>;
263 readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
264 readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
265 readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
266 // Polls desiredRunning + the instance's own ready flag until the
267 // backend reports ready, or the timeout elapses. Returns true on
268 // ready, false on timeout. Used by the WSL backend swap to drive its
269 // rollback path.
270 readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
272​
273// Spec describing one backend instance to spawn. The configResolve
274// effect is awaited each time the instance is (re)started so live
275// settings changes are picked up on the next start cycle. onReady and
276// onShutdown let the primary instance trigger UI side effects (window
277// open, global readiness flag) without coupling the factory to those
278// concerns; other instances pass them as undefined.
279export interface BackendInstanceSpec {
280 readonly id: BackendInstanceId;
281 readonly label: Effect.Effect<string>;
282 // configResolve can now fail with PlatformError because the
283 // bootstrap-token closure inside DesktopBackendConfiguration uses
284 // crypto.randomBytes (Effect 4 beta.73 migration).
285 readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
286 // Receives the *resolved* httpBaseUrl of the run that just became
287 // ready. The window service uses this to decide what URL to load
288 // (the WSL backend reports its distro IP, the Windows backend reports
289 // 127.0.0.1). Splitting this off from configResolve avoids races
290 // between "fired onReady" and "currentConfig already advanced".
291 readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
292 readonly onShutdown?: () => Effect.Effect<void>;
293 // Fired once when a fatal or bounded preflight failure has exhausted its
294 // retries. Returns true when the callback changed configuration and the
295 // manager should resolve once more; false stops the failed instance.
296 readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
298​
299interface ActiveBackendRun {
300 readonly id: number;
301 readonly scope: Scope.Closeable;
302 readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
303 readonly pid: Option.Option<number>;
304 readonly exitObserved: boolean;
305 readonly stopRequested: boolean;
307​
308interface BackendManagerState {
309 readonly desiredRunning: boolean;
310 readonly ready: boolean;
311 readonly config: Option.Option<DesktopBackendStartConfig>;
312 readonly active: Option.Option<ActiveBackendRun>;
313 readonly restartAttempt: number;
314 // Consecutive bounded/fatal preflight failures, reset on a clean or
315 // unbounded-transient preflight. restartAttempt counts all restarts.
316 readonly preflightFailureAttempt: number;
317 readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
318 readonly nextRunId: number;
320​
321const initialState: BackendManagerState = {
322 desiredRunning: false,
323 ready: false,
324 config: Option.none(),
325 active: Option.none(),
326 restartAttempt: 0,
327 preflightFailureAttempt: 0,
328 restartFiber: Option.none(),
329 nextRunId: 1,
330};
331​
332const activePid = (active: Option.Option<ActiveBackendRun>): Option.Option<number> =>
333 Option.flatMap(active, (run) => run.pid);
334​
335const withActiveRun =
336 (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
337 (state: BackendManagerState): BackendManagerState => ({
338 ...state,
339 active: Option.map(state.active, (run) => (run.id === runId ? f(run) : run)),
340 });
341​
342const calculateRestartDelay = (attempt: number): Duration.Duration =>
343 Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
344​
345const closeRun = (
346 run: ActiveBackendRun,
347 parentScope: Scope.Scope,
348 options?: { readonly timeout?: Duration.Duration },
349): Effect.Effect<boolean> => {
350 const waitForFiber = Option.match(run.fiber, {
351 onNone: () => Effect.void,
352 onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
353 });
354 const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
355 const timeout = options?.timeout;
356​
357 if (!timeout) {
358 return close.pipe(Effect.as(true));
359 }
360​
361 return Effect.forkIn(close, parentScope).pipe(
362 Effect.flatMap((closeFiber) =>
363 Fiber.await(closeFiber).pipe(Effect.timeoutOption(timeout), Effect.map(Option.isSome)),
364 ),
365 );
366};
367​
368export const waitForHttpReady = (
369 options: BackendProcessContext & { readonly timeout: Duration.Duration },
370): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
371 const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
372 return waitForHttpReadyShared({
373 baseUrl: options.httpBaseUrl.href,
374 path: BACKEND_READINESS_PATH,
375 timeoutMs: Duration.toMillis(options.timeout),
376 intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
377 probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
378 makeError: ({ cause }) =>
379 new BackendReadinessTimeoutError({
380 executablePath: options.executablePath,
381 entryPath: options.entryPath,
382 cwd: options.cwd,
383 httpBaseUrl: options.httpBaseUrl,
384 readinessUrl,
385 timeoutMs: Duration.toMillis(options.timeout),
386 cause,
387 }),
388 });
389};
390​
391function drainBackendOutput(
392 context: BackendProcessContext & { readonly pid: number },
393 streamName: BackendProcessOutputStream,
394 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
395 onOutput: (
396 streamName: BackendProcessOutputStream,
397 chunk: Uint8Array,
398 ) => Effect.Effect<void, Error>,
399 onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
400): Effect.Effect<void> {
401 return stream.pipe(
402 Stream.mapError(
403 (cause) =>
404 new BackendProcessOutputReadError({
405 ...context,
406 streamName,
407 cause,
408 }),
409 ),
410 Stream.runForEach((chunk) =>
411 onOutput(streamName, chunk).pipe(
412 Effect.mapError(
413 (cause) =>
414 new BackendProcessOutputHandlingError({
415 ...context,
416 streamName,
417 chunkByteLength: chunk.byteLength,
418 cause,
419 }),
420 ),
421 Effect.catchTag("BackendProcessOutputHandlingError", onOutputFailure),
422 ),
423 ),
424 Effect.catchTags({
425 BackendProcessOutputReadError: onOutputFailure,
426 }),
427 );
429​
430const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
431const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
432 Schema.fromJsonString(DesktopTelemetryControlMessage),
433);
434​
435export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
436 options: RunBackendProcessOptions,
437): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
438 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
439 const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
440 Effect.mapError(
441 (cause) =>
442 new BackendProcessBootstrapEncodeError({
443 executablePath: options.executablePath,
444 entryPath: options.entryPath,
445 cwd: options.cwd,
446 httpBaseUrl: options.httpBaseUrl,
447 cause,
448 }),
449 ),
450 );
451 const onOutput = options.onOutput ?? (() => Effect.void);
452 const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
453 const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {};
454 if (options.bootstrapDelivery === "fd3") {
455 additionalFds.fd3 = {
456 type: "input",
457 stream: bootstrapStream,
458 };
459 if (options.bootstrap.desktopTelemetryFd !== undefined) {
460 additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
461 type: "input",
462 stream: options.desktopTelemetryStream,
463 };
464 }
465 if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
466 additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
467 type: "output",
468 };
469 }
470 }
471 const command = ChildProcess.make(options.executablePath, options.args, {
472 cwd: options.cwd,
473 env: options.env,
474 extendEnv: options.extendEnv,
475 // In Electron main, process.execPath points to the Electron binary.
476 // Run the child in Node mode so this backend process does not become a GUI app instance.
477 stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
478 stdout: options.captureOutput ? "pipe" : "inherit",
479 stderr: options.captureOutput ? "pipe" : "inherit",
480 killSignal: "SIGTERM",
481 forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
482 // wsl.exe drops additional file descriptors when forwarding to the Linux
483 // side, so the WSL spawn path delivers the bootstrap envelope via stdin
484 // (`--bootstrap-fd 0`) instead.
485 ...(options.bootstrapDelivery === "fd3" ? { additionalFds } : {}),
486 });
487​
488 const handle = yield* spawner.spawn(command).pipe(
489 Effect.mapError(
490 (cause) =>
491 new BackendProcessSpawnError({
492 executablePath: options.executablePath,
493 entryPath: options.entryPath,
494 cwd: options.cwd,
495 httpBaseUrl: options.httpBaseUrl,
496 cause,
497 }),
498 ),
499 );
500 const outputFibers: Array<Fiber.Fiber<void, never>> = [];
501​
502 yield* options.onStarted?.(handle.pid) ?? Effect.void;
503 if (
504 options.bootstrap.desktopTelemetryControlFd !== undefined &&
505 options.onDesktopTelemetryControl !== undefined
506 ) {
507 const controlFd = options.bootstrap.desktopTelemetryControlFd;
508 const handleControl = options.onDesktopTelemetryControl;
509 yield* handle.getOutputFd(controlFd).pipe(
510 Stream.decodeText(),
511 Stream.splitLines,
512 Stream.filter((line) => line.trim().length > 0),
513 Stream.runForEach((line) =>
514 decodeDesktopTelemetryControlLine(line).pipe(
515 Effect.flatMap(handleControl),
516 Effect.catchCause((cause) =>
517 logBackendProcessWarning("ignored invalid desktop telemetry control message", {
518 fd: controlFd,
519 cause: Cause.pretty(cause),
520 }),
521 ),
522 ),
523 ),
524 Effect.catchCause((cause) =>
525 logBackendProcessWarning("desktop telemetry control stream stopped", {
526 fd: controlFd,
527 cause: Cause.pretty(cause),
528 }),
529 ),
530 Effect.ensuring(
531 handleControl({
532 version: 1,
533 type: "setDiagnosticsDemand",
534 enabled: false,
535 }),
536 ),
537 Effect.forkScoped,
538 );
539 }
540 if (options.captureOutput) {
541 const outputContext = {
542 executablePath: options.executablePath,
543 entryPath: options.entryPath,
544 cwd: options.cwd,
545 httpBaseUrl: options.httpBaseUrl,
546 pid: Number(handle.pid),
547 };
548 const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
549 outputFibers.push(
550 yield* drainBackendOutput(
551 outputContext,
552 "stdout",
553 handle.stdout,
554 onOutput,
555 onOutputFailure,
556 ).pipe(Effect.forkScoped),
557 yield* drainBackendOutput(
558 outputContext,
559 "stderr",
560 handle.stderr,
561 onOutput,
562 onOutputFailure,
563 ).pipe(Effect.forkScoped),
564 );
565 }
566 yield* waitForHttpReady({
567 executablePath: options.executablePath,
568 entryPath: options.entryPath,
569 cwd: options.cwd,
570 httpBaseUrl: options.httpBaseUrl,
571 timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
572 }).pipe(
573 Effect.tap(() => options.onReady?.() ?? Effect.void),
574 Effect.catchTags({
575 BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
576 }),
577 Effect.forkScoped,
578 );
579​
580 const exit = yield* handle.exitCode.pipe(
581 Effect.mapError(
582 (cause) =>
583 new BackendProcessExitStatusError({
584 executablePath: options.executablePath,
585 entryPath: options.entryPath,
586 cwd: options.cwd,
587 httpBaseUrl: options.httpBaseUrl,
588 pid: Number(handle.pid),
589 cause,
590 }),
591 ),
592 Effect.exit,
593 );
594 yield* options.onExitObserved?.() ?? Effect.void;
595 yield* Effect.forEach(outputFibers, Fiber.await, {
596 concurrency: "unbounded",
597 discard: true,
598 }).pipe(
599 Effect.timeout(options.outputDrainTimeout ?? DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT),
600 Effect.ignore,
601 );
602 if (Exit.isFailure(exit)) {
603 return yield* Effect.failCause(exit.cause);
604 }
605 const exitCode = exit.value;
606 return {
607 code: Option.some(exitCode),
608 reason: `code=${exitCode}`,
609 } satisfies BackendProcessExit;
610});
611​
612// Factory for one pooled backend instance. The returned instance owns
613// its own state Ref, mutex, restart loop, and active child process;
614// nothing is shared between instances created from separate
615// makeBackendInstance calls. The instance shuts down automatically when
616// the calling scope closes (typically the application scope).
617export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
618 spec: BackendInstanceSpec,
619): Effect.fn.Return<
620 DesktopBackendInstance,
621 never,
622 | FileSystem.FileSystem
623 | ChildProcessSpawner.ChildProcessSpawner
624 | HttpClient.HttpClient
625 | DesktopObservability.DesktopBackendOutputLogFactory
626 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
627 | Scope.Scope
628> {
629 const parentScope = yield* Scope.Scope;
630 const fileSystem = yield* FileSystem.FileSystem;
631 const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
632 const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
633 const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
634 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
635 const httpClient = yield* HttpClient.HttpClient;
636 const state = yield* Ref.make(initialState);
637 const mutex = yield* Semaphore.make(1);
638​
639 const { logWarning: logInstanceWarning, logError: logInstanceError } =
640 DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
641​
642 const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
643 Ref.update(state, withActiveRun(runId, f));
644​
645 const snapshot = Ref.get(state).pipe(
646 Effect.map(
647 (current): DesktopBackendSnapshot => ({
648 desiredRunning: current.desiredRunning,
649 ready: current.ready,
650 activePid: activePid(current.active),
651 restartAttempt: current.restartAttempt,
652 restartScheduled: Option.isSome(current.restartFiber),
653 }),
654 ),
655 );
656 const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config));
657​
658 const cancelRestart = Effect.gen(function* () {
659 const restartFiber = yield* Ref.modify(state, (current) => [
660 current.restartFiber,
661 {
662 ...current,
663 restartFiber: Option.none(),
664 },
665 ]);
666​
667 yield* Option.match(restartFiber, {
668 onNone: () => Effect.void,
669 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
670 });
671 });
672​
673 const start: Effect.Effect<void> = Effect.suspend(() =>
674 mutex.withPermits(1)(
675 Effect.gen(function* () {
676 const current = yield* Ref.get(state);
677 if (Option.isSome(current.active)) {
678 if (!current.desiredRunning) {
679 yield* Ref.update(state, (latest) => ({
680 ...latest,
681 desiredRunning: true,
682 }));
683 }
684 return;
685 }
686​
687 if (current.ready) {
688 yield* spec.onShutdown?.() ?? Effect.void;
689 yield* Ref.update(state, (latest) =>
690 latest.ready ? { ...latest, ready: false } : latest,
691 );
692 }
693 const config = yield* spec.configResolve.pipe(
694 Effect.tapError((error) =>
695 logInstanceError("failed to generate desktop backend configuration", {
696 cause: error.message,
697 }),
698 ),
699 Effect.option,
700 );
701 if (Option.isNone(config)) {
702 if (current.desiredRunning) {
703 yield* scheduleRestart("failed to generate desktop backend configuration");
704 }
705 return;
706 }
707 const entryExists = yield* fileSystem
708 .exists(config.value.entryPath)
709 .pipe(Effect.orElseSucceed(() => false));
710​
711 const resetFatalPreflightCounter =
712 !current.desiredRunning && current.preflightFailureAttempt > 0;
713 yield* cancelRestart;
714 yield* Ref.update(state, (latest) => ({
715 ...latest,
716 desiredRunning: true,
717 ready: false,
718 config: Option.some(config.value),
719 preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
720 }));
721​
722 const preflightFailure = config.value.preflightFailure;
723 if (Option.isSome(preflightFailure)) {
724 const { reason, fatal, retryLimit } = preflightFailure.value;
725 if (!fatal && retryLimit === undefined) {
726 // Transient (WSL cold-starting, wslpath while the VM boots). Keep
727 // retrying so the backend self-heals once WSL is ready. Reset a
728 // prior bounded/fatal streak because this is a different failure.
729 yield* Ref.update(state, (latest) =>
730 latest.preflightFailureAttempt === 0
731 ? latest
732 : { ...latest, preflightFailureAttempt: 0 },
733 );
734 yield* scheduleRestart(reason);
735 return;
736 }
737 const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
738 const attempt = yield* Ref.modify(state, (latest) => {
739 const next = latest.preflightFailureAttempt + 1;
740 return [next, { ...latest, preflightFailureAttempt: next }] as const;
741 });
742 if (attempt > attemptLimit) {
743 // We already surfaced and asked for the Windows fallback, yet we're
744 // still resolving the WSL primary — the fallback didn't take (e.g.
745 // the settings write failed). Stop rather than loop forever.
746 yield* logInstanceError("backend preflight still failing after fallback; stopping", {
747 reason,
748 attempt,
749 });
750 yield* Ref.update(state, (latest) => ({
751 ...latest,
752 desiredRunning: false,
753 ready: false,
754 }));
755 return;
756 }
757 if (attempt === attemptLimit) {
758 // Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
759 // on the primary, shows a dialog and persists Windows mode), then
760 // schedule one more restart so the next resolve picks up the Windows
761 // primary and a window can open.
762 yield* logInstanceError(
763 "backend preflight failed repeatedly; surfacing and falling back",
764 { reason, attempt },
765 );
766 const shouldRestart = yield* (
767 spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
768 );
769 if (shouldRestart) {
770 yield* scheduleRestart(reason);
771 } else {
772 yield* Ref.update(state, (latest) => ({
773 ...latest,
774 desiredRunning: false,
775 ready: false,
776 }));
777 }
778 return;
779 }
780 yield* scheduleRestart(reason);
781 return;
782 }
783 // Clean preflight — reset the fatal counter so a later failure gets a
784 // fresh allowance.
785 yield* Ref.update(state, (latest) =>
786 latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
787 );
788​
789 if (!entryExists) {
790 yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
791 return;
792 }
793​
794 const runScope = yield* Scope.make("sequential");
795 const runId = yield* Ref.modify(state, (latest) => [
796 latest.nextRunId,
797 {
798 ...latest,
799 active: Option.some({
800 id: latest.nextRunId,
801 scope: runScope,
802 fiber: Option.none(),
803 pid: Option.none(),
804 exitObserved: false,
805 stopRequested: false,
806 } satisfies ActiveBackendRun),
807 nextRunId: latest.nextRunId + 1,
808 },
809 ]);
810​
811 const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
812 reason: string,
813 ) {
814 yield* mutex.withPermits(1)(
815 Effect.gen(function* () {
816 const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
817 yield* Ref.modify(
818 state,
819 (
820 latest,
821 ): readonly [
822 {
823 readonly isCurrentRun: boolean;
824 readonly nextState: BackendManagerState;
825 readonly pid: Option.Option<number>;
826 readonly exitObserved: boolean;
827 readonly stopRequested: boolean;
828 readonly wasReady: boolean;
829 },
830 BackendManagerState,
831 ] => {
832 const currentRun = Option.getOrUndefined(latest.active);
833 if (currentRun?.id !== runId) {
834 return [
835 {
836 isCurrentRun: false,
837 nextState: latest,
838 pid: Option.none<number>(),
839 exitObserved: false,
840 stopRequested: false,
841 wasReady: false,
842 },
843 latest,
844 ] as const;
845 }
846​
847 const next = {
848 ...latest,
849 active: Option.none<ActiveBackendRun>(),
850 ready: false,
851 };
852 return [
853 {
854 isCurrentRun: true,
855 nextState: next,
856 pid: currentRun.pid,
857 exitObserved: currentRun.exitObserved,
858 stopRequested: currentRun.stopRequested,
859 wasReady: latest.ready,
860 },
861 next,
862 ] as const;
863 },
864 );
865​
866 if (isCurrentRun) {
867 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
868 if (Option.isSome(pid)) {
869 if (exitObserved && !stopRequested) {
870 yield* backendOutputLog.persistFailure({
871 details: `pid=${pid.value} ${reason}`,
872 });
873 } else {
874 yield* backendOutputLog.discardSession;
875 }
876 }
877 if (wasReady) {
878 yield* spec.onShutdown?.() ?? Effect.void;
879 }
880 }
881​
882 if (isCurrentRun && nextState.desiredRunning) {
883 yield* scheduleRestart(reason);
884 }
885 }),
886 );
887 });
888​
889 const program = runBackendProcess({
890 ...config.value,
891 desktopTelemetryStream: desktopTelemetryPublisher.encoded,
892 onDesktopTelemetryControl: (message) =>
893 desktopTelemetryPublisher.handleControlForSource(spec.id, message),
894 onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
895 yield* updateActiveRun(runId, (run) => ({
896 ...run,
897 pid: Option.some(pid),
898 }));
899 yield* backendOutputLog.beginSession({
900 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
901 });
902 }),
903 onExitObserved: () =>
904 updateActiveRun(runId, (run) => ({
905 ...run,
906 exitObserved: true,
907 })),
908 onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
909 const isCurrentRun = yield* Ref.modify(state, (latest) => {
910 const activeRun = Option.getOrUndefined(latest.active);
911 if (activeRun?.id !== runId) {
912 return [false, latest] as const;
913 }
914​
915 return [
916 true,
917 {
918 ...latest,
919 restartAttempt: 0,
920 ready: true,
921 },
922 ] as const;
923 });
924 if (!isCurrentRun) {
925 return;
926 }
927​
928 yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
929 }),
930 onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
931 function* (error) {
932 yield* logInstanceWarning("backend readiness check failed during bootstrap", {
933 error: error.message,
934 });
935 yield* backendOutputLog.persistFailureSnapshot({
936 details: error.message,
937 });
938 },
939 ),
940 onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
941 }).pipe(
942 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
943 Effect.provideService(HttpClient.HttpClient, httpClient),
944 Scope.provide(runScope),
945 Effect.matchEffect({
946 onFailure: (error) => finalizeRun(error.message),
947 onSuccess: (exit) => finalizeRun(exit.reason),
948 }),
949 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
950 );
951​
952 const fiber = yield* Effect.forkIn(program, parentScope);
953 yield* updateActiveRun(runId, (run) => ({
954 ...run,
955 fiber: Option.some(fiber),
956 }));
957 }),
958 ),
959 ).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
960​
961 const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
962 reason: string,
963 ) {
964 const scheduled = yield* Ref.modify(state, (latest) => {
965 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
966 return [Option.none<Duration.Duration>(), latest] as const;
967 }
968​
969 const delay = calculateRestartDelay(latest.restartAttempt);
970 return [
971 Option.some(delay),
972 {
973 ...latest,
974 restartAttempt: latest.restartAttempt + 1,
975 },
976 ] as const;
977 });
978​
979 yield* Option.match(scheduled, {
980 onNone: () => Effect.void,
981 onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
982 yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
983 reason,
984 delayMs: Duration.toMillis(delay),
985 });
986 const restartFiber = yield* Effect.forkIn(
987 Effect.sleep(delay).pipe(
988 Effect.andThen(
989 Ref.modify(state, (latest) => {
990 const shouldRestart = latest.desiredRunning;
991 return [
992 shouldRestart,
993 {
994 ...latest,
995 restartFiber: Option.none(),
996 },
997 ] as const;
998 }),
999 ),
1000 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
1001 Effect.catchCause((cause) =>
1002 logInstanceError("desktop backend restart fiber failed", {
1003 cause: Cause.pretty(cause),
1004 }),
1005 ),
1006 ),
1007 parentScope,
1008 );
1009 yield* Ref.update(state, (latest) =>
1010 Option.isNone(latest.restartFiber)
1011 ? {
1012 ...latest,
1013 restartFiber: Option.some(restartFiber),
1015 : latest,
1016 );
1017 }),
1018 });
1019 });
1020​
1021 const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
1022 readonly timeout?: Duration.Duration;
1023 }) {
1024 const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
1025 Effect.gen(function* () {
1026 const result = yield* Ref.modify(state, (latest) => {
1027 const active = Option.map(latest.active, (run) =>
1028 run.exitObserved ? run : { ...run, stopRequested: true },
1029 );
1030 return [
1032 active,
1033 restartFiber: latest.restartFiber,
1034 notifyShutdown: latest.ready,
1035 },
1037 ...latest,
1038 desiredRunning: false,
1039 ready: false,
1040 active,
1041 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
1042 },
1043 ] as const;
1044 });
1045 return result;
1046 }),
1047 );
1048​
1049 if (notifyShutdown) {
1050 yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
1052 yield* Option.match(restartFiber, {
1053 onNone: () => Effect.void,
1054 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
1055 });
1056 yield* Option.match(active, {
1057 onNone: () => Effect.void,
1058 onSome: (run) =>
1059 Effect.gen(function* () {
1060 const closed = yield* closeRun(run, parentScope, options);
1061 if (!closed) {
1062 return;
1064 const cleanup = yield* mutex.withPermits(1)(
1065 Ref.modify(
1066 state,
1068 latest,
1069 ): readonly [
1071 readonly needsCleanup: boolean;
1072 readonly shouldStart: boolean;
1073 },
1074 BackendManagerState,
1075 ] => {
1076 const current = Option.getOrUndefined(latest.active);
1077 if (current?.id !== run.id) {
1078 return [
1080 needsCleanup: false,
1081 shouldStart:
1082 latest.desiredRunning &&
1083 Option.isNone(latest.active) &&
1084 Option.isNone(latest.restartFiber),
1085 },
1086 latest,
1087 ];
1089 return [
1091 needsCleanup: true,
1092 shouldStart: latest.desiredRunning,
1093 },
1095 ...latest,
1096 active: Option.none<ActiveBackendRun>(),
1097 },
1098 ];
1099 },
1100 ),
1101 );
1102 if (cleanup.needsCleanup) {
1103 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
1104 yield* backendOutputLog.discardSession;
1106 if (cleanup.shouldStart) {
1107 yield* start;
1109 }),
1110 });
1111 });
1112​
1113 const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
1114 Effect.gen(function* () {
1115 const current = yield* Ref.get(state);
1116 // Return false early if an external `stop()` flipped desiredRunning off
1117 // — no point polling for a backend that is being torn down.
1118 if (!current.desiredRunning) return { done: true, ready: false };
1119 return current.ready ? { done: true, ready: true } : { done: false, ready: false };
1120 }).pipe(
1121 Effect.repeat({
1122 until: (status) => status.done,
1123 schedule: Schedule.spaced(Duration.millis(100)),
1124 }),
1125 Effect.map((status) => status.ready),
1126 Effect.timeoutOption(timeout),
1127 Effect.map(Option.getOrElse(() => false)),
1128 );
1129​
1130 yield* Effect.addFinalizer(() => stop());
1131​
1132 return {
1133 id: spec.id,
1134 label: spec.label,
1135 start,
1136 stop,
1137 currentConfig,
1138 snapshot,
1139 waitForReady,
1140 } satisfies DesktopBackendInstance;
1141});