Open History to see the last commit
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;
54}
55
56interface BackendProcessExit {
57 readonly code: Option.Option<number>;
58 readonly reason: string;
59 readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
60}
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 }
68}
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 }
78}
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 }
86}
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>;
99}
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;
107}
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>;
114}
115
116export class DesktopBackendManager extends Context.Service<
117 DesktopBackendManager,
118 DesktopBackendManagerShape
119>()("t3/desktop/BackendManager") {}
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>;
129}
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;
139}
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 };
213}
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 );
224}
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;
333 const entryExists = yield* fileSystem
334 .exists(config.entryPath)
335 .pipe(Effect.orElseSucceed(() => false));
336
337 yield* cancelRestart;
338 yield* Ref.update(state, (latest) => ({
339 ...latest,
340 desiredRunning: true,
341 ready: false,
342 config: Option.some(config),
343 }));
344
345 if (!entryExists) {
346 yield* scheduleRestart(`missing server entry at ${config.entryPath}`);
347 return;
348 }
349
350 const runScope = yield* Scope.make("sequential");
351 const runId = yield* Ref.modify(state, (latest) => [
352 latest.nextRunId,
353 {
354 ...latest,
355 active: Option.some({
356 id: latest.nextRunId,
357 scope: runScope,
358 fiber: Option.none(),
359 pid: Option.none(),
360 } satisfies ActiveBackendRun),
361 nextRunId: latest.nextRunId + 1,
362 },
363 ]);
364
365 const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
366 reason: string,
367 ) {
368 yield* mutex.withPermits(1)(
369 Effect.gen(function* () {
370 const { isCurrentRun, nextState, pid } = yield* Ref.modify(
371 state,
372 (
373 latest,
374 ): readonly [
375 {
376 readonly isCurrentRun: boolean;
377 readonly nextState: BackendManagerState;
378 readonly pid: Option.Option<number>;
379 },
380 BackendManagerState,
381 ] => {
382 const currentRun = Option.getOrUndefined(latest.active);
383 if (currentRun?.id !== runId) {
384 return [
385 {
386 isCurrentRun: false,
387 nextState: latest,
388 pid: Option.none<number>(),
389 },
390 latest,
391 ] as const;
392 }
393
394 const next = {
395 ...latest,
396 active: Option.none<ActiveBackendRun>(),
397 ready: false,
398 };
399 return [
400 {
401 isCurrentRun: true,
402 nextState: next,
403 pid: currentRun.pid,
404 },
405 next,
406 ] as const;
407 },
408 );
409
410 if (isCurrentRun) {
411 if (Option.isSome(pid)) {
412 yield* backendOutputLog.writeSessionBoundary({
413 phase: "END",
414 details: `pid=${pid.value} ${reason}`,
415 });
416 }
417 yield* Ref.set(desktopState.backendReady, false);
418 }
419
420 if (isCurrentRun && nextState.desiredRunning) {
421 yield* scheduleRestart(reason);
422 }
423 }),
424 );
425 });
426
427 const program = runBackendProcess({
428 ...config,
429 onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
430 yield* updateActiveRun(runId, (run) => ({
431 ...run,
432 pid: Option.some(pid),
433 }));
434 yield* backendOutputLog.writeSessionBoundary({
435 phase: "START",
436 details: `pid=${pid} port=${config.bootstrap.port} cwd=${config.cwd}`,
437 });
438 }),
439 onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
440 const isCurrentRun = yield* Ref.modify(state, (latest) => {
441 const activeRun = Option.getOrUndefined(latest.active);
442 if (activeRun?.id !== runId) {
443 return [false, latest] as const;
444 }
445
446 return [
447 true,
448 {
449 ...latest,
450 restartAttempt: 0,
451 ready: true,
452 },
453 ] as const;
454 });
455 if (!isCurrentRun) {
456 return;
457 }
458
459 yield* Ref.set(desktopState.backendReady, true);
460 yield* desktopWindow.handleBackendReady.pipe(
461 Effect.catch((error) =>
462 logBackendManagerError("failed to open main window after backend readiness", {
463 message: error.message,
464 }),
465 ),
466 );
467 }),
468 onReadinessFailure: (error) =>
469 logBackendManagerWarning("backend readiness check failed during bootstrap", {
470 error: error.message,
471 }),
472 onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
473 }).pipe(
474 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
475 Effect.provideService(HttpClient.HttpClient, httpClient),
476 Scope.provide(runScope),
477 Effect.matchEffect({
478 onFailure: (error) => finalizeRun(error.message),
479 onSuccess: (exit) => finalizeRun(exit.reason),
480 }),
481 Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
482 );
483
484 const fiber = yield* Effect.forkIn(program, parentScope);
485 yield* updateActiveRun(runId, (run) => ({
486 ...run,
487 fiber: Option.some(fiber),
488 }));
489 }),
490 ),
491 ).pipe(Effect.withSpan("desktop.backendManager.start"));
492
493 const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
494 reason: string,
495 ) {
496 const scheduled = yield* Ref.modify(state, (latest) => {
497 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
498 return [Option.none<Duration.Duration>(), latest] as const;
499 }
500
501 const delay = calculateRestartDelay(latest.restartAttempt);
502 return [
503 Option.some(delay),
504 {
505 ...latest,
506 restartAttempt: latest.restartAttempt + 1,
507 },
508 ] as const;
509 });
510
511 yield* Option.match(scheduled, {
512 onNone: () => Effect.void,
513 onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
514 yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
515 reason,
516 delayMs: Duration.toMillis(delay),
517 });
518 const restartFiber = yield* Effect.forkIn(
519 Effect.sleep(delay).pipe(
520 Effect.andThen(
521 Ref.modify(state, (latest) => {
522 const shouldRestart = latest.desiredRunning;
523 return [
524 shouldRestart,
525 {
526 ...latest,
527 restartFiber: Option.none(),
528 },
529 ] as const;
530 }),
531 ),
532 Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
533 Effect.catchCause((cause) =>
534 logBackendManagerError("desktop backend restart fiber failed", {
535 cause: Cause.pretty(cause),
536 }),
537 ),
538 ),
539 parentScope,
540 );
541 yield* Ref.update(state, (latest) =>
542 Option.isNone(latest.restartFiber)
543 ? {
544 ...latest,
545 restartFiber: Option.some(restartFiber),
546 }
547 : latest,
548 );
549 }),
550 });
551 });
552
553 const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
554 readonly timeout?: Duration.Duration;
555 }) {
556 const { active, restartFiber } = yield* mutex.withPermits(1)(
557 Effect.gen(function* () {
558 const result = yield* Ref.modify(state, (latest) => [
559 {
560 active: latest.active,
561 restartFiber: latest.restartFiber,
562 },
563 {
564 ...latest,
565 desiredRunning: false,
566 ready: false,
567 active: Option.none<ActiveBackendRun>(),
568 restartFiber: Option.none<Fiber.Fiber<void, never>>(),
569 },
570 ]);
571 yield* Ref.set(desktopState.backendReady, false);
572 return result;
573 }),
574 );
575
576 yield* Option.match(restartFiber, {
577 onNone: () => Effect.void,
578 onSome: (fiber) => Fiber.interrupt(fiber).pipe(Effect.asVoid),
579 });
580 yield* Option.match(active, {
581 onNone: () => Effect.void,
582 onSome: (run) => closeRun(run, options),
583 });
584 });
585
586 yield* Effect.addFinalizer(() => stop());
587
588 return DesktopBackendManager.of({
589 start,
590 stop,
591 currentConfig,
592 snapshot,
593 });
594});
595
596export const layer = Layer.effect(DesktopBackendManager, makeDesktopBackendManager());