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

DesktopBackendManager.ts

778 lines25.3 KB

1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
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 Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as PlatformError from "effect/PlatformError";
11import * as Ref from "effect/Ref";
12import * as Schedule from "effect/Schedule";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15import * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17import * as HttpClient from "effect/unstable/http/HttpClient";
18import * as ChildProcess from "effect/unstable/process/ChildProcess";
19import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
20​
21import {
22 DesktopBackendBootstrap,
23 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
24} from "@t3tools/contracts";
25​
26import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
27import * as DesktopObservability from "../app/DesktopObservability.ts";
28import * as DesktopState from "../app/DesktopState.ts";
29import * as DesktopWindow from "../window/DesktopWindow.ts";
30​
31const INITIAL_RESTART_DELAY = Duration.millis(500);
32const MAX_RESTART_DELAY = Duration.seconds(10);
33const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
34const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
35const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
36const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
37const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
38​
39type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
40​
41type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
42​
43export type BackendProcessOutputStream = "stdout" | "stderr";
44​
45export interface BackendProcessContext {
46 readonly executablePath: string;
47 readonly entryPath: string;
48 readonly cwd: string;
49 readonly httpBaseUrl: URL;
51​
52export interface DesktopBackendStartConfig extends BackendProcessContext {
53 readonly env: Record<string, string | undefined>;
54 readonly bootstrap: DesktopBackendBootstrapValue;
55 readonly captureOutput: boolean;
57​
58interface BackendProcessExit {
59 readonly code: Option.Option<number>;
60 readonly reason: string;
62​
63const backendProcessContextSchema = {
64 executablePath: Schema.String,
65 entryPath: Schema.String,
66 cwd: Schema.String,
67 httpBaseUrl: Schema.URL,
68};
69​
70export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
71 "BackendReadinessTimeoutError",
72 {
73 ...backendProcessContextSchema,
74 readinessUrl: Schema.URL,
75 timeoutMs: Schema.Number,
76 cause: Schema.Defect(),
77 },
78) {
79 override get message(): string {
80 return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
81 }
83​
84export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
85 "BackendProcessBootstrapEncodeError",
86 {
87 ...backendProcessContextSchema,
88 cause: Schema.Defect(),
89 },
90) {
91 override get message(): string {
92 return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
93 }
95​
96export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
97 "BackendProcessSpawnError",
98 {
99 ...backendProcessContextSchema,
100 cause: Schema.Defect(),
101 },
102) {
103 override get message(): string {
104 return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
105 }
107​
108export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
109 "BackendProcessOutputReadError",
110 {
111 ...backendProcessContextSchema,
112 pid: Schema.Number,
113 streamName: Schema.Literals(["stdout", "stderr"]),
114 cause: Schema.Defect(),
115 },
116) {
117 override get message(): string {
118 return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
119 }
121​
122export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
123 "BackendProcessOutputHandlingError",
124 {
125 ...backendProcessContextSchema,
126 pid: Schema.Number,
127 streamName: Schema.Literals(["stdout", "stderr"]),
128 chunkByteLength: Schema.Number,
129 cause: Schema.Defect(),
130 },
131) {
132 override get message(): string {
133 return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
134 }
136​
137export type BackendProcessOutputError =
138 | BackendProcessOutputReadError
139 | BackendProcessOutputHandlingError;
140​
141export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
142 "BackendProcessExitStatusError",
143 {
144 ...backendProcessContextSchema,
145 pid: Schema.Number,
146 cause: Schema.Defect(),
147 },
148) {
149 override get message(): string {
150 return `Failed to read the exit status of desktop backend process ${this.pid}.`;
151 }
153​
154export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
155 "DesktopBackendRestartError",
156 {
157 reason: Schema.String,
158 delayMs: Schema.Number,
159 cause: Schema.Defect(),
160 },
161) {
162 override get message(): string {
163 return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
164 }
166​
167export const BackendProcessError = Schema.Union([
168 BackendProcessBootstrapEncodeError,
169 BackendProcessSpawnError,
170 BackendProcessExitStatusError,
171]);
172export type BackendProcessError = typeof BackendProcessError.Type;
173​
174interface RunBackendProcessOptions extends DesktopBackendStartConfig {
175 readonly readinessTimeout?: Duration.Duration;
176 readonly onStarted?: (pid: number) => Effect.Effect<void>;
177 readonly onReady?: () => Effect.Effect<void>;
178 readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
179 readonly onOutput?: (
180 streamName: BackendProcessOutputStream,
181 chunk: Uint8Array,
182 ) => Effect.Effect<void, Error>;
183 readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
185​
186export interface DesktopBackendSnapshot {
187 readonly desiredRunning: boolean;
188 readonly ready: boolean;
189 readonly activePid: Option.Option<number>;
190 readonly restartAttempt: number;
191 readonly restartScheduled: boolean;
193​
194export class DesktopBackendManager extends Context.Service<
195 DesktopBackendManager,
196 {
197 readonly start: Effect.Effect<void>;
198 readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
199 readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
200 readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
201 }
202>()("@t3tools/desktop/backend/DesktopBackendManager") {}
203​
204const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
205 DesktopObservability.makeComponentLogger("desktop-backend-manager");
206​
207interface ActiveBackendRun {
208 readonly id: number;
209 readonly scope: Scope.Closeable;
210 readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
211 readonly pid: Option.Option<number>;
213​
214interface BackendManagerState {
215 readonly desiredRunning: boolean;
216 readonly ready: boolean;
217 readonly config: Option.Option<DesktopBackendStartConfig>;
218 readonly active: Option.Option<ActiveBackendRun>;
219 readonly restartAttempt: number;
220 readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
221 readonly nextRunId: number;
223​
224const initialState: BackendManagerState = {
225 desiredRunning: false,
226 ready: false,
227 config: Option.none(),
228 active: Option.none(),
229 restartAttempt: 0,
230 restartFiber: Option.none(),
231 nextRunId: 1,
232};
233​
234const activePid = (active: Option.Option<ActiveBackendRun>): Option.Option<number> =>
235 Option.flatMap(active, (run) => run.pid);
236​
237const withActiveRun =
238 (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
239 (state: BackendManagerState): BackendManagerState => ({
240 ...state,
241 active: Option.map(state.active, (run) => (run.id === runId ? f(run) : run)),
242 });
243​
244const calculateRestartDelay = (attempt: number): Duration.Duration =>
245 Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
246​
247const closeRun = (
248 run: ActiveBackendRun,
249 options?: { readonly timeout?: Duration.Duration },
250): Effect.Effect<void> => {
251 const waitForFiber = Option.match(run.fiber, {
252 onNone: () => Effect.void,
253 onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
254 });
255 const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
256​
257 return (
258 options?.timeout ? close.pipe(Effect.timeoutOption(options.timeout), Effect.asVoid) : close
259 ).pipe(Effect.ignore);
260};
261​
262export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
263 options: BackendProcessContext & { readonly timeout: Duration.Duration },
264): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
265 const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
266 const client = (yield* HttpClient.HttpClient).pipe(
267 HttpClient.filterStatusOk,
268 HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
269 HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
270 );
271​
272 yield* client.get(readinessUrl).pipe(
273 Effect.asVoid,
274 Effect.timeout(options.timeout),
275 Effect.mapError(
276 (cause) =>
277 new BackendReadinessTimeoutError({
278 executablePath: options.executablePath,
279 entryPath: options.entryPath,
280 cwd: options.cwd,
281 httpBaseUrl: options.httpBaseUrl,
282 readinessUrl,
283 timeoutMs: Duration.toMillis(options.timeout),
284 cause,
285 }),
286 ),
287 );
288});
289​
290function drainBackendOutput(
291 context: BackendProcessContext & { readonly pid: number },
292 streamName: BackendProcessOutputStream,
293 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
294 onOutput: (
295 streamName: BackendProcessOutputStream,
296 chunk: Uint8Array,
297 ) => Effect.Effect<void, Error>,
298 onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
299): Effect.Effect<void> {
300 return stream.pipe(
301 Stream.mapError(
302 (cause) =>
303 new BackendProcessOutputReadError({
304 ...context,
305 streamName,
306 cause,
307 }),
308 ),
309 Stream.runForEach((chunk) =>
310 onOutput(streamName, chunk).pipe(
311 Effect.mapError(
312 (cause) =>
313 new BackendProcessOutputHandlingError({
314 ...context,
315 streamName,
316 chunkByteLength: chunk.byteLength,
317 cause,
318 }),
319 ),
320 ),
321 ),
322 Effect.catchTags({
323 BackendProcessOutputReadError: onOutputFailure,
324 BackendProcessOutputHandlingError: onOutputFailure,
325 }),
326 );
328​
329const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
330​
331export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
332 options: RunBackendProcessOptions,
333): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
334 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
335 const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
336 Effect.mapError(
337 (cause) =>
338 new BackendProcessBootstrapEncodeError({
339 executablePath: options.executablePath,
340 entryPath: options.entryPath,
341 cwd: options.cwd,
342 httpBaseUrl: options.httpBaseUrl,
343 cause,
344 }),
345 ),
346 );
347 const onOutput = options.onOutput ?? (() => Effect.void);
348 const command = ChildProcess.make(
349 options.executablePath,
350 [options.entryPath, "--bootstrap-fd", "3"],
351 {
352 cwd: options.cwd,
353 env: options.env,
354 extendEnv: true,
355 // In Electron main, process.execPath points to the Electron binary.
356 // Run the child in Node mode so this backend process does not become a GUI app instance.
357 stdin: "ignore",
358 stdout: options.captureOutput ? "pipe" : "inherit",
359 stderr: options.captureOutput ? "pipe" : "inherit",
360 killSignal: "SIGTERM",
361 forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
362 additionalFds: {
363 fd3: {
364 type: "input",
365 stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
366 },
367 },
368 },
369 );
370​
371 const handle = yield* spawner.spawn(command).pipe(
372 Effect.mapError(
373 (cause) =>
374 new BackendProcessSpawnError({
375 executablePath: options.executablePath,
376 entryPath: options.entryPath,
377 cwd: options.cwd,
378 httpBaseUrl: options.httpBaseUrl,
379 cause,
380 }),
381 ),
382 );
383​
384 yield* options.onStarted?.(handle.pid) ?? Effect.void;
385 if (options.captureOutput) {
386 const outputContext = {
387 executablePath: options.executablePath,
388 entryPath: options.entryPath,
389 cwd: options.cwd,
390 httpBaseUrl: options.httpBaseUrl,
391 pid: Number(handle.pid),
392 };
393 const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
394 yield* drainBackendOutput(
395 outputContext,
396 "stdout",
397 handle.stdout,
398 onOutput,
399 onOutputFailure,
400 ).pipe(Effect.forkScoped);
401 yield* drainBackendOutput(
402 outputContext,
403 "stderr",
404 handle.stderr,
405 onOutput,
406 onOutputFailure,
407 ).pipe(Effect.forkScoped);
408 }
409 yield* waitForHttpReady({
410 executablePath: options.executablePath,
411 entryPath: options.entryPath,
412 cwd: options.cwd,
413 httpBaseUrl: options.httpBaseUrl,
414 timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
415 }).pipe(
416 Effect.tap(() => options.onReady?.() ?? Effect.void),
417 Effect.catchTags({
418 BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
419 }),
420 Effect.forkScoped,
421 );
422​
423 const exitCode = yield* handle.exitCode.pipe(
424 Effect.mapError(
425 (cause) =>
426 new BackendProcessExitStatusError({
427 executablePath: options.executablePath,
428 entryPath: options.entryPath,
429 cwd: options.cwd,
430 httpBaseUrl: options.httpBaseUrl,
431 pid: Number(handle.pid),
432 cause,
433 }),
434 ),
435 );
436 return {
437 code: Option.some(exitCode),
438 reason: `code=${exitCode}`,
439 } satisfies BackendProcessExit;
440});
441​
442export const make = Effect.gen(function* () {
443 const parentScope = yield* Scope.Scope;
444 const fileSystem = yield* FileSystem.FileSystem;
445 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
446 const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
447 const desktopState = yield* DesktopState.DesktopState;
448 const desktopWindow = yield* DesktopWindow.DesktopWindow;
449 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
450 const httpClient = yield* HttpClient.HttpClient;
451 const state = yield* Ref.make(initialState);
452 const mutex = yield* Semaphore.make(1);
453​
454 const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
455 Ref.update(state, withActiveRun(runId, f));
456​
457 const snapshot = Ref.get(state).pipe(
458 Effect.map(
459 (current): DesktopBackendSnapshot => ({
460 desiredRunning: current.desiredRunning,
461 ready: current.ready,
462 activePid: activePid(current.active),
463 restartAttempt: current.restartAttempt,
464 restartScheduled: Option.isSome(current.restartFiber),
465 }),
466 ),
467 );
468 const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config));
469​
470 const cancelRestart = Effect.gen(function* () {
471 const restartFiber = yield* Ref.modify(state, (current) => [
472 current.restartFiber,
473 {
474 ...current,
475 restartFiber: Option.none(),
476 },
477 ]);
478​
479 yield* Option.match(restartFiber, {
480 onNone: () => Effect.void,
481 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
482 });
483 });
484​
485 const start: Effect.Effect<void> = Effect.suspend(() =>
486 mutex.withPermits(1)(
487 Effect.gen(function* () {
488 const current = yield* Ref.get(state);
489 if (Option.isSome(current.active)) {
490 return;
491 }
492​
493 yield* Ref.set(desktopState.backendReady, false);
494 const config = yield* configuration.resolve.pipe(
495 Effect.tapError((error) =>
496 logBackendManagerError("failed to generate desktop backend configuration", {
497 cause: error,
498 }),
499 ),
500 Effect.option,
501 );
502 if (Option.isNone(config)) {
503 return;
504 }
505 const entryExists = yield* fileSystem
506 .exists(config.value.entryPath)
507 .pipe(Effect.orElseSucceed(() => false));
508​
509 yield* cancelRestart;
510 yield* Ref.update(state, (latest) => ({
511 ...latest,
512 desiredRunning: true,
513 ready: false,
514 config: Option.some(config.value),
515 }));
516​
517 if (!entryExists) {
518 yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
519 return;
520 }
521​
522 const runScope = yield* Scope.make("sequential");
523 const runId = yield* Ref.modify(state, (latest) => [
524 latest.nextRunId,
525 {
526 ...latest,
527 active: Option.some({
528 id: latest.nextRunId,
529 scope: runScope,
530 fiber: Option.none(),
531 pid: Option.none(),
532 } satisfies ActiveBackendRun),
533 nextRunId: latest.nextRunId + 1,
534 },
535 ]);
536​
537 const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
538 reason: string,
539 ) {
540 yield* mutex.withPermits(1)(
541 Effect.gen(function* () {
542 const { isCurrentRun, nextState, pid } = yield* Ref.modify(
543 state,
544 (
545 latest,
546 ): readonly [
547 {
548 readonly isCurrentRun: boolean;
549 readonly nextState: BackendManagerState;
550 readonly pid: Option.Option<number>;
551 },
552 BackendManagerState,
553 ] => {
554 const currentRun = Option.getOrUndefined(latest.active);
555 if (currentRun?.id !== runId) {
556 return [
557 {
558 isCurrentRun: false,
559 nextState: latest,
560 pid: Option.none<number>(),
561 },
562 latest,
563 ] as const;
564 }
565​
566 const next = {
567 ...latest,
568 active: Option.none<ActiveBackendRun>(),
569 ready: false,
570 };
571 return [
572 {
573 isCurrentRun: true,
574 nextState: next,
575 pid: currentRun.pid,
576 },
577 next,
578 ] as const;
579 },
580 );
581​
582 if (isCurrentRun) {
583 if (Option.isSome(pid)) {
584 yield* backendOutputLog.writeSessionBoundary({
585 phase: "END",
586 details: `pid=${pid.value} ${reason}`,
587 });
588 }
589 yield* Ref.set(desktopState.backendReady, false);
590 }
591​
592 if (isCurrentRun && nextState.desiredRunning) {
593 yield* scheduleRestart(reason);
594 }
595 }),
596 );
597 });
598​
599 const program = runBackendProcess({
600 ...config.value,
601 onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
602 yield* updateActiveRun(runId, (run) => ({
603 ...run,
604 pid: Option.some(pid),
605 }));
606 yield* backendOutputLog.writeSessionBoundary({
607 phase: "START",
608 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
609 });
610 }),
611 onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
612 const isCurrentRun = yield* Ref.modify(state, (latest) => {
613 const activeRun = Option.getOrUndefined(latest.active);
614 if (activeRun?.id !== runId) {
615 return [false, latest] as const;
616 }
617​
618 return [
619 true,
620 {
621 ...latest,
622 restartAttempt: 0,
623 ready: true,
624 },
625 ] as const;
626 });
627 if (!isCurrentRun) {
628 return;
629 }
630​
631 yield* Ref.set(desktopState.backendReady, true);
632 yield* desktopWindow.handleBackendReady.pipe(
633 Effect.catch((error) =>
634 logBackendManagerError("failed to open main window after backend readiness", {
635 cause: error,
636 }),
637 ),
638 );
639 }),
640 onReadinessFailure: (error) =>
641 logBackendManagerWarning("backend readiness check failed during bootstrap", {
642 error,
643 }),
644 onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
645 onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
646 }).pipe(
647 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
648 Effect.provideService(HttpClient.HttpClient, httpClient),
649 Scope.provide(runScope),
650 Effect.matchEffect({
651 onFailure: (error) =>
652 logBackendManagerError(error.message, { error }).pipe(
653 Effect.andThen(finalizeRun(error.message)),
654 ),
655 onSuccess: (exit) => finalizeRun(exit.reason),
656 }),
657 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
658 );
659​
660 const fiber = yield* Effect.forkIn(program, parentScope);
661 yield* updateActiveRun(runId, (run) => ({
662 ...run,
663 fiber: Option.some(fiber),
664 }));
665 }),
666 ),
667 ).pipe(Effect.withSpan("desktop.backendManager.start"));
668​
669 const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
670 reason: string,
671 ) {
672 const scheduled = yield* Ref.modify(state, (latest) => {
673 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
674 return [Option.none<Duration.Duration>(), latest] as const;
675 }
676​
677 const delay = calculateRestartDelay(latest.restartAttempt);
678 return [
679 Option.some(delay),
680 {
681 ...latest,
682 restartAttempt: latest.restartAttempt + 1,
683 },
684 ] as const;
685 });
686​
687 yield* Option.match(scheduled, {
688 onNone: () => Effect.void,
689 onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
690 yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
691 reason,
692 delayMs: Duration.toMillis(delay),
693 });
694 const restartFiber = yield* Effect.forkIn(
695 Effect.sleep(delay).pipe(
696 Effect.andThen(
697 Ref.modify(state, (latest) => {
698 const shouldRestart = latest.desiredRunning;
699 return [
700 shouldRestart,
701 {
702 ...latest,
703 restartFiber: Option.none(),
704 },
705 ] as const;
706 }),
707 ),
708 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
709 Effect.catchCause((cause) => {
710 if (Cause.hasInterruptsOnly(cause)) {
711 return Effect.void;
712 }
713 const error = new DesktopBackendRestartError({
714 reason,
715 delayMs: Duration.toMillis(delay),
716 cause,
717 });
718 return logBackendManagerError(error.message, { error });
719 }),
720 ),
721 parentScope,
722 );
723 yield* Ref.update(state, (latest) =>
724 Option.isNone(latest.restartFiber)
725 ? {
726 ...latest,
727 restartFiber: Option.some(restartFiber),
728 }
729 : latest,
730 );
731 }),
732 });
733 });
734​
735 const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
736 readonly timeout?: Duration.Duration;
737 }) {
738 const { active, restartFiber } = yield* mutex.withPermits(1)(
739 Effect.gen(function* () {
740 const result = yield* Ref.modify(state, (latest) => [
741 {
742 active: latest.active,
743 restartFiber: latest.restartFiber,
744 },
745 {
746 ...latest,
747 desiredRunning: false,
748 ready: false,
749 active: Option.none<ActiveBackendRun>(),
750 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
751 },
752 ]);
753 yield* Ref.set(desktopState.backendReady, false);
754 return result;
755 }),
756 );
757​
758 yield* Option.match(restartFiber, {
759 onNone: () => Effect.void,
760 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
761 });
762 yield* Option.match(active, {
763 onNone: () => Effect.void,
764 onSome: (run) => closeRun(run, options),
765 });
766 });
767​
768 yield* Effect.addFinalizer(() => stop());
769​
770 return DesktopBackendManager.of({
771 start,
772 stop,
773 currentConfig,
774 snapshot,
775 });
776});
777​
778export const layer = Layer.effect(DesktopBackendManager, make);