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