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

DesktopBackendManager.ts

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