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

DesktopBackendManager.ts

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