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// The desktop's SIGTERM grace before it escalates to SIGKILL; a lost launcher cannot escalate.
7const DEFAULT_SHUTDOWN_GRACE = Duration.seconds(5);
8
9// Capture before config and bootstrap reads to detect launcher loss during startup.
10const startupParentPid = process.ppid;
11
12interface LauncherWatchOptions {
13 readonly launcherPid?: number;
14 readonly getParentPid?: () => number;
15 readonly interval?: Duration.Input;
16}
17
18/**
19 * Any parent change signals launcher loss, including adoption by a Linux subreaper;
20 * otherwise an orphan backend keeps its ownership lock and blocks replacement launches.
21 * Skip init-launched backends and Windows, which retains the exited parent's id.
22 */
23export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(function* (
24 options?: LauncherWatchOptions,
25): Effect.fn.Return<void> {
26 const platform = yield* HostProcess.Platform;
27 const launcherPid = options?.launcherPid ?? startupParentPid;
28 const getParentPid = options?.getParentPid ?? (() => process.ppid);
29 const interval = options?.interval ?? DEFAULT_POLL_INTERVAL;
30 if (platform === "win32" || launcherPid <= 1) return yield* Effect.never;
31 const poll: Effect.Effect<void> = Effect.suspend(() => {
32 const parentPid = getParentPid();
33 return parentPid === launcherPid
34 ? Effect.flatMap(Effect.sleep(interval), () => poll)
35 : Effect.logWarning("desktop launcher is gone; shutting down the backend", {
36 launcherPid,
37 parentPid,
38 });
39 });
40 return yield* poll;
41});
42
43/**
44 * Interrupts `run` when the launcher is lost, and exits the process if shutdown outlasts the
45 * grace period: a stuck cleanup step would otherwise keep holding the T3 home's ownership lock.
46 */
47export const stopOnLauncherLoss = <A, E, R>(
48 run: Effect.Effect<A, E, R>,
49 options?: LauncherWatchOptions & {
50 readonly shutdownGrace?: Duration.Input;
51 readonly exit?: () => void;
52 },
53) =>
54 Effect.raceFirst(
55 run,
56 awaitLauncherLoss(options).pipe(
57 Effect.andThen(
58 Effect.forkDetach(
59 Effect.sleep(options?.shutdownGrace ?? DEFAULT_SHUTDOWN_GRACE).pipe(
60 Effect.andThen(Effect.logWarning("backend shutdown timed out after launcher loss")),
61 Effect.andThen(Effect.sync(options?.exit ?? (() => process.exit(1)))),
62 ),
63 ),
64 ),
65 // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit).
66 Effect.andThen(Effect.interrupt),
67 ),
68 );