mirror of
https://github.com/FranP-code/Baileys.git
synced 2025-10-13 00:32:22 +00:00
better cleanup
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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<void>
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
/**
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user