Skip to content

Commit 902293a

Browse files
fix(desktop): let lifecycle shutdown finish before exiting
1 parent cfafb4b commit 902293a

6 files changed

Lines changed: 85 additions & 6 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
},
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+
import { expect, it } from "@effect/vitest";
6+
7+
it("leaves SIGTERM to the lifecycle until its graceful shutdown completes", async ({
8+
onTestFinished,
9+
}) => {
10+
const runner = new URL("./DesktopRuntime.ts", import.meta.url).href;
11+
const child = NodeChildProcess.spawn(
12+
process.execPath,
13+
[
14+
"--experimental-strip-types",
15+
"--input-type=module",
16+
"-e",
17+
`
18+
import * as Effect from 'effect/Effect';
19+
import * as Deferred from 'effect/Deferred';
20+
import { runMain } from ${JSON.stringify(runner)};
21+
let released = false;
22+
runMain(Effect.scoped(Effect.gen(function* () {
23+
const done = yield* Deferred.make();
24+
yield* Effect.addFinalizer(() => Effect.sync(() => console.log(released ? 'CLEANED' : 'PREMATURE')));
25+
process.once('SIGTERM', () => {
26+
console.log('STOPPING');
27+
process.stdin.once('data', () => {
28+
released = true;
29+
void Effect.runPromise(Deferred.succeed(done, undefined)).then(() => process.stdin.destroy());
30+
});
31+
});
32+
console.log('READY');
33+
yield* Deferred.await(done);
34+
})));
35+
`,
36+
],
37+
{
38+
cwd: NodeURL.fileURLToPath(new URL("../../", import.meta.url)),
39+
stdio: ["pipe", "pipe", "pipe"],
40+
},
41+
);
42+
const exited = new Promise<readonly [number | null, string | null]>((resolve, reject) => {
43+
child.once("exit", (code, signal) => resolve([code, signal]));
44+
child.once("error", reject);
45+
});
46+
const lines: string[] = [];
47+
let stderr = "";
48+
child.stderr.on("data", (chunk) => {
49+
stderr += chunk;
50+
});
51+
onTestFinished(async () => {
52+
if (child.exitCode === null && child.signalCode === null) {
53+
child.kill("SIGKILL");
54+
await exited;
55+
}
56+
});
57+
for await (const line of NodeReadline.createInterface({ input: child.stdout })) {
58+
lines.push(line);
59+
if (line === "READY") child.kill("SIGTERM");
60+
if (line === "STOPPING") child.stdin.write("finish");
61+
}
62+
expect(await exited, stderr).toEqual([0, null]);
63+
expect(lines).toEqual(["READY", "STOPPING", "CLEANED"]);
64+
});
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+
});

‎apps/desktop/src/backend/DesktopBackendManager.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ describe("DesktopBackendManager", () => {
262262
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
263263
assert.equal(
264264
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
265-
5_000,
265+
30_000,
266266
);
267267

268268
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
@@ -1572,7 +1572,10 @@ describe("DesktopBackendManager", () => {
15721572
const started = yield* Queue.takeN(teardownStarted, 2);
15731573
assert.deepEqual(started.toSorted(), ["instance1", "instance2"]);
15741574

1575-
yield* TestClock.adjust(Duration.seconds(5));
1575+
yield* TestClock.adjust(Duration.seconds(6));
1576+
assert.isUndefined(quitFiber.pollUnsafe());
1577+
yield* TestClock.adjust(Duration.seconds(39));
1578+
15761579
yield* Fiber.join(quitFiber);
15771580
assert.equal(yield* Queue.size(teardownFinished), 0);
15781581

‎apps/desktop/src/backend/DesktopBackendManager.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
3939
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
4040
// Same as the service launcher. A killed backend leaves its agents running,
4141
// and a busy one needs a few seconds to stop every provider session.
42-
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5);
42+
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(30);
4343
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
4444
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
4545
const { logWarning: logBackendProcessWarning } =

‎apps/desktop/src/main.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ for (const stream of [process.stdout, process.stderr]) {
66
}
77

88
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
9-
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
9+
import * as DesktopRuntime from "./app/DesktopRuntime.ts";
1010
import * as NodeServices from "@effect/platform-node/NodeServices";
1111
// @effect-diagnostics-next-line nodeBuiltinImport:off - Version output must flush before Electron exits, without acquiring the runtime.
1212
import * as NodeFS from "node:fs";
@@ -242,4 +242,4 @@ const layerDesktopRuntime = layerDesktopClerk.pipe(
242242
Layer.provideMerge(DesktopPreReadyPlatform.layer),
243243
);
244244

245-
DesktopApp.program.pipe(Effect.provide(layerDesktopRuntime), NodeRuntime.runMain);
245+
DesktopApp.program.pipe(Effect.provide(layerDesktopRuntime), DesktopRuntime.runMain);

0 commit comments

Comments
 (0)