Skip to content

Commit

Permalink
fix: fix race condition when leaving rooms (#74)
Browse files Browse the repository at this point in the history
This should fix the related issue:

```
TypeError: Cannot read property 'size' of undefined
    at Adapter._del (/app/node_modules/socket.io-adapter/dist/index.js:67:37)
    at Adapter.delAll (/app/node_modules/socket.io-adapter/dist/index.js:83:18)
    at Socket.leaveAll (/app/node_modules/socket.io/dist/socket.js:190:22)
    at Socket._onclose (/app/node_modules/socket.io/dist/socket.js:334:14)
    at Client.onclose (/app/node_modules/socket.io/dist/client.js:245:20)
    at Socket.emit (events.js:412:35)
    at Socket.onClose (/app/node_modules/engine.io/lib/socket.js:348:12)
    at Object.onceWrapper (events.js:519:28)
    at WebSocket.emit (events.js:400:28)
    at WebSocket.onClose (/app/node_modules/engine.io/lib/transport.js:106:10)
```

A test case was added, which reproduces the issue by adding a listener
to the "leave-room" event. This does not seem to be the case for the
user reporting the issue though, which may indicate that the root cause
is elsewhere.
  • Loading branch information
sharat87 authored and darrachequesne committed Aug 28, 2021
1 parent 0667d82 commit 912e13a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
10 changes: 5 additions & 5 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,14 @@ export class Adapter extends EventEmitter {
this._del(room, id);
}

private _del(room, id) {
if (this.rooms.has(room)) {
const deleted = this.rooms.get(room).delete(id);
private _del(room: Room, id: SocketId) {
const _room = this.rooms.get(room);
if (_room != null) {
const deleted = _room.delete(id);
if (deleted) {
this.emit("leave-room", room, id);
}
if (this.rooms.get(room).size === 0) {
this.rooms.delete(room);
if (_room.size === 0 && this.rooms.delete(room)) {
this.emit("delete-room", room);
}
}
Expand Down
10 changes: 10 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,16 @@ describe("socket.io-adapter", () => {
adapter.del("s1", "r1");
});

it("should not throw when calling del twice", done => {
const adapter = new Adapter({ server: { encoder: null } });
adapter.on("leave-room", (room, sid) => {
adapter.del("s1", "r1");
process.nextTick(done);
});
adapter.addAll("s1", new Set(["r1"]));
adapter.del("s1", "r1");
});

it("should emit a 'leave-room' event with delAll method", done => {
const adapter = new Adapter({ server: { encoder: null } });
adapter.on("leave-room", (room, sid) => {
Expand Down

0 comments on commit 912e13a

Please sign in to comment.