| | | 1 | | using System.Text.Json; |
| | | 2 | | using Elsa.Extensions; |
| | | 3 | | using Elsa.Mediator.Contracts; |
| | | 4 | | using Elsa.Workflows.Attributes; |
| | | 5 | | using Elsa.Workflows.CommitStates; |
| | | 6 | | using Elsa.Workflows.Middleware.Activities; |
| | | 7 | | using Elsa.Workflows.Models; |
| | | 8 | | using Elsa.Workflows.Options; |
| | | 9 | | using Elsa.Workflows.Pipelines.ActivityExecution; |
| | | 10 | | using Elsa.Workflows.Runtime.Notifications; |
| | | 11 | | using Elsa.Workflows.Runtime.Stimuli; |
| | | 12 | | using JetBrains.Annotations; |
| | | 13 | | using Microsoft.Extensions.Logging; |
| | | 14 | | |
| | | 15 | | namespace Elsa.Workflows.Runtime.Middleware.Activities; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Collects the current activity for scheduling for execution from a background job if the activity is of kind <see cre |
| | | 19 | | /// </summary> |
| | | 20 | | [UsedImplicitly] |
| | | 21 | | public class BackgroundActivityInvokerMiddleware( |
| | | 22 | | ActivityMiddlewareDelegate next, |
| | | 23 | | ILogger<BackgroundActivityInvokerMiddleware> logger, |
| | | 24 | | IIdentityGenerator identityGenerator, |
| | | 25 | | IBackgroundActivityScheduler backgroundActivityScheduler, |
| | | 26 | | ICommitStrategyRegistry commitStrategyRegistry, |
| | | 27 | | IMediator mediator) |
| | 436 | 28 | | : DefaultActivityInvokerMiddleware(next, commitStrategyRegistry, logger) |
| | | 29 | | { |
| | 34 | 30 | | internal static string GetBackgroundActivityOutputKey(string activityNodeId) => $"__BackgroundActivityOutput:{activi |
| | 34 | 31 | | internal static string GetBackgroundActivityOutcomesKey(string activityNodeId) => $"__BackgroundActivityOutcomes:{ac |
| | 34 | 32 | | internal static string GetBackgroundActivityCompletedKey(string activityNodeId) => $"__BackgroundActivityCompleted:{ |
| | 34 | 33 | | internal static string GetBackgroundActivityJournalDataKey(string activityNodeId) => $"__BackgroundActivityJournalDa |
| | 34 | 34 | | internal static string GetBackgroundActivityScheduledActivitiesKey(string activityNodeId) => $"__BackgroundActivityS |
| | 34 | 35 | | internal static string GetBackgroundActivityBookmarksKey(string activityNodeId) => $"__BackgroundActivityBookmarks:{ |
| | 34 | 36 | | internal static string GetBackgroundActivityPropertiesKey(string activityNodeId) => $"__BackgroundActivityProperties |
| | | 37 | | internal const string BackgroundActivityBookmarkName = "BackgroundActivity"; |
| | | 38 | | |
| | | 39 | | /// <inheritdoc /> |
| | | 40 | | protected override async ValueTask ExecuteActivityAsync(ActivityExecutionContext context) |
| | | 41 | | { |
| | 3653 | 42 | | var shouldRunInBackground = GetShouldRunInBackground(context); |
| | | 43 | | |
| | 3653 | 44 | | if (shouldRunInBackground) |
| | 3 | 45 | | await ScheduleBackgroundActivityAsync(context); |
| | | 46 | | else |
| | | 47 | | { |
| | 3650 | 48 | | await base.ExecuteActivityAsync(context); |
| | | 49 | | |
| | | 50 | | // This part is either executed from the background or in the foreground when the activity is resumed. |
| | 3642 | 51 | | var isResuming = !GetIsBackgroundExecution(context) && context.ActivityDescriptor.Kind is ActivityKind.Task |
| | 3642 | 52 | | if (isResuming) |
| | | 53 | | { |
| | 31 | 54 | | CaptureOutputIfAny(context); |
| | 31 | 55 | | CaptureJournalData(context); |
| | 31 | 56 | | CaptureBookmarkData(context); |
| | 31 | 57 | | CapturePropertiesIfAny(context); |
| | 31 | 58 | | await CompleteBackgroundActivityOutcomesAsync(context); |
| | 31 | 59 | | await CompleteBackgroundActivityAsync(context); |
| | 31 | 60 | | await CompleteBackgroundActivityScheduledActivitiesAsync(context); |
| | 31 | 61 | | await mediator.SendAsync(new BackgroundActivityExecutionCompleted(context), context.CancellationToken); |
| | | 62 | | } |
| | | 63 | | } |
| | 3645 | 64 | | } |
| | | 65 | | |
| | | 66 | | /// <summary> |
| | | 67 | | /// Schedules the current activity for execution in the background. |
| | | 68 | | /// </summary> |
| | | 69 | | private async Task ScheduleBackgroundActivityAsync(ActivityExecutionContext context) |
| | | 70 | | { |
| | 3 | 71 | | var cancellationToken = context.CancellationToken; |
| | 3 | 72 | | var workflowInstanceId = context.WorkflowExecutionContext.Id; |
| | 3 | 73 | | var activityNodeId = context.NodeId; |
| | 3 | 74 | | var bookmarkId = identityGenerator.GenerateId(); |
| | 3 | 75 | | var scheduledBackgroundActivity = new ScheduledBackgroundActivity(workflowInstanceId, activityNodeId, bookmarkId |
| | 3 | 76 | | var jobId = await backgroundActivityScheduler.CreateAsync(scheduledBackgroundActivity, cancellationToken); |
| | 3 | 77 | | var stimulus = new BackgroundActivityStimulus |
| | 3 | 78 | | { |
| | 3 | 79 | | JobId = jobId |
| | 3 | 80 | | }; |
| | 3 | 81 | | var bookmarkOptions = new CreateBookmarkArgs |
| | 3 | 82 | | { |
| | 3 | 83 | | BookmarkId = bookmarkId, |
| | 3 | 84 | | BookmarkName = BackgroundActivityBookmarkName, |
| | 3 | 85 | | Stimulus = stimulus, |
| | 3 | 86 | | AutoComplete = false |
| | 3 | 87 | | }; |
| | 3 | 88 | | context.CreateBookmark(bookmarkOptions); |
| | | 89 | | |
| | 3 | 90 | | context.DeferTask(async () => |
| | 3 | 91 | | { |
| | 3 | 92 | | await backgroundActivityScheduler.ScheduleAsync(jobId, cancellationToken); |
| | 6 | 93 | | }); |
| | 3 | 94 | | } |
| | | 95 | | |
| | | 96 | | /// <summary> |
| | | 97 | | /// Determines whether the current activity should be executed in the background. |
| | | 98 | | /// </summary> |
| | | 99 | | private static bool GetShouldRunInBackground(ActivityExecutionContext context) |
| | | 100 | | { |
| | 3653 | 101 | | var activity = context.Activity; |
| | 3653 | 102 | | var activityDescriptor = context.ActivityDescriptor; |
| | 3653 | 103 | | var kind = activityDescriptor.Kind; |
| | | 104 | | |
| | 3653 | 105 | | return !GetIsBackgroundExecution(context) |
| | 3653 | 106 | | && context.WorkflowExecutionContext.ExecuteDelegate == null |
| | 3653 | 107 | | && (kind is ActivityKind.Job || GetTaskRunAsynchronously(context)); |
| | | 108 | | } |
| | | 109 | | |
| | | 110 | | private static bool GetTaskRunAsynchronously(ActivityExecutionContext context) |
| | | 111 | | { |
| | 3600 | 112 | | var activity = context.Activity; |
| | 3600 | 113 | | var activityDescriptor = context.ActivityDescriptor; |
| | 3600 | 114 | | var kind = activityDescriptor.Kind; |
| | | 115 | | |
| | 3600 | 116 | | if (kind is not ActivityKind.Task) |
| | 3580 | 117 | | return false; |
| | | 118 | | |
| | 20 | 119 | | var runAsynchronously = activity.GetRunAsynchronously(); |
| | | 120 | | |
| | 20 | 121 | | if (runAsynchronously is null) |
| | | 122 | | { |
| | 8 | 123 | | var taskActivityAttribute = activityDescriptor.Attributes.OfType<TaskActivityAttribute>().FirstOrDefault(); |
| | | 124 | | |
| | 8 | 125 | | return taskActivityAttribute is { RunAsynchronously: true }; |
| | | 126 | | } |
| | | 127 | | |
| | 12 | 128 | | return (bool)runAsynchronously; |
| | | 129 | | } |
| | | 130 | | |
| | 7295 | 131 | | private static bool GetIsBackgroundExecution(ActivityExecutionContext context) => context.TransientProperties.Contai |
| | | 132 | | |
| | | 133 | | /// <summary> |
| | | 134 | | /// If the input contains captured output from the background activity invoker, apply that to the execution context. |
| | | 135 | | /// </summary> |
| | | 136 | | private static void CaptureOutputIfAny(ActivityExecutionContext context) |
| | | 137 | | { |
| | 31 | 138 | | var activity = context.Activity; |
| | 31 | 139 | | var inputKey = GetBackgroundActivityOutputKey(activity.NodeId); |
| | 31 | 140 | | var capturedOutput = context.WorkflowExecutionContext.GetProperty<IDictionary<string, object>>(inputKey); |
| | | 141 | | |
| | 31 | 142 | | context.WorkflowExecutionContext.Properties.Remove(inputKey); |
| | | 143 | | |
| | 31 | 144 | | if (capturedOutput == null) |
| | 28 | 145 | | return; |
| | | 146 | | |
| | 18 | 147 | | foreach (var outputEntry in capturedOutput) |
| | | 148 | | { |
| | 15 | 149 | | var outputDescriptor = context.ActivityDescriptor.Outputs.FirstOrDefault(x => x.Name == outputEntry.Key); |
| | | 150 | | |
| | 6 | 151 | | if (outputDescriptor == null) |
| | | 152 | | continue; |
| | | 153 | | |
| | 6 | 154 | | var output = (Output?)outputDescriptor.ValueGetter(activity); |
| | 6 | 155 | | context.Set(output, outputEntry.Value, outputDescriptor.Name); |
| | | 156 | | } |
| | 3 | 157 | | } |
| | | 158 | | |
| | | 159 | | private void CaptureJournalData(ActivityExecutionContext context) |
| | | 160 | | { |
| | 31 | 161 | | var activity = context.Activity; |
| | 31 | 162 | | var journalDataKey = GetBackgroundActivityJournalDataKey(activity.NodeId); |
| | 31 | 163 | | var journalData = context.WorkflowExecutionContext.GetProperty<IDictionary<string, object>>(journalDataKey); |
| | | 164 | | |
| | 31 | 165 | | context.WorkflowExecutionContext.Properties.Remove(journalDataKey); |
| | | 166 | | |
| | 31 | 167 | | if (journalData == null) |
| | 28 | 168 | | return; |
| | | 169 | | |
| | 6 | 170 | | foreach (var journalEntry in journalData) |
| | 0 | 171 | | context.JournalData[journalEntry.Key] = journalEntry.Value; |
| | 3 | 172 | | } |
| | | 173 | | |
| | | 174 | | private void CaptureBookmarkData(ActivityExecutionContext context) |
| | | 175 | | { |
| | 31 | 176 | | var activity = context.Activity; |
| | 31 | 177 | | var bookmarksKey = GetBackgroundActivityBookmarksKey(activity.NodeId); |
| | 31 | 178 | | var bookmarks = context.WorkflowExecutionContext.GetProperty<ICollection<Bookmark>>(bookmarksKey); |
| | 31 | 179 | | if (bookmarks != null) |
| | | 180 | | { |
| | 3 | 181 | | context.AddBookmarks(bookmarks); |
| | | 182 | | } |
| | | 183 | | |
| | 31 | 184 | | context.WorkflowExecutionContext.Properties.Remove(bookmarksKey); |
| | 31 | 185 | | } |
| | | 186 | | |
| | | 187 | | private void CapturePropertiesIfAny(ActivityExecutionContext context) |
| | | 188 | | { |
| | 31 | 189 | | var activity = context.Activity; |
| | 31 | 190 | | var propertiesKey = GetBackgroundActivityPropertiesKey(activity.NodeId); |
| | 31 | 191 | | var capturedProperties = context.WorkflowExecutionContext.GetProperty<IDictionary<string, object>>(propertiesKey |
| | | 192 | | |
| | 31 | 193 | | context.WorkflowExecutionContext.Properties.Remove(propertiesKey); |
| | | 194 | | |
| | 31 | 195 | | if (capturedProperties == null) |
| | 28 | 196 | | return; |
| | | 197 | | |
| | 12 | 198 | | foreach (var property in capturedProperties) |
| | 3 | 199 | | context.Properties[property.Key] = property.Value; |
| | 3 | 200 | | } |
| | | 201 | | |
| | | 202 | | private async Task CompleteBackgroundActivityOutcomesAsync(ActivityExecutionContext context) |
| | | 203 | | { |
| | 31 | 204 | | var outcomesKey = GetBackgroundActivityOutcomesKey(context.NodeId); |
| | 31 | 205 | | var outcomes = context.WorkflowExecutionContext.GetProperty<ICollection<string>>(outcomesKey); |
| | | 206 | | |
| | 31 | 207 | | if (outcomes != null) |
| | | 208 | | { |
| | 0 | 209 | | await context.CompleteActivityWithOutcomesAsync(outcomes.ToArray()); |
| | | 210 | | } |
| | | 211 | | |
| | | 212 | | // Remove the outcomes from the workflow execution context. |
| | 31 | 213 | | context.WorkflowExecutionContext.Properties.Remove(outcomesKey); |
| | 31 | 214 | | } |
| | | 215 | | |
| | | 216 | | private async Task CompleteBackgroundActivityAsync(ActivityExecutionContext context) |
| | | 217 | | { |
| | 31 | 218 | | var completedKey = GetBackgroundActivityCompletedKey(context.NodeId); |
| | 31 | 219 | | var completed = context.WorkflowExecutionContext.GetProperty<bool?>(completedKey); |
| | | 220 | | |
| | 31 | 221 | | if (completed is true) |
| | | 222 | | { |
| | 3 | 223 | | await context.CompleteActivityAsync(); |
| | | 224 | | } |
| | | 225 | | |
| | | 226 | | // Remove the outcomes from the workflow execution context. |
| | 31 | 227 | | context.WorkflowExecutionContext.Properties.Remove(completedKey); |
| | 31 | 228 | | } |
| | | 229 | | |
| | | 230 | | private async Task CompleteBackgroundActivityScheduledActivitiesAsync(ActivityExecutionContext context) |
| | | 231 | | { |
| | 31 | 232 | | var scheduledActivitiesKey = GetBackgroundActivityScheduledActivitiesKey(context.NodeId); |
| | 31 | 233 | | var scheduledActivitiesJson = context.WorkflowExecutionContext.GetProperty<string>(scheduledActivitiesKey); |
| | 31 | 234 | | var scheduledActivities = scheduledActivitiesJson != null ? JsonSerializer.Deserialize<ICollection<ScheduledActi |
| | | 235 | | |
| | 31 | 236 | | if (scheduledActivities != null) |
| | | 237 | | { |
| | 6 | 238 | | foreach (var scheduledActivity in scheduledActivities) |
| | | 239 | | { |
| | 0 | 240 | | var activityNode = scheduledActivity.ActivityNodeId != null ? context.WorkflowExecutionContext.FindActiv |
| | 0 | 241 | | var owner = scheduledActivity.OwnerActivityInstanceId != null ? context.WorkflowExecutionContext.Activit |
| | 0 | 242 | | var options = scheduledActivity.Options != null |
| | 0 | 243 | | ? new ScheduleWorkOptions |
| | 0 | 244 | | { |
| | 0 | 245 | | ExistingActivityExecutionContext = scheduledActivity.Options.ExistingActivityInstanceId != null |
| | 0 | 246 | | Variables = scheduledActivity.Options?.Variables, |
| | 0 | 247 | | CompletionCallback = !string.IsNullOrEmpty(scheduledActivity.Options?.CompletionCallback) && own |
| | 0 | 248 | | PreventDuplicateScheduling = scheduledActivity.Options?.PreventDuplicateScheduling ?? false, |
| | 0 | 249 | | Input = scheduledActivity.Options?.Input, |
| | 0 | 250 | | Tag = scheduledActivity.Options?.Tag |
| | 0 | 251 | | } |
| | 0 | 252 | | : default; |
| | 0 | 253 | | await context.ScheduleActivityAsync(activityNode, owner, options); |
| | | 254 | | } |
| | | 255 | | } |
| | | 256 | | |
| | | 257 | | // Remove the scheduled activities from the workflow execution context. |
| | 31 | 258 | | context.WorkflowExecutionContext.Properties.Remove(scheduledActivitiesKey); |
| | 31 | 259 | | } |
| | | 260 | | } |