From b00971105883077f2932c9bddff989b77aa2ad72 Mon Sep 17 00:00:00 2001 From: Aleksander Nicacio da Silva Date: Fri, 29 Nov 2024 18:16:23 -0300 Subject: [PATCH] refactor: Omnichannel queue starting multiple times due to race condition --- .../server/services/omnichannel/queue.ts | 23 ++++++++++++------- .../server/services/omnichannel/service.ts | 6 ++++- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/apps/meteor/server/services/omnichannel/queue.ts b/apps/meteor/server/services/omnichannel/queue.ts index 8db6eedd386b..492468ec5821 100644 --- a/apps/meteor/server/services/omnichannel/queue.ts +++ b/apps/meteor/server/services/omnichannel/queue.ts @@ -15,6 +15,8 @@ export class OmnichannelQueue implements IOmnichannelQueue { private queues: (string | undefined)[] = []; + private lock = Promise.resolve(); + private delay() { const timeout = settings.get('Omnichannel_queue_delay_timeout') ?? 5; return timeout < 1 ? DEFAULT_RACE_TIMEOUT : timeout * 1000; @@ -25,16 +27,20 @@ export class OmnichannelQueue implements IOmnichannelQueue { } async start() { - if (this.running) { - return; - } + this.lock = this.lock.then(async () => { + if (this.running) { + return; + } + + const activeQueues = await this.getActiveQueues(); + queueLogger.debug(`Active queues: ${activeQueues.length}`); + this.running = true; - const activeQueues = await this.getActiveQueues(); - queueLogger.debug(`Active queues: ${activeQueues.length}`); - this.running = true; + queueLogger.info('Service started'); + await this.execute(); + }); - queueLogger.info('Service started'); - return this.execute(); + return this.lock; } async stop() { @@ -45,6 +51,7 @@ export class OmnichannelQueue implements IOmnichannelQueue { await LivechatInquiry.unlockAll(); this.running = false; + this.lock = Promise.resolve(); queueLogger.info('Service stopped'); } diff --git a/apps/meteor/server/services/omnichannel/service.ts b/apps/meteor/server/services/omnichannel/service.ts index e5b21f4aae97..ccfe2026b2ba 100644 --- a/apps/meteor/server/services/omnichannel/service.ts +++ b/apps/meteor/server/services/omnichannel/service.ts @@ -33,7 +33,11 @@ export class OmnichannelService extends ServiceClassInternal implements IOmnicha } async started() { - settings.watchMultiple(['Livechat_enabled', 'Livechat_Routing_Method'], () => { + settings.watch('Livechat_enabled', (enabled) => { + void (enabled && RoutingManager.isMethodSet() ? this.queueWorker.shouldStart() : this.queueWorker.stop()); + }); + + settings.watch('Livechat_Routing_Method', async () => { this.queueWorker.shouldStart(); });