Repository navigation
Description
Describe the bug
PGliteWorker.close() can run while #init is waiting in acquireLock() for the tab-close lock. At that point close() sets #closed, closes the channels that exist (none yet), and calls #releaseTabCloseLock?.(), which is still undefined. Then the lock is granted and #init carries on: it stores the release function, opens the pglite-broadcast:* and pglite-tab:* channels, and starts #leaderNotifyLoop(). Nothing releases or closes them afterwards, so the closed instance holds the lock and both channels until the page unloads.
This came up in #1147, which guards #leaderNotifyLoop() with !this.#closed. That check stops the loop but not the lock or the channels.
To Reproduce
Node 22 has no navigator.locks, so this uses a small stand-in, a fake worker (like the one in #1147's test), and a BroadcastChannel subclass that counts open channels. close() runs in the same task that delivers the worker's ready, so there's no lock contention:
// npm i @electric-sql/pglite@0.6.1 && node repro.mjs
const held = new Set()
const locks = {
request: (name, cb) =>
Promise.resolve().then(async () => {
held.add(name)
try { await cb() } finally { held.delete(name) }
}),
}
Object.defineProperty(globalThis, 'navigator', { value: { locks }, configurable: true })
let open = 0
const BC = globalThis.BroadcastChannel
globalThis.BroadcastChannel = class extends BC {
#open = true
constructor(n) { super(n); open++ }
close() { if (this.#open) { this.#open = false; open-- } return super.close() }
}
class FakeWorker extends EventTarget {
postMessage(m) { if (m.type === 'init') setTimeout(() => this.#send({ type: 'ready', id: 'w' })) }
terminate() {}
announce() { this.#send({ type: 'here' }) }
#send(data) { this.dispatchEvent(new MessageEvent('message', { data })) }
}
const { PGliteWorker } = await import('@electric-sql/pglite/worker')
const w = new FakeWorker()
const pg = new PGliteWorker(w)
w.addEventListener('message', (e) => { if (e.data.type === 'ready') pg.close() })
w.announce()
await new Promise((r) => setTimeout(r, 500))
console.log({ closed: pg.closed, tabCloseLocksHeld: held.size, openBroadcastChannels: open })
process.exit(0)Output: { closed: true, tabCloseLocksHeld: 1, openBroadcastChannels: 2 }. Closing after init has finished gives 0 and 0.
The same happens when close() runs while another holder has the tab-close lock and lets it go afterwards: 1 lock, 2 channels, and on 0.6.1 the closed instance also keeps posting tab-here (12 posts in 300 ms).
Details
- PGlite 0.6.1 (
@electric-sql/pglite/worker), no extensions - Windows 11, Node 22.16
- Not tested in a browser. The stubs stand in for the browser's lock manager and the worker.
Additional context
One possible fix is to check this.#closed after the acquireLock() await in #init and, if it's set, release the lock and return before opening the channels. Checking after the earlier awaits would help too. I haven't written or tested a patch.
Activity