fix: deduplicate getSid() listeners to prevent leak on concurrent calls#635
fix: deduplicate getSid() listeners to prevent leak on concurrent calls#635LautaroPetaccio wants to merge 6 commits intolivekit:mainfrom
Conversation
🦋 Changeset detectedLatest commit: 9e38994 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
|
||
| // Clear sidPromise before removing listeners so that a reconnect | ||
| // doesn't return a stale, permanently-pending promise. | ||
| this.sidPromise = undefined; |
There was a problem hiding this comment.
This should already be accounted for if you don't remove the handleDisconnect once listener above?
There was a problem hiding this comment.
The once-listener depends on the 'disconnected' FFI event arriving and being processed before the 'disconnect' callback resolves. Since we can't guarantee that ordering, and if the callback resolves first, removeAllListeners() wipes the once-listener before it fires, the explicit cleanup here is needed as a safety measure to prevent a stale sidPromise across reconnects.
Why
Each
getSid()call creates its ownRoomSidChanged+Disconnectedlistener pair. If multiple calls race, only one resolves the SID and cleans up itsRoomSidChangedlistener — the rest stay attached. Additionally, theDisconnectedlistener registered viaonce()was never removed on the success path, persisting until a disconnect event orremoveAllListeners().How
Add a
private sidPromise?: Promise<string>field. On the firstgetSid()call that needs to wait, create the promise and store it. Subsequent concurrent calls return the same promise. When the promise resolves or rejects,sidPromiseis cleared so future calls after a reconnect work normally. Both the resolve and reject paths now clean up both listeners — on success,handleDisconnectis removed; on disconnect,handleRoomUpdateis removed.Test coverage
New E2E test
concurrent getSid() calls share a single listener and resolve consistently— fires 3 concurrentgetSid()calls, asserts all return the same SID.