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

DesktopBackendManager.ts

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