Open History to see the last commit
1import * as Duration from "effect/Duration";
2import * as Effect from "effect/Effect";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4
5const DEFAULT_POLL_INTERVAL = Duration.seconds(2);
6
7// Sampled when this module loads, before config resolution and the bootstrap
8// read, so a launcher that dies during startup is still noticed.
9const startupParentPid = process.ppid;
10
11/**
12 * Completes when the process that launched this backend is gone.
13 *
14 * A desktop-launched backend reads its bootstrap envelope once and never looks
15 * at its launcher again. When the launcher dies without a graceful stop (a WSL
16 * relay killed during an app update, for instance), the backend would keep
17 * serving and holding its ownership lock while no desktop can reach it, and
18 * every replacement launch is refused. An orphan is adopted by init or, on
19 * Linux, by a subreaper, so any change of parent counts rather than only a
20 * move to pid 1. A backend that already starts under init has no launcher to
21 * lose, and Windows keeps the original parent id after the parent exits, so
22 * neither is watched.
23 */
24export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(function* (options?: {
25 readonly launcherPid?: number;
26 readonly getParentPid?: () => number;
27 readonly interval?: Duration.Input;
28}): Effect.fn.Return<void> {
29 const platform = yield* HostProcess.Platform;
30 const launcherPid = options?.launcherPid ?? startupParentPid;
31 const getParentPid = options?.getParentPid ?? (() => process.ppid);
32 const interval = options?.interval ?? DEFAULT_POLL_INTERVAL;
33 if (platform === "win32" || launcherPid <= 1) return yield* Effect.never;
34 const poll: Effect.Effect<void> = Effect.suspend(() => {
35 const parentPid = getParentPid();
36 return parentPid === launcherPid
37 ? Effect.flatMap(Effect.sleep(interval), () => poll)
38 : Effect.logWarning("desktop launcher is gone; shutting down the backend", {
39 launcherPid,
40 parentPid,
41 });
42 });
43 return yield* poll;
44});