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