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

launcherWatch.ts

45 lines2.0 KB

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 = (options?: {
25 readonly launcherPid?: number;
26 readonly getParentPid?: () => number;
27 readonly interval?: Duration.Input;
28}): Effect.Effect<void> =>
29 Effect.gen(function* () {
30 const platform = yield* HostProcess.Platform;
31 const launcherPid = options?.launcherPid ?? startupParentPid;
32 const getParentPid = options?.getParentPid ?? (() => process.ppid);
33 const interval = options?.interval ?? DEFAULT_POLL_INTERVAL;
34 if (platform === "win32" || launcherPid <= 1) return yield* Effect.never;
35 const poll: Effect.Effect<void> = Effect.suspend(() => {
36 const parentPid = getParentPid();
37 return parentPid === launcherPid
38 ? Effect.flatMap(Effect.sleep(interval), () => poll)
39 : Effect.logWarning("desktop launcher is gone; shutting down the backend", {
40 launcherPid,
41 parentPid,
42 });
43 });
44 return yield* poll;
45 });