refactor(core): Simplify webhook pubsub message handler (#11048)

This commit is contained in:
Iván Ovejero
2024-10-04 09:28:53 +02:00
committed by GitHub
parent 4b0187e7e8
commit 73a0d48073
7 changed files with 255 additions and 113 deletions

View File

@@ -1,7 +1,10 @@
import type { Redis as SingleNodeClient, Cluster as MultiNodeClient } from 'ioredis';
import debounce from 'lodash/debounce';
import { jsonParse } from 'n8n-workflow';
import { Service } from 'typedi';
import config from '@/config';
import { EventService } from '@/events/event.service';
import { Logger } from '@/logging/logger.service';
import { RedisClientService } from '@/services/redis-client.service';
@@ -21,6 +24,7 @@ export class Subscriber {
constructor(
private readonly logger: Logger,
private readonly redisClientService: RedisClientService,
private readonly eventService: EventService,
) {
// @TODO: Once this class is only ever initialized in scaling mode, throw in the next line instead.
if (config.getEnv('executions.mode') !== 'queue') return;
@@ -62,4 +66,39 @@ export class Subscriber {
}
// #endregion
// #region Commands
setCommandMessageHandler() {
const handlerFn = debounce((str: string) => {
const msg = this.parseCommandMessage(str);
if (msg) this.eventService.emit(msg.command, msg.payload);
}, 300);
this.setMessageHandler('n8n.commands', handlerFn);
}
private parseCommandMessage(str: string) {
const msg = jsonParse<PubSub.Command | null>(str, { fallbackValue: null });
if (!msg) {
this.logger.debug('Received invalid string via command channel', { message: str });
return null;
}
this.logger.debug('Received message via command channel', msg);
const queueModeId = config.getEnv('redis.queueModeId');
if (msg.senderId === queueModeId || (msg.targets && !msg.targets.includes(queueModeId))) {
this.logger.debug('Disregarding message - not for this instance', msg);
return null;
}
return msg;
}
// #endregion
}