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

DesktopBackendManager.ts

1,142 lines41.4 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;
63// One-shot probe; a WSL backend over /mnt/c regularly needs 60-98s to answer.
64const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(3);
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 /mnt/c/...\.t3.
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 { logWarning: logInstanceWarning, logError: logInstanceError } =
641 DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
642​
643 const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
644 Ref.update(state, withActiveRun(runId, f));
645​
646 const snapshot = Ref.get(state).pipe(
647 Effect.map(
648 (current): DesktopBackendSnapshot => ({
649 desiredRunning: current.desiredRunning,
650 ready: current.ready,
651 activePid: activePid(current.active),
652 restartAttempt: current.restartAttempt,
653 restartScheduled: Option.isSome(current.restartFiber),
654 }),
655 ),
656 );
657 const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config));
658​
659 const cancelRestart = Effect.gen(function* () {
660 const restartFiber = yield* Ref.modify(state, (current) => [
661 current.restartFiber,
662 {
663 ...current,
664 restartFiber: Option.none(),
665 },
666 ]);
667​
668 yield* Option.match(restartFiber, {
669 onNone: () => Effect.void,
670 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
671 });
672 });
673​
674 const start: Effect.Effect<void> = Effect.suspend(() =>
675 mutex.withPermits(1)(
676 Effect.gen(function* () {
677 const current = yield* Ref.get(state);
678 if (Option.isSome(current.active)) {
679 if (!current.desiredRunning) {
680 yield* Ref.update(state, (latest) => ({
681 ...latest,
682 desiredRunning: true,
683 }));
684 }
685 return;
686 }
687​
688 if (current.ready) {
689 yield* spec.onShutdown?.() ?? Effect.void;
690 yield* Ref.update(state, (latest) =>
691 latest.ready ? { ...latest, ready: false } : latest,
692 );
693 }
694 const config = yield* spec.configResolve.pipe(
695 Effect.tapError((error) =>
696 logInstanceError("failed to generate desktop backend configuration", {
697 cause: error.message,
698 }),
699 ),
700 Effect.option,
701 );
702 if (Option.isNone(config)) {
703 if (current.desiredRunning) {
704 yield* scheduleRestart("failed to generate desktop backend configuration");
705 }
706 return;
707 }
708 const entryExists = yield* fileSystem
709 .exists(config.value.entryPath)
710 .pipe(Effect.orElseSucceed(() => false));
711​
712 const resetFatalPreflightCounter =
713 !current.desiredRunning && current.preflightFailureAttempt > 0;
714 yield* cancelRestart;
715 yield* Ref.update(state, (latest) => ({
716 ...latest,
717 desiredRunning: true,
718 ready: false,
719 config: Option.some(config.value),
720 preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
721 }));
722​
723 const preflightFailure = config.value.preflightFailure;
724 if (Option.isSome(preflightFailure)) {
725 const { reason, fatal, retryLimit } = preflightFailure.value;
726 if (!fatal && retryLimit === undefined) {
727 // Transient (WSL cold-starting, wslpath while the VM boots). Keep
728 // retrying so the backend self-heals once WSL is ready. Reset a
729 // prior bounded/fatal streak because this is a different failure.
730 yield* Ref.update(state, (latest) =>
731 latest.preflightFailureAttempt === 0
732 ? latest
733 : { ...latest, preflightFailureAttempt: 0 },
734 );
735 yield* scheduleRestart(reason);
736 return;
737 }
738 const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
739 const attempt = yield* Ref.modify(state, (latest) => {
740 const next = latest.preflightFailureAttempt + 1;
741 return [next, { ...latest, preflightFailureAttempt: next }] as const;
742 });
743 if (attempt > attemptLimit) {
744 // We already surfaced and asked for the Windows fallback, yet we're
745 // still resolving the WSL primary — the fallback didn't take (e.g.
746 // the settings write failed). Stop rather than loop forever.
747 yield* logInstanceError("backend preflight still failing after fallback; stopping", {
748 reason,
749 attempt,
750 });
751 yield* Ref.update(state, (latest) => ({
752 ...latest,
753 desiredRunning: false,
754 ready: false,
755 }));
756 return;
757 }
758 if (attempt === attemptLimit) {
759 // Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
760 // on the primary, shows a dialog and persists Windows mode), then
761 // schedule one more restart so the next resolve picks up the Windows
762 // primary and a window can open.
763 yield* logInstanceError(
764 "backend preflight failed repeatedly; surfacing and falling back",
765 { reason, attempt },
766 );
767 const shouldRestart = yield* (
768 spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
769 );
770 if (shouldRestart) {
771 yield* scheduleRestart(reason);
772 } else {
773 yield* Ref.update(state, (latest) => ({
774 ...latest,
775 desiredRunning: false,
776 ready: false,
777 }));
778 }
779 return;
780 }
781 yield* scheduleRestart(reason);
782 return;
783 }
784 // Clean preflight — reset the fatal counter so a later failure gets a
785 // fresh allowance.
786 yield* Ref.update(state, (latest) =>
787 latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
788 );
789​
790 if (!entryExists) {
791 yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
792 return;
793 }
794​
795 const runScope = yield* Scope.make("sequential");
796 const runId = yield* Ref.modify(state, (latest) => [
797 latest.nextRunId,
798 {
799 ...latest,
800 active: Option.some({
801 id: latest.nextRunId,
802 scope: runScope,
803 fiber: Option.none(),
804 pid: Option.none(),
805 exitObserved: false,
806 stopRequested: false,
807 } satisfies ActiveBackendRun),
808 nextRunId: latest.nextRunId + 1,
809 },
810 ]);
811​
812 const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
813 reason: string,
814 ) {
815 yield* mutex.withPermits(1)(
816 Effect.gen(function* () {
817 const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
818 yield* Ref.modify(
819 state,
820 (
821 latest,
822 ): readonly [
823 {
824 readonly isCurrentRun: boolean;
825 readonly nextState: BackendManagerState;
826 readonly pid: Option.Option<number>;
827 readonly exitObserved: boolean;
828 readonly stopRequested: boolean;
829 readonly wasReady: boolean;
830 },
831 BackendManagerState,
832 ] => {
833 const currentRun = Option.getOrUndefined(latest.active);
834 if (currentRun?.id !== runId) {
835 return [
836 {
837 isCurrentRun: false,
838 nextState: latest,
839 pid: Option.none<number>(),
840 exitObserved: false,
841 stopRequested: false,
842 wasReady: false,
843 },
844 latest,
845 ] as const;
846 }
847​
848 const next = {
849 ...latest,
850 active: Option.none<ActiveBackendRun>(),
851 ready: false,
852 };
853 return [
854 {
855 isCurrentRun: true,
856 nextState: next,
857 pid: currentRun.pid,
858 exitObserved: currentRun.exitObserved,
859 stopRequested: currentRun.stopRequested,
860 wasReady: latest.ready,
861 },
862 next,
863 ] as const;
864 },
865 );
866​
867 if (isCurrentRun) {
868 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
869 if (Option.isSome(pid)) {
870 if (exitObserved && !stopRequested) {
871 yield* backendOutputLog.persistFailure({
872 details: `pid=${pid.value} ${reason}`,
873 });
874 } else {
875 yield* backendOutputLog.discardSession;
876 }
877 }
878 if (wasReady) {
879 yield* spec.onShutdown?.() ?? Effect.void;
880 }
881 }
882​
883 if (isCurrentRun && nextState.desiredRunning) {
884 yield* scheduleRestart(reason);
885 }
886 }),
887 );
888 });
889​
890 const program = runBackendProcess({
891 ...config.value,
892 desktopTelemetryStream: desktopTelemetryPublisher.encoded,
893 onDesktopTelemetryControl: (message) =>
894 desktopTelemetryPublisher.handleControlForSource(spec.id, message),
895 onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
896 yield* updateActiveRun(runId, (run) => ({
897 ...run,
898 pid: Option.some(pid),
899 }));
900 yield* backendOutputLog.beginSession({
901 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
902 });
903 }),
904 onExitObserved: () =>
905 updateActiveRun(runId, (run) => ({
906 ...run,
907 exitObserved: true,
908 })),
909 onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
910 const isCurrentRun = yield* Ref.modify(state, (latest) => {
911 const activeRun = Option.getOrUndefined(latest.active);
912 if (activeRun?.id !== runId) {
913 return [false, latest] as const;
914 }
915​
916 return [
917 true,
918 {
919 ...latest,
920 restartAttempt: 0,
921 ready: true,
922 },
923 ] as const;
924 });
925 if (!isCurrentRun) {
926 return;
927 }
928​
929 yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
930 }),
931 onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
932 function* (error) {
933 yield* logInstanceWarning("backend readiness check failed during bootstrap", {
934 error: error.message,
935 });
936 yield* backendOutputLog.persistFailureSnapshot({
937 details: error.message,
938 });
939 },
940 ),
941 onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
942 }).pipe(
943 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
944 Effect.provideService(HttpClient.HttpClient, httpClient),
945 Scope.provide(runScope),
946 Effect.matchEffect({
947 onFailure: (error) => finalizeRun(error.message),
948 onSuccess: (exit) => finalizeRun(exit.reason),
949 }),
950 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
951 );
952​
953 const fiber = yield* Effect.forkIn(program, parentScope);
954 yield* updateActiveRun(runId, (run) => ({
955 ...run,
956 fiber: Option.some(fiber),
957 }));
958 }),
959 ),
960 ).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
961​
962 const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
963 reason: string,
964 ) {
965 const scheduled = yield* Ref.modify(state, (latest) => {
966 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
967 return [Option.none<Duration.Duration>(), latest] as const;
968 }
969​
970 const delay = calculateRestartDelay(latest.restartAttempt);
971 return [
972 Option.some(delay),
973 {
974 ...latest,
975 restartAttempt: latest.restartAttempt + 1,
976 },
977 ] as const;
978 });
979​
980 yield* Option.match(scheduled, {
981 onNone: () => Effect.void,
982 onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
983 yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
984 reason,
985 delayMs: Duration.toMillis(delay),
986 });
987 const restartFiber = yield* Effect.forkIn(
988 Effect.sleep(delay).pipe(
989 Effect.andThen(
990 Ref.modify(state, (latest) => {
991 const shouldRestart = latest.desiredRunning;
992 return [
993 shouldRestart,
994 {
995 ...latest,
996 restartFiber: Option.none(),
997 },
998 ] as const;
999 }),
1000 ),
1001 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
1002 Effect.catchCause((cause) =>
1003 logInstanceError("desktop backend restart fiber failed", {
1004 cause: Cause.pretty(cause),
1005 }),
1006 ),
1007 ),
1008 parentScope,
1009 );
1010 yield* Ref.update(state, (latest) =>
1011 Option.isNone(latest.restartFiber)
1012 ? {
1013 ...latest,
1014 restartFiber: Option.some(restartFiber),
1016 : latest,
1017 );
1018 }),
1019 });
1020 });
1021​
1022 const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
1023 readonly timeout?: Duration.Duration;
1024 }) {
1025 const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
1026 Effect.gen(function* () {
1027 const result = yield* Ref.modify(state, (latest) => {
1028 const active = Option.map(latest.active, (run) =>
1029 run.exitObserved ? run : { ...run, stopRequested: true },
1030 );
1031 return [
1033 active,
1034 restartFiber: latest.restartFiber,
1035 notifyShutdown: latest.ready,
1036 },
1038 ...latest,
1039 desiredRunning: false,
1040 ready: false,
1041 active,
1042 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
1043 },
1044 ] as const;
1045 });
1046 return result;
1047 }),
1048 );
1049​
1050 if (notifyShutdown) {
1051 yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
1053 yield* Option.match(restartFiber, {
1054 onNone: () => Effect.void,
1055 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
1056 });
1057 yield* Option.match(active, {
1058 onNone: () => Effect.void,
1059 onSome: (run) =>
1060 Effect.gen(function* () {
1061 const closed = yield* closeRun(run, parentScope, options);
1062 if (!closed) {
1063 return;
1065 const cleanup = yield* mutex.withPermits(1)(
1066 Ref.modify(
1067 state,
1069 latest,
1070 ): readonly [
1072 readonly needsCleanup: boolean;
1073 readonly shouldStart: boolean;
1074 },
1075 BackendManagerState,
1076 ] => {
1077 const current = Option.getOrUndefined(latest.active);
1078 if (current?.id !== run.id) {
1079 return [
1081 needsCleanup: false,
1082 shouldStart:
1083 latest.desiredRunning &&
1084 Option.isNone(latest.active) &&
1085 Option.isNone(latest.restartFiber),
1086 },
1087 latest,
1088 ];
1090 return [
1092 needsCleanup: true,
1093 shouldStart: latest.desiredRunning,
1094 },
1096 ...latest,
1097 active: Option.none<ActiveBackendRun>(),
1098 },
1099 ];
1100 },
1101 ),
1102 );
1103 if (cleanup.needsCleanup) {
1104 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
1105 yield* backendOutputLog.discardSession;
1107 if (cleanup.shouldStart) {
1108 yield* start;
1110 }),
1111 });
1112 });
1113​
1114 const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
1115 Effect.gen(function* () {
1116 const current = yield* Ref.get(state);
1117 // Return false early if an external `stop()` flipped desiredRunning off
1118 // — no point polling for a backend that is being torn down.
1119 if (!current.desiredRunning) return { done: true, ready: false };
1120 return current.ready ? { done: true, ready: true } : { done: false, ready: false };
1121 }).pipe(
1122 Effect.repeat({
1123 until: (status) => status.done,
1124 schedule: Schedule.spaced(Duration.millis(100)),
1125 }),
1126 Effect.map((status) => status.ready),
1127 Effect.timeoutOption(timeout),
1128 Effect.map(Option.getOrElse(() => false)),
1129 );
1130​
1131 yield* Effect.addFinalizer(() => stop());
1132​
1133 return {
1134 id: spec.id,
1135 label: spec.label,
1136 start,
1137 stop,
1138 currentConfig,
1139 snapshot,
1140 waitForReady,
1141 } satisfies DesktopBackendInstance;
1142});