refactor(core): Move methods from WorkflowHelpers into various workflow services (no-changelog) (#8348)
This commit is contained in:
committed by
GitHub
parent
ab52aaf7e9
commit
7cdbb424e3
@@ -1,30 +1,29 @@
|
||||
import * as WorkflowHelpers from '@/WorkflowHelpers';
|
||||
import { Service } from 'typedi';
|
||||
import omit from 'lodash/omit';
|
||||
import { ApplicationError, NodeOperationError } from 'n8n-workflow';
|
||||
|
||||
import type { CredentialsEntity } from '@db/entities/CredentialsEntity';
|
||||
import type { User } from '@db/entities/User';
|
||||
import type { WorkflowEntity } from '@db/entities/WorkflowEntity';
|
||||
import { CredentialsRepository } from '@db/repositories/credentials.repository';
|
||||
import { WorkflowRepository } from '@db/repositories/workflow.repository';
|
||||
import { SharedWorkflowRepository } from '@db/repositories/sharedWorkflow.repository';
|
||||
import { CredentialsService } from '@/credentials/credentials.service';
|
||||
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
|
||||
import { NotFoundError } from '@/errors/response-errors/not-found.error';
|
||||
import { Logger } from '@/Logger';
|
||||
import type {
|
||||
CredentialUsedByWorkflow,
|
||||
WorkflowWithSharingsAndCredentials,
|
||||
} from './workflows.types';
|
||||
import { CredentialsService } from '@/credentials/credentials.service';
|
||||
import { ApplicationError, NodeOperationError } from 'n8n-workflow';
|
||||
import { Service } from 'typedi';
|
||||
import type { CredentialsEntity } from '@db/entities/CredentialsEntity';
|
||||
import { SharedWorkflowRepository } from '@db/repositories/sharedWorkflow.repository';
|
||||
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
|
||||
import { NotFoundError } from '@/errors/response-errors/not-found.error';
|
||||
import { WorkflowRepository } from '@/databases/repositories/workflow.repository';
|
||||
import { CredentialsRepository } from '@/databases/repositories/credentials.repository';
|
||||
import { RoleService } from '@/services/role.service';
|
||||
import { UserRepository } from '@/databases/repositories/user.repository';
|
||||
|
||||
@Service()
|
||||
export class EnterpriseWorkflowService {
|
||||
constructor(
|
||||
private readonly logger: Logger,
|
||||
private readonly sharedWorkflowRepository: SharedWorkflowRepository,
|
||||
private readonly workflowRepository: WorkflowRepository,
|
||||
private readonly credentialsRepository: CredentialsRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
private readonly roleService: RoleService,
|
||||
) {}
|
||||
|
||||
async isOwned(
|
||||
@@ -143,11 +142,7 @@ export class EnterpriseWorkflowService {
|
||||
const allCredentials = await CredentialsService.getMany(user);
|
||||
|
||||
try {
|
||||
return WorkflowHelpers.validateWorkflowCredentialUsage(
|
||||
workflow,
|
||||
previousVersion,
|
||||
allCredentials,
|
||||
);
|
||||
return this.validateWorkflowCredentialUsage(workflow, previousVersion, allCredentials);
|
||||
} catch (error) {
|
||||
if (error instanceof NodeOperationError) {
|
||||
throw new BadRequestError(error.message);
|
||||
@@ -157,4 +152,90 @@ export class EnterpriseWorkflowService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
validateWorkflowCredentialUsage(
|
||||
newWorkflowVersion: WorkflowEntity,
|
||||
previousWorkflowVersion: WorkflowEntity,
|
||||
credentialsUserHasAccessTo: CredentialsEntity[],
|
||||
) {
|
||||
/**
|
||||
* We only need to check nodes that use credentials the current user cannot access,
|
||||
* since these can be 2 possibilities:
|
||||
* - Same ID already exist: it's a read only node and therefore cannot be changed
|
||||
* - It's a new node which indicates tampering and therefore must fail saving
|
||||
*/
|
||||
|
||||
const allowedCredentialIds = credentialsUserHasAccessTo.map((cred) => cred.id);
|
||||
|
||||
const nodesWithCredentialsUserDoesNotHaveAccessTo = this.getNodesWithInaccessibleCreds(
|
||||
newWorkflowVersion,
|
||||
allowedCredentialIds,
|
||||
);
|
||||
|
||||
// If there are no nodes with credentials the user does not have access to we can skip the rest
|
||||
if (nodesWithCredentialsUserDoesNotHaveAccessTo.length === 0) {
|
||||
return newWorkflowVersion;
|
||||
}
|
||||
|
||||
const previouslyExistingNodeIds = previousWorkflowVersion.nodes.map((node) => node.id);
|
||||
|
||||
// If it's a new node we can't allow it to be saved
|
||||
// since it uses creds the node doesn't have access
|
||||
const isTamperingAttempt = (inaccessibleCredNodeId: string) =>
|
||||
!previouslyExistingNodeIds.includes(inaccessibleCredNodeId);
|
||||
|
||||
nodesWithCredentialsUserDoesNotHaveAccessTo.forEach((node) => {
|
||||
if (isTamperingAttempt(node.id)) {
|
||||
this.logger.verbose('Blocked workflow update due to tampering attempt', {
|
||||
nodeType: node.type,
|
||||
nodeName: node.name,
|
||||
nodeId: node.id,
|
||||
nodeCredentials: node.credentials,
|
||||
});
|
||||
// Node is new, so this is probably a tampering attempt. Throw an error
|
||||
throw new NodeOperationError(
|
||||
node,
|
||||
`You don't have access to the credentials in the '${node.name}' node. Ask the owner to share them with you.`,
|
||||
);
|
||||
}
|
||||
// Replace the node with the previous version of the node
|
||||
// Since it cannot be modified (read only node)
|
||||
const nodeIdx = newWorkflowVersion.nodes.findIndex(
|
||||
(newWorkflowNode) => newWorkflowNode.id === node.id,
|
||||
);
|
||||
|
||||
this.logger.debug('Replacing node with previous version when saving updated workflow', {
|
||||
nodeType: node.type,
|
||||
nodeName: node.name,
|
||||
nodeId: node.id,
|
||||
});
|
||||
const previousNodeVersion = previousWorkflowVersion.nodes.find(
|
||||
(previousNode) => previousNode.id === node.id,
|
||||
);
|
||||
// Allow changing only name, position and disabled status for read-only nodes
|
||||
Object.assign(
|
||||
newWorkflowVersion.nodes[nodeIdx],
|
||||
omit(previousNodeVersion, ['name', 'position', 'disabled']),
|
||||
);
|
||||
});
|
||||
|
||||
return newWorkflowVersion;
|
||||
}
|
||||
|
||||
/** Get all nodes in a workflow where the node credential is not accessible to the user. */
|
||||
getNodesWithInaccessibleCreds(workflow: WorkflowEntity, userCredIds: string[]) {
|
||||
if (!workflow.nodes) {
|
||||
return [];
|
||||
}
|
||||
return workflow.nodes.filter((node) => {
|
||||
if (!node.credentials) return false;
|
||||
|
||||
const allUsedCredentials = Object.values(node.credentials);
|
||||
|
||||
const allUsedCredentialIds = allUsedCredentials.map((nodeCred) => nodeCred.id?.toString());
|
||||
return allUsedCredentialIds.some(
|
||||
(nodeCredId) => nodeCredId && !userCredIds.includes(nodeCredId),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,28 @@
|
||||
import Container, { Service } from 'typedi';
|
||||
import type { INode, IPinData } from 'n8n-workflow';
|
||||
import { NodeApiError, Workflow } from 'n8n-workflow';
|
||||
import { NodeApiError } from 'n8n-workflow';
|
||||
import pick from 'lodash/pick';
|
||||
import omit from 'lodash/omit';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import { ActiveWorkflowRunner } from '@/ActiveWorkflowRunner';
|
||||
import * as WorkflowHelpers from '@/WorkflowHelpers';
|
||||
import { BinaryDataService } from 'n8n-core';
|
||||
|
||||
import config from '@/config';
|
||||
import type { User } from '@db/entities/User';
|
||||
import type { WorkflowEntity } from '@db/entities/WorkflowEntity';
|
||||
import { ExecutionRepository } from '@db/repositories/execution.repository';
|
||||
import { SharedWorkflowRepository } from '@db/repositories/sharedWorkflow.repository';
|
||||
import { WorkflowTagMappingRepository } from '@db/repositories/workflowTagMapping.repository';
|
||||
import { WorkflowRepository } from '@db/repositories/workflow.repository';
|
||||
import { ActiveWorkflowRunner } from '@/ActiveWorkflowRunner';
|
||||
import * as WorkflowHelpers from '@/WorkflowHelpers';
|
||||
import { validateEntity } from '@/GenericHelpers';
|
||||
import { ExternalHooks } from '@/ExternalHooks';
|
||||
import { hasSharing, type ListQuery } from '@/requests';
|
||||
import type { WorkflowRequest } from '@/workflows/workflow.request';
|
||||
import { TagService } from '@/services/tag.service';
|
||||
import type { IWorkflowDb, IWorkflowExecutionDataProcess } from '@/Interfaces';
|
||||
import { NodeTypes } from '@/NodeTypes';
|
||||
import { WorkflowRunner } from '@/WorkflowRunner';
|
||||
import * as WorkflowExecuteAdditionalData from '@/WorkflowExecuteAdditionalData';
|
||||
import { TestWebhooks } from '@/TestWebhooks';
|
||||
import { InternalHooks } from '@/InternalHooks';
|
||||
import { WorkflowRepository } from '@db/repositories/workflow.repository';
|
||||
import { OwnershipService } from '@/services/ownership.service';
|
||||
import { WorkflowHistoryService } from './workflowHistory/workflowHistory.service.ee';
|
||||
import { BinaryDataService } from 'n8n-core';
|
||||
import { Logger } from '@/Logger';
|
||||
import { MultiMainSetup } from '@/services/orchestration/main/MultiMainSetup.ee';
|
||||
import { SharedWorkflowRepository } from '@db/repositories/sharedWorkflow.repository';
|
||||
import { WorkflowTagMappingRepository } from '@db/repositories/workflowTagMapping.repository';
|
||||
import { ExecutionRepository } from '@db/repositories/execution.repository';
|
||||
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
|
||||
import { NotFoundError } from '@/errors/response-errors/not-found.error';
|
||||
|
||||
@@ -45,54 +39,10 @@ export class WorkflowService {
|
||||
private readonly tagService: TagService,
|
||||
private readonly workflowHistoryService: WorkflowHistoryService,
|
||||
private readonly multiMainSetup: MultiMainSetup,
|
||||
private readonly nodeTypes: NodeTypes,
|
||||
private readonly testWebhooks: TestWebhooks,
|
||||
private readonly externalHooks: ExternalHooks,
|
||||
private readonly activeWorkflowRunner: ActiveWorkflowRunner,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Find the pinned trigger to execute the workflow from, if any.
|
||||
*
|
||||
* - In a full execution, select the _first_ pinned trigger.
|
||||
* - In a partial execution,
|
||||
* - select the _first_ pinned trigger that leads to the executed node,
|
||||
* - else select the executed pinned trigger.
|
||||
*/
|
||||
findPinnedTrigger(workflow: IWorkflowDb, startNodes?: string[], pinData?: IPinData) {
|
||||
if (!pinData || !startNodes) return null;
|
||||
|
||||
const isTrigger = (nodeTypeName: string) =>
|
||||
['trigger', 'webhook'].some((suffix) => nodeTypeName.toLowerCase().includes(suffix));
|
||||
|
||||
const pinnedTriggers = workflow.nodes.filter(
|
||||
(node) => !node.disabled && pinData[node.name] && isTrigger(node.type),
|
||||
);
|
||||
|
||||
if (pinnedTriggers.length === 0) return null;
|
||||
|
||||
if (startNodes?.length === 0) return pinnedTriggers[0]; // full execution
|
||||
|
||||
const [startNodeName] = startNodes;
|
||||
|
||||
const parentNames = new Workflow({
|
||||
nodes: workflow.nodes,
|
||||
connections: workflow.connections,
|
||||
active: workflow.active,
|
||||
nodeTypes: this.nodeTypes,
|
||||
}).getParentNodes(startNodeName);
|
||||
|
||||
let checkNodeName = '';
|
||||
|
||||
if (parentNames.length === 0) {
|
||||
checkNodeName = startNodeName;
|
||||
} else {
|
||||
checkNodeName = parentNames.find((pn) => pn === pinnedTriggers[0].name) as string;
|
||||
}
|
||||
|
||||
return pinnedTriggers.find((pt) => pt.name === checkNodeName) ?? null; // partial execution
|
||||
}
|
||||
|
||||
async getMany(sharedWorkflowIds: string[], options?: ListQuery.Options) {
|
||||
const { workflows, count } = await this.workflowRepository.getMany(sharedWorkflowIds, options);
|
||||
|
||||
@@ -293,70 +243,6 @@ export class WorkflowService {
|
||||
return updatedWorkflow;
|
||||
}
|
||||
|
||||
async runManually(
|
||||
{
|
||||
workflowData,
|
||||
runData,
|
||||
pinData,
|
||||
startNodes,
|
||||
destinationNode,
|
||||
}: WorkflowRequest.ManualRunPayload,
|
||||
user: User,
|
||||
sessionId?: string,
|
||||
) {
|
||||
const pinnedTrigger = this.findPinnedTrigger(workflowData, startNodes, pinData);
|
||||
|
||||
// If webhooks nodes exist and are active we have to wait for till we receive a call
|
||||
if (
|
||||
pinnedTrigger === null &&
|
||||
(runData === undefined ||
|
||||
startNodes === undefined ||
|
||||
startNodes.length === 0 ||
|
||||
destinationNode === undefined)
|
||||
) {
|
||||
const additionalData = await WorkflowExecuteAdditionalData.getBase(user.id);
|
||||
|
||||
const needsWebhook = await this.testWebhooks.needsWebhook(
|
||||
user.id,
|
||||
workflowData,
|
||||
additionalData,
|
||||
runData,
|
||||
sessionId,
|
||||
destinationNode,
|
||||
);
|
||||
|
||||
if (needsWebhook) return { waitingForWebhook: true };
|
||||
}
|
||||
|
||||
// For manual testing always set to not active
|
||||
workflowData.active = false;
|
||||
|
||||
// Start the workflow
|
||||
const data: IWorkflowExecutionDataProcess = {
|
||||
destinationNode,
|
||||
executionMode: 'manual',
|
||||
runData,
|
||||
pinData,
|
||||
sessionId,
|
||||
startNodes,
|
||||
workflowData,
|
||||
userId: user.id,
|
||||
};
|
||||
|
||||
const hasRunData = (node: INode) => runData !== undefined && !!runData[node.name];
|
||||
|
||||
if (pinnedTrigger && !hasRunData(pinnedTrigger)) {
|
||||
data.startNodes = [pinnedTrigger.name];
|
||||
}
|
||||
|
||||
const workflowRunner = new WorkflowRunner();
|
||||
const executionId = await workflowRunner.run(data);
|
||||
|
||||
return {
|
||||
executionId,
|
||||
};
|
||||
}
|
||||
|
||||
async delete(user: User, workflowId: string): Promise<WorkflowEntity | undefined> {
|
||||
await this.externalHooks.run('workflow.delete', [workflowId]);
|
||||
|
||||
|
||||
286
packages/cli/src/workflows/workflowExecution.service.ts
Normal file
286
packages/cli/src/workflows/workflowExecution.service.ts
Normal file
@@ -0,0 +1,286 @@
|
||||
import { Service } from 'typedi';
|
||||
import type { IExecuteData, INode, IPinData, IRunExecutionData } from 'n8n-workflow';
|
||||
import {
|
||||
SubworkflowOperationError,
|
||||
Workflow,
|
||||
ErrorReporterProxy as ErrorReporter,
|
||||
} from 'n8n-workflow';
|
||||
|
||||
import config from '@/config';
|
||||
import type { User } from '@db/entities/User';
|
||||
import { ExecutionRepository } from '@db/repositories/execution.repository';
|
||||
import { WorkflowRepository } from '@db/repositories/workflow.repository';
|
||||
import * as WorkflowHelpers from '@/WorkflowHelpers';
|
||||
import type { WorkflowRequest } from '@/workflows/workflow.request';
|
||||
import type {
|
||||
ExecutionPayload,
|
||||
IWorkflowDb,
|
||||
IWorkflowErrorData,
|
||||
IWorkflowExecutionDataProcess,
|
||||
} from '@/Interfaces';
|
||||
import { NodeTypes } from '@/NodeTypes';
|
||||
import { WorkflowRunner } from '@/WorkflowRunner';
|
||||
import * as WorkflowExecuteAdditionalData from '@/WorkflowExecuteAdditionalData';
|
||||
import { TestWebhooks } from '@/TestWebhooks';
|
||||
import { Logger } from '@/Logger';
|
||||
import { PermissionChecker } from '@/UserManagement/PermissionChecker';
|
||||
|
||||
@Service()
|
||||
export class WorkflowExecutionService {
|
||||
constructor(
|
||||
private readonly logger: Logger,
|
||||
private readonly executionRepository: ExecutionRepository,
|
||||
private readonly workflowRepository: WorkflowRepository,
|
||||
private readonly nodeTypes: NodeTypes,
|
||||
private readonly testWebhooks: TestWebhooks,
|
||||
private readonly permissionChecker: PermissionChecker,
|
||||
) {}
|
||||
|
||||
async executeManually(
|
||||
{
|
||||
workflowData,
|
||||
runData,
|
||||
pinData,
|
||||
startNodes,
|
||||
destinationNode,
|
||||
}: WorkflowRequest.ManualRunPayload,
|
||||
user: User,
|
||||
sessionId?: string,
|
||||
) {
|
||||
const pinnedTrigger = this.findPinnedTrigger(workflowData, startNodes, pinData);
|
||||
|
||||
// If webhooks nodes exist and are active we have to wait for till we receive a call
|
||||
if (
|
||||
pinnedTrigger === null &&
|
||||
(runData === undefined ||
|
||||
startNodes === undefined ||
|
||||
startNodes.length === 0 ||
|
||||
destinationNode === undefined)
|
||||
) {
|
||||
const additionalData = await WorkflowExecuteAdditionalData.getBase(user.id);
|
||||
|
||||
const needsWebhook = await this.testWebhooks.needsWebhook(
|
||||
user.id,
|
||||
workflowData,
|
||||
additionalData,
|
||||
runData,
|
||||
sessionId,
|
||||
destinationNode,
|
||||
);
|
||||
|
||||
if (needsWebhook) return { waitingForWebhook: true };
|
||||
}
|
||||
|
||||
// For manual testing always set to not active
|
||||
workflowData.active = false;
|
||||
|
||||
// Start the workflow
|
||||
const data: IWorkflowExecutionDataProcess = {
|
||||
destinationNode,
|
||||
executionMode: 'manual',
|
||||
runData,
|
||||
pinData,
|
||||
sessionId,
|
||||
startNodes,
|
||||
workflowData,
|
||||
userId: user.id,
|
||||
};
|
||||
|
||||
const hasRunData = (node: INode) => runData !== undefined && !!runData[node.name];
|
||||
|
||||
if (pinnedTrigger && !hasRunData(pinnedTrigger)) {
|
||||
data.startNodes = [pinnedTrigger.name];
|
||||
}
|
||||
|
||||
const workflowRunner = new WorkflowRunner();
|
||||
const executionId = await workflowRunner.run(data);
|
||||
|
||||
return {
|
||||
executionId,
|
||||
};
|
||||
}
|
||||
|
||||
/** Executes an error workflow */
|
||||
async executeErrorWorkflow(
|
||||
workflowId: string,
|
||||
workflowErrorData: IWorkflowErrorData,
|
||||
runningUser: User,
|
||||
): Promise<void> {
|
||||
// Wrap everything in try/catch to make sure that no errors bubble up and all get caught here
|
||||
try {
|
||||
const workflowData = await this.workflowRepository.findOneBy({ id: workflowId });
|
||||
if (workflowData === null) {
|
||||
// The error workflow could not be found
|
||||
this.logger.error(
|
||||
`Calling Error Workflow for "${workflowErrorData.workflow.id}". Could not find error workflow "${workflowId}"`,
|
||||
{ workflowId },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const executionMode = 'error';
|
||||
const workflowInstance = new Workflow({
|
||||
id: workflowId,
|
||||
name: workflowData.name,
|
||||
nodeTypes: this.nodeTypes,
|
||||
nodes: workflowData.nodes,
|
||||
connections: workflowData.connections,
|
||||
active: workflowData.active,
|
||||
staticData: workflowData.staticData,
|
||||
settings: workflowData.settings,
|
||||
});
|
||||
|
||||
try {
|
||||
const failedNode = workflowErrorData.execution?.lastNodeExecuted
|
||||
? workflowInstance.getNode(workflowErrorData.execution?.lastNodeExecuted)
|
||||
: undefined;
|
||||
await this.permissionChecker.checkSubworkflowExecutePolicy(
|
||||
workflowInstance,
|
||||
workflowErrorData.workflow.id!,
|
||||
failedNode ?? undefined,
|
||||
);
|
||||
} catch (error) {
|
||||
const initialNode = workflowInstance.getStartNode();
|
||||
if (initialNode) {
|
||||
const errorWorkflowPermissionError = new SubworkflowOperationError(
|
||||
`Another workflow: (ID ${workflowErrorData.workflow.id}) tried to invoke this workflow to handle errors.`,
|
||||
"Unfortunately current permissions do not allow this. Please check that this workflow's settings allow it to be called by others",
|
||||
);
|
||||
|
||||
// Create a fake execution and save it to DB.
|
||||
const fakeExecution = WorkflowHelpers.generateFailedExecutionFromError(
|
||||
'error',
|
||||
errorWorkflowPermissionError,
|
||||
initialNode,
|
||||
);
|
||||
|
||||
const fullExecutionData: ExecutionPayload = {
|
||||
data: fakeExecution.data,
|
||||
mode: fakeExecution.mode,
|
||||
finished: false,
|
||||
startedAt: new Date(),
|
||||
stoppedAt: new Date(),
|
||||
workflowData,
|
||||
waitTill: null,
|
||||
status: fakeExecution.status,
|
||||
workflowId: workflowData.id,
|
||||
};
|
||||
|
||||
await this.executionRepository.createNewExecution(fullExecutionData);
|
||||
}
|
||||
this.logger.info('Error workflow execution blocked due to subworkflow settings', {
|
||||
erroredWorkflowId: workflowErrorData.workflow.id,
|
||||
errorWorkflowId: workflowId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let node: INode;
|
||||
let workflowStartNode: INode | undefined;
|
||||
const ERROR_TRIGGER_TYPE = config.getEnv('nodes.errorTriggerType');
|
||||
for (const nodeName of Object.keys(workflowInstance.nodes)) {
|
||||
node = workflowInstance.nodes[nodeName];
|
||||
if (node.type === ERROR_TRIGGER_TYPE) {
|
||||
workflowStartNode = node;
|
||||
}
|
||||
}
|
||||
|
||||
if (workflowStartNode === undefined) {
|
||||
this.logger.error(
|
||||
`Calling Error Workflow for "${workflowErrorData.workflow.id}". Could not find "${ERROR_TRIGGER_TYPE}" in workflow "${workflowId}"`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Can execute without webhook so go on
|
||||
// Initialize the data of the webhook node
|
||||
const nodeExecutionStack: IExecuteData[] = [];
|
||||
nodeExecutionStack.push({
|
||||
node: workflowStartNode,
|
||||
data: {
|
||||
main: [
|
||||
[
|
||||
{
|
||||
json: workflowErrorData,
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
source: null,
|
||||
});
|
||||
|
||||
const runExecutionData: IRunExecutionData = {
|
||||
startData: {},
|
||||
resultData: {
|
||||
runData: {},
|
||||
},
|
||||
executionData: {
|
||||
contextData: {},
|
||||
metadata: {},
|
||||
nodeExecutionStack,
|
||||
waitingExecution: {},
|
||||
waitingExecutionSource: {},
|
||||
},
|
||||
};
|
||||
|
||||
const runData: IWorkflowExecutionDataProcess = {
|
||||
executionMode,
|
||||
executionData: runExecutionData,
|
||||
workflowData,
|
||||
userId: runningUser.id,
|
||||
};
|
||||
|
||||
const workflowRunner = new WorkflowRunner();
|
||||
await workflowRunner.run(runData);
|
||||
} catch (error) {
|
||||
ErrorReporter.error(error);
|
||||
this.logger.error(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
`Calling Error Workflow for "${workflowErrorData.workflow.id}": "${error.message}"`,
|
||||
{ workflowId: workflowErrorData.workflow.id },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the pinned trigger to execute the workflow from, if any.
|
||||
*
|
||||
* - In a full execution, select the _first_ pinned trigger.
|
||||
* - In a partial execution,
|
||||
* - select the _first_ pinned trigger that leads to the executed node,
|
||||
* - else select the executed pinned trigger.
|
||||
*/
|
||||
private findPinnedTrigger(workflow: IWorkflowDb, startNodes?: string[], pinData?: IPinData) {
|
||||
if (!pinData || !startNodes) return null;
|
||||
|
||||
const isTrigger = (nodeTypeName: string) =>
|
||||
['trigger', 'webhook'].some((suffix) => nodeTypeName.toLowerCase().includes(suffix));
|
||||
|
||||
const pinnedTriggers = workflow.nodes.filter(
|
||||
(node) => !node.disabled && pinData[node.name] && isTrigger(node.type),
|
||||
);
|
||||
|
||||
if (pinnedTriggers.length === 0) return null;
|
||||
|
||||
if (startNodes?.length === 0) return pinnedTriggers[0]; // full execution
|
||||
|
||||
const [startNodeName] = startNodes;
|
||||
|
||||
const parentNames = new Workflow({
|
||||
nodes: workflow.nodes,
|
||||
connections: workflow.connections,
|
||||
active: workflow.active,
|
||||
nodeTypes: this.nodeTypes,
|
||||
}).getParentNodes(startNodeName);
|
||||
|
||||
let checkNodeName = '';
|
||||
|
||||
if (parentNames.length === 0) {
|
||||
checkNodeName = startNodeName;
|
||||
} else {
|
||||
checkNodeName = parentNames.find((pn) => pn === pinnedTriggers[0].name) as string;
|
||||
}
|
||||
|
||||
return pinnedTriggers.find((pt) => pt.name === checkNodeName) ?? null; // partial execution
|
||||
}
|
||||
}
|
||||
36
packages/cli/src/workflows/workflowSharing.service.ts
Normal file
36
packages/cli/src/workflows/workflowSharing.service.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Service } from 'typedi';
|
||||
import { In, type FindOptionsWhere } from 'typeorm';
|
||||
|
||||
import type { RoleNames } from '@db/entities/Role';
|
||||
import type { SharedWorkflow } from '@db/entities/SharedWorkflow';
|
||||
import type { User } from '@db/entities/User';
|
||||
import { RoleRepository } from '@db/repositories/role.repository';
|
||||
import { SharedWorkflowRepository } from '@db/repositories/sharedWorkflow.repository';
|
||||
|
||||
@Service()
|
||||
export class WorkflowSharingService {
|
||||
constructor(
|
||||
private readonly roleRepository: RoleRepository,
|
||||
private readonly sharedWorkflowRepository: SharedWorkflowRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get the IDs of the workflows that have been shared with the user.
|
||||
* Returns all IDs if user has the 'workflow:read' scope.
|
||||
*/
|
||||
async getSharedWorkflowIds(user: User, roleNames?: RoleNames[]): Promise<string[]> {
|
||||
const where: FindOptionsWhere<SharedWorkflow> = {};
|
||||
if (!user.hasGlobalScope('workflow:read')) {
|
||||
where.userId = user.id;
|
||||
}
|
||||
if (roleNames?.length) {
|
||||
const roleIds = await this.roleRepository.getIdsInScopeWorkflowByNames(roleNames);
|
||||
where.roleId = In(roleIds);
|
||||
}
|
||||
const sharedWorkflows = await this.sharedWorkflowRepository.find({
|
||||
where,
|
||||
select: ['workflowId'],
|
||||
});
|
||||
return sharedWorkflows.map(({ workflowId }) => workflowId);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,15 @@ export class WorkflowStaticDataService {
|
||||
private readonly workflowRepository: WorkflowRepository,
|
||||
) {}
|
||||
|
||||
/** Returns the static data of workflow */
|
||||
async getStaticDataById(workflowId: string) {
|
||||
const workflowData = await this.workflowRepository.findOne({
|
||||
select: ['staticData'],
|
||||
where: { id: workflowId },
|
||||
});
|
||||
return workflowData?.staticData ?? {};
|
||||
}
|
||||
|
||||
/** Saves the static data if it changed */
|
||||
async saveStaticData(workflow: Workflow): Promise<void> {
|
||||
if (workflow.staticData.__dataChanged === true) {
|
||||
|
||||
@@ -1,22 +1,27 @@
|
||||
import { Service } from 'typedi';
|
||||
import express from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
import axios from 'axios';
|
||||
|
||||
import * as Db from '@/Db';
|
||||
import * as GenericHelpers from '@/GenericHelpers';
|
||||
import * as ResponseHelper from '@/ResponseHelper';
|
||||
import * as WorkflowHelpers from '@/WorkflowHelpers';
|
||||
import type { IWorkflowResponse } from '@/Interfaces';
|
||||
import config from '@/config';
|
||||
import { Authorized, Delete, Get, Patch, Post, Put, RestController } from '@/decorators';
|
||||
import type { RoleNames } from '@db/entities/Role';
|
||||
import { SharedWorkflow } from '@db/entities/SharedWorkflow';
|
||||
import { WorkflowEntity } from '@db/entities/WorkflowEntity';
|
||||
import { SharedWorkflowRepository } from '@db/repositories/sharedWorkflow.repository';
|
||||
import { TagRepository } from '@db/repositories/tag.repository';
|
||||
import { WorkflowRepository } from '@db/repositories/workflow.repository';
|
||||
import { UserRepository } from '@db/repositories/user.repository';
|
||||
import { validateEntity } from '@/GenericHelpers';
|
||||
import { ExternalHooks } from '@/ExternalHooks';
|
||||
import { ListQuery } from '@/requests';
|
||||
import { isBelowOnboardingThreshold } from '@/WorkflowHelpers';
|
||||
import { WorkflowService } from './workflow.service';
|
||||
import { isSharingEnabled } from '@/UserManagement/UserManagementHelper';
|
||||
import Container, { Service } from 'typedi';
|
||||
import { InternalHooks } from '@/InternalHooks';
|
||||
import { RoleService } from '@/services/role.service';
|
||||
import * as utils from '@/utils';
|
||||
@@ -24,20 +29,17 @@ import { listQueryMiddleware } from '@/middlewares';
|
||||
import { TagService } from '@/services/tag.service';
|
||||
import { WorkflowHistoryService } from './workflowHistory/workflowHistory.service.ee';
|
||||
import { Logger } from '@/Logger';
|
||||
import { SharedWorkflowRepository } from '@db/repositories/sharedWorkflow.repository';
|
||||
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
|
||||
import { NotFoundError } from '@/errors/response-errors/not-found.error';
|
||||
import { InternalServerError } from '@/errors/response-errors/internal-server.error';
|
||||
import { NamingService } from '@/services/naming.service';
|
||||
import { TagRepository } from '@/databases/repositories/tag.repository';
|
||||
import { EnterpriseWorkflowService } from './workflow.service.ee';
|
||||
import { WorkflowRepository } from '@/databases/repositories/workflow.repository';
|
||||
import type { RoleNames } from '@/databases/entities/Role';
|
||||
import { UnauthorizedError } from '@/errors/response-errors/unauthorized.error';
|
||||
import { NamingService } from '@/services/naming.service';
|
||||
import { UserOnboardingService } from '@/services/userOnboarding.service';
|
||||
import { CredentialsService } from '../credentials/credentials.service';
|
||||
import { UserRepository } from '@/databases/repositories/user.repository';
|
||||
import { Authorized, Delete, Get, Patch, Post, Put, RestController } from '@/decorators';
|
||||
import { WorkflowRequest } from './workflow.request';
|
||||
import { EnterpriseWorkflowService } from './workflow.service.ee';
|
||||
import { WorkflowExecutionService } from './workflowExecution.service';
|
||||
import { WorkflowSharingService } from './workflowSharing.service';
|
||||
|
||||
@Service()
|
||||
@Authorized()
|
||||
@@ -53,8 +55,11 @@ export class WorkflowsController {
|
||||
private readonly workflowHistoryService: WorkflowHistoryService,
|
||||
private readonly tagService: TagService,
|
||||
private readonly namingService: NamingService,
|
||||
private readonly userOnboardingService: UserOnboardingService,
|
||||
private readonly workflowRepository: WorkflowRepository,
|
||||
private readonly workflowService: WorkflowService,
|
||||
private readonly workflowExecutionService: WorkflowExecutionService,
|
||||
private readonly workflowSharingService: WorkflowSharingService,
|
||||
private readonly sharedWorkflowRepository: SharedWorkflowRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
@@ -142,9 +147,12 @@ export class WorkflowsController {
|
||||
async getAll(req: ListQuery.Request, res: express.Response) {
|
||||
try {
|
||||
const roles: RoleNames[] = isSharingEnabled() ? [] : ['owner'];
|
||||
const sharedWorkflowIds = await WorkflowHelpers.getSharedWorkflowIds(req.user, roles);
|
||||
const sharedWorkflowIds = await this.workflowSharingService.getSharedWorkflowIds(
|
||||
req.user,
|
||||
roles,
|
||||
);
|
||||
|
||||
const { workflows: data, count } = await Container.get(WorkflowService).getMany(
|
||||
const { workflows: data, count } = await this.workflowService.getMany(
|
||||
sharedWorkflowIds,
|
||||
req.listQueryOptions,
|
||||
);
|
||||
@@ -166,7 +174,7 @@ export class WorkflowsController {
|
||||
const onboardingFlowEnabled =
|
||||
!config.getEnv('workflows.onboardingFlowDisabled') &&
|
||||
!req.user.settings?.isOnboarded &&
|
||||
(await isBelowOnboardingThreshold(req.user));
|
||||
(await this.userOnboardingService.isBelowThreshold(req.user));
|
||||
|
||||
return { name, onboardingFlowEnabled };
|
||||
}
|
||||
@@ -321,7 +329,11 @@ export class WorkflowsController {
|
||||
}
|
||||
}
|
||||
|
||||
return this.workflowService.runManually(req.body, req.user, GenericHelpers.getSessionId(req));
|
||||
return this.workflowExecutionService.executeManually(
|
||||
req.body,
|
||||
req.user,
|
||||
GenericHelpers.getSessionId(req),
|
||||
);
|
||||
}
|
||||
|
||||
@Put('/:workflowId/share')
|
||||
|
||||
Reference in New Issue
Block a user