Open History to see the last commit
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;
69}
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;
85}
86
87export interface PreflightFailure {
88 readonly reason: string;
89 readonly fatal: boolean;
90 readonly retryLimit?: number;
91}
92
93interface BackendProcessExit {
94 readonly code: Option.Option<number>;
95 readonly reason: string;
96}
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 }
117}
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 }
129}
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 }
141}
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 }
155}
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 }
170}
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 }
187}
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>;
214}
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;
222}
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;
237}
238
239export interface DesktopBackendInstance {
240 readonly id: BackendInstanceId;
241 readonly label: Effect.Effect<string>;
242 readonly start: Effect.Effect<void>;
243 /** Timeout controls the warning; stop still waits for process teardown and exit. */
244 readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
245 readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
246 readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
247 readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
248}
249
250export interface BackendInstanceSpec {
251 readonly id: BackendInstanceId;
252 readonly label: Effect.Effect<string>;
253 readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
254 /** Receives the ready run's resolved URL; reading current config could race a subsequent restart. */
255 readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
256 readonly onShutdown?: () => Effect.Effect<void>;
257 readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
258 readonly onStateDirOwned?: () => Effect.Effect<void>;
259 /** Fires on each repeated crash or readiness timeout until the backend becomes ready. */
260 readonly onStartupFailure?: (failure: BackendStartupFailure) => Effect.Effect<void>;
261}
262
263interface ActiveBackendRun {
264 readonly id: number;
265 readonly scope: Scope.Closeable;
266 readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
267 readonly pid: Option.Option<number>;
268 readonly exitObserved: boolean;
269 readonly stopRequested: boolean;
270}
271
272interface BackendManagerState {
273 readonly desiredRunning: boolean;
274 readonly ready: boolean;
275 readonly config: Option.Option<DesktopBackendStartConfig>;
276 readonly active: Option.Option<ActiveBackendRun>;
277 readonly restartAttempt: number;
278 readonly preflightFailureAttempt: number;
279 readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
280 readonly nextRunId: number;
281}
282
283const initialState: BackendManagerState = {
284 desiredRunning: false,
285 ready: false,
286 config: Option.none(),
287 active: Option.none(),
288 restartAttempt: 0,
289 preflightFailureAttempt: 0,
290 restartFiber: Option.none(),
291 nextRunId: 1,
292};
293
294const activePid = (active: Option.Option<ActiveBackendRun>): Option.Option<number> =>
295 Option.flatMap(active, (run) => run.pid);
296
297const withActiveRun =
298 (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
299 (state: BackendManagerState): BackendManagerState => ({
300 ...state,
301 active: Option.map(state.active, (run) => (run.id === runId ? f(run) : run)),
302 });
303
304const calculateRestartDelay = (attempt: number): Duration.Duration =>
305 Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
306
307const closeRun = (
308 run: ActiveBackendRun,
309 parentScope: Scope.Scope,
310 options?: { readonly timeout?: Duration.Duration },
311) => {
312 const waitForFiber = Option.match(run.fiber, {
313 onNone: () => Effect.void,
314 onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
315 });
316 const close = Scope.close(run.scope, Exit.void).pipe(
317 Effect.withSpan("desktop.backendInstance.closeScope"),
318 Effect.andThen(waitForFiber.pipe(Effect.withSpan("desktop.backendInstance.awaitRun"))),
319 );
320 const timeout = options?.timeout;
321
322 if (!timeout) {
323 return close;
324 }
325
326 return Effect.forkIn(close, parentScope, { startImmediately: true }).pipe(
327 Effect.flatMap((closeFiber) =>
328 Fiber.await(closeFiber).pipe(
329 Effect.timeoutOption(timeout),
330 Effect.tap((completed) =>
331 Option.isNone(completed)
332 ? logBackendProcessWarning("backend shutdown exceeded timeout; waiting for exit", {
333 timeoutMs: Duration.toMillis(timeout),
334 })
335 : Effect.void,
336 ),
337 // Parent-scope interruption still finishes release; do not cancel sibling stops.
338 Effect.andThen(Fiber.await(closeFiber)),
339 Effect.asVoid,
340 ),
341 ),
342 );
343};
344
345const waitForHttpReady = (
346 options: BackendProcessContext & { readonly timeout: Duration.Duration },
347): Effect.Effect<void, BackendReadinessTimeoutError, HttpClient.HttpClient> => {
348 const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
349 return waitForHttpReadyShared({
350 baseUrl: options.httpBaseUrl.href,
351 path: BACKEND_READINESS_PATH,
352 timeoutMs: Duration.toMillis(options.timeout),
353 intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
354 probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
355 makeError: ({ cause }) =>
356 new BackendReadinessTimeoutError({
357 executablePath: options.executablePath,
358 entryPath: options.entryPath,
359 cwd: options.cwd,
360 httpBaseUrl: options.httpBaseUrl,
361 readinessUrl,
362 timeoutMs: Duration.toMillis(options.timeout),
363 cause,
364 }),
365 });
366};
367
368function drainBackendOutput(
369 context: BackendProcessContext & { readonly pid: number },
370 streamName: BackendProcessOutputStream,
371 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
372 onOutput: (
373 streamName: BackendProcessOutputStream,
374 chunk: Uint8Array,
375 ) => Effect.Effect<void, Error>,
376 onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
377): Effect.Effect<void> {
378 return stream.pipe(
379 Stream.mapError(
380 (cause) =>
381 new BackendProcessOutputReadError({
382 ...context,
383 streamName,
384 cause,
385 }),
386 ),
387 Stream.runForEach((chunk) =>
388 onOutput(streamName, chunk).pipe(
389 Effect.mapError(
390 (cause) =>
391 new BackendProcessOutputHandlingError({
392 ...context,
393 streamName,
394 chunkByteLength: chunk.byteLength,
395 cause,
396 }),
397 ),
398 Effect.catchTags({ BackendProcessOutputHandlingError: onOutputFailure }),
399 ),
400 ),
401 Effect.catchTags({
402 BackendProcessOutputReadError: onOutputFailure,
403 }),
404 );
405}
406
407const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
408const decodeDesktopTelemetryControlLine = Schema.decodeUnknownEffect(
409 Schema.fromJsonString(DesktopTelemetryControlMessage),
410);
411
412export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
413 options: RunBackendProcessOptions,
414): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
415 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
416 const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
417 Effect.mapError(
418 (cause) =>
419 new BackendProcessBootstrapEncodeError({
420 executablePath: options.executablePath,
421 entryPath: options.entryPath,
422 cwd: options.cwd,
423 httpBaseUrl: options.httpBaseUrl,
424 cause,
425 }),
426 ),
427 );
428 const onOutput = options.onOutput ?? (() => Effect.void);
429 const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
430 const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {};
431 if (options.bootstrapDelivery === "fd3") {
432 additionalFds.fd3 = {
433 type: "input",
434 stream: bootstrapStream,
435 };
436 if (options.bootstrap.desktopTelemetryFd !== undefined) {
437 additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
438 type: "input",
439 stream: options.desktopTelemetryStream,
440 };
441 }
442 if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
443 additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
444 type: "output",
445 };
446 }
447 if (
448 options.bootstrap.desktopBrowserFd !== undefined &&
449 options.desktopBrowserStream !== undefined
450 ) {
451 additionalFds[`fd${options.bootstrap.desktopBrowserFd}`] = {
452 type: "input",
453 stream: options.desktopBrowserStream,
454 };
455 }
456 if (options.bootstrap.desktopBrowserControlFd !== undefined) {
457 additionalFds[`fd${options.bootstrap.desktopBrowserControlFd}`] = { type: "output" };
458 }
459 }
460 const command = ChildProcess.make(options.executablePath, options.args, {
461 cwd: options.cwd,
462 env: options.env,
463 extendEnv: options.extendEnv,
464 stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
465 stdout: options.captureOutput ? "pipe" : "inherit",
466 stderr: options.captureOutput ? "pipe" : "inherit",
467 killSignal: "SIGTERM",
468 forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
469 // wsl.exe drops extra file descriptors; deliver its bootstrap via stdin.
470 ...(options.bootstrapDelivery === "fd3" ? { additionalFds } : {}),
471 });
472
473 const handle = yield* spawner.spawn(command).pipe(
474 Effect.mapError(
475 (cause) =>
476 new BackendProcessSpawnError({
477 executablePath: options.executablePath,
478 entryPath: options.entryPath,
479 cwd: options.cwd,
480 httpBaseUrl: options.httpBaseUrl,
481 cause,
482 }),
483 ),
484 );
485 const outputFibers: Array<Fiber.Fiber<void, never>> = [];
486
487 yield* options.onStarted?.(handle.pid) ?? Effect.void;
488 if (
489 options.bootstrap.desktopTelemetryControlFd !== undefined &&
490 options.onDesktopTelemetryControl !== undefined
491 ) {
492 const controlFd = options.bootstrap.desktopTelemetryControlFd;
493 const handleControl = options.onDesktopTelemetryControl;
494 yield* handle.getOutputFd(controlFd).pipe(
495 Stream.decodeText(),
496 Stream.splitLines,
497 Stream.filter((line) => line.trim().length > 0),
498 Stream.runForEach((line) =>
499 decodeDesktopTelemetryControlLine(line).pipe(
500 Effect.flatMap(handleControl),
501 Effect.catchCause((cause) =>
502 logBackendProcessWarning("ignored invalid desktop telemetry control message", {
503 fd: controlFd,
504 cause: Cause.pretty(cause),
505 }),
506 ),
507 ),
508 ),
509 Effect.catchCause((cause) =>
510 logBackendProcessWarning("desktop telemetry control stream stopped", {
511 fd: controlFd,
512 cause: Cause.pretty(cause),
513 }),
514 ),
515 Effect.ensuring(
516 handleControl({
517 version: 1,
518 type: "setDiagnosticsDemand",
519 enabled: false,
520 }),
521 ),
522 Effect.forkScoped,
523 );
524 }
525 if (
526 options.bootstrap.desktopBrowserControlFd !== undefined &&
527 options.onDesktopBrowserCommand !== undefined
528 ) {
529 const browserFd = options.bootstrap.desktopBrowserControlFd;
530 const handleCommand = options.onDesktopBrowserCommand;
531 yield* handle.getOutputFd(browserFd).pipe(
532 Stream.decodeText(),
533 Stream.splitLines,
534 Stream.filter((line) => line.length > 0),
535 Stream.runForEach(handleCommand),
536 Effect.catchCause((cause) =>
537 logBackendProcessWarning("desktop browser command stream stopped", {
538 fd: browserFd,
539 cause: Cause.pretty(cause),
540 }),
541 ),
542 Effect.forkScoped,
543 );
544 }
545 if (options.captureOutput) {
546 const outputContext = {
547 executablePath: options.executablePath,
548 entryPath: options.entryPath,
549 cwd: options.cwd,
550 httpBaseUrl: options.httpBaseUrl,
551 pid: Number(handle.pid),
552 };
553 const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
554 outputFibers.push(
555 yield* drainBackendOutput(
556 outputContext,
557 "stdout",
558 handle.stdout,
559 onOutput,
560 onOutputFailure,
561 ).pipe(Effect.forkScoped),
562 yield* drainBackendOutput(
563 outputContext,
564 "stderr",
565 handle.stderr,
566 onOutput,
567 onOutputFailure,
568 ).pipe(Effect.forkScoped),
569 );
570 }
571 // Cold WSL boots across /mnt/c can exceed one probe budget; retry while the backend is alive.
572 const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() =>
573 waitForHttpReady({
574 executablePath: options.executablePath,
575 entryPath: options.entryPath,
576 cwd: options.cwd,
577 httpBaseUrl: options.httpBaseUrl,
578 timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
579 }).pipe(
580 Effect.flatMap(() => options.onReady?.() ?? Effect.void),
581 Effect.as(true),
582 Effect.catchTags({
583 BackendReadinessTimeoutError: (error) =>
584 (options.onReadinessFailure?.(error) ?? Effect.void).pipe(Effect.as(false)),
585 }),
586 ),
587 );
588
589 yield* probeReadiness().pipe(Effect.repeat({ while: (ready) => !ready }), Effect.forkScoped);
590
591 const exit = yield* handle.exitCode.pipe(
592 Effect.withSpan("desktop.backendProcess.awaitExit"),
593 Effect.map((exitCode) => ({
594 code: Option.some(exitCode),
595 reason: `code=${exitCode}`,
596 })),
597 Effect.catch((cause) => {
598 // Effect's Node spawner exposes signal exits only through this cause message.
599 const signal =
600 cause.cause instanceof Error
601 ? /^Process interrupted due to receipt of signal: '(SIG[A-Z0-9]+)'$/.exec(
602 cause.cause.message,
603 )?.[1]
604 : undefined;
605 if (signal !== undefined) {
606 return Effect.succeed({ code: Option.none(), reason: `killed by ${signal}` });
607 }
608 return Effect.fail(
609 new BackendProcessExitStatusError({
610 executablePath: options.executablePath,
611 entryPath: options.entryPath,
612 cwd: options.cwd,
613 httpBaseUrl: options.httpBaseUrl,
614 pid: Number(handle.pid),
615 cause,
616 }),
617 );
618 }),
619 Effect.exit,
620 );
621 yield* options.onExitObserved?.() ?? Effect.void;
622 yield* Effect.forEach(outputFibers, Fiber.await, {
623 concurrency: "unbounded",
624 discard: true,
625 }).pipe(
626 Effect.timeout(options.outputDrainTimeout ?? DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT),
627 Effect.ignore,
628 Effect.withSpan("desktop.backendProcess.drainOutput"),
629 );
630 if (Exit.isFailure(exit)) {
631 return yield* Effect.failCause(exit.cause);
632 }
633 return exit.value;
634});
635
636export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
637 spec: BackendInstanceSpec,
638): Effect.fn.Return<
639 DesktopBackendInstance,
640 never,
641 | FileSystem.FileSystem
642 | ChildProcessSpawner.ChildProcessSpawner
643 | HttpClient.HttpClient
644 | DesktopObservability.DesktopBackendOutputLogFactory
645 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
646 | DesktopBrowserHost.DesktopBrowserHost
647 | DesktopWslEnvironment.DesktopWslEnvironment
648 | Scope.Scope
649> {
650 const parentScope = yield* Scope.Scope;
651 const fileSystem = yield* FileSystem.FileSystem;
652 const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
653 const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
654 const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
655 const desktopBrowserHost = yield* DesktopBrowserHost.DesktopBrowserHost;
656 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
657 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
658 const httpClient = yield* HttpClient.HttpClient;
659 const state = yield* SubscriptionRef.make(initialState);
660 const mutex = yield* Semaphore.make(1);
661 const outputTail = yield* Ref.make("");
662 // One streaming decoder per stream keeps UTF-8 characters split across chunks intact.
663 const makeOutputDecoders = () => ({ stdout: new TextDecoder(), stderr: new TextDecoder() });
664 let outputDecoders = makeOutputDecoders();
665 const reportStartupFailure = (reason: string, managedPolicy = false) =>
666 Ref.get(outputTail).pipe(
667 Effect.flatMap(
668 (output) => spec.onStartupFailure?.({ reason, managedPolicy, output }) ?? Effect.void,
669 ),
670 );
671
672 const { logWarning: logInstanceWarning, logError: logInstanceError } =
673 DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
674
675 const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
676 SubscriptionRef.update(state, withActiveRun(runId, f));
677
678 const snapshot = SubscriptionRef.get(state).pipe(
679 Effect.map((current): DesktopBackendSnapshot => ({
680 desiredRunning: current.desiredRunning,
681 ready: current.ready,
682 activePid: activePid(current.active),
683 restartAttempt: current.restartAttempt,
684 restartScheduled: Option.isSome(current.restartFiber),
685 })),
686 );
687 const currentConfig = SubscriptionRef.get(state).pipe(Effect.map((current) => current.config));
688
689 const cancelRestart = Effect.gen(function* () {
690 const restartFiber = yield* SubscriptionRef.modify(state, (current) => [
691 current.restartFiber,
692 {
693 ...current,
694 restartFiber: Option.none(),
695 },
696 ]);
697
698 yield* Option.match(restartFiber, {
699 onNone: () => Effect.void,
700 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
701 });
702 });
703
704 const start: Effect.Effect<void> = Effect.suspend(() =>
705 mutex.withPermits(1)(
706 Effect.gen(function* () {
707 const current = yield* SubscriptionRef.get(state);
708 if (Option.isSome(current.active)) {
709 if (!current.desiredRunning) {
710 yield* SubscriptionRef.update(state, (latest) => ({
711 ...latest,
712 desiredRunning: true,
713 }));
714 }
715 return;
716 }
717
718 if (current.ready) {
719 yield* spec.onShutdown?.() ?? Effect.void;
720 yield* SubscriptionRef.update(state, (latest) =>
721 latest.ready ? { ...latest, ready: false } : latest,
722 );
723 }
724 const config = yield* spec.configResolve.pipe(
725 Effect.tapError((error) =>
726 logInstanceError("failed to generate desktop backend configuration", {
727 cause: error.message,
728 }),
729 ),
730 Effect.option,
731 );
732 if (Option.isNone(config)) {
733 if (current.desiredRunning) {
734 yield* scheduleRestart("failed to generate desktop backend configuration");
735 }
736 return;
737 }
738 const entryExists = yield* fileSystem
739 .exists(config.value.entryPath)
740 .pipe(Effect.orElseSucceed(() => false));
741
742 const resetFatalPreflightCounter =
743 !current.desiredRunning && current.preflightFailureAttempt > 0;
744 yield* cancelRestart;
745 yield* SubscriptionRef.update(state, (latest) => ({
746 ...latest,
747 desiredRunning: true,
748 ready: false,
749 config: Option.some(config.value),
750 preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
751 }));
752
753 const preflightFailure = config.value.preflightFailure;
754 if (Option.isSome(preflightFailure)) {
755 const { reason, fatal, retryLimit } = preflightFailure.value;
756 if (!fatal && retryLimit === undefined) {
757 yield* SubscriptionRef.update(state, (latest) =>
758 latest.preflightFailureAttempt === 0
759 ? latest
760 : { ...latest, preflightFailureAttempt: 0 },
761 );
762 yield* scheduleRestart(reason);
763 return;
764 }
765 const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
766 const attempt = yield* SubscriptionRef.modify(state, (latest) => {
767 const next = latest.preflightFailureAttempt + 1;
768 return [next, { ...latest, preflightFailureAttempt: next }] as const;
769 });
770 if (attempt > attemptLimit) {
771 yield* logInstanceError("backend preflight still failing after fallback; stopping", {
772 reason,
773 attempt,
774 });
775 yield* SubscriptionRef.update(state, (latest) => ({
776 ...latest,
777 desiredRunning: false,
778 ready: false,
779 }));
780 return;
781 }
782 if (attempt === attemptLimit) {
783 yield* logInstanceError(
784 "backend preflight failed repeatedly; surfacing and falling back",
785 { reason, attempt },
786 );
787 const shouldRestart = yield* (
788 spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
789 );
790 if (shouldRestart) {
791 yield* scheduleRestart(reason);
792 } else {
793 yield* SubscriptionRef.update(state, (latest) => ({
794 ...latest,
795 desiredRunning: false,
796 ready: false,
797 }));
798 }
799 return;
800 }
801 yield* scheduleRestart(reason);
802 return;
803 }
804 yield* SubscriptionRef.update(state, (latest) =>
805 latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
806 );
807
808 if (!entryExists) {
809 yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
810 return;
811 }
812
813 const runScope = yield* Scope.make("sequential");
814 const runId = yield* SubscriptionRef.modify(state, (latest) => [
815 latest.nextRunId,
816 {
817 ...latest,
818 active: Option.some({
819 id: latest.nextRunId,
820 scope: runScope,
821 fiber: Option.none(),
822 pid: Option.none(),
823 exitObserved: false,
824 stopRequested: false,
825 } satisfies ActiveBackendRun),
826 nextRunId: latest.nextRunId + 1,
827 },
828 ]);
829
830 const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
831 reason: string,
832 exitCode?: number,
833 ) {
834 const stateDirOwned = exitCode === SERVER_EXIT_CODE_STATE_DIR_OWNED;
835 yield* mutex.withPermits(1)(
836 Effect.gen(function* () {
837 const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
838 yield* SubscriptionRef.modify(
839 state,
840 (
841 latest,
842 ): readonly [
843 {
844 readonly isCurrentRun: boolean;
845 readonly nextState: BackendManagerState;
846 readonly pid: Option.Option<number>;
847 readonly exitObserved: boolean;
848 readonly stopRequested: boolean;
849 readonly wasReady: boolean;
850 },
851 BackendManagerState,
852 ] => {
853 const currentRun = Option.getOrUndefined(latest.active);
854 if (currentRun?.id !== runId) {
855 return [
856 {
857 isCurrentRun: false,
858 nextState: latest,
859 pid: Option.none<number>(),
860 exitObserved: false,
861 stopRequested: false,
862 wasReady: false,
863 },
864 latest,
865 ] as const;
866 }
867
868 const next = {
869 ...latest,
870 active: Option.none<ActiveBackendRun>(),
871 ready: false,
872 };
873 return [
874 {
875 isCurrentRun: true,
876 nextState: next,
877 pid: currentRun.pid,
878 exitObserved: currentRun.exitObserved,
879 stopRequested: currentRun.stopRequested,
880 wasReady: latest.ready,
881 },
882 next,
883 ] as const;
884 },
885 );
886
887 if (isCurrentRun) {
888 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
889 if (Option.isSome(pid)) {
890 if (exitObserved && !stopRequested) {
891 yield* backendOutputLog.persistFailure({
892 details: `pid=${pid.value} ${reason}`,
893 });
894 } else {
895 yield* backendOutputLog.discardSession;
896 }
897 }
898 if (wasReady) {
899 yield* spec.onShutdown?.() ?? Effect.void;
900 }
901 }
902
903 if (isCurrentRun && nextState.desiredRunning) {
904 if (stateDirOwned && !stopRequested) {
905 yield* SubscriptionRef.update(state, (latest) => ({
906 ...latest,
907 desiredRunning: false,
908 }));
909 yield* (spec.onStateDirOwned?.() ?? Effect.void).pipe(Effect.ignore);
910 return;
911 }
912 yield* scheduleRestart(reason, exitCode);
913 }
914 }),
915 );
916 });
917
918 const program = runBackendProcess({
919 ...config.value,
920 desktopTelemetryStream: desktopTelemetryPublisher.encoded,
921 desktopBrowserStream: desktopBrowserHost.events,
922 onDesktopBrowserCommand: desktopBrowserHost.handleCommandLine,
923 onDesktopTelemetryControl: (message) =>
924 desktopTelemetryPublisher.handleControlForSource(spec.id, message),
925 onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
926 yield* updateActiveRun(runId, (run) => ({
927 ...run,
928 pid: Option.some(pid),
929 }));
930 yield* Ref.set(outputTail, "");
931 outputDecoders = makeOutputDecoders();
932 yield* backendOutputLog.beginSession({
933 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
934 });
935 }),
936 onExitObserved: () =>
937 updateActiveRun(runId, (run) => ({
938 ...run,
939 exitObserved: true,
940 })),
941 onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
942 const isCurrentRun = yield* SubscriptionRef.modify(state, (latest) => {
943 const activeRun = Option.getOrUndefined(latest.active);
944 if (activeRun?.id !== runId) {
945 return [false, latest] as const;
946 }
947
948 return [
949 true,
950 {
951 ...latest,
952 restartAttempt: 0,
953 ready: true,
954 },
955 ] as const;
956 });
957 if (!isCurrentRun) {
958 return;
959 }
960
961 yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
962 if (
963 config.value.runningDistro !== undefined &&
964 config.value.wslRuntimeId !== undefined
965 ) {
966 yield* wslEnvironment.pruneRuntimes(
967 config.value.runningDistro,
968 config.value.wslRuntimeId,
969 );
970 }
971 }),
972 onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")(
973 function* (error) {
974 yield* logInstanceWarning("backend readiness check failed during bootstrap", {
975 error: error.message,
976 });
977 yield* backendOutputLog.persistFailureSnapshot({
978 details: error.message,
979 });
980 yield* reportStartupFailure("The server started but did not become ready in time.");
981 },
982 ),
983 onOutput: (streamName, chunk) =>
984 Ref.update(outputTail, (tail) =>
985 // A cut through a surrogate pair would make encodeURIComponent throw when rendering.
986 (tail + outputDecoders[streamName].decode(chunk, { stream: true }))
987 .slice(-STARTUP_FAILURE_OUTPUT_CHARS)
988 .toWellFormed(),
989 ).pipe(Effect.andThen(backendOutputLog.writeOutputChunk(streamName, chunk))),
990 }).pipe(
991 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
992 Effect.provideService(HttpClient.HttpClient, httpClient),
993 Scope.provide(runScope),
994 Effect.matchEffect({
995 onFailure: (error) => finalizeRun(error.message),
996 onSuccess: (exit) => finalizeRun(exit.reason, Option.getOrUndefined(exit.code)),
997 }),
998 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
999 );
1000
1001 const fiber = yield* Effect.forkIn(program, parentScope);
1002 yield* updateActiveRun(runId, (run) => ({
1003 ...run,
1004 fiber: Option.some(fiber),
1005 }));
1006 }),
1007 ),
1008 ).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
1009
1010 const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
1011 reason: string,
1012 exitCode?: number,
1013 ) {
1014 const scheduled = yield* SubscriptionRef.modify(state, (latest) => {
1015 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
1016 return [Option.none<{ delay: Duration.Duration; attempt: number }>(), latest] as const;
1017 }
1018
1019 const attempt = latest.restartAttempt + 1;
1020 return [
1021 Option.some({ delay: calculateRestartDelay(latest.restartAttempt), attempt }),
1022 { ...latest, restartAttempt: attempt },
1023 ] as const;
1024 });
1025
1026 yield* Option.match(scheduled, {
1027 onNone: () => Effect.void,
1028 onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* ({
1029 delay,
1030 attempt,
1031 }) {
1032 yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
1033 reason,
1034 delayMs: Duration.toMillis(delay),
1035 });
1036 // Retrying cannot fix a policy refusal, so say so at once; retries still pick up a fix.
1037 const managedPolicy = exitCode === SERVER_EXIT_CODE_MANAGED_POLICY;
1038 if (managedPolicy || attempt >= STARTUP_FAILURE_RESTART_ATTEMPTS) {
1039 yield* reportStartupFailure(`The server could not start (${reason}).`, managedPolicy);
1040 }
1041 const restartFiber = yield* Effect.forkIn(
1042 Effect.sleep(delay).pipe(
1043 Effect.andThen(
1044 SubscriptionRef.modify(state, (latest) => {
1045 const shouldRestart = latest.desiredRunning;
1046 return [
1047 shouldRestart,
1048 {
1049 ...latest,
1050 restartFiber: Option.none(),
1051 },
1052 ] as const;
1053 }),
1054 ),
1055 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
1056 Effect.catchCause((cause) =>
1057 logInstanceError("desktop backend restart fiber failed", {
1058 cause: Cause.pretty(cause),
1059 }),
1060 ),
1061 ),
1062 parentScope,
1063 );
1064 yield* SubscriptionRef.update(state, (latest) =>
1065 Option.isNone(latest.restartFiber)
1066 ? {
1067 ...latest,
1068 restartFiber: Option.some(restartFiber),
1069 }
1070 : latest,
1071 );
1072 }),
1073 });
1074 });
1075
1076 const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
1077 readonly timeout?: Duration.Duration;
1078 }) {
1079 const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
1080 Effect.gen(function* () {
1081 const result = yield* SubscriptionRef.modify(state, (latest) => {
1082 const active = Option.map(latest.active, (run) =>
1083 run.exitObserved ? run : { ...run, stopRequested: true },
1084 );
1085 return [
1086 {
1087 active,
1088 restartFiber: latest.restartFiber,
1089 notifyShutdown: latest.ready,
1090 },
1091 {
1092 ...latest,
1093 desiredRunning: false,
1094 ready: false,
1095 active,
1096 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
1097 },
1098 ] as const;
1099 });
1100 return result;
1101 }),
1102 );
1103
1104 if (notifyShutdown) {
1105 yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
1106 }
1107 yield* Option.match(restartFiber, {
1108 onNone: () => Effect.void,
1109 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
1110 });
1111 yield* Option.match(active, {
1112 onNone: () => Effect.void,
1113 // The enclosing operation owns the span for this inline handler.
1114 onSome: Effect.fnUntraced(function* (run) {
1115 yield* closeRun(run, parentScope, options);
1116 const cleanup = yield* mutex.withPermits(1)(
1117 SubscriptionRef.modify(
1118 state,
1119 (
1120 latest,
1121 ): readonly [
1122 {
1123 readonly needsCleanup: boolean;
1124 readonly shouldStart: boolean;
1125 },
1126 BackendManagerState,
1127 ] => {
1128 const current = Option.getOrUndefined(latest.active);
1129 if (current?.id !== run.id) {
1130 return [
1131 {
1132 needsCleanup: false,
1133 shouldStart:
1134 latest.desiredRunning &&
1135 Option.isNone(latest.active) &&
1136 Option.isNone(latest.restartFiber),
1137 },
1138 latest,
1139 ];
1140 }
1141 return [
1142 {
1143 needsCleanup: true,
1144 shouldStart: latest.desiredRunning,
1145 },
1146 {
1147 ...latest,
1148 active: Option.none<ActiveBackendRun>(),
1149 },
1150 ];
1151 },
1152 ),
1153 );
1154 if (cleanup.needsCleanup) {
1155 yield* desktopTelemetryPublisher.removeControlSource(spec.id);
1156 yield* backendOutputLog.discardSession;
1157 }
1158 if (cleanup.shouldStart) {
1159 yield* start;
1160 }
1161 }),
1162 });
1163 });
1164
1165 const waitForReady = Effect.fn("DesktopBackendManager.waitForReady")(
1166 (timeout: Duration.Duration) =>
1167 SubscriptionRef.changes(state).pipe(
1168 Stream.filter((current) => current.ready || !current.desiredRunning),
1169 Stream.map((current) => current.ready),
1170 Stream.runHead,
1171 Effect.timeoutOption(timeout),
1172 Effect.map(
1173 (result) => Option.isSome(result) && Option.getOrElse(result.value, () => false),
1174 ),
1175 ),
1176 );
1177
1178 yield* Effect.addFinalizer(() => stop());
1179
1180 return {
1181 id: spec.id,
1182 label: spec.label,
1183 start,
1184 stop,
1185 currentConfig,
1186 snapshot,
1187 waitForReady,
1188 } satisfies DesktopBackendInstance;
1189});