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

DesktopBackendManager.ts

1,179 lines41.7 KB

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