diff --git a/src/events/EventClient.ts b/src/events/EventClient.ts index 7f779bd5..c151ac4b 100644 --- a/src/events/EventClient.ts +++ b/src/events/EventClient.ts @@ -36,6 +36,12 @@ export interface EventClientOptions { * @default 10 */ pongTimeout: number; + + /** + * Maximum time in seconds between init and first message + * @default 10 + */ + connectTimeout: number; } /** @@ -67,6 +73,7 @@ export class EventClient extends EventEmitter< #socket: WebSocket | undefined; #heartbeatIntervalReference: number | undefined; #pongTimeoutReference: number | undefined; + #connectTimeoutReference: number | undefined; #lastError: any; @@ -89,6 +96,7 @@ export class EventClient extends EventEmitter< this.options = { heartbeatInterval: 30, pongTimeout: 10, + connectTimeout: 10, debug: false, ...options, }; @@ -123,6 +131,11 @@ export class EventClient extends EventEmitter< this.#lastError = undefined; this.setState(ConnectionState.Connecting); + this.#connectTimeoutReference = setTimeout( + () => this.disconnect(), + this.options.pongTimeout * 1e3 + ) as never; + this.#socket = new WebSocket( `${uri}?version=${this.#protocolVersion}&format=${ this.#transportFormat @@ -145,6 +158,8 @@ export class EventClient extends EventEmitter< }; this.#socket.onmessage = (event) => { + clearInterval(this.#connectTimeoutReference); + if (this.#transportFormat === "json") { if (typeof event.data === "string") { this.handle(JSON.parse(event.data)); @@ -156,6 +171,7 @@ export class EventClient extends EventEmitter< this.#socket.onclose = () => { if (closed) return; closed = true; + this.setState(ConnectionState.Disconnected); this.disconnect(); }; } @@ -166,10 +182,11 @@ export class EventClient extends EventEmitter< disconnect() { if (!this.#socket) return; clearInterval(this.#heartbeatIntervalReference); + clearInterval(this.#connectTimeoutReference); + clearInterval(this.#pongTimeoutReference); const socket = this.#socket; this.#socket = undefined; socket.close(); - this.setState(ConnectionState.Disconnected); } /** diff --git a/src/events/v1.ts b/src/events/v1.ts index a53c1ad2..59463631 100644 --- a/src/events/v1.ts +++ b/src/events/v1.ts @@ -18,8 +18,8 @@ import type { User, } from "revolt-api"; -import { Client } from "../index.js"; import { hydrate } from "../hydration/index.js"; +import { Client } from "../index.js"; /** * Version 1 of the events protocol @@ -255,6 +255,8 @@ export async function handleEvent( event.author && event.author != "00000000000000000000000000" && !event.webhook && + // TODO: this is causing a lot of extra requests! + // usually 2 extra requests before a message can come through!! client.options.eagerFetching ) { await client.users.fetch(event.author);