File size: 19,907 Bytes
aec3094 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | import { Logger } from '@n8n/backend-common';
import { ExecutionRepository } from '@n8n/db';
import { LifecycleMetadata } from '@n8n/decorators';
import { Container, Service } from '@n8n/di';
import { stringify } from 'flatted';
import { ErrorReporter, InstanceSettings, ExecutionLifecycleHooks } from 'n8n-core';
import type {
IWorkflowBase,
WorkflowExecuteMode,
IWorkflowExecutionDataProcess,
} from 'n8n-workflow';
import { EventService } from '@/events/event.service';
import { ExternalHooks } from '@/external-hooks';
import { Push } from '@/push';
import { WorkflowStatisticsService } from '@/services/workflow-statistics.service';
import { isWorkflowIdValid } from '@/utils';
import { WorkflowStaticDataService } from '@/workflows/workflow-static-data.service';
// eslint-disable-next-line import/no-cycle
import { executeErrorWorkflow } from './execute-error-workflow';
import { restoreBinaryDataId } from './restore-binary-data-id';
import { saveExecutionProgress } from './save-execution-progress';
import {
determineFinalExecutionStatus,
prepareExecutionDataForDbUpdate,
updateExistingExecution,
} from './shared/shared-hook-functions';
import { type ExecutionSaveSettings, toSaveSettings } from './to-save-settings';
@Service()
class ModulesHooksRegistry {
addHooks(hooks: ExecutionLifecycleHooks) {
const handlers = Container.get(LifecycleMetadata).getHandlers();
for (const { handlerClass, methodName, eventName } of handlers) {
const instance = Container.get(handlerClass);
switch (eventName) {
case 'workflowExecuteAfter':
hooks.addHandler(eventName, async function (runData, newStaticData) {
const context = {
type: 'workflowExecuteAfter',
workflow: this.workflowData,
runData,
newStaticData,
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/return-await
return await instance[methodName].call(instance, context);
});
break;
case 'nodeExecuteBefore':
hooks.addHandler(eventName, async function (nodeName, taskData) {
const context = {
type: 'nodeExecuteBefore',
workflow: this.workflowData,
nodeName,
taskData,
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/return-await
return await instance[methodName].call(instance, context);
});
break;
case 'nodeExecuteAfter':
hooks.addHandler(eventName, async function (nodeName, taskData, executionData) {
const context = {
type: 'nodeExecuteAfter',
workflow: this.workflowData,
nodeName,
taskData,
executionData,
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/return-await
return await instance[methodName].call(instance, context);
});
break;
case 'workflowExecuteBefore':
hooks.addHandler(eventName, async function (workflowInstance, executionData) {
const context = {
type: 'workflowExecuteBefore',
workflow: this.workflowData,
workflowInstance,
executionData,
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/return-await
return await instance[methodName].call(instance, context);
});
break;
}
}
}
}
type HooksSetupParameters = {
saveSettings: ExecutionSaveSettings;
pushRef?: string;
retryOf?: string;
};
function hookFunctionsWorkflowEvents(hooks: ExecutionLifecycleHooks, userId?: string) {
const eventService = Container.get(EventService);
hooks.addHandler('workflowExecuteBefore', function () {
const { executionId, workflowData } = this;
eventService.emit('workflow-pre-execute', { executionId, data: workflowData });
});
hooks.addHandler('workflowExecuteAfter', function (runData) {
if (runData.status === 'waiting') return;
const { executionId, workflowData: workflow } = this;
if (runData.data.startData) {
const originalDestination = runData.data.startData.originalDestinationNode;
if (originalDestination) {
runData.data.startData.destinationNode = originalDestination;
runData.data.startData.originalDestinationNode = undefined;
}
}
eventService.emit('workflow-post-execute', { executionId, runData, workflow, userId });
});
}
function hookFunctionsNodeEvents(hooks: ExecutionLifecycleHooks) {
const eventService = Container.get(EventService);
hooks.addHandler('nodeExecuteBefore', function (nodeName) {
const { executionId, workflowData: workflow } = this;
const node = workflow.nodes.find((n) => n.name === nodeName);
eventService.emit('node-pre-execute', {
executionId,
workflow,
nodeId: node?.id,
nodeName,
nodeType: node?.type,
});
});
hooks.addHandler('nodeExecuteAfter', function (nodeName) {
const { executionId, workflowData: workflow } = this;
const node = workflow.nodes.find((n) => n.name === nodeName);
eventService.emit('node-post-execute', {
executionId,
workflow,
nodeId: node?.id,
nodeName,
nodeType: node?.type,
});
});
}
/**
* Returns hook functions to push data to Editor-UI
*/
function hookFunctionsPush(
hooks: ExecutionLifecycleHooks,
{ pushRef, retryOf }: HooksSetupParameters,
) {
if (!pushRef) return;
const logger = Container.get(Logger);
const pushInstance = Container.get(Push);
hooks.addHandler('nodeExecuteBefore', function (nodeName, data) {
const { executionId } = this;
// Push data to session which started workflow before each
// node which starts rendering
logger.debug(`Executing hook on node "${nodeName}" (hookFunctionsPush)`, {
executionId,
pushRef,
workflowId: this.workflowData.id,
});
pushInstance.send(
{ type: 'nodeExecuteBefore', data: { executionId, nodeName, data } },
pushRef,
);
});
hooks.addHandler('nodeExecuteAfter', function (nodeName, data) {
const { executionId } = this;
// Push data to session which started workflow after each rendered node
logger.debug(`Executing hook on node "${nodeName}" (hookFunctionsPush)`, {
executionId,
pushRef,
workflowId: this.workflowData.id,
});
pushInstance.send({ type: 'nodeExecuteAfter', data: { executionId, nodeName, data } }, pushRef);
});
hooks.addHandler('workflowExecuteBefore', function (_workflow, data) {
const { executionId } = this;
const { id: workflowId, name: workflowName } = this.workflowData;
logger.debug('Executing hook (hookFunctionsPush)', {
executionId,
pushRef,
workflowId,
});
// Push data to session which started the workflow
pushInstance.send(
{
type: 'executionStarted',
data: {
executionId,
mode: this.mode,
startedAt: new Date(),
retryOf,
workflowId,
workflowName,
flattedRunData: data?.resultData.runData
? stringify(data.resultData.runData)
: stringify({}),
},
},
pushRef,
);
});
hooks.addHandler('workflowExecuteAfter', function (fullRunData) {
const { executionId } = this;
const { id: workflowId } = this.workflowData;
logger.debug('Executing hook (hookFunctionsPush)', {
executionId,
pushRef,
workflowId,
});
const { status } = fullRunData;
if (status === 'waiting') {
pushInstance.send({ type: 'executionWaiting', data: { executionId } }, pushRef);
} else {
const rawData = stringify(fullRunData.data);
pushInstance.send(
{ type: 'executionFinished', data: { executionId, workflowId, status, rawData } },
pushRef,
);
}
});
}
function hookFunctionsExternalHooks(hooks: ExecutionLifecycleHooks) {
const externalHooks = Container.get(ExternalHooks);
hooks.addHandler('workflowExecuteBefore', async function (workflow) {
await externalHooks.run('workflow.preExecute', [workflow, this.mode]);
});
hooks.addHandler('workflowExecuteAfter', async function (fullRunData) {
await externalHooks.run('workflow.postExecute', [
fullRunData,
this.workflowData,
this.executionId,
]);
});
}
function hookFunctionsSaveProgress(
hooks: ExecutionLifecycleHooks,
{ saveSettings }: HooksSetupParameters,
) {
if (!saveSettings.progress) return;
hooks.addHandler('nodeExecuteAfter', async function (nodeName, data, executionData) {
await saveExecutionProgress(
this.workflowData.id,
this.executionId,
nodeName,
data,
executionData,
);
});
}
/** This should ideally be added before any other `workflowExecuteAfter` hook to ensure all hooks get the same execution status */
function hookFunctionsFinalizeExecutionStatus(hooks: ExecutionLifecycleHooks) {
hooks.addHandler('workflowExecuteAfter', (fullRunData) => {
fullRunData.status = determineFinalExecutionStatus(fullRunData);
});
}
function hookFunctionsStatistics(hooks: ExecutionLifecycleHooks) {
const workflowStatisticsService = Container.get(WorkflowStatisticsService);
hooks.addHandler('nodeFetchedData', (workflowId, node) => {
workflowStatisticsService.emit('nodeFetchedData', { workflowId, node });
});
}
/**
* Returns hook functions to save workflow execution and call error workflow
*/
function hookFunctionsSave(
hooks: ExecutionLifecycleHooks,
{ pushRef, retryOf, saveSettings }: HooksSetupParameters,
) {
const logger = Container.get(Logger);
const errorReporter = Container.get(ErrorReporter);
const executionRepository = Container.get(ExecutionRepository);
const workflowStaticDataService = Container.get(WorkflowStaticDataService);
const workflowStatisticsService = Container.get(WorkflowStatisticsService);
hooks.addHandler('workflowExecuteAfter', async function (fullRunData, newStaticData) {
logger.debug('Executing hook (hookFunctionsSave)', {
executionId: this.executionId,
workflowId: this.workflowData.id,
});
await restoreBinaryDataId(fullRunData, this.executionId, this.mode);
const isManualMode = this.mode === 'manual';
try {
if (!isManualMode && isWorkflowIdValid(this.workflowData.id) && newStaticData) {
// Workflow is saved so update in database
try {
await workflowStaticDataService.saveStaticDataById(this.workflowData.id, newStaticData);
} catch (e) {
errorReporter.error(e);
logger.error(
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
`There was a problem saving the workflow with id "${this.workflowData.id}" to save changed staticData: "${e.message}" (hookFunctionsSave)`,
{ executionId: this.executionId, workflowId: this.workflowData.id },
);
}
}
if (isManualMode && !saveSettings.manual && !fullRunData.waitTill) {
/**
* When manual executions are not being saved, we only soft-delete
* the execution so that the user can access its binary data
* while building their workflow.
*
* The manual execution and its binary data will be hard-deleted
* on the next pruning cycle after the grace period set by
* `EXECUTIONS_DATA_HARD_DELETE_BUFFER`.
*/
await executionRepository.softDelete(this.executionId);
return;
}
const shouldNotSave =
(fullRunData.status === 'success' && !saveSettings.success) ||
(fullRunData.status !== 'success' && !saveSettings.error);
if (shouldNotSave && !fullRunData.waitTill && !isManualMode) {
executeErrorWorkflow(this.workflowData, fullRunData, this.mode, this.executionId, retryOf);
await executionRepository.hardDelete({
workflowId: this.workflowData.id,
executionId: this.executionId,
});
return;
}
// Although it is treated as IWorkflowBase here, it's being instantiated elsewhere with properties that may be sensitive
// As a result, we should create an IWorkflowBase object with only the data we want to save in it.
const fullExecutionData = prepareExecutionDataForDbUpdate({
runData: fullRunData,
workflowData: this.workflowData,
workflowStatusFinal: fullRunData.status,
retryOf,
});
// When going into the waiting state, store the pushRef in the execution-data
if (fullRunData.waitTill && isManualMode) {
fullExecutionData.data.pushRef = pushRef;
}
await updateExistingExecution({
executionId: this.executionId,
workflowId: this.workflowData.id,
executionData: fullExecutionData,
});
if (!isManualMode) {
executeErrorWorkflow(this.workflowData, fullRunData, this.mode, this.executionId, retryOf);
}
} finally {
workflowStatisticsService.emit('workflowExecutionCompleted', {
workflowData: this.workflowData,
fullRunData,
});
}
});
}
/**
* Returns hook functions to save workflow execution and call error workflow
* for running with queues. Manual executions should never run on queues as
* they are always executed in the main process.
*/
function hookFunctionsSaveWorker(
hooks: ExecutionLifecycleHooks,
{ pushRef, retryOf }: HooksSetupParameters,
) {
const logger = Container.get(Logger);
const errorReporter = Container.get(ErrorReporter);
const workflowStaticDataService = Container.get(WorkflowStaticDataService);
const workflowStatisticsService = Container.get(WorkflowStatisticsService);
hooks.addHandler('workflowExecuteAfter', async function (fullRunData, newStaticData) {
logger.debug('Executing hook (hookFunctionsSaveWorker)', {
executionId: this.executionId,
workflowId: this.workflowData.id,
});
const isManualMode = this.mode === 'manual';
try {
if (!isManualMode && isWorkflowIdValid(this.workflowData.id) && newStaticData) {
// Workflow is saved so update in database
try {
await workflowStaticDataService.saveStaticDataById(this.workflowData.id, newStaticData);
} catch (e) {
errorReporter.error(e);
logger.error(
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
`There was a problem saving the workflow with id "${this.workflowData.id}" to save changed staticData: "${e.message}" (workflowExecuteAfter)`,
{ workflowId: this.workflowData.id },
);
}
}
if (!isManualMode && fullRunData.status !== 'success' && fullRunData.status !== 'waiting') {
executeErrorWorkflow(this.workflowData, fullRunData, this.mode, this.executionId, retryOf);
}
// Although it is treated as IWorkflowBase here, it's being instantiated elsewhere with properties that may be sensitive
// As a result, we should create an IWorkflowBase object with only the data we want to save in it.
const fullExecutionData = prepareExecutionDataForDbUpdate({
runData: fullRunData,
workflowData: this.workflowData,
workflowStatusFinal: fullRunData.status,
retryOf,
});
// When going into the waiting state, store the pushRef in the execution-data
if (fullRunData.waitTill && isManualMode) {
fullExecutionData.data.pushRef = pushRef;
}
await updateExistingExecution({
executionId: this.executionId,
workflowId: this.workflowData.id,
executionData: fullExecutionData,
});
} finally {
workflowStatisticsService.emit('workflowExecutionCompleted', {
workflowData: this.workflowData,
fullRunData,
});
}
});
}
/**
* Returns ExecutionLifecycleHooks instance for running integrated workflows
* (Workflows which get started inside of another workflow)
*/
export function getLifecycleHooksForSubExecutions(
mode: WorkflowExecuteMode,
executionId: string,
workflowData: IWorkflowBase,
userId?: string,
): ExecutionLifecycleHooks {
const hooks = new ExecutionLifecycleHooks(mode, executionId, workflowData);
const saveSettings = toSaveSettings(workflowData.settings);
hookFunctionsWorkflowEvents(hooks, userId);
hookFunctionsNodeEvents(hooks);
hookFunctionsFinalizeExecutionStatus(hooks);
hookFunctionsSave(hooks, { saveSettings });
hookFunctionsSaveProgress(hooks, { saveSettings });
hookFunctionsStatistics(hooks);
hookFunctionsExternalHooks(hooks);
return hooks;
}
/**
* Returns ExecutionLifecycleHooks instance for worker in scaling mode.
*/
export function getLifecycleHooksForScalingWorker(
data: IWorkflowExecutionDataProcess,
executionId: string,
): ExecutionLifecycleHooks {
const { pushRef, retryOf, executionMode, workflowData } = data;
const hooks = new ExecutionLifecycleHooks(executionMode, executionId, workflowData);
const saveSettings = toSaveSettings(workflowData.settings);
const optionalParameters = { pushRef, retryOf: retryOf ?? undefined, saveSettings };
hookFunctionsNodeEvents(hooks);
hookFunctionsFinalizeExecutionStatus(hooks);
hookFunctionsSaveWorker(hooks, optionalParameters);
hookFunctionsSaveProgress(hooks, optionalParameters);
hookFunctionsStatistics(hooks);
hookFunctionsExternalHooks(hooks);
if (executionMode === 'manual' && Container.get(InstanceSettings).isWorker) {
hookFunctionsPush(hooks, optionalParameters);
}
Container.get(ModulesHooksRegistry).addHooks(hooks);
return hooks;
}
/**
* Returns ExecutionLifecycleHooks instance for main process in scaling mode.
*/
export function getLifecycleHooksForScalingMain(
data: IWorkflowExecutionDataProcess,
executionId: string,
): ExecutionLifecycleHooks {
const { pushRef, retryOf, executionMode, workflowData, userId } = data;
const hooks = new ExecutionLifecycleHooks(executionMode, executionId, workflowData);
const saveSettings = toSaveSettings(workflowData.settings);
const optionalParameters = { pushRef, retryOf: retryOf ?? undefined, saveSettings };
const executionRepository = Container.get(ExecutionRepository);
hookFunctionsWorkflowEvents(hooks, userId);
hookFunctionsSaveProgress(hooks, optionalParameters);
hookFunctionsExternalHooks(hooks);
hookFunctionsFinalizeExecutionStatus(hooks);
hooks.addHandler('workflowExecuteAfter', async function (fullRunData) {
// Don't delete executions before they are finished
if (!fullRunData.finished) return;
const isManualMode = this.mode === 'manual';
if (isManualMode && !saveSettings.manual && !fullRunData.waitTill) {
/**
* When manual executions are not being saved, we only soft-delete
* the execution so that the user can access its binary data
* while building their workflow.
*
* The manual execution and its binary data will be hard-deleted
* on the next pruning cycle after the grace period set by
* `EXECUTIONS_DATA_HARD_DELETE_BUFFER`.
*/
await executionRepository.softDelete(this.executionId);
return;
}
const shouldNotSave =
(fullRunData.status === 'success' && !saveSettings.success) ||
(fullRunData.status !== 'success' && !saveSettings.error);
if (!isManualMode && shouldNotSave && !fullRunData.waitTill) {
await executionRepository.hardDelete({
workflowId: this.workflowData.id,
executionId: this.executionId,
});
}
});
// When running with worker mode, main process executes
// Only workflowExecuteBefore + workflowExecuteAfter
// So to avoid confusion, we are removing other hooks.
hooks.handlers.nodeExecuteBefore = [];
hooks.handlers.nodeExecuteAfter = [];
Container.get(ModulesHooksRegistry).addHooks(hooks);
return hooks;
}
/**
* Returns ExecutionLifecycleHooks instance for the main process in regular mode
*/
export function getLifecycleHooksForRegularMain(
data: IWorkflowExecutionDataProcess,
executionId: string,
): ExecutionLifecycleHooks {
const { pushRef, retryOf, executionMode, workflowData, userId } = data;
const hooks = new ExecutionLifecycleHooks(executionMode, executionId, workflowData);
const saveSettings = toSaveSettings(workflowData.settings);
const optionalParameters = { pushRef, retryOf: retryOf ?? undefined, saveSettings };
hookFunctionsWorkflowEvents(hooks, userId);
hookFunctionsNodeEvents(hooks);
hookFunctionsFinalizeExecutionStatus(hooks);
hookFunctionsSave(hooks, optionalParameters);
hookFunctionsPush(hooks, optionalParameters);
hookFunctionsSaveProgress(hooks, optionalParameters);
hookFunctionsStatistics(hooks);
hookFunctionsExternalHooks(hooks);
Container.get(ModulesHooksRegistry).addHooks(hooks);
return hooks;
}
|