n8n
Version:
n8n Workflow Automation Tool
331 lines • 14.9 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExecutionService = exports.allowedExecutionsQueryFilterFields = exports.schemaGetExecutionsQueryFilter = void 0;
const typedi_1 = require("typedi");
const jsonschema_1 = require("jsonschema");
const n8n_workflow_1 = require("n8n-workflow");
const ActiveExecutions_1 = require("../ActiveExecutions");
const NodeTypes_1 = require("../NodeTypes");
const Queue_1 = require("../Queue");
const WorkflowRunner_1 = require("../WorkflowRunner");
const executionHelpers_1 = require("./executionHelpers");
const execution_repository_1 = require("../databases/repositories/execution.repository");
const workflow_repository_1 = require("../databases/repositories/workflow.repository");
const Logger_1 = require("../Logger");
const internal_server_error_1 = require("../errors/response-errors/internal-server.error");
const not_found_error_1 = require("../errors/response-errors/not-found.error");
const config_1 = __importDefault(require("../config"));
const WaitTracker_1 = require("../WaitTracker");
const aborted_execution_retry_error_1 = require("../errors/aborted-execution-retry.error");
exports.schemaGetExecutionsQueryFilter = {
$id: '/IGetExecutionsQueryFilter',
type: 'object',
properties: {
id: { type: 'string' },
finished: { type: 'boolean' },
mode: { type: 'string' },
retryOf: { type: 'string' },
retrySuccessId: { type: 'string' },
status: {
type: 'array',
items: { type: 'string' },
},
waitTill: { type: 'boolean' },
workflowId: { anyOf: [{ type: 'integer' }, { type: 'string' }] },
metadata: { type: 'array', items: { $ref: '#/$defs/metadata' } },
startedAfter: { type: 'date-time' },
startedBefore: { type: 'date-time' },
},
$defs: {
metadata: {
type: 'object',
required: ['key', 'value'],
properties: {
key: {
type: 'string',
},
value: { type: 'string' },
},
},
},
};
exports.allowedExecutionsQueryFilterFields = Object.keys(exports.schemaGetExecutionsQueryFilter.properties);
let ExecutionService = class ExecutionService {
constructor(logger, queue, activeExecutions, executionRepository, workflowRepository, nodeTypes, waitTracker, workflowRunner) {
this.logger = logger;
this.queue = queue;
this.activeExecutions = activeExecutions;
this.executionRepository = executionRepository;
this.workflowRepository = workflowRepository;
this.nodeTypes = nodeTypes;
this.waitTracker = waitTracker;
this.workflowRunner = workflowRunner;
this.isRegularMode = config_1.default.getEnv('executions.mode') === 'regular';
}
async findOne(req, sharedWorkflowIds) {
if (!sharedWorkflowIds.length)
return undefined;
const { id: executionId } = req.params;
const execution = await this.executionRepository.findIfShared(executionId, sharedWorkflowIds);
if (!execution) {
this.logger.info('Attempt to read execution was blocked due to insufficient permissions', {
userId: req.user.id,
executionId,
});
return undefined;
}
if (!execution.status) {
const { data, workflowData, ...rest } = execution;
n8n_workflow_1.ErrorReporterProxy.info('Detected `null` execution status', { extra: { execution: rest } });
execution.status = (0, executionHelpers_1.getStatusUsingPreviousExecutionStatusMethod)(execution);
}
return execution;
}
async retry(req, sharedWorkflowIds) {
const { id: executionId } = req.params;
const execution = await this.executionRepository.findWithUnflattenedData(executionId, sharedWorkflowIds);
if (!execution) {
this.logger.info('Attempt to retry an execution was blocked due to insufficient permissions', {
userId: req.user.id,
executionId,
});
throw new not_found_error_1.NotFoundError(`The execution with the ID "${executionId}" does not exist.`);
}
if (!execution.data.executionData)
throw new aborted_execution_retry_error_1.AbortedExecutionRetryError();
if (execution.finished) {
throw new n8n_workflow_1.ApplicationError('The execution succeeded, so it cannot be retried.');
}
const executionMode = 'retry';
execution.workflowData.active = false;
const data = {
executionMode,
executionData: execution.data,
retryOf: req.params.id,
workflowData: execution.workflowData,
userId: req.user.id,
};
const { lastNodeExecuted } = data.executionData.resultData;
if (lastNodeExecuted) {
delete data.executionData.resultData.error;
const { length } = data.executionData.resultData.runData[lastNodeExecuted];
if (length > 0 &&
data.executionData.resultData.runData[lastNodeExecuted][length - 1].error !== undefined) {
data.executionData.resultData.runData[lastNodeExecuted].pop();
}
}
if (req.body.loadWorkflow) {
const workflowId = execution.workflowData.id;
const workflowData = (await this.workflowRepository.findOneBy({
id: workflowId,
}));
if (workflowData === undefined) {
throw new n8n_workflow_1.ApplicationError('Workflow could not be found and so the data not be loaded for the retry.', { extra: { workflowId } });
}
data.workflowData = workflowData;
const workflowInstance = new n8n_workflow_1.Workflow({
id: workflowData.id,
name: workflowData.name,
nodes: workflowData.nodes,
connections: workflowData.connections,
active: false,
nodeTypes: this.nodeTypes,
staticData: undefined,
settings: workflowData.settings,
});
for (const stack of data.executionData.executionData.nodeExecutionStack) {
const node = workflowInstance.getNode(stack.node.name);
if (node === null) {
this.logger.error('Failed to retry an execution because a node could not be found', {
userId: req.user.id,
executionId,
nodeName: stack.node.name,
});
throw new n8n_workflow_1.WorkflowOperationError(`Could not find the node "${stack.node.name}" in workflow. It probably got deleted or renamed. Without it the workflow can sadly not be retried.`);
}
stack.node = node;
}
}
const retriedExecutionId = await this.workflowRunner.run(data);
const executionData = await this.activeExecutions.getPostExecutePromise(retriedExecutionId);
if (!executionData) {
throw new n8n_workflow_1.ApplicationError('The retry did not start for an unknown reason.');
}
return !!executionData.finished;
}
async delete(req, sharedWorkflowIds) {
const { deleteBefore, ids, filters: requestFiltersRaw } = req.body;
let requestFilters;
if (requestFiltersRaw) {
try {
Object.keys(requestFiltersRaw).map((key) => {
if (!exports.allowedExecutionsQueryFilterFields.includes(key))
delete requestFiltersRaw[key];
});
if ((0, jsonschema_1.validate)(requestFiltersRaw, exports.schemaGetExecutionsQueryFilter).valid) {
requestFilters = requestFiltersRaw;
}
}
catch (error) {
throw new internal_server_error_1.InternalServerError('Parameter "filter" contained invalid JSON string.');
}
}
return await this.executionRepository.deleteExecutionsByFilter(requestFilters, sharedWorkflowIds, {
deleteBefore,
ids,
});
}
async createErrorExecution(error, node, workflowData, workflow, mode) {
var _a;
const saveDataErrorExecutionDisabled = ((_a = workflowData === null || workflowData === void 0 ? void 0 : workflowData.settings) === null || _a === void 0 ? void 0 : _a.saveDataErrorExecution) === 'none';
if (saveDataErrorExecutionDisabled)
return;
const executionData = {
startData: {
destinationNode: node.name,
runNodeFilter: [node.name],
},
executionData: {
contextData: {},
metadata: {},
nodeExecutionStack: [
{
node,
data: {
main: [
[
{
json: {},
pairedItem: {
item: 0,
},
},
],
],
},
source: null,
},
],
waitingExecution: {},
waitingExecutionSource: {},
},
resultData: {
runData: {
[node.name]: [
{
startTime: 0,
executionTime: 0,
error,
source: [],
},
],
},
error,
lastNodeExecuted: node.name,
},
};
const fullExecutionData = {
data: executionData,
mode,
finished: false,
startedAt: new Date(),
workflowData,
workflowId: workflow.id,
stoppedAt: new Date(),
status: 'error',
};
await this.executionRepository.createNewExecution(fullExecutionData);
}
async findRangeWithCount(query) {
const results = await this.executionRepository.findManyByRangeQuery(query);
if (config_1.default.getEnv('database.type') === 'postgresdb') {
const liveRows = await this.executionRepository.getLiveExecutionRowsOnPostgres();
if (liveRows === -1)
return { count: -1, estimated: false, results };
if (liveRows > 100000) {
return { count: liveRows, estimated: true, results };
}
}
const { range: _, ...countQuery } = query;
const count = await this.executionRepository.fetchCount({ ...countQuery, kind: 'count' });
return { results, count, estimated: false };
}
async findAllRunningAndLatest(query) {
const currentlyRunningStatuses = ['new', 'running'];
const allStatuses = new Set(n8n_workflow_1.ExecutionStatusList);
currentlyRunningStatuses.forEach((status) => allStatuses.delete(status));
const notRunningStatuses = Array.from(allStatuses);
const [activeResult, finishedResult] = await Promise.all([
this.findRangeWithCount({ ...query, status: currentlyRunningStatuses }),
this.findRangeWithCount({
...query,
status: notRunningStatuses,
order: { stoppedAt: 'DESC' },
}),
]);
return {
results: activeResult.results.concat(finishedResult.results),
count: finishedResult.count,
estimated: finishedResult.estimated,
};
}
async stop(executionId) {
const execution = await this.executionRepository.findOneBy({ id: executionId });
if (!execution)
throw new not_found_error_1.NotFoundError('Execution not found');
const stopResult = await this.activeExecutions.stopExecution(execution.id);
if (stopResult)
return this.toExecutionStopResult(execution);
if (this.isRegularMode) {
return await this.waitTracker.stopExecution(execution.id);
}
try {
return await this.waitTracker.stopExecution(execution.id);
}
catch {
}
const activeJobs = await this.queue.getJobs(['active', 'waiting']);
const job = activeJobs.find(({ data }) => data.executionId === execution.id);
if (job) {
await this.queue.stopJob(job);
}
else {
this.logger.debug('Job to stop no longer in queue', { jobId: execution.id });
}
return this.toExecutionStopResult(execution);
}
toExecutionStopResult(execution) {
return {
mode: execution.mode,
startedAt: new Date(execution.startedAt),
stoppedAt: execution.stoppedAt ? new Date(execution.stoppedAt) : undefined,
finished: execution.finished,
status: execution.status,
};
}
};
exports.ExecutionService = ExecutionService;
exports.ExecutionService = ExecutionService = __decorate([
(0, typedi_1.Service)(),
__metadata("design:paramtypes", [Logger_1.Logger,
Queue_1.Queue,
ActiveExecutions_1.ActiveExecutions,
execution_repository_1.ExecutionRepository,
workflow_repository_1.WorkflowRepository,
NodeTypes_1.NodeTypes,
WaitTracker_1.WaitTracker,
WorkflowRunner_1.WorkflowRunner])
], ExecutionService);
//# sourceMappingURL=execution.service.js.map
;