diff --git a/src/Tests/Tests.Connect.ts b/src/Tests/Tests.Connect.ts index 71a8df1..aad4be1 100644 --- a/src/Tests/Tests.Connect.ts +++ b/src/Tests/Tests.Connect.ts @@ -40,6 +40,28 @@ describe('Test Connect', () => { conn.close() auth = conn.base64EncodedAuthInfo() }) + /** + * the idea is to test closing the connection at multiple points in the connection + * and see if the library cleans up resources correctly + */ + it('should cleanup correctly', async () => { + const conn = new WAConnection() + conn.loadAuthInfo ('./auth_info.json') + + let timeout = 0.1 + + while (true) { + setTimeout (() => conn.close(), timeout*1000) + try { + await conn.connect () + break + } catch (error) { + + } + // exponentially increase the timeout disconnect + timeout *= 2 + } + }) it('should reconnect', async () => { const conn = new WAConnection() await conn diff --git a/src/WAConnection/3.Connect.ts b/src/WAConnection/3.Connect.ts index 7c52781..6205e7b 100644 --- a/src/WAConnection/3.Connect.ts +++ b/src/WAConnection/3.Connect.ts @@ -23,7 +23,6 @@ export class WAConnection extends Base { .then (() => this.log(`connected to WhatsApp Web server, authenticating via ${options.reconnectID ? 'reconnect' : 'takeover'}`, MessageLogLevel.info)) .then (() => this.authenticate(options?.reconnectID)) .then (() => { - this.startKeepAliveRequest() this.conn.removeAllListeners ('error') this.conn.removeAllListeners ('close') this.conn.on ('close', () => this.unexpectedDisconnect (DisconnectReason.close)) @@ -36,6 +35,8 @@ export class WAConnection extends Base { throw err }) as Promise + this.on ('close', cancel) + try { const tasks = [promise] @@ -49,6 +50,7 @@ export class WAConnection extends Base { this.emit ('open') + this.startKeepAliveRequest() this.registerPhoneConnectionPoll () this.releasePendingRequests () @@ -59,8 +61,13 @@ export class WAConnection extends Base { const loggedOut = error instanceof BaileysError && error.status === 401 if (loggedOut && this.cancelReconnect) this.cancelReconnect () - this.closeInternal (loggedOut ? 'invalid_session' : error.message) + if ((this.state as string) !== 'close') { + this.closeInternal (loggedOut ? 'invalid_session' : error.message) + } + throw error + } finally { + this.off ('close', cancel) } } /** diff --git a/src/WAConnection/Utils.ts b/src/WAConnection/Utils.ts index 3065096..672455c 100644 --- a/src/WAConnection/Utils.ts +++ b/src/WAConnection/Utils.ts @@ -130,8 +130,10 @@ export const openWebSocketConnection = (timeoutMs: number, retryOnNetworkError: while (!cancelled) { try { const ws = await newWS() - if (!cancelled) return ws - break + if (cancelled) { + ws.close () + break + } else return ws } catch (error) { if (!retryOnNetworkError) throw error await delay (1000)