Add validation for unique input/output names in workflows

Introduces a `ValidateWorkflow` notification handler to enforce validation of unique input and output names in workflows. Adds validation errors when duplicate names are detected, improving the integrity of workflow definitions. Integrates the handler into the workflow management feature.
This commit is contained in:
Sipke Schoorstra 2025-01-27 18:44:47 +01:00
parent a2efe5a941
commit be94a51b8c
3 changed files with 32 additions and 0 deletions

View file

@ -241,6 +241,7 @@ public class WorkflowManagementFeature : FeatureBase
.AddNotificationHandler<DeleteWorkflowInstances>()
.AddNotificationHandler<RefreshActivityRegistry>()
.AddNotificationHandler<UpdateConsumingWorkflows>()
.AddNotificationHandler<ValidateWorkflow>()
;
Services.Configure<ManagementOptions>(options =>

View file

@ -0,0 +1,31 @@
using Elsa.Mediator.Contracts;
using Elsa.Workflows.Management.Models;
using Elsa.Workflows.Management.Notifications;
using Elsa.Workflows.Models;
namespace Elsa.Workflows.Management.Handlers.Notification;
public class ValidateWorkflow : INotificationHandler<WorkflowDefinitionValidating>
{
public Task HandleAsync(WorkflowDefinitionValidating notification, CancellationToken cancellationToken)
{
var workflow = notification.Workflow;
var inputs = workflow.Inputs;
var outputs = workflow.Outputs;
ValidateUniqueNames(inputs, "inputs", notification.ValidationErrors);
ValidateUniqueNames(outputs, "outputs", notification.ValidationErrors);
return Task.CompletedTask;
}
private void ValidateUniqueNames(IEnumerable<ArgumentDefinition> variables, string variableType, ICollection<WorkflowValidationError> validationErrors)
{
var duplicateNames = variables.GroupBy(x => x.Name).Where(x => x.Count() > 1).Select(x => x.Key).ToList();
if (duplicateNames.Any())
{
var message = $"The following {variableType} are defined more than once: {string.Join(", ", duplicateNames)}";
validationErrors.Add(new(message));
}
}
}