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