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

DesktopBackendManager.ts

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