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

DesktopBackendManager.ts

606 lines20.5 KB

1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Data from "effect/Data";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as PlatformError from "effect/PlatformError";
12import * as Ref from "effect/Ref";
13import * as Result from "effect/Result";
14import * as Schedule from "effect/Schedule";
15import * as Schema from "effect/Schema";
16import * as Semaphore from "effect/Semaphore";
17import * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19import { HttpClient } from "effect/unstable/http";
20import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
21​
22import {
23 DesktopBackendBootstrap,
24 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
25} from "@t3tools/contracts";
26​
27import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
28import * as DesktopObservability from "../app/DesktopObservability.ts";
29import * as DesktopState from "../app/DesktopState.ts";
30import * as DesktopWindow from "../window/DesktopWindow.ts";
31​
32const INITIAL_RESTART_DELAY = Duration.millis(500);
33const MAX_RESTART_DELAY = Duration.seconds(10);
34const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
35const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
36const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
37const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
38const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
39​
40type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
41​
42type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
43​
44export type BackendProcessOutputStream = "stdout" | "stderr";
45​
46export interface DesktopBackendStartConfig {
47 readonly executablePath: string;
48 readonly entryPath: string;
49 readonly cwd: string;
50 readonly env: Record<string, string | undefined>;
51 readonly bootstrap: DesktopBackendBootstrapValue;
52 readonly httpBaseUrl: URL;
53 readonly captureOutput: boolean;
55​
56interface BackendProcessExit {
57 readonly code: Option.Option<number>;
58 readonly reason: string;
59 readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
61​
62export class BackendTimeoutError extends Data.TaggedError("BackendTimeoutError")<{
63 readonly url: URL;
64}> {
65 override get message() {
66 return `Timed out waiting for backend readiness at ${this.url.href}.`;
67 }
69​
70class BackendProcessBootstrapEncodeError extends Data.TaggedError(
71 "BackendProcessBootstrapEncodeError",
72)<{
73 readonly cause: Schema.SchemaError;
74}> {
75 override get message() {
76 return `Failed to encode desktop backend bootstrap payload: ${this.cause.message}`;
77 }
79​
80class BackendProcessSpawnError extends Data.TaggedError("BackendProcessSpawnError")<{
81 readonly cause: PlatformError.PlatformError;
82}> {
83 override get message() {
84 return `Failed to spawn desktop backend process: ${this.cause.message}`;
85 }
87​
88type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
89​
90interface RunBackendProcessOptions extends DesktopBackendStartConfig {
91 readonly readinessTimeout?: Duration.Duration;
92 readonly onStarted?: (pid: number) => Effect.Effect<void>;
93 readonly onReady?: () => Effect.Effect<void>;
94 readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
95 readonly onOutput?: (
96 streamName: BackendProcessOutputStream,
97 chunk: Uint8Array,
98 ) => Effect.Effect<void>;
100​
101export interface DesktopBackendSnapshot {
102 readonly desiredRunning: boolean;
103 readonly ready: boolean;
104 readonly activePid: Option.Option<number>;
105 readonly restartAttempt: number;
106 readonly restartScheduled: boolean;
108​
109export interface DesktopBackendManagerShape {
110 readonly start: Effect.Effect<void>;
111 readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
112 readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
113 readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
115​
116export class DesktopBackendManager extends Context.Service<
117 DesktopBackendManager,
118 DesktopBackendManagerShape
119>()("@t3tools/desktop/backend/DesktopBackendManager") {}
120​
121const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
122 DesktopObservability.makeComponentLogger("desktop-backend-manager");
123​
124interface ActiveBackendRun {
125 readonly id: number;
126 readonly scope: Scope.Closeable;
127 readonly fiber: Option.Option<Fiber.Fiber<void, never>>;
128 readonly pid: Option.Option<number>;
130​
131interface BackendManagerState {
132 readonly desiredRunning: boolean;
133 readonly ready: boolean;
134 readonly config: Option.Option<DesktopBackendStartConfig>;
135 readonly active: Option.Option<ActiveBackendRun>;
136 readonly restartAttempt: number;
137 readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
138 readonly nextRunId: number;
140​
141const initialState: BackendManagerState = {
142 desiredRunning: false,
143 ready: false,
144 config: Option.none(),
145 active: Option.none(),
146 restartAttempt: 0,
147 restartFiber: Option.none(),
148 nextRunId: 1,
149};
150​
151const activePid = (active: Option.Option<ActiveBackendRun>): Option.Option<number> =>
152 Option.flatMap(active, (run) => run.pid);
153​
154const withActiveRun =
155 (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
156 (state: BackendManagerState): BackendManagerState => ({
157 ...state,
158 active: Option.map(state.active, (run) => (run.id === runId ? f(run) : run)),
159 });
160​
161const calculateRestartDelay = (attempt: number): Duration.Duration =>
162 Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
163​
164const closeRun = (
165 run: ActiveBackendRun,
166 options?: { readonly timeout?: Duration.Duration },
167): Effect.Effect<void> => {
168 const waitForFiber = Option.match(run.fiber, {
169 onNone: () => Effect.void,
170 onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
171 });
172 const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber));
173​
174 return (
175 options?.timeout ? close.pipe(Effect.timeoutOption(options.timeout), Effect.asVoid) : close
176 ).pipe(Effect.ignore);
177};
178​
179const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
180 baseUrl: URL,
181 timeout: Duration.Duration,
182): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
183 const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
184 const client = (yield* HttpClient.HttpClient).pipe(
185 HttpClient.filterStatusOk,
186 HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
187 HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
188 );
189​
190 yield* client.get(readinessUrl).pipe(
191 Effect.asVoid,
192 Effect.timeout(timeout),
193 Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
194 );
195});
196​
197function describeProcessExit(
198 result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
199): BackendProcessExit {
200 if (Result.isSuccess(result)) {
201 return {
202 code: Option.some(result.success),
203 reason: `code=${result.success}`,
204 result,
205 };
206 }
207​
208 return {
209 code: Option.none(),
210 reason: result.failure.message,
211 result,
212 };
214​
215function drainBackendOutput(
216 streamName: BackendProcessOutputStream,
217 stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
218 onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
219): Effect.Effect<void> {
220 return stream.pipe(
221 Stream.runForEach((chunk) => onOutput(streamName, chunk)),
222 Effect.ignore,
223 );
225​
226const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
227​
228const runBackendProcess = Effect.fn("runBackendProcess")(function* (
229 options: RunBackendProcessOptions,
230): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
231 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
232 const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
233 Effect.mapError((cause) => new BackendProcessBootstrapEncodeError({ cause })),
234 );
235 const onOutput = options.onOutput ?? (() => Effect.void);
236 const command = ChildProcess.make(
237 options.executablePath,
238 [options.entryPath, "--bootstrap-fd", "3"],
239 {
240 cwd: options.cwd,
241 env: options.env,
242 extendEnv: true,
243 // In Electron main, process.execPath points to the Electron binary.
244 // Run the child in Node mode so this backend process does not become a GUI app instance.
245 stdin: "ignore",
246 stdout: options.captureOutput ? "pipe" : "inherit",
247 stderr: options.captureOutput ? "pipe" : "inherit",
248 killSignal: "SIGTERM",
249 forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
250 additionalFds: {
251 fd3: {
252 type: "input",
253 stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
254 },
255 },
256 },
257 );
258​
259 const handle = yield* spawner
260 .spawn(command)
261 .pipe(Effect.mapError((cause) => new BackendProcessSpawnError({ cause })));
262​
263 yield* options.onStarted?.(handle.pid) ?? Effect.void;
264 if (options.captureOutput) {
265 yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
266 yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
267 }
268 yield* waitForHttpReady(
269 options.httpBaseUrl,
270 options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
271 ).pipe(
272 Effect.tap(() => options.onReady?.() ?? Effect.void),
273 Effect.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
274 Effect.forkScoped,
275 );
276​
277 return describeProcessExit(yield* Effect.result(handle.exitCode));
278});
279​
280const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(function* () {
281 const parentScope = yield* Scope.Scope;
282 const fileSystem = yield* FileSystem.FileSystem;
283 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
284 const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
285 const desktopState = yield* DesktopState.DesktopState;
286 const desktopWindow = yield* DesktopWindow.DesktopWindow;
287 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
288 const httpClient = yield* HttpClient.HttpClient;
289 const state = yield* Ref.make(initialState);
290 const mutex = yield* Semaphore.make(1);
291​
292 const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
293 Ref.update(state, withActiveRun(runId, f));
294​
295 const snapshot = Ref.get(state).pipe(
296 Effect.map(
297 (current): DesktopBackendSnapshot => ({
298 desiredRunning: current.desiredRunning,
299 ready: current.ready,
300 activePid: activePid(current.active),
301 restartAttempt: current.restartAttempt,
302 restartScheduled: Option.isSome(current.restartFiber),
303 }),
304 ),
305 );
306 const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config));
307​
308 const cancelRestart = Effect.gen(function* () {
309 const restartFiber = yield* Ref.modify(state, (current) => [
310 current.restartFiber,
311 {
312 ...current,
313 restartFiber: Option.none(),
314 },
315 ]);
316​
317 yield* Option.match(restartFiber, {
318 onNone: () => Effect.void,
319 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
320 });
321 });
322​
323 const start: Effect.Effect<void> = Effect.suspend(() =>
324 mutex.withPermits(1)(
325 Effect.gen(function* () {
326 const current = yield* Ref.get(state);
327 if (Option.isSome(current.active)) {
328 return;
329 }
330​
331 yield* Ref.set(desktopState.backendReady, false);
332 const config = yield* configuration.resolve.pipe(
333 Effect.tapError((error) =>
334 logBackendManagerError("failed to generate desktop backend configuration", {
335 cause: error.message,
336 }),
337 ),
338 Effect.option,
339 );
340 if (Option.isNone(config)) {
341 return;
342 }
343 const entryExists = yield* fileSystem
344 .exists(config.value.entryPath)
345 .pipe(Effect.orElseSucceed(() => false));
346​
347 yield* cancelRestart;
348 yield* Ref.update(state, (latest) => ({
349 ...latest,
350 desiredRunning: true,
351 ready: false,
352 config: Option.some(config.value),
353 }));
354​
355 if (!entryExists) {
356 yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
357 return;
358 }
359​
360 const runScope = yield* Scope.make("sequential");
361 const runId = yield* Ref.modify(state, (latest) => [
362 latest.nextRunId,
363 {
364 ...latest,
365 active: Option.some({
366 id: latest.nextRunId,
367 scope: runScope,
368 fiber: Option.none(),
369 pid: Option.none(),
370 } satisfies ActiveBackendRun),
371 nextRunId: latest.nextRunId + 1,
372 },
373 ]);
374​
375 const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
376 reason: string,
377 ) {
378 yield* mutex.withPermits(1)(
379 Effect.gen(function* () {
380 const { isCurrentRun, nextState, pid } = yield* Ref.modify(
381 state,
382 (
383 latest,
384 ): readonly [
385 {
386 readonly isCurrentRun: boolean;
387 readonly nextState: BackendManagerState;
388 readonly pid: Option.Option<number>;
389 },
390 BackendManagerState,
391 ] => {
392 const currentRun = Option.getOrUndefined(latest.active);
393 if (currentRun?.id !== runId) {
394 return [
395 {
396 isCurrentRun: false,
397 nextState: latest,
398 pid: Option.none<number>(),
399 },
400 latest,
401 ] as const;
402 }
403​
404 const next = {
405 ...latest,
406 active: Option.none<ActiveBackendRun>(),
407 ready: false,
408 };
409 return [
410 {
411 isCurrentRun: true,
412 nextState: next,
413 pid: currentRun.pid,
414 },
415 next,
416 ] as const;
417 },
418 );
419​
420 if (isCurrentRun) {
421 if (Option.isSome(pid)) {
422 yield* backendOutputLog.writeSessionBoundary({
423 phase: "END",
424 details: `pid=${pid.value} ${reason}`,
425 });
426 }
427 yield* Ref.set(desktopState.backendReady, false);
428 }
429​
430 if (isCurrentRun && nextState.desiredRunning) {
431 yield* scheduleRestart(reason);
432 }
433 }),
434 );
435 });
436​
437 const program = runBackendProcess({
438 ...config.value,
439 onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
440 yield* updateActiveRun(runId, (run) => ({
441 ...run,
442 pid: Option.some(pid),
443 }));
444 yield* backendOutputLog.writeSessionBoundary({
445 phase: "START",
446 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
447 });
448 }),
449 onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
450 const isCurrentRun = yield* Ref.modify(state, (latest) => {
451 const activeRun = Option.getOrUndefined(latest.active);
452 if (activeRun?.id !== runId) {
453 return [false, latest] as const;
454 }
455​
456 return [
457 true,
458 {
459 ...latest,
460 restartAttempt: 0,
461 ready: true,
462 },
463 ] as const;
464 });
465 if (!isCurrentRun) {
466 return;
467 }
468​
469 yield* Ref.set(desktopState.backendReady, true);
470 yield* desktopWindow.handleBackendReady.pipe(
471 Effect.catch((error) =>
472 logBackendManagerError("failed to open main window after backend readiness", {
473 message: error.message,
474 }),
475 ),
476 );
477 }),
478 onReadinessFailure: (error) =>
479 logBackendManagerWarning("backend readiness check failed during bootstrap", {
480 error: error.message,
481 }),
482 onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
483 }).pipe(
484 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
485 Effect.provideService(HttpClient.HttpClient, httpClient),
486 Scope.provide(runScope),
487 Effect.matchEffect({
488 onFailure: (error) => finalizeRun(error.message),
489 onSuccess: (exit) => finalizeRun(exit.reason),
490 }),
491 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
492 );
493​
494 const fiber = yield* Effect.forkIn(program, parentScope);
495 yield* updateActiveRun(runId, (run) => ({
496 ...run,
497 fiber: Option.some(fiber),
498 }));
499 }),
500 ),
501 ).pipe(Effect.withSpan("desktop.backendManager.start"));
502​
503 const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
504 reason: string,
505 ) {
506 const scheduled = yield* Ref.modify(state, (latest) => {
507 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
508 return [Option.none<Duration.Duration>(), latest] as const;
509 }
510​
511 const delay = calculateRestartDelay(latest.restartAttempt);
512 return [
513 Option.some(delay),
514 {
515 ...latest,
516 restartAttempt: latest.restartAttempt + 1,
517 },
518 ] as const;
519 });
520​
521 yield* Option.match(scheduled, {
522 onNone: () => Effect.void,
523 onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
524 yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
525 reason,
526 delayMs: Duration.toMillis(delay),
527 });
528 const restartFiber = yield* Effect.forkIn(
529 Effect.sleep(delay).pipe(
530 Effect.andThen(
531 Ref.modify(state, (latest) => {
532 const shouldRestart = latest.desiredRunning;
533 return [
534 shouldRestart,
535 {
536 ...latest,
537 restartFiber: Option.none(),
538 },
539 ] as const;
540 }),
541 ),
542 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
543 Effect.catchCause((cause) =>
544 logBackendManagerError("desktop backend restart fiber failed", {
545 cause: Cause.pretty(cause),
546 }),
547 ),
548 ),
549 parentScope,
550 );
551 yield* Ref.update(state, (latest) =>
552 Option.isNone(latest.restartFiber)
553 ? {
554 ...latest,
555 restartFiber: Option.some(restartFiber),
556 }
557 : latest,
558 );
559 }),
560 });
561 });
562​
563 const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
564 readonly timeout?: Duration.Duration;
565 }) {
566 const { active, restartFiber } = yield* mutex.withPermits(1)(
567 Effect.gen(function* () {
568 const result = yield* Ref.modify(state, (latest) => [
569 {
570 active: latest.active,
571 restartFiber: latest.restartFiber,
572 },
573 {
574 ...latest,
575 desiredRunning: false,
576 ready: false,
577 active: Option.none<ActiveBackendRun>(),
578 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
579 },
580 ]);
581 yield* Ref.set(desktopState.backendReady, false);
582 return result;
583 }),
584 );
585​
586 yield* Option.match(restartFiber, {
587 onNone: () => Effect.void,
588 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
589 });
590 yield* Option.match(active, {
591 onNone: () => Effect.void,
592 onSome: (run) => closeRun(run, options),
593 });
594 });
595​
596 yield* Effect.addFinalizer(() => stop());
597​
598 return DesktopBackendManager.of({
599 start,
600 stop,
601 currentConfig,
602 snapshot,
603 });
604});
605​
606export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager());