Skip to content

Commit 4de822c

Browse files
fix(desktop): let lifecycle shutdown finish before exiting (#20303)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 888a6a0 commit 4de822c

8 files changed

Lines changed: 253 additions & 125 deletions

File tree

‎apps/desktop/src/app/DesktopApp.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,8 @@ export const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances"
153153
const instances = yield* pool.list;
154154
yield* Effect.forEach(
155155
instances,
156-
(instance) => instance.stop({ timeout: Duration.seconds(5) }),
156+
// Exceeds the backend's 30s graceful termination and output drain budget.
157+
(instance) => instance.stop({ timeout: Duration.seconds(45) }),
157158
{ concurrency: "unbounded" },
158159
);
159160
},

‎apps/desktop/src/app/DesktopLifecycle.test.ts‎

Lines changed: 110 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
1+
// @effect-diagnostics-next-line nodeBuiltinImport:off - A real Node process verifies OS signal ownership outside Effect's process runtime.
2+
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeReadline from "node:readline";
4+
import * as NodeURL from "node:url";
5+
16
import { assert, describe, it } from "@effect/vitest";
7+
import * as HostProcess from "@t3tools/shared/HostProcess";
28
import * as Deferred from "effect/Deferred";
39
import * as Effect from "effect/Effect";
10+
import * as Fiber from "effect/Fiber";
411
import * as Layer from "effect/Layer";
512
import * as Ref from "effect/Ref";
613

@@ -103,6 +110,67 @@ function layerDesktopWindow(
103110
}
104111

105112
describe("DesktopLifecycle", () => {
113+
it.skipIf(HostProcess.Platform.defaultValue() === "win32")(
114+
"leaves SIGTERM to the lifecycle until its graceful shutdown completes",
115+
async ({ onTestFinished }) => {
116+
const runner = new URL("./DesktopRuntime.ts", import.meta.url).href;
117+
const child = NodeChildProcess.spawn(
118+
process.execPath,
119+
[
120+
"--experimental-strip-types",
121+
"--input-type=module",
122+
"-e",
123+
`
124+
import * as Effect from 'effect/Effect';
125+
import * as Deferred from 'effect/Deferred';
126+
import { runMain } from ${JSON.stringify(runner)};
127+
process.stdin.resume();
128+
let released = false;
129+
runMain(Effect.scoped(Effect.gen(function* () {
130+
const done = yield* Deferred.make();
131+
yield* Effect.addFinalizer(() => Effect.sync(() => console.log(released ? 'CLEANED' : 'PREMATURE')));
132+
process.once('SIGTERM', () => {
133+
console.log('STOPPING');
134+
process.stdin.once('data', () => {
135+
released = true;
136+
void Effect.runPromise(Deferred.succeed(done, undefined)).then(() => process.stdin.destroy());
137+
});
138+
});
139+
console.log('READY');
140+
yield* Deferred.await(done);
141+
})));
142+
`,
143+
],
144+
{
145+
cwd: NodeURL.fileURLToPath(new URL("../../", import.meta.url)),
146+
stdio: ["pipe", "pipe", "pipe"],
147+
},
148+
);
149+
const exited = new Promise<readonly [number | null, string | null]>((resolve, reject) => {
150+
child.once("exit", (code, signal) => resolve([code, signal]));
151+
child.once("error", reject);
152+
});
153+
const lines: string[] = [];
154+
let stderr = "";
155+
child.stderr.on("data", (chunk) => {
156+
stderr += chunk;
157+
});
158+
onTestFinished(async () => {
159+
if (child.exitCode === null && child.signalCode === null) {
160+
child.kill("SIGKILL");
161+
await exited;
162+
}
163+
});
164+
for await (const line of NodeReadline.createInterface({ input: child.stdout })) {
165+
lines.push(line);
166+
if (line === "READY") child.kill("SIGTERM");
167+
if (line === "STOPPING") child.stdin.write("finish");
168+
}
169+
assert.deepEqual(await exited, [0, null], stderr);
170+
assert.deepEqual(lines, ["READY", "STOPPING", "CLEANED"]);
171+
},
172+
);
173+
106174
it.effect.each(["darwin", "win32", "linux"] satisfies ReadonlyArray<NodeJS.Platform>)(
107175
"lets the updater's quit event proceed on %s",
108176
(platform) => {
@@ -158,12 +226,18 @@ describe("DesktopLifecycle", () => {
158226
},
159227
);
160228

161-
it.effect("destroys windows before waiting for backend shutdown", () =>
229+
it.effect("destroys windows and retains signal ownership until backend shutdown completes", () =>
162230
Effect.gen(function* () {
163231
const appListeners = new Map<string, (...args: readonly unknown[]) => void>();
164232
const shutdownRequested = yield* Deferred.make<void>();
165233
const allowShutdown = yield* Deferred.make<void>();
166234
const quitRequested = yield* Deferred.make<void>();
235+
const backendStopping = yield* Deferred.make<void>();
236+
const finishBackendShutdown = yield* Deferred.make<void>();
237+
const originalSignals = {
238+
SIGINT: process.listeners("SIGINT"),
239+
SIGTERM: process.listeners("SIGTERM"),
240+
};
167241
const events: string[] = [];
168242

169243
const quit = Effect.sync(() => {
@@ -204,20 +278,47 @@ describe("DesktopLifecycle", () => {
204278
yield* Effect.scoped(
205279
Effect.gen(function* () {
206280
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
207-
yield* lifecycle.register;
281+
const shutdown = yield* DesktopShutdown.DesktopShutdown;
282+
const program = yield* Effect.scoped(
283+
Effect.gen(function* () {
284+
yield* Effect.addFinalizer(() =>
285+
Deferred.succeed(backendStopping, undefined).pipe(
286+
Effect.andThen(Deferred.await(finishBackendShutdown)),
287+
Effect.andThen(shutdown.markComplete),
288+
),
289+
);
290+
yield* lifecycle.register;
291+
const event = { preventDefault: () => undefined } as Electron.Event;
292+
appListeners.get("before-quit")?.(event);
293+
yield* shutdown.awaitRequest;
294+
}),
295+
).pipe(Effect.forkScoped);
208296

209-
const event = { preventDefault: () => undefined } as Electron.Event;
210-
appListeners.get("before-quit")?.(event);
297+
yield* Deferred.await(backendStopping);
298+
yield* Effect.addFinalizer(() =>
299+
Deferred.succeed(finishBackendShutdown, undefined).pipe(Effect.asVoid),
300+
);
211301

212-
yield* Deferred.await(shutdownRequested);
213-
const eventsBeforeCleanup = [...events];
214-
yield* Deferred.succeed(allowShutdown, undefined);
215-
yield* Deferred.await(quitRequested);
302+
for (const signal of ["SIGINT", "SIGTERM"] as const) {
303+
const listeners = process
304+
.listeners(signal)
305+
.filter((listener) => !originalSignals[signal].includes(listener));
306+
assert.lengthOf(listeners, 1, `${signal} must remain owned during backend cleanup`);
307+
listeners[0]?.(signal);
308+
}
309+
assert.deepEqual(events, ["flush", "destroy", "request"]);
310+
assert.equal(appListeners.size, 0, "Electron listeners still follow the program scope");
311+
assert.isFalse(yield* shutdown.isComplete);
216312

217-
assert.deepEqual(eventsBeforeCleanup, ["flush", "destroy", "request"]);
313+
yield* Deferred.succeed(finishBackendShutdown, undefined);
314+
yield* Fiber.join(program);
315+
yield* Deferred.await(quitRequested);
218316
assert.deepEqual(events, ["flush", "destroy", "request", "quit"]);
219317
}),
220318
).pipe(Effect.provide(layer));
319+
320+
assert.deepEqual(process.listeners("SIGINT"), originalSignals.SIGINT);
321+
assert.deepEqual(process.listeners("SIGTERM"), originalSignals.SIGTERM);
221322
}),
222323
);
223324

‎apps/desktop/src/app/DesktopLifecycle.ts‎

Lines changed: 104 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -160,108 +160,113 @@ function quitFromSignal(
160160
}
161161

162162
/** @public Service construction is part of the canonical Effect module API. */
163-
export const make = DesktopLifecycle.of({
164-
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
165-
const electronApp = yield* ElectronApp.ElectronApp;
166-
const environment = yield* DesktopEnvironment.DesktopEnvironment;
167-
const state = yield* DesktopState.DesktopState;
168-
yield* logLifecycleInfo("desktop relaunch requested", { reason });
169-
yield* Effect.gen(function* () {
170-
yield* Effect.yieldNow;
171-
yield* Ref.set(state.quitting, true);
172-
yield* requestDesktopShutdownAndWait();
173-
if (environment.isDevelopment) {
174-
yield* electronApp.exit(75);
175-
return;
176-
}
177-
yield* electronApp.relaunch({
178-
execPath: process.execPath,
179-
args: process.argv.slice(1),
180-
});
181-
yield* electronApp.exit(0);
182-
}).pipe(
183-
Effect.catchCause((cause) => {
184-
const error = new DesktopLifecycleRelaunchError({ reason, cause });
185-
return logLifecycleError(error.message, { error });
186-
}),
187-
Effect.forkDetach,
188-
Effect.asVoid,
189-
);
190-
}),
191-
register: Effect.gen(function* () {
192-
const desktopWindow = yield* DesktopWindow.DesktopWindow;
193-
const electronWindow = yield* ElectronWindow.ElectronWindow;
194-
const electronApp = yield* ElectronApp.ElectronApp;
195-
const electronTheme = yield* ElectronTheme.ElectronTheme;
196-
const environment = yield* DesktopEnvironment.DesktopEnvironment;
197-
const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();
198-
const runEffect = Effect.runPromiseWith(context);
199-
let quitAllowed = false;
200-
let updaterQuitAllowed = false;
201-
yield* electronTheme.onUpdated(() => {
202-
void runEffect(
203-
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
163+
export const make = Effect.gen(function* () {
164+
const signalScope = yield* Scope.Scope;
165+
return DesktopLifecycle.of({
166+
relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
167+
const electronApp = yield* ElectronApp.ElectronApp;
168+
const environment = yield* DesktopEnvironment.DesktopEnvironment;
169+
const state = yield* DesktopState.DesktopState;
170+
yield* logLifecycleInfo("desktop relaunch requested", { reason });
171+
yield* Effect.gen(function* () {
172+
yield* Effect.yieldNow;
173+
yield* Ref.set(state.quitting, true);
174+
yield* requestDesktopShutdownAndWait();
175+
if (environment.isDevelopment) {
176+
yield* electronApp.exit(75);
177+
return;
178+
}
179+
yield* electronApp.relaunch({
180+
execPath: process.execPath,
181+
args: process.argv.slice(1),
182+
});
183+
yield* electronApp.exit(0);
184+
}).pipe(
185+
Effect.catchCause((cause) => {
186+
const error = new DesktopLifecycleRelaunchError({ reason, cause });
187+
return logLifecycleError(error.message, { error });
188+
}),
189+
Effect.forkDetach,
190+
Effect.asVoid,
204191
);
205-
});
206-
yield* electronApp.onBeforeQuitForUpdate(() => {
207-
// Electron's updater owns the remaining quit/install/relaunch sequence.
208-
// Cancelling the following app "before-quit" event breaks that sequence,
209-
// most visibly on macOS where the native updater performs the relaunch.
210-
updaterQuitAllowed = true;
211-
// This event is synchronous and the updater's quit proceeds as soon as
212-
// the listener returns, so a forked destroyAll would race the quit
213-
// and windows could still be open when the process exits (visible on
214-
// macOS). Destroy them inline.
215-
Effect.runSyncWith(context)(
216-
electronWindow.destroyAll.pipe(
217-
Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),
218-
Effect.catchCause((cause) =>
219-
logLifecycleError("failed to destroy windows before updater quit", { cause }),
192+
}),
193+
register: Effect.gen(function* () {
194+
const desktopWindow = yield* DesktopWindow.DesktopWindow;
195+
const electronWindow = yield* ElectronWindow.ElectronWindow;
196+
const electronApp = yield* ElectronApp.ElectronApp;
197+
const electronTheme = yield* ElectronTheme.ElectronTheme;
198+
const environment = yield* DesktopEnvironment.DesktopEnvironment;
199+
const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();
200+
const runEffect = Effect.runPromiseWith(context);
201+
let quitAllowed = false;
202+
let updaterQuitAllowed = false;
203+
yield* electronTheme.onUpdated(() => {
204+
void runEffect(
205+
desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
206+
);
207+
});
208+
yield* electronApp.onBeforeQuitForUpdate(() => {
209+
// Electron's updater owns the remaining quit/install/relaunch sequence.
210+
// Cancelling the following app "before-quit" event breaks that sequence,
211+
// most visibly on macOS where the native updater performs the relaunch.
212+
updaterQuitAllowed = true;
213+
// This event is synchronous and the updater's quit proceeds as soon as
214+
// the listener returns, so a forked destroyAll would race the quit
215+
// and windows could still be open when the process exits (visible on
216+
// macOS). Destroy them inline.
217+
Effect.runSyncWith(context)(
218+
electronWindow.destroyAll.pipe(
219+
Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),
220+
Effect.catchCause((cause) =>
221+
logLifecycleError("failed to destroy windows before updater quit", { cause }),
222+
),
223+
Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
220224
),
221-
Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
222-
),
223-
);
224-
});
225-
yield* electronApp.on("before-quit", (event: Electron.Event) => {
226-
handleBeforeQuit(
227-
event,
228-
runEffect,
229-
() => quitAllowed || updaterQuitAllowed,
230-
() => {
231-
quitAllowed = true;
232-
},
233-
);
234-
});
235-
yield* electronApp.on("activate", () => {
236-
void runEffect(
237-
Effect.gen(function* () {
238-
const state = yield* DesktopState.DesktopState;
239-
if (yield* Ref.get(state.quitting)) return;
240-
yield* desktopWindow.activate;
241-
}).pipe(Effect.withSpan("desktop.lifecycle.activate")),
242-
);
243-
});
244-
yield* electronApp.on("window-all-closed", () => {
245-
void runEffect(
246-
Effect.gen(function* () {
247-
const app = yield* ElectronApp.ElectronApp;
248-
const state = yield* DesktopState.DesktopState;
249-
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
250-
yield* app.quit;
251-
}
252-
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
253-
);
254-
});
255-
256-
if (environment.platform !== "win32") {
257-
yield* addScopedListener(process, "SIGINT", () => {
258-
quitFromSignal("SIGINT", runEffect);
225+
);
226+
});
227+
yield* electronApp.on("before-quit", (event: Electron.Event) => {
228+
handleBeforeQuit(
229+
event,
230+
runEffect,
231+
() => quitAllowed || updaterQuitAllowed,
232+
() => {
233+
quitAllowed = true;
234+
},
235+
);
236+
});
237+
yield* electronApp.on("activate", () => {
238+
void runEffect(
239+
Effect.gen(function* () {
240+
const state = yield* DesktopState.DesktopState;
241+
if (yield* Ref.get(state.quitting)) return;
242+
yield* desktopWindow.activate;
243+
}).pipe(Effect.withSpan("desktop.lifecycle.activate")),
244+
);
259245
});
260-
yield* addScopedListener(process, "SIGTERM", () => {
261-
quitFromSignal("SIGTERM", runEffect);
246+
yield* electronApp.on("window-all-closed", () => {
247+
void runEffect(
248+
Effect.gen(function* () {
249+
const app = yield* ElectronApp.ElectronApp;
250+
const state = yield* DesktopState.DesktopState;
251+
if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
252+
yield* app.quit;
253+
}
254+
}).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
255+
);
262256
});
263-
}
264-
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
257+
258+
if (environment.platform !== "win32") {
259+
// The layer outlives program finalizers, so repeated signals stay owned
260+
// while backends stop. Electron listeners still follow the program scope.
261+
yield* addScopedListener(process, "SIGINT", () => {
262+
quitFromSignal("SIGINT", runEffect);
263+
}).pipe(Scope.provide(signalScope));
264+
yield* addScopedListener(process, "SIGTERM", () => {
265+
quitFromSignal("SIGTERM", runEffect);
266+
}).pipe(Scope.provide(signalScope));
267+
}
268+
}).pipe(Effect.withSpan("desktop.lifecycle.register")),
269+
});
265270
});
266271

267-
export const layer = Layer.succeed(DesktopLifecycle, make);
272+
export const layer = Layer.effect(DesktopLifecycle, make);
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import * as Runtime from "effect/Runtime";
2+
3+
// DesktopLifecycle owns signals and waits for backend shutdown before quitting
4+
// Electron. NodeRuntime's competing signal handler interrupts that sequence.
5+
export const runMain = Runtime.makeRunMain(({ fiber, teardown }) => {
6+
fiber.addObserver((exit) => {
7+
teardown(exit, (code) => {
8+
if (code !== 0) process.exit(code);
9+
});
10+
});
11+
});

0 commit comments

Comments
 (0)