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

DesktopBackendRecoveryProcess.ts

99 lines3.7 KB

1// @effect-diagnostics globalTimers:off -- Worker deadlines run at child-process callback boundaries outside Effect fibers.
2// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only helper owns a Node child process.
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFSP from "node:fs/promises";
5import * as NodePath from "node:path";
6​
7export type RecoveryWorkerMessage =
8 | { readonly type: "recovering"; readonly pid: number }
9 | { readonly type: "error"; readonly operation: string }
10 | { readonly type: "tracked"; readonly record: string };
11​
12const trackDeadlineMs = 5_000;
13// Covers the worker's SIGTERM and SIGKILL grace periods with room to start.
14const recoverDeadlineMs = 10_000;
15​
16/** Runs recovery's native process inspection in a helper so a stall cannot block desktop main. */
17export function make(input: {
18 readonly appDataDirectory: string;
19 readonly stateDir: string;
20 readonly onRecovery: (pid: number) => void;
21 readonly onError: (operation: string) => void;
22}) {
23 const run = (
24 operation: "track" | "recover",
25 deadlineMs: number,
26 options: { readonly backendPid?: number; readonly signal?: AbortSignal } = {},
27 ) =>
28 new Promise<string | undefined>((resolve) => {
29 let record: string | undefined;
30 let worker: NodeChildProcess.ChildProcess;
31 try {
32 worker = NodeChildProcess.fork(
33 // Main is bundled to dist-electron/main.cjs; the worker is a separate entry under it.
34 NodePath.join(__dirname, "backend", "DesktopBackendRecoveryWorker.cjs"),
35 [
36 operation,
37 input.appDataDirectory,
38 input.stateDir,
39 String(process.pid),
40 ...(options.backendPid === undefined ? [] : [String(options.backendPid)]),
41 ],
42 {
43 // The default macOS Helper executable would not match the backend's recorded executable.
44 execPath: process.execPath,
45 env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
46 execArgv: [],
47 stdio: ["ignore", "ignore", "inherit", "ipc"],
48 },
49 );
50 } catch {
51 input.onError("start recovery worker");
52 resolve(undefined);
53 return;
54 }
55 let settled = false;
56 const finish = () => {
57 if (settled) return;
58 settled = true;
59 clearTimeout(deadline);
60 options.signal?.removeEventListener("abort", stop);
61 resolve(record);
62 };
63 const stop = () => {
64 worker.kill("SIGKILL");
65 finish();
66 };
67 const deadline = setTimeout(() => {
68 input.onError(`${operation} deadline`);
69 stop();
70 }, deadlineMs);
71 deadline.unref();
72 if (options.signal?.aborted) stop();
73 else options.signal?.addEventListener("abort", stop, { once: true });
74 worker.on("message", (raw) => {
75 const message = raw as RecoveryWorkerMessage;
76 if (message.type === "recovering") input.onRecovery(message.pid);
77 else if (message.type === "error") input.onError(message.operation);
78 else record = message.record;
79 });
80 worker.once("error", () => {
81 input.onError("recovery worker");
82 stop();
83 });
84 worker.once("exit", finish);
85 });
86​
87 return {
88 track: async (backendPid: number) => {
89 const record = await run("track", trackDeadlineMs, { backendPid });
90 if (record === undefined) return undefined;
91 return () =>
92 NodeFSP.unlink(record).catch((error: NodeJS.ErrnoException) => {
93 if (error.code !== "ENOENT") input.onError("forget backend");
94 });
95 },
96 recover: (signal: AbortSignal) =>
97 run("recover", recoverDeadlineMs, { signal }).then(() => undefined),
98 };