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

DesktopLifecycle.ts

346 lines13.1 KB

1import * as Clock from "effect/Clock";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Ref from "effect/Ref";
7import * as Schema from "effect/Schema";
8import * as Scope from "effect/Scope";
9​
10import type * as Electron from "electron";
11​
12import * as HostProcess from "@t3tools/shared/HostProcess";
13​
14import * as DesktopEnvironment from "./DesktopEnvironment.ts";
15import { stopChildProcessesBeforeExit } from "./DesktopExitChildren.ts";
16import { makeComponentLogger } from "./DesktopObservability.ts";
17import * as DesktopShutdown from "./DesktopShutdown.ts";
18import * as ElectronApp from "../electron/ElectronApp.ts";
19import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
20import * as ElectronTheme from "../electron/ElectronTheme.ts";
21import * as ElectronWindow from "../electron/ElectronWindow.ts";
22import * as DesktopState from "./DesktopState.ts";
23import * as DesktopWindow from "../window/DesktopWindow.ts";
24​
25export class DesktopLifecycleRelaunchError extends Schema.TaggedError<DesktopLifecycleRelaunchError>()(
26 "DesktopLifecycleRelaunchError",
27 {
28 reason: Schema.String,
29 cause: Schema.Defect(),
30 },
31) {
32 override get message(): string {
33 return `Desktop relaunch failed for reason "${this.reason}".`;
34 }
36​
37export type DesktopLifecycleRuntimeServices =
38 | DesktopEnvironment.DesktopEnvironment
39 | DesktopShutdown.DesktopShutdown
40 | DesktopState.DesktopState
41 | DesktopWindow.DesktopWindow
42 | ElectronApp.ElectronApp
43 | ElectronTheme.ElectronTheme;
44​
45type DesktopLifecycleRegistrationServices =
46 | DesktopLifecycleRuntimeServices
47 | ElectronWindow.ElectronWindow;
48​
49/**
50 * @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme | ElectronWindow
51 */
52export class DesktopLifecycle extends Context.Service<
53 DesktopLifecycle,
54 {
55 readonly relaunch: (
56 reason: string,
57 ) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>;
58 readonly register: Effect.Effect<
59 void,
60 never,
61 Scope.Scope | DesktopLifecycleRegistrationServices
62 >;
63 }
64>()("@t3tools/desktop/app/DesktopLifecycle") {}
65​
66const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
67 makeComponentLogger("desktop-lifecycle");
68​
69function addScopedListener<Args extends ReadonlyArray<unknown>>(
70 target: unknown,
71 eventName: string,
72 listener: (...args: Args) => void,
73 options: { readonly prepend?: boolean } = {},
74): Effect.Effect<void, never, Scope.Scope> {
75 const eventTarget = target as {
76 on: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
77 prependListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
78 removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
79 };
80 const untypedListener = listener as unknown as (...args: Array<unknown>) => void;
81 return Effect.acquireRelease(
82 Effect.sync(() => {
83 if (options.prepend) eventTarget.prependListener(eventName, untypedListener);
84 else eventTarget.on(eventName, untypedListener);
85 }),
86 () =>
87 Effect.sync(() => {
88 eventTarget.removeListener(eventName, untypedListener);
89 }),
90 ).pipe(Effect.asVoid);
92​
93const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")(
94 function* (
95 afterBoundsFlush: Effect.Effect<void> = Effect.void,
96 ): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow> {
97 const shutdown = yield* DesktopShutdown.DesktopShutdown;
98 const desktopWindow = yield* DesktopWindow.DesktopWindow;
99 yield* desktopWindow.flushMainWindowBounds;
100 yield* afterBoundsFlush;
101 yield* shutdown.request;
102 yield* shutdown.awaitComplete;
103 },
104);
105​
106interface QuitState {
107 phase: "running" | "waiting" | "allowed";
108 waitingSinceNanos: bigint;
110​
111// Longer than a backend's stop budget (SIGTERM, 5s grace, SIGKILL, 1s wait),
112// so a double Cmd-Q at the start of a normal quit cannot cut the backend stop
113// short and orphan it.
114const SHUTDOWN_STALL_THRESHOLD = Duration.seconds(10);
115​
116const startWaitingForShutdown = Effect.fn("desktop.lifecycle.startWaitingForShutdown")(function* (
117 quit: QuitState,
118) {
119 quit.phase = "waiting";
120 quit.waitingSinceNanos = yield* Clock.monotonicTimeNanos;
121});
122​
123// While a quit waits on shutdown, `quitting` makes activation open nothing. If
124// that shutdown stalls, a repeated Quit or SIGTERM is the user's only way out
125// short of SIGKILL.
126const exitIfShutdownStalled = Effect.fn("desktop.lifecycle.exitIfShutdownStalled")(function* (
127 quit: QuitState,
128 source: string,
129) {
130 const pendingMs = Number(
131 ((yield* Clock.monotonicTimeNanos) - quit.waitingSinceNanos) / 1_000_000n,
132 );
133 if (pendingMs < Duration.toMillis(SHUTDOWN_STALL_THRESHOLD)) {
134 yield* logLifecycleInfo("quit already in progress", { source, pendingMs });
135 return;
136 }
137 yield* logLifecycleError("desktop shutdown stalled; exiting without it", { source, pendingMs });
138 const electronApp = yield* ElectronApp.ElectronApp;
139 yield* electronApp.exit(0);
140});
141​
142function handleBeforeQuit(
143 event: Electron.Event,
144 runEffect: <A, E>(
145 effect: Effect.Effect<A, E, DesktopLifecycleRegistrationServices>,
146 ) => Promise<A>,
147 quit: QuitState,
148): void {
149 if (quit.phase === "allowed") {
150 void runEffect(
151 Effect.gen(function* () {
152 const state = yield* DesktopState.DesktopState;
153 yield* Ref.set(state.quitting, true);
154 yield* logLifecycleInfo("before-quit received");
155 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
156 );
157 return;
158 }
159​
160 event.preventDefault();
161 if (quit.phase === "waiting") {
162 void runEffect(exitIfShutdownStalled(quit, "before-quit"));
163 return;
164 }
165 void runEffect(
166 Effect.gen(function* () {
167 const state = yield* DesktopState.DesktopState;
168 const electronWindow = yield* ElectronWindow.ElectronWindow;
169 yield* startWaitingForShutdown(quit);
170 yield* Ref.set(state.quitting, true);
171 yield* logLifecycleInfo("before-quit received");
172 yield* requestDesktopShutdownAndWait(
173 electronWindow.destroyAll.pipe(
174 Effect.catchCause((cause) =>
175 logLifecycleError("failed to destroy windows before shutdown", { cause }),
176 ),
177 ),
178 );
179 }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")),
180 ).finally(() => {
181 quit.phase = "allowed";
182 void runEffect(
183 Effect.gen(function* () {
184 const electronApp = yield* ElectronApp.ElectronApp;
185 yield* electronApp.quit;
186 }).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")),
187 );
188 });
190​
191function quitFromSignal(
192 signal: "SIGINT" | "SIGTERM",
193 runEffect: <A, E>(
194 effect: Effect.Effect<A, E, DesktopLifecycleRegistrationServices>,
195 ) => Promise<A>,
196 quit: QuitState,
197): void {
198 if (quit.phase === "waiting") {
199 void runEffect(exitIfShutdownStalled(quit, signal));
200 return;
201 }
202 void runEffect(
203 Effect.gen(function* () {
204 yield* Effect.annotateCurrentSpan({ signal });
205 const electronApp = yield* ElectronApp.ElectronApp;
206 const state = yield* DesktopState.DesktopState;
207 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
208 if (wasQuitting) return;
209 yield* startWaitingForShutdown(quit);
210 yield* logLifecycleInfo("process signal received", { signal });
211 yield* requestDesktopShutdownAndWait();
212 quit.phase = "allowed";
213 yield* electronApp.quit;
214 }).pipe(Effect.withSpan("desktop.lifecycle.processSignal")),
215 );
217​
218/** @public */
219export const make = DesktopLifecycle.of({
220 relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
221 const electronApp = yield* ElectronApp.ElectronApp;
222 const environment = yield* DesktopEnvironment.DesktopEnvironment;
223 const state = yield* DesktopState.DesktopState;
224 yield* logLifecycleInfo("desktop relaunch requested", { reason });
225 yield* Effect.gen(function* () {
226 yield* Effect.yieldNow;
227 yield* Ref.set(state.quitting, true);
228 yield* requestDesktopShutdownAndWait();
229 if (environment.isDevelopment) {
230 yield* electronApp.exit(75);
231 return;
232 }
233 // Startup already acted on the app link that launched it; passing it on replays it.
234 const appLinkPrefix = `${ElectronProtocol.getDesktopScheme(environment.isDevelopment)}:`;
235 const args = yield* HostProcess.Arguments;
236 yield* electronApp.relaunch({
237 execPath: yield* HostProcess.ExecutablePath,
238 args: args.slice(1).filter((arg) => !arg.toLowerCase().startsWith(appLinkPrefix)),
239 });
240 yield* electronApp.exit(0);
241 }).pipe(
242 Effect.catchCause((cause) => {
243 const error = new DesktopLifecycleRelaunchError({ reason, cause });
244 return logLifecycleError(error.message, { error });
245 }),
246 Effect.forkDetach,
247 Effect.asVoid,
248 );
249 }),
250 register: Effect.gen(function* () {
251 const desktopWindow = yield* DesktopWindow.DesktopWindow;
252 const electronWindow = yield* ElectronWindow.ElectronWindow;
253 const electronApp = yield* ElectronApp.ElectronApp;
254 const electronTheme = yield* ElectronTheme.ElectronTheme;
255 const environment = yield* DesktopEnvironment.DesktopEnvironment;
256 const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();
257 const runEffect = Effect.runPromiseWith(context);
258 const quit: QuitState = { phase: "running", waitingSinceNanos: 0n };
259 yield* electronTheme.onUpdated(() => {
260 void runEffect(
261 desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
262 );
263 });
264 yield* electronApp.onBeforeQuitForUpdate(() => {
265 // Electron's updater owns the remaining quit/install/relaunch sequence.
266 // Cancelling the following app "before-quit" event breaks that sequence,
267 // most visibly on macOS where the native updater performs the relaunch.
268 quit.phase = "allowed";
269 // This event is synchronous and the updater's quit proceeds as soon as
270 // the listener returns, so a forked destroyAll would race the quit
271 // and windows could still be open when the process exits (visible on
272 // macOS). Destroy them inline.
273 Effect.runSyncWith(context)(
274 electronWindow.destroyAll.pipe(
275 Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),
276 Effect.catchCause((cause) =>
277 logLifecycleError("failed to destroy windows before updater quit", { cause }),
278 ),
279 Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
280 ),
281 );
282 });
283 yield* electronApp.on("before-quit", (event: Electron.Event) => {
284 handleBeforeQuit(event, runEffect, quit);
285 });
286 yield* electronApp.on("activate", () => {
287 void runEffect(
288 Effect.gen(function* () {
289 const state = yield* DesktopState.DesktopState;
290 if (yield* Ref.get(state.quitting)) return;
291 yield* desktopWindow.activate;
292 }).pipe(Effect.withSpan("desktop.lifecycle.activate")),
293 );
294 });
295 yield* electronApp.on("window-all-closed", () => {
296 void runEffect(
297 Effect.gen(function* () {
298 const app = yield* ElectronApp.ElectronApp;
299 const state = yield* DesktopState.DesktopState;
300 if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
301 yield* app.quit;
302 }
303 }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
304 );
305 });
306​
307 // Electron can exit without before-quit, e.g. when the X11/Wayland connection drops.
308 // Children (the backend too) get SIGTERM while main still holds an AppImage mount open.
309 // Prepended so the record is buffered before the trace sink's own exit flush runs.
310 yield* addScopedListener(
311 process,
312 "exit",
313 (exitCode: number) => {
314 Effect.runSyncWith(context)(
315 Effect.gen(function* () {
316 const shutdown = yield* DesktopShutdown.DesktopShutdown;
317 // "allowed" without a finished shutdown is the updater's quit; its relaunched app is a child.
318 if (quit.phase === "allowed" || (yield* shutdown.isComplete)) return;
319 const attributes = { exitCode, quitPhase: quit.phase };
320 yield* Effect.gen(function* () {
321 yield* logLifecycleError(
322 "desktop main process exiting before shutdown completed",
323 attributes,
324 );
325 if (environment.platform !== "linux") return;
326 const killed = stopChildProcessesBeforeExit(process.pid);
327 yield* Effect.annotateCurrentSpan({ killedChildPids: killed });
328 }).pipe(Effect.withSpan("desktop.lifecycle.exit", { attributes }));
329 }),
330 );
331 },
332 { prepend: true },
333 );
334​
335 if (environment.platform !== "win32") {
336 yield* addScopedListener(process, "SIGINT", () => {
337 quitFromSignal("SIGINT", runEffect, quit);
338 });
339 yield* addScopedListener(process, "SIGTERM", () => {
340 quitFromSignal("SIGTERM", runEffect, quit);
341 });
342 }
343 }).pipe(Effect.withSpan("desktop.lifecycle.register")),
344});
345​
346export const layer = Layer.succeed(DesktopLifecycle, make);