TypeScript
fix(desktop): let lifecycle shutdown finish before exiting (#20303)
ObliviousObserver4de822c85e98
diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.tsindex 03e2f635f9f..7f5bdb80817 100644--- a/apps/desktop/src/app/DesktopApp.ts+++ b/apps/desktop/src/app/DesktopApp.ts@@ -153,7 +153,8 @@ export const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances"const instances = yield* pool.list;yield* Effect.forEach(instances,- (instance) => instance.stop({ timeout: Duration.seconds(5) }),+ // Exceeds the backend's 30s graceful termination and output drain budget.+ (instance) => instance.stop({ timeout: Duration.seconds(45) }),{ concurrency: "unbounded" },);},diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.tsindex f9f38dea3dd..43fb27cac6c 100644--- a/apps/desktop/src/app/DesktopLifecycle.test.ts+++ b/apps/desktop/src/app/DesktopLifecycle.test.ts@@ -1,6 +1,13 @@+// @effect-diagnostics-next-line nodeBuiltinImport:off - A real Node process verifies OS signal ownership outside Effect's process runtime.+import * as NodeChildProcess from "node:child_process";+import * as NodeReadline from "node:readline";+import * as NodeURL from "node:url";+import { assert, describe, it } from "@effect/vitest";+import * as HostProcess from "@t3tools/shared/HostProcess";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Ref from "effect/Ref";@@ -103,6 +110,67 @@ function layerDesktopWindow(}describe("DesktopLifecycle", () => {+ it.skipIf(HostProcess.Platform.defaultValue() === "win32")(+ "leaves SIGTERM to the lifecycle until its graceful shutdown completes",+ async ({ onTestFinished }) => {+ const runner = new URL("./DesktopRuntime.ts", import.meta.url).href;+ const child = NodeChildProcess.spawn(+ process.execPath,+ [+ "--experimental-strip-types",+ "--input-type=module",+ "-e",+ `+ import * as Effect from 'effect/Effect';+ import * as Deferred from 'effect/Deferred';+ import { runMain } from ${JSON.stringify(runner)};+ process.stdin.resume();+ let released = false;+ runMain(Effect.scoped(Effect.gen(function* () {+ const done = yield* Deferred.make();+ yield* Effect.addFinalizer(() => Effect.sync(() => console.log(released ? 'CLEANED' : 'PREMATURE')));+ process.once('SIGTERM', () => {+ console.log('STOPPING');+ process.stdin.once('data', () => {+ released = true;+ void Effect.runPromise(Deferred.succeed(done, undefined)).then(() => process.stdin.destroy());+ });+ });+ console.log('READY');+ yield* Deferred.await(done);+ })));+ `,+ ],+ {+ cwd: NodeURL.fileURLToPath(new URL("../../", import.meta.url)),+ stdio: ["pipe", "pipe", "pipe"],+ },+ );+ const exited = new Promise<readonly [number | null, string | null]>((resolve, reject) => {+ child.once("exit", (code, signal) => resolve([code, signal]));+ child.once("error", reject);+ });+ const lines: string[] = [];+ let stderr = "";+ child.stderr.on("data", (chunk) => {+ stderr += chunk;+ });+ onTestFinished(async () => {+ if (child.exitCode === null && child.signalCode === null) {+ child.kill("SIGKILL");+ await exited;+ }+ });+ for await (const line of NodeReadline.createInterface({ input: child.stdout })) {+ lines.push(line);+ if (line === "READY") child.kill("SIGTERM");+ if (line === "STOPPING") child.stdin.write("finish");+ }+ assert.deepEqual(await exited, [0, null], stderr);+ assert.deepEqual(lines, ["READY", "STOPPING", "CLEANED"]);+ },+ );+it.effect.each(["darwin", "win32", "linux"] satisfies ReadonlyArray<NodeJS.Platform>)("lets the updater's quit event proceed on %s",(platform) => {@@ -158,12 +226,18 @@ describe("DesktopLifecycle", () => {},);- it.effect("destroys windows before waiting for backend shutdown", () =>+ it.effect("destroys windows and retains signal ownership until backend shutdown completes", () =>Effect.gen(function* () {const appListeners = new Map<string, (...args: readonly unknown[]) => void>();const shutdownRequested = yield* Deferred.make<void>();const allowShutdown = yield* Deferred.make<void>();const quitRequested = yield* Deferred.make<void>();+ const backendStopping = yield* Deferred.make<void>();+ const finishBackendShutdown = yield* Deferred.make<void>();+ const originalSignals = {+ SIGINT: process.listeners("SIGINT"),+ SIGTERM: process.listeners("SIGTERM"),+ };const events: string[] = [];const quit = Effect.sync(() => {@@ -204,20 +278,47 @@ describe("DesktopLifecycle", () => {yield* Effect.scoped(Effect.gen(function* () {const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;- yield* lifecycle.register;+ const shutdown = yield* DesktopShutdown.DesktopShutdown;+ const program = yield* Effect.scoped(+ Effect.gen(function* () {+ yield* Effect.addFinalizer(() =>+ Deferred.succeed(backendStopping, undefined).pipe(+ Effect.andThen(Deferred.await(finishBackendShutdown)),+ Effect.andThen(shutdown.markComplete),+ ),+ );+ yield* lifecycle.register;+ const event = { preventDefault: () => undefined } as Electron.Event;+ appListeners.get("before-quit")?.(event);+ yield* shutdown.awaitRequest;+ }),+ ).pipe(Effect.forkScoped);- const event = { preventDefault: () => undefined } as Electron.Event;- appListeners.get("before-quit")?.(event);+ yield* Deferred.await(backendStopping);+ yield* Effect.addFinalizer(() =>+ Deferred.succeed(finishBackendShutdown, undefined).pipe(Effect.asVoid),+ );- yield* Deferred.await(shutdownRequested);- const eventsBeforeCleanup = [...events];- yield* Deferred.succeed(allowShutdown, undefined);- yield* Deferred.await(quitRequested);+ for (const signal of ["SIGINT", "SIGTERM"] as const) {+ const listeners = process+ .listeners(signal)+ .filter((listener) => !originalSignals[signal].includes(listener));+ assert.lengthOf(listeners, 1, `${signal} must remain owned during backend cleanup`);+ listeners[0]?.(signal);+ }+ assert.deepEqual(events, ["flush", "destroy", "request"]);+ assert.equal(appListeners.size, 0, "Electron listeners still follow the program scope");+ assert.isFalse(yield* shutdown.isComplete);- assert.deepEqual(eventsBeforeCleanup, ["flush", "destroy", "request"]);+ yield* Deferred.succeed(finishBackendShutdown, undefined);+ yield* Fiber.join(program);+ yield* Deferred.await(quitRequested);assert.deepEqual(events, ["flush", "destroy", "request", "quit"]);}),).pipe(Effect.provide(layer));++ assert.deepEqual(process.listeners("SIGINT"), originalSignals.SIGINT);+ assert.deepEqual(process.listeners("SIGTERM"), originalSignals.SIGTERM);}),);diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.tsindex 924341781aa..6a464021171 100644--- a/apps/desktop/src/app/DesktopLifecycle.ts+++ b/apps/desktop/src/app/DesktopLifecycle.ts@@ -160,108 +160,113 @@ function quitFromSignal(}/** @public Service construction is part of the canonical Effect module API. */-export const make = DesktopLifecycle.of({- relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {- const electronApp = yield* ElectronApp.ElectronApp;- const environment = yield* DesktopEnvironment.DesktopEnvironment;- const state = yield* DesktopState.DesktopState;- yield* logLifecycleInfo("desktop relaunch requested", { reason });- yield* Effect.gen(function* () {- yield* Effect.yieldNow;- yield* Ref.set(state.quitting, true);- yield* requestDesktopShutdownAndWait();- if (environment.isDevelopment) {- yield* electronApp.exit(75);- return;- }- yield* electronApp.relaunch({- execPath: process.execPath,- args: process.argv.slice(1),- });- yield* electronApp.exit(0);- }).pipe(- Effect.catchCause((cause) => {- const error = new DesktopLifecycleRelaunchError({ reason, cause });- return logLifecycleError(error.message, { error });- }),- Effect.forkDetach,- Effect.asVoid,- );- }),- register: Effect.gen(function* () {- const desktopWindow = yield* DesktopWindow.DesktopWindow;- const electronWindow = yield* ElectronWindow.ElectronWindow;- const electronApp = yield* ElectronApp.ElectronApp;- const electronTheme = yield* ElectronTheme.ElectronTheme;- const environment = yield* DesktopEnvironment.DesktopEnvironment;- const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();- const runEffect = Effect.runPromiseWith(context);- let quitAllowed = false;- let updaterQuitAllowed = false;- yield* electronTheme.onUpdated(() => {- void runEffect(- desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),+export const make = Effect.gen(function* () {+ const signalScope = yield* Scope.Scope;+ return DesktopLifecycle.of({+ relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {+ const electronApp = yield* ElectronApp.ElectronApp;+ const environment = yield* DesktopEnvironment.DesktopEnvironment;+ const state = yield* DesktopState.DesktopState;+ yield* logLifecycleInfo("desktop relaunch requested", { reason });+ yield* Effect.gen(function* () {+ yield* Effect.yieldNow;+ yield* Ref.set(state.quitting, true);+ yield* requestDesktopShutdownAndWait();+ if (environment.isDevelopment) {+ yield* electronApp.exit(75);+ return;+ }+ yield* electronApp.relaunch({+ execPath: process.execPath,+ args: process.argv.slice(1),+ });+ yield* electronApp.exit(0);+ }).pipe(+ Effect.catchCause((cause) => {+ const error = new DesktopLifecycleRelaunchError({ reason, cause });+ return logLifecycleError(error.message, { error });+ }),+ Effect.forkDetach,+ Effect.asVoid,);- });- yield* electronApp.onBeforeQuitForUpdate(() => {- // Electron's updater owns the remaining quit/install/relaunch sequence.- // Cancelling the following app "before-quit" event breaks that sequence,- // most visibly on macOS where the native updater performs the relaunch.- updaterQuitAllowed = true;- // This event is synchronous and the updater's quit proceeds as soon as- // the listener returns, so a forked destroyAll would race the quit- // and windows could still be open when the process exits (visible on- // macOS). Destroy them inline.- Effect.runSyncWith(context)(- electronWindow.destroyAll.pipe(- Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),- Effect.catchCause((cause) =>- logLifecycleError("failed to destroy windows before updater quit", { cause }),+ }),+ register: Effect.gen(function* () {+ const desktopWindow = yield* DesktopWindow.DesktopWindow;+ const electronWindow = yield* ElectronWindow.ElectronWindow;+ const electronApp = yield* ElectronApp.ElectronApp;+ const electronTheme = yield* ElectronTheme.ElectronTheme;+ const environment = yield* DesktopEnvironment.DesktopEnvironment;+ const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();+ const runEffect = Effect.runPromiseWith(context);+ let quitAllowed = false;+ let updaterQuitAllowed = false;+ yield* electronTheme.onUpdated(() => {+ void runEffect(+ desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),+ );+ });+ yield* electronApp.onBeforeQuitForUpdate(() => {+ // Electron's updater owns the remaining quit/install/relaunch sequence.+ // Cancelling the following app "before-quit" event breaks that sequence,+ // most visibly on macOS where the native updater performs the relaunch.+ updaterQuitAllowed = true;+ // This event is synchronous and the updater's quit proceeds as soon as+ // the listener returns, so a forked destroyAll would race the quit+ // and windows could still be open when the process exits (visible on+ // macOS). Destroy them inline.+ Effect.runSyncWith(context)(+ electronWindow.destroyAll.pipe(+ Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),+ Effect.catchCause((cause) =>+ logLifecycleError("failed to destroy windows before updater quit", { cause }),+ ),+ Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),),- Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),- ),- );- });- yield* electronApp.on("before-quit", (event: Electron.Event) => {- handleBeforeQuit(- event,- runEffect,- () => quitAllowed || updaterQuitAllowed,- () => {- quitAllowed = true;- },- );- });- yield* electronApp.on("activate", () => {- void runEffect(- Effect.gen(function* () {- const state = yield* DesktopState.DesktopState;- if (yield* Ref.get(state.quitting)) return;- yield* desktopWindow.activate;- }).pipe(Effect.withSpan("desktop.lifecycle.activate")),- );- });- yield* electronApp.on("window-all-closed", () => {- void runEffect(- Effect.gen(function* () {- const app = yield* ElectronApp.ElectronApp;- const state = yield* DesktopState.DesktopState;- if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {- yield* app.quit;- }- }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),- );- });-- if (environment.platform !== "win32") {- yield* addScopedListener(process, "SIGINT", () => {- quitFromSignal("SIGINT", runEffect);+ );+ });+ yield* electronApp.on("before-quit", (event: Electron.Event) => {+ handleBeforeQuit(+ event,+ runEffect,+ () => quitAllowed || updaterQuitAllowed,+ () => {+ quitAllowed = true;+ },+ );+ });+ yield* electronApp.on("activate", () => {+ void runEffect(+ Effect.gen(function* () {+ const state = yield* DesktopState.DesktopState;+ if (yield* Ref.get(state.quitting)) return;+ yield* desktopWindow.activate;+ }).pipe(Effect.withSpan("desktop.lifecycle.activate")),+ );});- yield* addScopedListener(process, "SIGTERM", () => {- quitFromSignal("SIGTERM", runEffect);+ yield* electronApp.on("window-all-closed", () => {+ void runEffect(+ Effect.gen(function* () {+ const app = yield* ElectronApp.ElectronApp;+ const state = yield* DesktopState.DesktopState;+ if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {+ yield* app.quit;+ }+ }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),+ );});- }- }).pipe(Effect.withSpan("desktop.lifecycle.register")),++ if (environment.platform !== "win32") {+ // The layer outlives program finalizers, so repeated signals stay owned+ // while backends stop. Electron listeners still follow the program scope.+ yield* addScopedListener(process, "SIGINT", () => {+ quitFromSignal("SIGINT", runEffect);+ }).pipe(Scope.provide(signalScope));+ yield* addScopedListener(process, "SIGTERM", () => {+ quitFromSignal("SIGTERM", runEffect);+ }).pipe(Scope.provide(signalScope));+ }+ }).pipe(Effect.withSpan("desktop.lifecycle.register")),+ });});-export const layer = Layer.succeed(DesktopLifecycle, make);+export const layer = Layer.effect(DesktopLifecycle, make);diff --git a/apps/desktop/src/app/DesktopRuntime.ts b/apps/desktop/src/app/DesktopRuntime.tsnew file mode 100644index 00000000000..17fc96b93b6--- /dev/null+++ b/apps/desktop/src/app/DesktopRuntime.ts@@ -0,0 +1,11 @@+import * as Runtime from "effect/Runtime";++// DesktopLifecycle owns signals and waits for backend shutdown before quitting+// Electron. NodeRuntime's competing signal handler interrupts that sequence.+export const runMain = Runtime.makeRunMain(({ fiber, teardown }) => {+ fiber.addObserver((exit) => {+ teardown(exit, (code) => {+ if (code !== 0) process.exit(code);+ });+ });+});diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.tsindex eaf7fc30845..725779de476 100644--- a/apps/desktop/src/backend/DesktopBackendManager.test.ts+++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts@@ -262,7 +262,7 @@ describe("DesktopBackendManager", () => {assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");assert.equal(Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),- 5_000,+ 30_000,);assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);@@ -1546,14 +1546,15 @@ describe("DesktopBackendManager", () => {),);- it.effect("stopAllPoolInstances bounds the quit finalizer when backends hang", () =>+ it.effect("stopAllPoolInstances allows slow cleanup but bounds hung backends", () =>Effect.scoped(Effect.gen(function* () {const teardownStarted = yield* Queue.unbounded<string>();const teardownFinished = yield* Queue.unbounded<string>();- const allowTeardown = yield* Deferred.make<void>();+ const allowSlowTeardown = yield* Deferred.make<void>();+ const allowHungTeardown = yield* Deferred.make<void>();- const makeInstance = (name: string) =>+ const makeInstance = (name: string, allowTeardown: Deferred.Deferred<void>) =>makeTestInstance({spawnerLayer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner,@@ -1575,8 +1576,8 @@ describe("DesktopBackendManager", () => {httpClientLayer: layerHttpClient(() => Effect.never),});- const instance1 = yield* makeInstance("instance1");- const instance2 = yield* makeInstance("instance2");+ const instance1 = yield* makeInstance("instance1", allowSlowTeardown);+ const instance2 = yield* makeInstance("instance2", allowHungTeardown);yield* instance1.start;yield* instance2.start;@@ -1594,15 +1595,25 @@ describe("DesktopBackendManager", () => {).pipe(Effect.provide(layerMockPool), Effect.forkChild);const started = yield* Queue.takeN(teardownStarted, 2);+ yield* Effect.addFinalizer(() =>+ Deferred.succeed(allowSlowTeardown, undefined).pipe(+ Effect.andThen(Deferred.succeed(allowHungTeardown, undefined)),+ ),+ );assert.deepEqual(started.toSorted(), ["instance1", "instance2"]);- yield* TestClock.adjust(Duration.seconds(5));+ yield* TestClock.adjust(Duration.seconds(6));+ assert.isUndefined(quitFiber.pollUnsafe());+ yield* Deferred.succeed(allowSlowTeardown, undefined);+ assert.equal(yield* Queue.take(teardownFinished), "instance1");+ assert.isUndefined(quitFiber.pollUnsafe());+ yield* TestClock.adjust(Duration.seconds(39));+yield* Fiber.join(quitFiber);assert.equal(yield* Queue.size(teardownFinished), 0);- yield* Deferred.succeed(allowTeardown, undefined);- const finished = yield* Queue.takeN(teardownFinished, 2);- assert.deepEqual(finished.toSorted(), ["instance1", "instance2"]);+ yield* Deferred.succeed(allowHungTeardown, undefined);+ assert.equal(yield* Queue.take(teardownFinished), "instance2");}).pipe(Effect.provide(TestClock.layer())),),);diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.tsindex e74e98a079b..50587ac26f8 100644--- a/apps/desktop/src/backend/DesktopBackendManager.ts+++ b/apps/desktop/src/backend/DesktopBackendManager.ts@@ -37,9 +37,8 @@ const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);-// Same as the service launcher. A killed backend leaves its agents running,-// and a busy one needs a few seconds to stop every provider session.-const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5);+// Give busy backends time to stop provider sessions before forcing termination.+const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(30);const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);const BACKEND_READINESS_PATH = "/.well-known/t3/environment";const { logWarning: logBackendProcessWarning } =diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 0aac282bbf8..e9477cd322b 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -6,7 +6,6 @@ for (const stream of [process.stdout, process.stderr]) {}import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";-import * as NodeRuntime from "@effect/platform-node/NodeRuntime";import * as NodeServices from "@effect/platform-node/NodeServices";// @effect-diagnostics-next-line nodeBuiltinImport:off - Version output must flush before Electron exits, without acquiring the runtime.import * as NodeFS from "node:fs";@@ -22,6 +21,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";import serverPackageJson from "../../server/package.json" with { type: "json" };+import * as DesktopRuntime from "./app/DesktopRuntime.ts";import * as DesktopIpc from "./ipc/DesktopIpc.ts";import * as ElectronApp from "./electron/ElectronApp.ts";import * as ElectronDialog from "./electron/ElectronDialog.ts";@@ -246,4 +246,4 @@ const layerDesktopRuntime = layerDesktopClerk.pipe(Layer.provideMerge(DesktopPreReadyPlatform.layer),);-DesktopApp.program.pipe(Effect.provide(layerDesktopRuntime), NodeRuntime.runMain);+DesktopApp.program.pipe(Effect.provide(layerDesktopRuntime), DesktopRuntime.runMain);diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.tsindex a2b97043854..592d453cf60 100644--- a/apps/desktop/src/updates/DesktopUpdates.ts+++ b/apps/desktop/src/updates/DesktopUpdates.ts@@ -801,7 +801,7 @@ export const make = Effect.gen(function* () {yield* Ref.set(installRunningBackendsRef, runningInstances);yield* Effect.forEach(instances,- (instance) => instance.stop({ timeout: Duration.seconds(5) }),+ (instance) => instance.stop({ timeout: Duration.seconds(45) }),{ concurrency: "unbounded" },);yield* electronUpdater.quitAndInstall({