mirror of
https://github.com/Abdulazizzn/n8n-enterprise-unlocked.git
synced 2025-12-17 18:12:04 +00:00
refactor(core): Move event and telemetry handling into workers in queue mode (#7138)
# Motivation In Queue mode, finished executions would cause the main instance to always pull all execution data from the database, unflatten it and then use it to send out event log events and telemetry events, as well as required returns to Respond to Webhook nodes etc. This could cause OOM errors when the data was large, since it had to be fully unpacked and transformed on the main instance’s side, using up a lot of memory (and time). This PR attempts to limit this behaviour to only happen in those required cases where the data has to be forwarded to some waiting webhook, for example. # Changes Execution data is only required in cases, where the active execution has a `postExecutePromise` attached to it. These usually forward the data to some other endpoint (e.g. a listening webhook connection). By adding a helper `getPostExecutePromiseCount()`, we can decide that in cases where there is nothing listening at all, there is no reason to pull the data on the main instance. Previously, there would always be postExecutePromises because the telemetry events were called. Now, these have been moved into the workers, which have been given the various InternalHooks calls to their hook function arrays, so they themselves issue these telemetry and event calls. This results in all event log messages to now be logged on the worker’s event log, as well as the worker’s eventbus being the one to send out the events to destinations. The main event log does…pretty much nothing. We are not logging executions on the main event log any more, because this would require all events to be replicated 1:1 from the workers to the main instance(s) (this IS possible and implemented, see the worker’s `replicateToRedisEventLogFunction` - but it is not enabled to reduce the amount of traffic over redis). Partial events in the main log could confuse the recovery process and would result in, ironically, the recovery corrupting the execution data by considering them crashed. # Refactor I have also used the opportunity to reduce duplicate code and move some of the hook functionality into `packages/cli/src/executionLifecycleHooks/shared/sharedHookFunctions.ts` in preparation for a future full refactor of the hooks
This commit is contained in:
committed by
GitHub
parent
07a6417f0f
commit
0c6169ee22
@@ -2,13 +2,18 @@ import express from 'express';
|
||||
import http from 'http';
|
||||
import type PCancelable from 'p-cancelable';
|
||||
import { Container } from 'typedi';
|
||||
import * as os from 'os';
|
||||
|
||||
import { flags } from '@oclif/command';
|
||||
import { WorkflowExecute } from 'n8n-core';
|
||||
|
||||
import type { ExecutionStatus, IExecuteResponsePromiseData, INodeTypes, IRun } from 'n8n-workflow';
|
||||
import { Workflow, NodeOperationError, LoggerProxy, sleep, jsonParse } from 'n8n-workflow';
|
||||
import type {
|
||||
ExecutionError,
|
||||
ExecutionStatus,
|
||||
IExecuteResponsePromiseData,
|
||||
INodeTypes,
|
||||
IRun,
|
||||
} from 'n8n-workflow';
|
||||
import { Workflow, NodeOperationError, LoggerProxy, sleep } from 'n8n-workflow';
|
||||
|
||||
import * as Db from '@/Db';
|
||||
import * as ResponseHelper from '@/ResponseHelper';
|
||||
@@ -32,8 +37,7 @@ import { eventBus } from '../eventbus';
|
||||
import { RedisServicePubSubPublisher } from '../services/redis/RedisServicePubSubPublisher';
|
||||
import { RedisServicePubSubSubscriber } from '../services/redis/RedisServicePubSubSubscriber';
|
||||
import { EventMessageGeneric } from '../eventbus/EventMessageClasses/EventMessageGeneric';
|
||||
import { COMMAND_REDIS_CHANNEL } from '@/services/redis/RedisServiceHelper';
|
||||
import { type RedisServiceCommandObject } from '@/services/redis/RedisServiceCommands';
|
||||
import { getWorkerCommandReceivedHandler } from '../worker/workerCommandHandler';
|
||||
|
||||
export class Worker extends BaseCommand {
|
||||
static description = '\nStarts a n8n worker';
|
||||
@@ -179,7 +183,9 @@ export class Worker extends BaseCommand {
|
||||
fullExecutionData.mode,
|
||||
job.data.executionId,
|
||||
fullExecutionData.workflowData,
|
||||
{ retryOf: fullExecutionData.retryOf as string },
|
||||
{
|
||||
retryOf: fullExecutionData.retryOf as string,
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -193,7 +199,7 @@ export class Worker extends BaseCommand {
|
||||
);
|
||||
await additionalData.hooks.executeHookFunctions('workflowExecuteAfter', [failedExecution]);
|
||||
}
|
||||
return { success: true };
|
||||
return { success: true, error: error as ExecutionError };
|
||||
}
|
||||
|
||||
additionalData.hooks.hookFunctions.sendResponse = [
|
||||
@@ -236,6 +242,9 @@ export class Worker extends BaseCommand {
|
||||
|
||||
delete Worker.runningJobs[job.id];
|
||||
|
||||
// do NOT call workflowExecuteAfter hook here, since it is being called from processSuccessExecution()
|
||||
// already!
|
||||
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
@@ -283,7 +292,12 @@ export class Worker extends BaseCommand {
|
||||
await this.redisSubscriber.subscribeToCommandChannel();
|
||||
this.redisSubscriber.addMessageHandler(
|
||||
'WorkerCommandReceivedHandler',
|
||||
this.getWorkerCommandReceivedHandler(),
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
getWorkerCommandReceivedHandler({
|
||||
uniqueInstanceId: this.uniqueInstanceId,
|
||||
redisPublisher: this.redisPublisher,
|
||||
getRunningJobIds: () => Object.keys(Worker.runningJobs),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -464,78 +478,4 @@ export class Worker extends BaseCommand {
|
||||
async catch(error: Error) {
|
||||
await this.exitWithCrash('Worker exiting due to an error.', error);
|
||||
}
|
||||
|
||||
private getWorkerCommandReceivedHandler() {
|
||||
const { uniqueInstanceId, redisPublisher } = this;
|
||||
const getRunningJobIds = () => Object.keys(Worker.runningJobs);
|
||||
return async (channel: string, messageString: string) => {
|
||||
if (channel === COMMAND_REDIS_CHANNEL) {
|
||||
if (!messageString) return;
|
||||
let message: RedisServiceCommandObject;
|
||||
try {
|
||||
message = jsonParse<RedisServiceCommandObject>(messageString);
|
||||
} catch {
|
||||
LoggerProxy.debug(
|
||||
`Received invalid message via channel ${COMMAND_REDIS_CHANNEL}: "${messageString}"`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (message) {
|
||||
if (message.targets && !message.targets.includes(uniqueInstanceId)) {
|
||||
return; // early return if the message is not for this worker
|
||||
}
|
||||
switch (message.command) {
|
||||
case 'getStatus':
|
||||
await redisPublisher.publishToWorkerChannel({
|
||||
workerId: uniqueInstanceId,
|
||||
command: message.command,
|
||||
payload: {
|
||||
workerId: uniqueInstanceId,
|
||||
runningJobs: getRunningJobIds(),
|
||||
freeMem: os.freemem(),
|
||||
totalMem: os.totalmem(),
|
||||
uptime: process.uptime(),
|
||||
loadAvg: os.loadavg(),
|
||||
cpus: os.cpus().map((cpu) => `${cpu.model} - speed: ${cpu.speed}`),
|
||||
arch: os.arch(),
|
||||
platform: os.platform(),
|
||||
hostname: os.hostname(),
|
||||
net: Object.values(os.networkInterfaces()).flatMap(
|
||||
(interfaces) =>
|
||||
interfaces?.map((net) => `${net.family} - address: ${net.address}`) ?? '',
|
||||
),
|
||||
},
|
||||
});
|
||||
break;
|
||||
case 'getId':
|
||||
await redisPublisher.publishToWorkerChannel({
|
||||
workerId: uniqueInstanceId,
|
||||
command: message.command,
|
||||
});
|
||||
break;
|
||||
case 'restartEventBus':
|
||||
await eventBus.restart();
|
||||
await redisPublisher.publishToWorkerChannel({
|
||||
workerId: uniqueInstanceId,
|
||||
command: message.command,
|
||||
payload: {
|
||||
result: 'success',
|
||||
},
|
||||
});
|
||||
break;
|
||||
case 'stopWorker':
|
||||
// TODO: implement proper shutdown
|
||||
// await this.stopProcess();
|
||||
break;
|
||||
default:
|
||||
LoggerProxy.debug(
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
`Received unknown command via channel ${COMMAND_REDIS_CHANNEL}: "${message.command}"`,
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user