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