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

DesktopBackendManager.ts

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