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

DesktopLifecycle.ts

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