Skip to content

Commit

Permalink
Fix race edgecase between subsequent disconnect and connect calls
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasIO committed Dec 20, 2022
1 parent f1ba2ab commit fdaac95
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/weak-kings-move.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'livekit-client': patch
---

Fix race edgecase between subsequent disconnect and connect calls
9 changes: 8 additions & 1 deletion src/room/Room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,14 +239,19 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
await fetch(`http${url.substring(2)}`, { method: 'HEAD' });
}

connect = (url: string, token: string, opts?: RoomConnectOptions): Promise<void> => {
connect = async (url: string, token: string, opts?: RoomConnectOptions): Promise<void> => {
// In case a disconnect called happened right before the connect call, make sure the disconnect is completed first by awaiting its lock
const unlockDisconnect = await this.disconnectLock.lock();

if (this.state === ConnectionState.Connected) {
// when the state is reconnecting or connected, this function returns immediately
log.info(`already connected to room ${this.name}`);
unlockDisconnect();
return Promise.resolve();
}

if (this.connectFuture) {
unlockDisconnect();
return this.connectFuture.promise;
}

Expand All @@ -256,6 +261,8 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
if (!this.abortController || this.abortController.signal.aborted) {
this.abortController = new AbortController();
}
// at this point the intention to connect has been signalled so we can allow cancelling of the connection via disconnect() again
unlockDisconnect();

if (this.state === ConnectionState.Reconnecting) {
log.info('Reconnection attempt replaced by new connection attempt');
Expand Down

0 comments on commit fdaac95

Please sign in to comment.