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