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

DesktopBackendManager.ts

1,221 lines43.7 KB

1import * as Brand from "effect/Brand";
2import * as Cause from "effect/Cause";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as PlatformError from "effect/PlatformError";
11import * as Ref from "effect/Ref";
12import * as SubscriptionRef from "effect/SubscriptionRef";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15import * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17import { HttpClient } from "effect/http";
18import { ChildProcess, ChildProcessSpawner } from "effect/process";
19​
20import {
21 SERVER_EXIT_CODE_MANAGED_POLICY,
22 SERVER_EXIT_CODE_STATE_DIR_OWNED,
23 DesktopBackendBootstrap,
24 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
25 PRIMARY_LOCAL_ENVIRONMENT_ID,
26 DesktopTelemetryControlMessage,
27 type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
28} from "@t3tools/contracts";
29import { isRunningDatabaseMigrations } from "@t3tools/shared/databaseMigrationLog";
30import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
31​
32import * as DesktopObservability from "../app/DesktopObservability.ts";
33import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
34import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
35import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
36​
37const INITIAL_RESTART_DELAY = Duration.millis(500);
38const MAX_RESTART_DELAY = Duration.seconds(10);
39const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
40// Large state databases can take over a minute to become ready.
41const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(3);
42const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
43const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
44// Match the service launcher's grace period so backends can stop provider sessions.
45const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5);
46// Allow SIGKILL and the spawner exit wait after the SIGTERM grace so quit cannot
47// orphan a backend whose shutdown hangs.
48export const BACKEND_QUIT_STOP_TIMEOUT = Duration.sum(
49 DEFAULT_BACKEND_TERMINATE_GRACE,
50 Duration.seconds(2),
51);
52const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
53const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
54// Three restarts without readiness is about 2 s of backoff: past a blip, early enough to help.
55const STARTUP_FAILURE_RESTART_ATTEMPTS = 3;
56const STARTUP_FAILURE_OUTPUT_CHARS = 4_000;
57const { logWarning: logBackendProcessWarning } =
58 DesktopObservability.makeComponentLogger("desktop-backend-process");
59​
60type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
61​
62type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
63​
64export type BackendProcessOutputStream = "stdout" | "stderr";
65​
66export interface BackendProcessContext {
67 readonly executablePath: string;
68 readonly entryPath: string;
69 readonly cwd: string;
70 readonly httpBaseUrl: URL;
72​
73export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
74​
75export interface DesktopBackendStartConfig extends BackendProcessContext {
76 readonly args: ReadonlyArray<string>;
77 readonly env: Record<string, string | undefined>;
78 /** False passes env verbatim, preventing the Windows T3CODE_HOME from leaking into WSL. */
79 readonly extendEnv: boolean;
80 readonly bootstrap: DesktopBackendBootstrapValue;
81 readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
82 readonly httpBaseUrl: URL;
83 readonly captureOutput: boolean;
84 readonly preflightFailure: Option.Option<PreflightFailure>;
85 readonly runningDistro?: string;
86 readonly wslRuntimeId?: string;
88​
89export interface PreflightFailure {
90 readonly reason: string;
91 readonly fatal: boolean;
92 readonly retryLimit?: number;
94​
95interface BackendProcessExit {
96 readonly code: Option.Option<number>;
97 readonly reason: string;
99​
100const backendProcessContextSchema = {
101 executablePath: Schema.String,
102 entryPath: Schema.String,
103 cwd: Schema.String,
104 httpBaseUrl: Schema.URL,
105};
106​
107export class BackendReadinessTimeoutError extends Schema.TaggedError<BackendReadinessTimeoutError>()(
108 "BackendReadinessTimeoutError",
109 {
110 ...backendProcessContextSchema,
111 readinessUrl: Schema.URL,
112 timeoutMs: Schema.Number,
113 cause: Schema.Defect(),
114 },
115) {
116 override get message(): string {
117 return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
118 }
120​
121export class BackendProcessBootstrapEncodeError extends Schema.TaggedError<BackendProcessBootstrapEncodeError>()(
122 "BackendProcessBootstrapEncodeError",
123 {
124 ...backendProcessContextSchema,
125 cause: Schema.Defect(),
126 },
127) {
128 override get message(): string {
129 return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
130 }
132​
133export class BackendProcessSpawnError extends Schema.TaggedError<BackendProcessSpawnError>()(
134 "BackendProcessSpawnError",
135 {
136 ...backendProcessContextSchema,
137 cause: Schema.Defect(),
138 },
139) {
140 override get message(): string {
141 return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
142 }
144​
145export class BackendProcessOutputReadError extends Schema.TaggedError<BackendProcessOutputReadError>()(
146 "BackendProcessOutputReadError",
147 {
148 ...backendProcessContextSchema,
149 pid: Schema.Number,
150 streamName: Schema.Literals(["stdout", "stderr"]),
151 cause: Schema.Defect(),
152 },
153) {
154 override get message(): string {
155 return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
156 }
158​
159export class BackendProcessOutputHandlingError extends Schema.TaggedError<BackendProcessOutputHandlingError>()(
160 "BackendProcessOutputHandlingError",
161 {
162 ...backendProcessContextSchema,
163 pid: Schema.Number,
164 streamName: Schema.Literals(["stdout", "stderr"]),
165 chunkByteLength: Schema.Number,
166 cause: Schema.Defect(),
167 },
168) {
169 override get message(): string {
170 return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
171 }
173​
174export type BackendProcessOutputError =
175 | BackendProcessOutputReadError
176 | BackendProcessOutputHandlingError;
177​
178export class BackendProcessExitStatusError extends Schema.TaggedError<BackendProcessExitStatusError>()(
179 "BackendProcessExitStatusError",
180 {
181 ...backendProcessContextSchema,
182 pid: Schema.Number,
183 cause: Schema.Defect(),
184 },
185) {
186 override get message(): string {
187 return `Failed to read the exit status of desktop backend process ${this.pid}.`;
188 }
190​
191export const BackendProcessError = Schema.Union([
192 BackendProcessBootstrapEncodeError,
193 BackendProcessSpawnError,
194 BackendProcessExitStatusError,
195]);
196export type BackendProcessError = typeof BackendProcessError.Type;
197​
198interface RunBackendProcessOptions extends DesktopBackendStartConfig {
199 readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
200 readonly desktopBrowserStream?: Stream.Stream<Uint8Array>;
201 readonly onDesktopBrowserCommand?: (line: string) => Effect.Effect<void>;
202 readonly onDesktopTelemetryControl?: (
203 message: DesktopTelemetryControlMessageValue,
204 ) => Effect.Effect<void>;
205 readonly readinessTimeout?: Duration.Duration;
206 readonly outputDrainTimeout?: Duration.Duration;
207 readonly onStarted?: (pid: number) => Effect.Effect<void>;
208 readonly onExitObserved?: () => Effect.Effect<void>;
209 readonly onReady?: (pid: number) => Effect.Effect<void>;
210 readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
211 readonly onOutput?: (
212 streamName: BackendProcessOutputStream,
213 chunk: Uint8Array,
214 ) => Effect.Effect<void, Error>;
215 readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
217​
218export interface DesktopBackendSnapshot {
219 readonly desiredRunning: boolean;
220 readonly ready: boolean;
221 readonly activePid: Option.Option<number>;
222 readonly restartAttempt: number;
223 readonly restartScheduled: boolean;
225​
226export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
227export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
228​
229export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
230 PRIMARY_LOCAL_ENVIRONMENT_ID,
231);
232​
233export interface BackendStartupFailure {
234 readonly reason: string;
235 /** The server refused to start under this machine's managed policy. */
236 readonly managedPolicy: boolean;
237 /** Tail of the last run's stdout and stderr. */
238 readonly output: string;
240​
241export interface DesktopBackendInstance {
242 readonly id: BackendInstanceId;
243 readonly label: Effect.Effect<string>;
244 readonly start: Effect.Effect<void>;
245 /** Timeout controls the warning; stop still waits for process teardown and exit. */
246 readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
247 readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
248 readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
249 readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
251​
252export interface BackendInstanceSpec {
253 readonly id: BackendInstanceId;
254 readonly label: Effect.Effect<string>;
255 readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
256 /** Receives the ready run's URL and pid; reading current config could race a subsequent restart. */
257 readonly onReady?: (httpBaseUrl: URL, pid: number) => Effect.Effect<void>;
258 readonly onShutdown?: () => Effect.Effect<void>;
259 readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
260 readonly onStateDirOwned?: () => Effect.Effect<void>;
261 /** Fires on each repeated crash or readiness timeout until the backend becomes ready. */
262 readonly onStartupFailure?: (failure: BackendStartupFailure) => Effect.Effect<void>;
264​
265interface ActiveBackendRun {
266 readonly id: number;
267 readonly scope: Scope.Closeable;
268 readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
269 readonly pid: Option.Option<number>;
270 readonly exitObserved: boolean;
271 readonly stopRequested: boolean;
273​
274interface BackendManagerState {
275 readonly desiredRunning: boolean;
276 readonly ready: boolean;
277 readonly config: Option.Option<DesktopBackendStartConfig>;
278 readonly active: Option.Option<ActiveBackendRun>;
279 readonly restartAttempt: number;
280 readonly preflightFailureAttempt: number;
281 readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
282 readonly nextRunId: number;
284​
285const initialState: BackendManagerState = {
286 desiredRunning: false,
287 ready: false,
288 config: Option.none(),
289 active: Option.none(),
290 restartAttempt: 0,
291 preflightFailureAttempt: 0,
292 restartFiber: Option.none(),
293 nextRunId: 1,
294};
295​
296const activePid = (active: Option.Option<ActiveBackendRun>): Option.Option<number> =>
297 Option.flatMap(active, (run) => run.pid);
298​
299const withActiveRun =
300 (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
301 (state: BackendManagerState): BackendManagerState => ({
302 ...state,
303 active: Option.map(state.active, (run) => (run.id === runId ? f(run) : run)),
304 });
305​
306const calculateRestartDelay = (attempt: number): Duration.Duration =>
307 Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
308​
309const closeRun = (
310 run: ActiveBackendRun,
311 parentScope: Scope.Scope,
312 options?: { readonly timeout?: Duration.Duration },
313) => {
314 const waitForFiber = Option.match(run.fiber, {
315 onNone: () => Effect.void,
316 onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
317 });
318 const close = Scope.close(run.scope, Exit.void).pipe(
319 Effect.withSpan("desktop.backendInstance.closeScope"),
320 Effect.andThen(waitForFiber.pipe(Effect.withSpan("desktop.backendInstance.awaitRun"))),
321 );
322 const timeout = options?.timeout;
323​
324 if (!timeout) {
325 return close;
326 }
327​
328 return Effect.forkIn(close, parentScope, { startImmediately: true }).pipe(
329 Effect.flatMap((closeFiber) =>
330 Fiber.await(closeFiber).pipe(
331 Effect.timeoutOption(timeout),
332 Effect.tap((completed) =>
333 Option.isNone(completed)
334 ? logBackendProcessWarning("backend shutdown exceeded timeout; waiting for exit", {
335 timeoutMs: Duration.toMillis(timeout),
336 })
337 : Effect.void,
338 ),
339 // Parent-scope interruption still finishes release; do not cancel sibling stops.
340 Effect.andThen(Fiber.await(closeFiber)),
341 Effect.asVoid,
342 ),
343 ),
344 );
345};
346​
347const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
348// Windows takes about a second to fail a refused connection to a non-loopback address such as a
349// WSL distro IP, so one sequential poller notices readiness up to a second late.
350const STAGGERED_READINESS_POLLERS = 4;
351const READINESS_POLLER_STAGGER = Duration.millis(250);
352​
353const waitForHttpReady = (
354 options: BackendProcessContext & { readonly timeout: Duration.Duration },
355): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
356 const poll = pollHttpReady(options);
357 if (LOOPBACK_HOSTNAMES.has(options.httpBaseUrl.hostname)) return poll;
358 return Effect.raceAll(
359 Array.from({ length: STAGGERED_READINESS_POLLERS }, (_, index) =>
360 Effect.sleep(Duration.times(READINESS_POLLER_STAGGER, index)).pipe(Effect.andThen(poll)),
361 ),
362 );
363};
364​
365const pollHttpReady = (
366 options: BackendProcessContext & { readonly timeout: Duration.Duration },
367): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
368 const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
369 return waitForHttpReadyShared({
370 baseUrl: options.httpBaseUrl.href,
371 path: BACKEND_READINESS_PATH,
372 timeoutMs: Duration.toMillis(options.timeout),
373 intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
374 probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
375 makeError: ({ cause }) =>
376 new BackendReadinessTimeoutError({
377 executablePath: options.executablePath,
378 entryPath: options.entryPath,
379 cwd: options.cwd,
380 httpBaseUrl: options.httpBaseUrl,
381 readinessUrl,
382 timeoutMs: Duration.toMillis(options.timeout),
383 cause,
384 }),
385 });
386};
387​
388function drainBackendOutput(
389 context: BackendProcessContext & { readonly pid: number },
390 streamName: BackendProcessOutputStream,
391 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
392 onOutput: (
393 streamName: BackendProcessOutputStream,
394 chunk: Uint8Array,
395 ) => Effect.Effect<void, Error>,
396 onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
397): Effect.Effect<void> {
398 return stream.pipe(
399 Stream.mapError(
400 (cause) =>
401 new BackendProcessOutputReadError({
402 ...context,
403 streamName,
404 cause,
405 }),
406 ),
407 Stream.runForEach((chunk) =>
408 onOutput(streamName, chunk).pipe(
409 Effect.mapError(
410 (cause) =>
411 new BackendProcessOutputHandlingError({
412 ...context,
413 streamName,
414 chunkByteLength: chunk.byteLength,
415 cause,
416 }),
417 ),
418 Effect.catchTags({ BackendProcessOutputHandlingError: onOutputFailure }),
419 ),
420 ),
421 Effect.catchTags({
422 BackendProcessOutputReadError: onOutputFailure,
423 }),
424 );
426​
427const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
428const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
429 Schema.fromJsonString(DesktopTelemetryControlMessage),
430);
431​
432export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
433 options: RunBackendProcessOptions,
434): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
435 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
436 const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
437 Effect.mapError(
438 (cause) =>
439 new BackendProcessBootstrapEncodeError({
440 executablePath: options.executablePath,
441 entryPath: options.entryPath,
442 cwd: options.cwd,
443 httpBaseUrl: options.httpBaseUrl,
444 cause,
445 }),
446 ),
447 );
448 const onOutput = options.onOutput ?? (() => Effect.void);
449 const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
450 const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {};
451 if (options.bootstrapDelivery === "fd3") {
452 additionalFds.fd3 = {
453 type: "input",
454 stream: bootstrapStream,
455 };
456 if (options.bootstrap.desktopTelemetryFd !== undefined) {
457 additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
458 type: "input",
459 stream: options.desktopTelemetryStream,
460 };
461 }
462 if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
463 additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
464 type: "output",
465 };
466 }
467 if (
468 options.bootstrap.desktopBrowserFd !== undefined &&
469 options.desktopBrowserStream !== undefined
470 ) {
471 additionalFds[`fd${options.bootstrap.desktopBrowserFd}`] = {
472 type: "input",
473 stream: options.desktopBrowserStream,
474 };
475 }
476 if (options.bootstrap.desktopBrowserControlFd !== undefined) {
477 additionalFds[`fd${options.bootstrap.desktopBrowserControlFd}`] = { type: "output" };
478 }
479 }
480 const command = ChildProcess.make(options.executablePath, options.args, {
481 cwd: options.cwd,
482 env: options.env,
483 extendEnv: options.extendEnv,
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 extra file descriptors; deliver its bootstrap via stdin.
490 ...(options.bootstrapDelivery === "fd3" ? { additionalFds } : {}),
491 });
492​
493 const handle = yield* spawner.spawn(command).pipe(
494 Effect.mapError(
495 (cause) =>
496 new BackendProcessSpawnError({
497 executablePath: options.executablePath,
498 entryPath: options.entryPath,
499 cwd: options.cwd,
500 httpBaseUrl: options.httpBaseUrl,
501 cause,
502 }),
503 ),
504 );
505 const outputFibers: Array<Fiber.Fiber<void, never>> = [];
506 const serverReady = yield* Deferred.make<void>();
507​
508 yield* options.onStarted?.(handle.pid) ?? Effect.void;
509 if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
510 const controlFd = options.bootstrap.desktopTelemetryControlFd;
511 const handleControl = options.onDesktopTelemetryControl ?? (() => Effect.void);
512 yield* handle.getOutputFd(controlFd).pipe(
513 Stream.decodeText(),
514 Stream.splitLines,
515 Stream.filter((line) => line.trim().length > 0),
516 Stream.runForEach((line) =>
517 decodeDesktopTelemetryControlLine(line).pipe(
518 Effect.flatMap((message) =>
519 message.type === "serverReady"
520 ? Deferred.succeed(serverReady, undefined)
521 : handleControl(message),
522 ),
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 (
548 options.bootstrap.desktopBrowserControlFd !== undefined &&
549 options.onDesktopBrowserCommand !== undefined
550 ) {
551 const browserFd = options.bootstrap.desktopBrowserControlFd;
552 const handleCommand = options.onDesktopBrowserCommand;
553 yield* handle.getOutputFd(browserFd).pipe(
554 Stream.decodeText(),
555 Stream.splitLines,
556 Stream.filter((line) => line.length > 0),
557 Stream.runForEach(handleCommand),
558 Effect.catchCause((cause) =>
559 logBackendProcessWarning("desktop browser command stream stopped", {
560 fd: browserFd,
561 cause: Cause.pretty(cause),
562 }),
563 ),
564 Effect.forkScoped,
565 );
566 }
567 if (options.captureOutput) {
568 const outputContext = {
569 executablePath: options.executablePath,
570 entryPath: options.entryPath,
571 cwd: options.cwd,
572 httpBaseUrl: options.httpBaseUrl,
573 pid: Number(handle.pid),
574 };
575 const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
576 outputFibers.push(
577 yield* drainBackendOutput(
578 outputContext,
579 "stdout",
580 handle.stdout,
581 onOutput,
582 onOutputFailure,
583 ).pipe(Effect.forkScoped),
584 yield* drainBackendOutput(
585 outputContext,
586 "stderr",
587 handle.stderr,
588 onOutput,
589 onOutputFailure,
590 ).pipe(Effect.forkScoped),
591 );
592 }
593 // Cold WSL boots across /mnt/c can exceed one probe budget; retry while the backend is alive.
594 // HTTP polling stays as the fallback for backends without the control fd, such as WSL.
595 const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() =>
596 Effect.raceFirst(
597 waitForHttpReady({
598 executablePath: options.executablePath,
599 entryPath: options.entryPath,
600 cwd: options.cwd,
601 httpBaseUrl: options.httpBaseUrl,
602 timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
603 }),
604 Deferred.await(serverReady),
605 ).pipe(
606 Effect.flatMap(() => options.onReady?.(handle.pid) ?? Effect.void),
607 Effect.as(true),
608 Effect.catchTags({
609 BackendReadinessTimeoutError: (error) =>
610 (options.onReadinessFailure?.(error) ?? Effect.void).pipe(Effect.as(false)),
611 }),
612 ),
613 );
614​
615 yield* probeReadiness().pipe(Effect.repeat({ while: (ready) => !ready }), Effect.forkScoped);
616​
617 const exit = yield* handle.exitCode.pipe(
618 Effect.withSpan("desktop.backendProcess.awaitExit"),
619 Effect.map((exitCode) => ({
620 code: Option.some(exitCode),
621 reason: `code=${exitCode}`,
622 })),
623 Effect.catch((cause) => {
624 // Effect's Node spawner exposes signal exits only through this cause message.
625 const signal =
626 cause.cause instanceof Error
627 ? /^Process interrupted due to receipt of signal: '(SIG[A-Z0-9]+)'$/.exec(
628 cause.cause.message,
629 )?.[1]
630 : undefined;
631 if (signal !== undefined) {
632 return Effect.succeed({ code: Option.none(), reason: `killed by ${signal}` });
633 }
634 return Effect.fail(
635 new BackendProcessExitStatusError({
636 executablePath: options.executablePath,
637 entryPath: options.entryPath,
638 cwd: options.cwd,
639 httpBaseUrl: options.httpBaseUrl,
640 pid: Number(handle.pid),
641 cause,
642 }),
643 );
644 }),
645 Effect.exit,
646 );
647 yield* options.onExitObserved?.() ?? Effect.void;
648 yield* Effect.forEach(outputFibers, Fiber.await, {
649 concurrency: "unbounded",
650 discard: true,
651 }).pipe(
652 Effect.timeout(options.outputDrainTimeout ?? DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT),
653 Effect.ignore,
654 Effect.withSpan("desktop.backendProcess.drainOutput"),
655 );
656 if (Exit.isFailure(exit)) {
657 return yield* Effect.failCause(exit.cause);
658 }
659 return exit.value;
660});
661​
662export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
663 spec: BackendInstanceSpec,
664): Effect.fn.Return<
665 DesktopBackendInstance,
666 never,
667 | FileSystem.FileSystem
668 | ChildProcessSpawner.ChildProcessSpawner
669 | HttpClient.HttpClient
670 | DesktopObservability.DesktopBackendOutputLogFactory
671 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
672 | DesktopBrowserHost.DesktopBrowserHost
673 | DesktopWslEnvironment.DesktopWslEnvironment
674 | Scope.Scope
675> {
676 const parentScope = yield* Scope.Scope;
677 const fileSystem = yield* FileSystem.FileSystem;
678 const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
679 const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
680 const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
681 const desktopBrowserHost = yield* DesktopBrowserHost.DesktopBrowserHost;
682 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
683 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
684 const httpClient = yield* HttpClient.HttpClient;
685 const state = yield* SubscriptionRef.make(initialState);
686 const mutex = yield* Semaphore.make(1);
687 const outputTail = yield* Ref.make("");
688 // One streaming decoder per stream keeps UTF-8 characters split across chunks intact.
689 const makeOutputDecoders = () => ({ stdout: new TextDecoder(), stderr: new TextDecoder() });
690 let outputDecoders = makeOutputDecoders();
691 const reportStartupFailure = (reason: string, managedPolicy = false) =>
692 Ref.get(outputTail).pipe(
693 Effect.flatMap(
694 (output) => spec.onStartupFailure?.({ reason, managedPolicy, output }) ?? Effect.void,
695 ),
696 );
697​
698 const { logWarning: logInstanceWarning, logError: logInstanceError } =
699 DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
700​
701 const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
702 SubscriptionRef.update(state, withActiveRun(runId, f));
703​
704 const snapshot = SubscriptionRef.get(state).pipe(
705 Effect.map((current): DesktopBackendSnapshot => ({
706 desiredRunning: current.desiredRunning,
707 ready: current.ready,
708 activePid: activePid(current.active),
709 restartAttempt: current.restartAttempt,
710 restartScheduled: Option.isSome(current.restartFiber),
711 })),
712 );
713 const currentConfig = SubscriptionRef.get(state).pipe(Effect.map((current) => current.config));
714​
715 const cancelRestart = Effect.gen(function* () {
716 const restartFiber = yield* SubscriptionRef.modify(state, (current) => [
717 current.restartFiber,
718 {
719 ...current,
720 restartFiber: Option.none(),
721 },
722 ]);
723​
724 yield* Option.match(restartFiber, {
725 onNone: () => Effect.void,
726 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
727 });
728 });
729​
730 const start: Effect.Effect<void> = Effect.suspend(() =>
731 mutex.withPermits(1)(
732 Effect.gen(function* () {
733 const current = yield* SubscriptionRef.get(state);
734 if (Option.isSome(current.active)) {
735 if (!current.desiredRunning) {
736 yield* SubscriptionRef.update(state, (latest) => ({
737 ...latest,
738 desiredRunning: true,
739 }));
740 }
741 return;
742 }
743​
744 if (current.ready) {
745 yield* spec.onShutdown?.() ?? Effect.void;
746 yield* SubscriptionRef.update(state, (latest) =>
747 latest.ready ? { ...latest, ready: false } : latest,
748 );
749 }
750 const config = yield* spec.configResolve.pipe(
751 Effect.tapError((error) =>
752 logInstanceError("failed to generate desktop backend configuration", {
753 cause: error.message,
754 }),
755 ),
756 Effect.option,
757 );
758 if (Option.isNone(config)) {
759 if (current.desiredRunning) {
760 yield* scheduleRestart("failed to generate desktop backend configuration");
761 }
762 return;
763 }
764 const entryExists = yield* fileSystem
765 .exists(config.value.entryPath)
766 .pipe(Effect.orElseSucceed(() => false));
767​
768 const resetFatalPreflightCounter =
769 !current.desiredRunning && current.preflightFailureAttempt > 0;
770 yield* cancelRestart;
771 yield* SubscriptionRef.update(state, (latest) => ({
772 ...latest,
773 desiredRunning: true,
774 ready: false,
775 config: Option.some(config.value),
776 preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
777 }));
778​
779 const preflightFailure = config.value.preflightFailure;
780 if (Option.isSome(preflightFailure)) {
781 const { reason, fatal, retryLimit } = preflightFailure.value;
782 if (!fatal && retryLimit === undefined) {
783 yield* SubscriptionRef.update(state, (latest) =>
784 latest.preflightFailureAttempt === 0
785 ? latest
786 : { ...latest, preflightFailureAttempt: 0 },
787 );
788 yield* scheduleRestart(reason);
789 return;
790 }
791 const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
792 const attempt = yield* SubscriptionRef.modify(state, (latest) => {
793 const next = latest.preflightFailureAttempt + 1;
794 return [next, { ...latest, preflightFailureAttempt: next }] as const;
795 });
796 if (attempt > attemptLimit) {
797 yield* logInstanceError("backend preflight still failing after fallback; stopping", {
798 reason,
799 attempt,
800 });
801 yield* SubscriptionRef.update(state, (latest) => ({
802 ...latest,
803 desiredRunning: false,
804 ready: false,
805 }));
806 return;
807 }
808 if (attempt === attemptLimit) {
809 yield* logInstanceError(
810 "backend preflight failed repeatedly; surfacing and falling back",
811 { reason, attempt },
812 );
813 const shouldRestart = yield* (
814 spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
815 );
816 if (shouldRestart) {
817 yield* scheduleRestart(reason);
818 } else {
819 yield* SubscriptionRef.update(state, (latest) => ({
820 ...latest,
821 desiredRunning: false,
822 ready: false,
823 }));
824 }
825 return;
826 }
827 yield* scheduleRestart(reason);
828 return;
829 }
830 yield* SubscriptionRef.update(state, (latest) =>
831 latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
832 );
833​
834 if (!entryExists) {
835 yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
836 return;
837 }
838​
839 const runScope = yield* Scope.make("sequential");
840 const runId = yield* SubscriptionRef.modify(state, (latest) => [
841 latest.nextRunId,
842 {
843 ...latest,
844 active: Option.some({
845 id: latest.nextRunId,
846 scope: runScope,
847 fiber: Option.none(),
848 pid: Option.none(),
849 exitObserved: false,
850 stopRequested: false,
851 } satisfies ActiveBackendRun),
852 nextRunId: latest.nextRunId + 1,
853 },
854 ]);
855​
856 const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
857 reason: string,
858 exitCode?: number,
859 ) {
860 const stateDirOwned = exitCode === SERVER_EXIT_CODE_STATE_DIR_OWNED;
861 yield* mutex.withPermits(1)(
862 Effect.gen(function* () {
863 const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
864 yield* SubscriptionRef.modify(
865 state,
866 (
867 latest,
868 ): readonly [
869 {
870 readonly isCurrentRun: boolean;
871 readonly nextState: BackendManagerState;
872 readonly pid: Option.Option<number>;
873 readonly exitObserved: boolean;
874 readonly stopRequested: boolean;
875 readonly wasReady: boolean;
876 },
877 BackendManagerState,
878 ] => {
879 const currentRun = Option.getOrUndefined(latest.active);
880 if (currentRun?.id !== runId) {
881 return [
882 {
883 isCurrentRun: false,
884 nextState: latest,
885 pid: Option.none<number>(),
886 exitObserved: false,
887 stopRequested: false,
888 wasReady: false,
889 },
890 latest,
891 ] as const;
892 }
893​
894 const next = {
895 ...latest,
896 active: Option.none<ActiveBackendRun>(),
897 ready: false,
898 };
899 return [
900 {
901 isCurrentRun: true,
902 nextState: next,
903 pid: currentRun.pid,
904 exitObserved: currentRun.exitObserved,
905 stopRequested: currentRun.stopRequested,
906 wasReady: latest.ready,
907 },
908 next,
909 ] as const;
910 },
911 );
912​
913 if (isCurrentRun) {
914 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
915 if (Option.isSome(pid)) {
916 if (exitObserved && !stopRequested) {
917 yield* backendOutputLog.persistFailure({
918 details: `pid=${pid.value} ${reason}`,
919 });
920 } else {
921 yield* backendOutputLog.discardSession;
922 }
923 }
924 if (wasReady) {
925 yield* spec.onShutdown?.() ?? Effect.void;
926 }
927 }
928​
929 if (isCurrentRun && nextState.desiredRunning) {
930 if (stateDirOwned && !stopRequested) {
931 yield* SubscriptionRef.update(state, (latest) => ({
932 ...latest,
933 desiredRunning: false,
934 }));
935 yield* (spec.onStateDirOwned?.() ?? Effect.void).pipe(Effect.ignore);
936 return;
937 }
938 yield* scheduleRestart(reason, exitCode);
939 }
940 }),
941 );
942 });
943​
944 const program = runBackendProcess({
945 ...config.value,
946 desktopTelemetryStream: desktopTelemetryPublisher.encoded,
947 desktopBrowserStream: desktopBrowserHost.events,
948 onDesktopBrowserCommand: desktopBrowserHost.handleCommandLine,
949 onDesktopTelemetryControl: (message) =>
950 desktopTelemetryPublisher.handleControlForSource(spec.id, message),
951 onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
952 yield* updateActiveRun(runId, (run) => ({
953 ...run,
954 pid: Option.some(pid),
955 }));
956 yield* Ref.set(outputTail, "");
957 outputDecoders = makeOutputDecoders();
958 yield* backendOutputLog.beginSession({
959 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
960 });
961 }),
962 onExitObserved: () =>
963 updateActiveRun(runId, (run) => ({
964 ...run,
965 exitObserved: true,
966 })),
967 onReady: Effect.fn("desktop.backendInstance.onReady")(function* (pid) {
968 const isCurrentRun = yield* SubscriptionRef.modify(state, (latest) => {
969 const activeRun = Option.getOrUndefined(latest.active);
970 if (activeRun?.id !== runId) {
971 return [false, latest] as const;
972 }
973​
974 return [
975 true,
976 {
977 ...latest,
978 restartAttempt: 0,
979 ready: true,
980 },
981 ] as const;
982 });
983 if (!isCurrentRun) {
984 return;
985 }
986​
987 yield* spec.onReady?.(config.value.httpBaseUrl, pid) ?? Effect.void;
988 if (
989 config.value.runningDistro !== undefined &&
990 config.value.wslRuntimeId !== undefined
991 ) {
992 yield* wslEnvironment.pruneRuntimes(
993 config.value.runningDistro,
994 config.value.wslRuntimeId,
995 );
996 }
997 }),
998 onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
999 function* (error) {
1000 if (isRunningDatabaseMigrations(yield* Ref.get(outputTail))) {
1001 yield* logInstanceWarning("backend is still migrating its database; waiting", {
1002 error: error.message,
1003 });
1004 return;
1006 yield* logInstanceWarning("backend readiness check failed during bootstrap", {
1007 error: error.message,
1008 });
1009 yield* backendOutputLog.persistFailureSnapshot({
1010 details: error.message,
1011 });
1012 yield* reportStartupFailure("The server started but did not become ready in time.");
1013 },
1014 ),
1015 onOutput: (streamName, chunk) =>
1016 Ref.update(outputTail, (tail) =>
1017 // A cut through a surrogate pair would make encodeURIComponent throw when rendering.
1018 (tail + outputDecoders[streamName].decode(chunk, { stream: true }))
1019 .slice(-STARTUP_FAILURE_OUTPUT_CHARS)
1020 .toWellFormed(),
1021 ).pipe(Effect.andThen(backendOutputLog.writeOutputChunk(streamName, chunk))),
1022 }).pipe(
1023 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1024 Effect.provideService(HttpClient.HttpClient, httpClient),
1025 Scope.provide(runScope),
1026 Effect.matchEffect({
1027 onFailure: (error) => finalizeRun(error.message),
1028 onSuccess: (exit) => finalizeRun(exit.reason, Option.getOrUndefined(exit.code)),
1029 }),
1030 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
1031 );
1032​
1033 const fiber = yield* Effect.forkIn(program, parentScope);
1034 yield* updateActiveRun(runId, (run) => ({
1035 ...run,
1036 fiber: Option.some(fiber),
1037 }));
1038 }),
1039 ),
1040 ).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
1041​
1042 const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
1043 reason: string,
1044 exitCode?: number,
1045 ) {
1046 const scheduled = yield* SubscriptionRef.modify(state, (latest) => {
1047 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
1048 return [Option.none<{ delay: Duration.Duration; attempt: number }>(), latest] as const;
1050​
1051 const attempt = latest.restartAttempt + 1;
1052 return [
1053 Option.some({ delay: calculateRestartDelay(latest.restartAttempt), attempt }),
1054 { ...latest, restartAttempt: attempt },
1055 ] as const;
1056 });
1057​
1058 yield* Option.match(scheduled, {
1059 onNone: () => Effect.void,
1060 onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* ({
1061 delay,
1062 attempt,
1063 }) {
1064 yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
1065 reason,
1066 delayMs: Duration.toMillis(delay),
1067 });
1068 // Retrying cannot fix a policy refusal, so say so at once; retries still pick up a fix.
1069 const managedPolicy = exitCode === SERVER_EXIT_CODE_MANAGED_POLICY;
1070 if (managedPolicy || attempt >= STARTUP_FAILURE_RESTART_ATTEMPTS) {
1071 yield* reportStartupFailure(`The server could not start (${reason}).`, managedPolicy);
1073 const restartFiber = yield* Effect.forkIn(
1074 Effect.sleep(delay).pipe(
1075 Effect.andThen(
1076 SubscriptionRef.modify(state, (latest) => {
1077 const shouldRestart = latest.desiredRunning;
1078 return [
1079 shouldRestart,
1081 ...latest,
1082 restartFiber: Option.none(),
1083 },
1084 ] as const;
1085 }),
1086 ),
1087 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
1088 Effect.catchCause((cause) =>
1089 logInstanceError("desktop backend restart fiber failed", {
1090 cause: Cause.pretty(cause),
1091 }),
1092 ),
1093 ),
1094 parentScope,
1095 );
1096 yield* SubscriptionRef.update(state, (latest) =>
1097 Option.isNone(latest.restartFiber)
1098 ? {
1099 ...latest,
1100 restartFiber: Option.some(restartFiber),
1102 : latest,
1103 );
1104 }),
1105 });
1106 });
1107​
1108 const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
1109 readonly timeout?: Duration.Duration;
1110 }) {
1111 const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
1112 Effect.gen(function* () {
1113 const result = yield* SubscriptionRef.modify(state, (latest) => {
1114 const active = Option.map(latest.active, (run) =>
1115 run.exitObserved ? run : { ...run, stopRequested: true },
1116 );
1117 return [
1119 active,
1120 restartFiber: latest.restartFiber,
1121 notifyShutdown: latest.ready,
1122 },
1124 ...latest,
1125 desiredRunning: false,
1126 ready: false,
1127 active,
1128 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
1129 },
1130 ] as const;
1131 });
1132 return result;
1133 }),
1134 );
1135​
1136 if (notifyShutdown) {
1137 yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
1139 yield* Option.match(restartFiber, {
1140 onNone: () => Effect.void,
1141 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
1142 });
1143 yield* Option.match(active, {
1144 onNone: () => Effect.void,
1145 // The enclosing operation owns the span for this inline handler.
1146 onSome: Effect.fnUntraced(function* (run) {
1147 yield* closeRun(run, parentScope, options);
1148 const cleanup = yield* mutex.withPermits(1)(
1149 SubscriptionRef.modify(
1150 state,
1152 latest,
1153 ): readonly [
1155 readonly needsCleanup: boolean;
1156 readonly shouldStart: boolean;
1157 },
1158 BackendManagerState,
1159 ] => {
1160 const current = Option.getOrUndefined(latest.active);
1161 if (current?.id !== run.id) {
1162 return [
1164 needsCleanup: false,
1165 shouldStart:
1166 latest.desiredRunning &&
1167 Option.isNone(latest.active) &&
1168 Option.isNone(latest.restartFiber),
1169 },
1170 latest,
1171 ];
1173 return [
1175 needsCleanup: true,
1176 shouldStart: latest.desiredRunning,
1177 },
1179 ...latest,
1180 active: Option.none<ActiveBackendRun>(),
1181 },
1182 ];
1183 },
1184 ),
1185 );
1186 if (cleanup.needsCleanup) {
1187 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
1188 yield* backendOutputLog.discardSession;
1190 if (cleanup.shouldStart) {
1191 yield* start;
1193 }),
1194 });
1195 });
1196​
1197 const waitForReady = Effect.fn("DesktopBackendManager.waitForReady")(
1198 (timeout: Duration.Duration) =>
1199 SubscriptionRef.changes(state).pipe(
1200 Stream.filter((current) => current.ready || !current.desiredRunning),
1201 Stream.map((current) => current.ready),
1202 Stream.runHead,
1203 Effect.timeoutOption(timeout),
1204 Effect.map(
1205 (result) => Option.isSome(result) && Option.getOrElse(result.value, () => false),
1206 ),
1207 ),
1208 );
1209​
1210 yield* Effect.addFinalizer(() => stop());
1211​
1212 return {
1213 id: spec.id,
1214 label: spec.label,
1215 start,
1216 stop,
1217 currentConfig,
1218 snapshot,
1219 waitForReady,
1220 } satisfies DesktopBackendInstance;
1221});