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

DesktopBackendManager.ts

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