Skip to content

Commit 9975366

Browse files
committed
fix(desktop): await external installer cancellation before recovery
1 parent a470d22 commit 9975366

2 files changed

Lines changed: 207 additions & 60 deletions

File tree

‎apps/desktop/src/electron/ElectronUpdater.test.ts‎

Lines changed: 133 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import * as NodePath from "@effect/platform-node/NodePath";
22
import * as TestClock from "effect/testing/TestClock";
33
import * as NodeEvents from "node:events";
4+
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
5+
import * as FileSystem from "effect/FileSystem";
46
import * as HostProcess from "@t3tools/shared/HostProcess";
57
import { assert, describe, it } from "@effect/vitest";
68
import * as Effect from "effect/Effect";
@@ -36,11 +38,13 @@ vi.mock("electron-updater", async () => {
3638

3739
const installer = "/opt/T3 scripts/install-macos-update.sh";
3840
const archive = "/cache/T3 update $(untouched).zip";
41+
const helperPid = 42424;
3942

4043
beforeEach(() => {
4144
vi.resetAllMocks();
4245
mocks.spawn.mockImplementation(() => {
4346
const child = Object.assign(new NodeEvents.EventEmitter(), {
47+
pid: helperPid,
4448
unref: vi.fn(),
4549
kill: vi.fn(),
4650
stdout: Object.assign(new NodeEvents.EventEmitter(), { destroy: vi.fn() }),
@@ -114,11 +118,20 @@ describe("ElectronUpdater install handoff", () => {
114118
"stops the unready helper on %s without quitting T3",
115119
(failure) =>
116120
Effect.gen(function* () {
121+
let markSignalled!: () => void;
122+
const signalled = new Promise<void>((resolve) => {
123+
markSignalled = resolve;
124+
});
117125
const child = Object.assign(new NodeEvents.EventEmitter(), {
118-
kill: vi.fn(),
126+
pid: helperPid,
127+
kill: vi.fn(markSignalled),
119128
stdout: Object.assign(new NodeEvents.EventEmitter(), { destroy: vi.fn() }),
120129
stderr: Object.assign(new NodeEvents.EventEmitter(), { destroy: vi.fn() }),
121130
});
131+
using signals = vi.spyOn(process, "kill").mockImplementation(() => {
132+
markSignalled();
133+
return true;
134+
});
122135
const started = new Promise<void>((resolveStarted) => {
123136
mocks.spawn.mockImplementation(() => {
124137
queueMicrotask(resolveStarted);
@@ -127,16 +140,27 @@ describe("ElectronUpdater install handoff", () => {
127140
});
128141
const fiber = yield* install(true).pipe(Effect.forkChild);
129142
yield* Effect.promise(() => started);
130-
if (failure === "interrupt") yield* Fiber.interrupt(fiber);
131-
else {
132-
yield* TestClock.adjust("120 seconds");
133-
assert.equal((yield* Fiber.join(fiber))._tag, "Failure");
143+
const stopping = yield* (
144+
failure === "interrupt" ? Fiber.interrupt(fiber) : TestClock.adjust("120 seconds")
145+
).pipe(Effect.forkChild);
146+
yield* Effect.promise(() => signalled);
147+
try {
148+
assert.deepEqual(signals.mock.calls, [[-helperPid, "SIGTERM"]]);
149+
assert.isUndefined(fiber.pollUnsafe(), "installation waits for its helper to close");
150+
child.emit("exit", null, "SIGTERM");
151+
yield* Effect.promise(() => Promise.resolve());
152+
assert.isUndefined(fiber.pollUnsafe(), "exit alone does not finish cleanup");
153+
} finally {
154+
child.emit("close", null, "SIGTERM");
134155
}
135-
assert.equal(child.kill.mock.calls.length, 1);
156+
yield* Fiber.join(stopping);
157+
if (failure === "timeout") assert.equal((yield* Fiber.join(fiber))._tag, "Failure");
158+
assert.equal(child.kill.mock.calls.length, 0);
136159
assert.equal(mocks.quit.mock.calls.length, 0);
137160
assert.equal(mocks.nativeInstall.mock.calls.length, 0);
138161
}),
139162
);
163+
140164
it.effect.each(["linux", "win32"] as const)(
141165
"keeps the native installer on %s even when an external macOS installer is configured",
142166
(platform) =>
@@ -179,22 +203,38 @@ describe("ElectronUpdater install handoff", () => {
179203
"helper-rejection",
180204
"invalid-readiness",
181205
"quit-failure",
206+
"before-quit-failure",
182207
])("keeps T3 open without native fallback after %s", (failure) =>
183208
Effect.gen(function* () {
209+
using signals = vi.spyOn(process, "kill").mockImplementation(() => {
210+
queueMicrotask(() => mocks.spawn.mock.results[0]?.value.emit("close", null, "SIGTERM"));
211+
return true;
212+
});
213+
if (failure === "before-quit-failure")
214+
mocks.beforeQuit.mockImplementation(() => {
215+
throw new Error("quit gate rejected");
216+
});
184217
if (failure === "quit-failure")
185218
mocks.quit.mockImplementation(() => {
186219
throw new Error("quit rejected");
187220
});
188-
if (failure !== "missing-download" && failure !== "quit-failure") {
221+
if (
222+
failure !== "missing-download" &&
223+
failure !== "quit-failure" &&
224+
failure !== "before-quit-failure"
225+
) {
189226
mocks.spawn.mockImplementation(() => {
190227
const child = Object.assign(new NodeEvents.EventEmitter(), {
228+
pid: failure === "spawn-failure" ? undefined : helperPid,
191229
kill: vi.fn(),
192230
stdout: Object.assign(new NodeEvents.EventEmitter(), { destroy: vi.fn() }),
193231
stderr: Object.assign(new NodeEvents.EventEmitter(), { destroy: vi.fn() }),
194232
});
195233
queueMicrotask(() => {
196-
if (failure === "spawn-failure")
234+
if (failure === "spawn-failure") {
197235
child.emit("error", new Error("cannot spawn installer"));
236+
child.emit("close", -1);
237+
}
198238
if (failure === "helper-rejection") {
199239
child.emit("exit", 1);
200240
child.stderr.emit("data", Buffer.from("invalid "));
@@ -215,16 +255,99 @@ describe("ElectronUpdater install handoff", () => {
215255
result.failure.stage,
216256
failure === "missing-download"
217257
? "validation"
218-
: failure === "quit-failure"
258+
: failure === "quit-failure" || failure === "before-quit-failure"
219259
? "shutdown"
220260
: "handoff",
221261
);
222262
if (failure === "helper-rejection")
223263
assert.equal((result.failure.cause as Error).message, "invalid signature");
224264
}
225265
assert.equal(mocks.quit.mock.calls.length, failure === "quit-failure" ? 1 : 0);
226-
assert.equal(mocks.beforeQuit.mock.calls.length, failure === "quit-failure" ? 1 : 0);
266+
assert.equal(
267+
mocks.beforeQuit.mock.calls.length,
268+
failure === "quit-failure" || failure === "before-quit-failure" ? 1 : 0,
269+
);
270+
assert.deepEqual(
271+
signals.mock.calls,
272+
["invalid-readiness", "quit-failure", "before-quit-failure"].includes(failure)
273+
? [[-helperPid, "SIGTERM"]]
274+
: [],
275+
);
227276
assert.equal(mocks.nativeInstall.mock.calls.length, 0);
228277
}),
229278
);
230279
});
280+
281+
describe.runIf(HostProcess.Platform.defaultValue() !== "win32")("POSIX installer ownership", () => {
282+
it.live("reaps a foreground tool and runs shell cleanup before cancellation returns", () =>
283+
Effect.gen(function* () {
284+
const { spawn } = yield* Effect.promise(() =>
285+
vi.importActual<typeof import("node:child_process")>("node:child_process"),
286+
);
287+
const fs = yield* FileSystem.FileSystem;
288+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "installer-group-" });
289+
yield* fs.writeFileString(`${root}/candidate`, "staged payload");
290+
yield* fs.writeFileString(`${root}/untouched`, "unrelated");
291+
let child: import("node:child_process").ChildProcess | undefined;
292+
let closed: Promise<void> | undefined;
293+
let didClose = false;
294+
const started = new Promise<number>((resolve, reject) => {
295+
mocks.spawn.mockImplementation(() => {
296+
child = spawn(
297+
"/bin/sh",
298+
[
299+
"-c",
300+
`set -eu
301+
trap 'rm -f "$FIXTURE_ROOT/candidate"' EXIT
302+
trap 'exit 1' TERM
303+
/bin/sh -c 'printf "tool:%s\\n" "$$" >&2; exec /bin/sleep 60'
304+
exit 0`,
305+
],
306+
{
307+
detached: true,
308+
stdio: ["ignore", "pipe", "pipe"],
309+
env: { ...process.env, FIXTURE_ROOT: root },
310+
},
311+
);
312+
closed = new Promise<void>((resolveClosed) =>
313+
child!.once("close", () => {
314+
didClose = true;
315+
resolveClosed();
316+
}),
317+
);
318+
let output = "";
319+
child.stderr!.on("data", (chunk: Buffer) => {
320+
output += chunk.toString();
321+
const pid = /tool:(\d+)/.exec(output)?.[1];
322+
if (pid) resolve(Number(pid));
323+
});
324+
child.once("error", reject);
325+
return child;
326+
});
327+
});
328+
try {
329+
const fiber = yield* install(true).pipe(Effect.forkChild);
330+
const toolPid = yield* Effect.promise(() => started);
331+
assert.notEqual(toolPid, child!.pid, "fixture has a distinct foreground child");
332+
yield* Fiber.interrupt(fiber);
333+
assert.isTrue(didClose, "cancellation awaits its helper and foreground tool");
334+
assert.throws(() => process.kill(toolPid, 0), /ESRCH/);
335+
assert.isFalse(yield* fs.exists(`${root}/candidate`));
336+
assert.equal(yield* fs.readFileString(`${root}/untouched`), "unrelated");
337+
assert.equal(mocks.quit.mock.calls.length, 0);
338+
} finally {
339+
if (!didClose && child?.pid !== undefined) {
340+
yield* Effect.sync(() => {
341+
try {
342+
process.kill(-child!.pid!, "SIGTERM");
343+
} catch (cause) {
344+
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH"))
345+
throw cause;
346+
}
347+
});
348+
}
349+
if (closed) yield* Effect.promise(() => closed!);
350+
}
351+
}).pipe(Effect.scoped, Effect.provide(NodeFileSystem.layer)),
352+
);
353+
});

‎apps/desktop/src/electron/ElectronUpdater.ts‎

Lines changed: 74 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,10 @@ export const make = Effect.gen(function* () {
171171
return Effect.suspend(() => {
172172
const channel = autoUpdater.channel;
173173
let stage: "validation" | "handoff" | "shutdown" = "validation";
174+
let helperPid: number | undefined;
175+
let helperClosed = false;
176+
let closed: Promise<void> | undefined;
177+
let committed = false;
174178
const installError = (cause: unknown) =>
175179
new ElectronUpdaterQuitAndInstallError({
176180
channel,
@@ -194,67 +198,87 @@ export const make = Effect.gen(function* () {
194198
}
195199
const appBundle = path.resolve(execPath, "../../..");
196200
stage = "handoff";
197-
const installerProcess = await new Promise<NodeChildProcess.ChildProcess>(
198-
(resolveReady, reject) => {
199-
const child = NodeChildProcess.spawn(
200-
installer,
201-
[
202-
selected.archive,
203-
appBundle,
204-
selected.version,
205-
String(process.pid),
206-
String(isForceRunAfter),
207-
],
208-
{ detached: true, stdio: ["ignore", "pipe", "pipe"] },
209-
);
210-
let output = "";
211-
let errors = "";
212-
let finished = false;
213-
const finish = (error?: Error) => {
214-
if (finished) return;
215-
finished = true;
216-
signal.removeEventListener("abort", abort);
201+
await new Promise<void>((resolveReady, reject) => {
202+
const child = NodeChildProcess.spawn(
203+
installer,
204+
[
205+
selected.archive,
206+
appBundle,
207+
selected.version,
208+
String(process.pid),
209+
String(isForceRunAfter),
210+
],
211+
{ detached: true, stdio: ["ignore", "pipe", "pipe"] },
212+
);
213+
helperPid = child.pid;
214+
closed = new Promise<void>((resolveClosed) =>
215+
child.once("close", () => {
216+
helperClosed = true;
217+
resolveClosed();
218+
}),
219+
);
220+
let output = "";
221+
let errors = "";
222+
let finished = false;
223+
const finish = (error?: Error) => {
224+
if (finished) return;
225+
finished = true;
226+
signal.removeEventListener("abort", abort);
227+
if (error) {
228+
reject(error);
229+
} else {
217230
child.stdout?.destroy();
218231
child.stderr?.destroy();
219-
if (error) {
220-
child.kill();
221-
reject(error);
222-
} else {
223-
child.unref();
224-
resolveReady(child);
225-
}
226-
};
227-
const abort = () => finish(new Error("External installer handoff was cancelled."));
228-
signal.addEventListener("abort", abort, { once: true });
229-
child.once("error", finish);
230-
child.once("close", () =>
231-
finish(new Error(errors || "External installer exited before becoming ready.")),
232-
);
233-
child.stderr?.on("data", (chunk: Buffer) => {
234-
errors = (errors + chunk.toString()).slice(-8192);
235-
});
236-
child.stdout?.on("data", (chunk: Buffer) => {
237-
output += chunk.toString();
238-
if (output === "ready\n") finish();
239-
else if (output.includes("\n") || output.length > 4096)
240-
finish(new Error("Invalid external installer readiness response."));
241-
});
242-
if (signal.aborted) abort();
243-
},
244-
);
245-
if (signal.aborted) {
246-
installerProcess.kill();
247-
signal.throwIfAborted();
248-
}
232+
child.unref();
233+
resolveReady();
234+
}
235+
};
236+
const abort = () => finish(new Error("External installer handoff was cancelled."));
237+
signal.addEventListener("abort", abort, { once: true });
238+
child.once("error", finish);
239+
child.once("close", () =>
240+
finish(new Error(errors || "External installer exited before becoming ready.")),
241+
);
242+
child.stderr?.on("data", (chunk: Buffer) => {
243+
errors = (errors + chunk.toString()).slice(-8192);
244+
});
245+
child.stdout?.on("data", (chunk: Buffer) => {
246+
if (finished) return;
247+
output += chunk.toString();
248+
if (output === "ready\n") finish();
249+
else if (output.includes("\n") || output.length > 4096)
250+
finish(new Error("Invalid external installer readiness response."));
251+
});
252+
if (signal.aborted) abort();
253+
});
254+
signal.throwIfAborted();
249255
stage = "shutdown";
250256
// Reuse the synchronous quit gate without invoking Squirrel or ShipIt.
251257
Electron.autoUpdater.emit("before-quit-for-update");
252258
Electron.app.quit();
259+
committed = true;
253260
},
254261
catch: installError,
255262
}).pipe(
256263
Effect.timeout("120 seconds"),
257264
Effect.catchTags({ TimeoutError: (cause) => Effect.fail(installError(cause)) }),
265+
Effect.ensuring(
266+
Effect.tryPromise({
267+
try: async () => {
268+
if (committed || closed === undefined) return;
269+
if (!helperClosed && helperPid !== undefined) {
270+
try {
271+
process.kill(-helperPid, "SIGTERM");
272+
} catch (cause) {
273+
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH"))
274+
throw cause;
275+
}
276+
}
277+
await closed;
278+
},
279+
catch: installError,
280+
}).pipe(Effect.orDie),
281+
),
258282
);
259283
});
260284
}),

0 commit comments

Comments
 (0)