PGliteWorker can post to a closed BroadcastChannel during teardown
Reproduction
Reproduced with @electric-sql/pglite 0.5.0, 0.5.6, 0.5.7, and 0.5.8 in Chromium.
pglite.worker.ts:
import { PGlite } from "@electric-sql/pglite";
import { worker } from "@electric-sql/pglite/worker";
worker({
async init(options) {
return new PGlite({ dataDir: options.dataDir });
},
});main.ts:
import { PGliteWorker } from "@electric-sql/pglite/worker";
import PGliteWorkerScript from "./pglite.worker?worker";
window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled rejection:", event.reason);
});
const db = await PGliteWorker.create(
new PGliteWorkerScript({ type: "module" }),
{ id: "broadcast-channel-close-repro" },
);
console.log("ready at close:", db.ready); // Usually false
await db.close();
await new Promise((resolve) => setTimeout(resolve, 100));db.ready is commonly false when close() runs. The error is asynchronous, so wait briefly after closing.
Expected
close() should not produce an uncaught exception.
Actual
Shortly after closing:
InvalidStateError: Failed to execute 'postMessage' on 'BroadcastChannel': Channel is closedIn a multi-tab handoff this may also coincide with LeaderChangedError.
Cause
The notification loop schedules a timer while disconnected:
async #leaderNotifyLoop() {
if (!this.#connected) {
this.#broadcastChannel!.postMessage({
type: "tab-here",
id: this.#tabId,
});
setTimeout(() => this.#leaderNotifyLoop(), 16);
}
}close() closes the channel but does not cancel or guard the timer:
async close() {
if (this.#closed) return;
this.#closed = true;
this.#broadcastChannel?.close();
this.#tabChannel?.close();
this.#releaseTabCloseLock?.();
this.#workerProcess.terminate();
}The timer callback discards the async loop's promise, so postMessage() throwing becomes an unhandled rejection. The leader-here handler can re-arm the same loop during handoff.
Request
Please ensure that after close() resolves no internal timer accesses a closed channel or produces an unhandled rejection, with a regression test covering startup and leader-change teardown.
This is distinct from PR #1109, which addresses RPCs hanging across leader changes.
Source: electric-sql/pglite