| | | 1 | | using Elsa.Alterations.Core.Contexts; |
| | | 2 | | using Elsa.Alterations.Core.Contracts; |
| | | 3 | | using Elsa.Alterations.Core.Models; |
| | | 4 | | using Elsa.Extensions; |
| | | 5 | | using Elsa.Workflows; |
| | | 6 | | using Elsa.Workflows.Pipelines.WorkflowExecution; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Alterations.Middleware.Workflows; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Middleware that runs alterations. |
| | | 12 | | /// </summary> |
| | 1 | 13 | | internal class RunAlterationsMiddleware(WorkflowMiddlewareDelegate next, IEnumerable<IAlterationHandler> handlers) : Wor |
| | | 14 | | { |
| | 1 | 15 | | public static readonly object AlterationsPropertyKey = new(); |
| | 1 | 16 | | public static readonly object AlterationsLogPropertyKey = new(); |
| | | 17 | | |
| | | 18 | | public override async ValueTask InvokeAsync(WorkflowExecutionContext context) |
| | | 19 | | { |
| | 1 | 20 | | var alterations = (IEnumerable<IAlteration>)(context.TransientProperties.GetValue(AlterationsPropertyKey) ?? thr |
| | 1 | 21 | | var log = (AlterationLog)(context.TransientProperties.GetValue(AlterationsLogPropertyKey) ?? throw new InvalidOp |
| | 1 | 22 | | await RunAsync(context, alterations, log, context.CancellationToken); |
| | 1 | 23 | | } |
| | | 24 | | |
| | | 25 | | private async Task RunAsync(WorkflowExecutionContext workflowExecutionContext, IEnumerable<IAlteration> alterations, |
| | | 26 | | { |
| | 1 | 27 | | var commitActions = new List<Func<Task>>(); |
| | | 28 | | |
| | 4 | 29 | | foreach (var alteration in alterations) |
| | | 30 | | { |
| | | 31 | | // Find handlers. |
| | 6 | 32 | | var supportedHandlers = handlers.Where(x => x.CanHandle(alteration)).ToList(); |
| | | 33 | | |
| | 4 | 34 | | foreach (var handler in supportedHandlers) |
| | | 35 | | { |
| | | 36 | | // Execute handler. |
| | 1 | 37 | | var alterationContext = new AlterationContext(alteration, workflowExecutionContext, log, cancellationTok |
| | 1 | 38 | | await handler.HandleAsync(alterationContext); |
| | | 39 | | |
| | | 40 | | // If the handler has failed, exit. |
| | 1 | 41 | | if (alterationContext.HasFailed) |
| | 0 | 42 | | return; |
| | | 43 | | |
| | | 44 | | // Collect the commit handler, if any. |
| | 1 | 45 | | if (alterationContext.CommitAction != null) |
| | 0 | 46 | | commitActions.Add(alterationContext.CommitAction); |
| | 1 | 47 | | } |
| | 1 | 48 | | } |
| | | 49 | | |
| | | 50 | | // Execute commit handlers. |
| | 2 | 51 | | foreach (var commitAction in commitActions) |
| | 0 | 52 | | await commitAction(); |
| | | 53 | | |
| | | 54 | | // Add alteration logs to the workflow execution log. |
| | 4 | 55 | | foreach (var alterationLogEntry in log.LogEntries) |
| | 1 | 56 | | workflowExecutionContext.AddExecutionLogEntry(alterationLogEntry.EventName ?? alterationLogEntry.Message, al |
| | 1 | 57 | | } |
| | | 58 | | } |