Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopBackendManager.ts

1,143 lines40.0 KB

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