From 180a281b26c324bd484191ebb99b875b2acebb69 Mon Sep 17 00:00:00 2001 From: Vilsonei Machado Date: Wed, 3 Jul 2024 20:29:38 -0300 Subject: [PATCH] =?UTF-8?q?-=20Corre=C3=A7=C3=A3o=20do=20funcionamento=20d?= =?UTF-8?q?a=20vari=C3=A1vel=20de=20configura=C3=A7=C3=A3o=20INSTANCE=5FEX?= =?UTF-8?q?PIRATION=5FTIME=20(arquivo=20.env)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Correção do gerenciamento de instâncias, quando havia muitas instâncias simutâneas e o QrCode expirava, a mais antiga desconectava a mais recente, mesmo quando a mais recente já estava conectada. - Remoção dos ouvintes de eventos para instâncias em memória que já não estavam sendo usadas - Correção do timeout de exclusão de instâncias não conectadas para tratar eventualidades de várias instâncias criadas ao mesmo tempo na memória --- src/config/env.config.ts | 6 +- .../controllers/instance.controller.ts | 5 +- src/whatsapp/services/monitor.service.ts | 67 +++++++++++++------ 3 files changed, 52 insertions(+), 26 deletions(-) diff --git a/src/config/env.config.ts b/src/config/env.config.ts index 3b1e20a0..e0862986 100644 --- a/src/config/env.config.ts +++ b/src/config/env.config.ts @@ -191,9 +191,9 @@ export class ConfigService { LEVEL: process.env?.LOG_LEVEL.split('|') as LogLevel[], COLOR: process.env?.LOG_COLOR === 'true', }, - INSTANCE_EXPIRATION_TIME: isBooleanString(process.env?.DEL_INSTANCE) - ? process.env.DEL_INSTANCE === 'true' - : Number.parseInt(process.env?.DEL_INSTANCE || '5'), + INSTANCE_EXPIRATION_TIME: process.env?.INSTANCE_EXPIRATION_TIME === 'false' + ? false + : Number.parseInt(process.env?.INSTANCE_EXPIRATION_TIME || '5'), GLOBAL_WEBHOOK: { URL: process.env?.WEBHOOK_GLOBAL_URL, ENABLED: process.env?.WEBHOOK_GLOBAL_ENABLED === 'true', diff --git a/src/whatsapp/controllers/instance.controller.ts b/src/whatsapp/controllers/instance.controller.ts index fd5e0823..c9989750 100644 --- a/src/whatsapp/controllers/instance.controller.ts +++ b/src/whatsapp/controllers/instance.controller.ts @@ -125,10 +125,7 @@ export class InstanceController { this.providerFiles, ); await instance.setInstanceName(instanceName); - this.waMonitor.waInstances.set(instance.instanceName, instance); - this.waMonitor.delInstanceTime(instance.instanceName); - - this.waMonitor.waInstances.set(instanceName, instance); + this.waMonitor.addInstance(instanceName, instance); } const state = instance?.connectionStatus?.state; diff --git a/src/whatsapp/services/monitor.service.ts b/src/whatsapp/services/monitor.service.ts index aa80ca8b..b0dd8cf7 100644 --- a/src/whatsapp/services/monitor.service.ts +++ b/src/whatsapp/services/monitor.service.ts @@ -75,17 +75,33 @@ export class WAMonitoringService { this.configService.get('PROVIDER'), ); + private readonly instanceDelTimeout = {}; + + public addInstance(instanceName: string, instance: WAStartupService) { + const currentInstance = this.waInstances.get(instanceName); + if (currentInstance) { + this.clearListeners(instanceName); + } + this.waInstances.set(instanceName, instance); + this.delInstanceTime(instanceName); + } + public delInstanceTime(instance: string) { const time = this.configService.get( 'INSTANCE_EXPIRATION_TIME', ); if (typeof time === 'number' && time > 0) { - setTimeout( + if (this.instanceDelTimeout[instance]) { + clearTimeout(this.instanceDelTimeout[instance]); + } + + this.instanceDelTimeout[instance] = setTimeout( () => { const ref = this.waInstances.get(instance); if (ref?.connectionStatus?.state !== 'open') { this.waInstances.delete(instance); } + delete this.instanceDelTimeout[instance]; }, 1000 * 60 * time, ); @@ -93,9 +109,7 @@ export class WAMonitoringService { } private async cleaningUp({ name }: Instance) { - this.waInstances.get(name)?.client?.ev.removeAllListeners('connection.update'); - this.waInstances.get(name)?.client?.ev.flush(); - this.waInstances.delete(name); + this.clearListeners(name); if (this.providerSession?.ENABLED) { await this.providerFiles.removeSession(name); } else { @@ -110,6 +124,16 @@ export class WAMonitoringService { }); } + private clearListeners(instanceName: string) { + try { + this.waInstances.get(instanceName)?.client?.ev.removeAllListeners('connection.update'); + this.waInstances.get(instanceName)?.client?.ev.flush(); + this.waInstances.delete(instanceName); + } catch { + this.logger.error(`Error clearing ${instanceName} instance listeners`); + } + } + public async loadInstance() { const set = async (name: string) => { const instance = await this.repository.instance.findUnique({ @@ -125,8 +149,8 @@ export class WAMonitoringService { this.providerFiles, ); await init.setInstanceName(name); + this.addInstance(init.instanceName, init); await init.connectToWhatsapp(); - this.waInstances.set(name, init); }; try { @@ -185,21 +209,26 @@ export class WAMonitoringService { private noConnection() { this.eventEmitter.on('no.connection', async (instance: Instance) => { - const del = this.configService.get( - 'INSTANCE_EXPIRATION_TIME', - ); - if (del) { - try { - this.cleaningUp(instance); - } catch (error) { - this.logger.error({ - localError: 'noConnection', - warn: 'Error deleting instance from memory.', - error, - }); - } finally { - this.logger.warn(`Instance "${instance.name}" - NOT CONNECTION`); + const waInstance = this.waInstances.get(instance.name); + if (waInstance?.connectionStatus?.state !== 'open') { + const del = this.configService.get( + 'INSTANCE_EXPIRATION_TIME', + ); + if (del) { + try { + this.cleaningUp(instance); + } catch (error) { + this.logger.error({ + localError: 'noConnection', + warn: 'Error deleting instance from memory.', + error, + }); + } finally { + this.logger.warn(`Instance "${instance.name}" - NOT CONNECTION`); + } } + } else { + this.logger.info(`Instance ${waInstance.instanceName} already connected!`); } }); }