Skip to content

Commit

Permalink
fix(*): handle server-induced disconnects (#356)
Browse files Browse the repository at this point in the history
  • Loading branch information
garrappachc authored Jun 20, 2023
1 parent bb4d5b4 commit b57c2dd
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
45 changes: 45 additions & 0 deletions e2e/handles-server-disconnects.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { Client } from '@';
import { waitABit } from './utils/wait-a-bit';

jest.setTimeout(60 * 1000);

describe('Handles server disconnects (e2e)', () => {
let client1: Client;
let client2: Client;

beforeAll(async () => {
client1 = new Client({
host: 'localhost',
port: 64738,
username: 'tester',
rejectUnauthorized: false,
});

client2 = new Client({
host: 'localhost',
port: 64738,
username: 'tester',
rejectUnauthorized: false,
});

await client1.connect();
await waitABit(1000);
});

afterAll(async () => {
await waitABit(1000);
client1.disconnect();
client2.disconnect();
});

it('should handle error', async () => {
let wasDisconnected = false;
client1.on('disconnect', () => (wasDisconnected = true));

await waitABit(5000);

await client2.connect(); // will cause client1 to get disconnected
await waitABit(5000);
expect(wasDisconnected).toBe(true);
});
});
15 changes: 14 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
Reject,
ServerConfig,
ServerSync,
UserRemove,
Version,
} from '@tf2pickup-org/mumble-protocol';
import { User } from './user';
Expand Down Expand Up @@ -81,6 +82,18 @@ export class Client extends EventEmitter {
this.permissions.set(channelId, permissions);
});

this.socket.packet
.pipe(
filterPacket(UserRemove),
filter(userRemove => userRemove.session === this.user?.session),
)
.subscribe(userRemove => {
this.emit(EventNames.disconnect, {
reason: userRemove.reason,
});
this.socket = undefined;
});

const initialize: Promise<this> = lastValueFrom(
race(
zip(
Expand Down Expand Up @@ -192,6 +205,6 @@ export class Client extends EventEmitter {
const subscription = interval(this.options.pingInterval)
.pipe(exhaustMap(() => this.ping()))
.subscribe();
this.on('disconnect', () => subscription.unsubscribe());
this.on(EventNames.disconnect, () => subscription.unsubscribe());
}
}

0 comments on commit b57c2dd

Please sign in to comment.