feat: shard#ping method

This commit is contained in:
MARCROCK22 2024-05-30 18:54:51 +00:00
parent c409628a43
commit 5338248ff8
2 changed files with 386 additions and 365 deletions

View File

@ -1,3 +1,4 @@
import { randomUUID } from 'node:crypto';
import NodeWebSocket from 'ws';
export class BaseSocket {
@ -32,6 +33,21 @@ export class BaseSocket {
return this.internal.close(...args);
}
async ping() {
if (!('ping' in this.internal)) throw new Error('Unexpected: Method ping not implemented');
return new Promise<number>(res => {
const nonce = randomUUID();
const start = performance.now();
const listener = (data: Buffer) => {
if (data.toString() !== nonce) return;
(this.internal as NodeWebSocket).removeListener('pong', listener);
res(performance.now() - start);
};
(this.internal as NodeWebSocket).on('pong', listener);
(this.internal as NodeWebSocket).ping(nonce);
});
}
get readyState() {
return this.internal.readyState;
}

View File

@ -74,6 +74,11 @@ export class Shard {
return url.href;
}
ping() {
if (!this.websocket) return Promise.resolve(Number.POSITIVE_INFINITY);
return this.websocket.ping();
}
async connect() {
await this.connectTimeout.wait();
if (this.isOpen) {