| | | 1 | | using System.ComponentModel; |
| | | 2 | | using System.Runtime.CompilerServices; |
| | | 3 | | using System.Text.Json.Serialization; |
| | | 4 | | using Elsa.Expressions.Contracts; |
| | | 5 | | using Elsa.Extensions; |
| | | 6 | | using Elsa.Workflows.Activities; |
| | | 7 | | using Elsa.Workflows.Activities.StateMachine.Models; |
| | | 8 | | using Elsa.Workflows.Attributes; |
| | | 9 | | using Elsa.Workflows.Models; |
| | | 10 | | using Elsa.Workflows.Options; |
| | | 11 | | using JetBrains.Annotations; |
| | | 12 | | |
| | | 13 | | namespace Elsa.Workflows.Activities.StateMachine.Activities; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Executes a state machine made of named states and trigger-driven transitions. |
| | | 17 | | /// </summary> |
| | | 18 | | [Activity("Elsa", "Flow", "Executes a state machine made of named states and trigger-driven transitions.")] |
| | | 19 | | [PublicAPI] |
| | | 20 | | public class StateMachine : Activity |
| | | 21 | | { |
| | | 22 | | private const string PhaseEntering = "Entering"; |
| | | 23 | | private const string PhaseContinuing = "Continuing"; |
| | | 24 | | private const string CurrentStateProperty = "CurrentState"; |
| | 34 | 25 | | private readonly Inline _automaticTransitionContinuation = new(); |
| | | 26 | | |
| | | 27 | | /// <inheritdoc /> |
| | 34 | 28 | | public StateMachine([CallerFilePath] string? source = null, [CallerLineNumber] int? line = null) : base(source, line |
| | | 29 | | { |
| | 34 | 30 | | } |
| | | 31 | | |
| | | 32 | | /// <summary> |
| | | 33 | | /// The states in declaration order. |
| | | 34 | | /// </summary> |
| | 311 | 35 | | public ICollection<StateMachineState> States { get; set; } = new List<StateMachineState>(); |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// The transitions in declaration order. |
| | | 39 | | /// </summary> |
| | 379 | 40 | | public ICollection<Transition> Transitions { get; set; } = new List<Transition>(); |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// The first state to enter when no current state is set. |
| | | 44 | | /// </summary> |
| | 58 | 45 | | public string? InitialState { get; set; } |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// The currently active state. |
| | | 49 | | /// </summary> |
| | 71 | 50 | | public string? CurrentState { get; set; } |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// Exposes nested activities to the workflow graph builder. |
| | | 54 | | /// </summary> |
| | | 55 | | [JsonIgnore] |
| | | 56 | | [Browsable(false)] |
| | 26 | 57 | | public IEnumerable<IActivity> Activities => GetActivities(); |
| | | 58 | | |
| | | 59 | | /// <inheritdoc /> |
| | | 60 | | protected override async ValueTask ExecuteAsync(ActivityExecutionContext context) |
| | | 61 | | { |
| | 26 | 62 | | EnsureSupportedTriggerIdentities(); |
| | | 63 | | |
| | 24 | 64 | | var currentState = GetCurrentState(context); |
| | 24 | 65 | | SetCurrentState(context, string.IsNullOrWhiteSpace(currentState) ? InitialState : currentState); |
| | | 66 | | |
| | 24 | 67 | | if (FindState(GetCurrentState(context)) == null) |
| | | 68 | | { |
| | 0 | 69 | | await context.CompleteActivityAsync(); |
| | 0 | 70 | | return; |
| | | 71 | | } |
| | | 72 | | |
| | 24 | 73 | | await EnterStateAsync(context); |
| | 24 | 74 | | } |
| | | 75 | | |
| | | 76 | | private async ValueTask EnterStateAsync(ActivityExecutionContext context, ActivityExecutionContext? schedulingContex |
| | | 77 | | { |
| | 37 | 78 | | var state = FindState(GetCurrentState(context)); |
| | | 79 | | |
| | 37 | 80 | | if (state == null) |
| | | 81 | | { |
| | 0 | 82 | | await context.CompleteActivityAsync(); |
| | 0 | 83 | | return; |
| | | 84 | | } |
| | | 85 | | |
| | 37 | 86 | | if (state.Entry != null) |
| | | 87 | | { |
| | 20 | 88 | | await ScheduleAsync(context, state.Entry, OnStateEntryCompletedAsync, PhaseEntering, schedulingContext); |
| | 20 | 89 | | return; |
| | | 90 | | } |
| | | 91 | | |
| | 17 | 92 | | await ScheduleOutboundTriggersAsync(context, schedulingContext); |
| | 37 | 93 | | } |
| | | 94 | | |
| | | 95 | | private async ValueTask OnStateEntryCompletedAsync(ActivityCompletedContext context) |
| | | 96 | | { |
| | 17 | 97 | | await ScheduleOutboundTriggersAsync(context.TargetContext, context.ChildContext); |
| | 17 | 98 | | } |
| | | 99 | | |
| | | 100 | | private async ValueTask ScheduleOutboundTriggersAsync(ActivityExecutionContext context, ActivityExecutionContext? sc |
| | | 101 | | { |
| | 82 | 102 | | var outboundTransitions = GetOutboundTransitions(GetCurrentState(context)).Where(x => FindState(x.To) != null).T |
| | | 103 | | |
| | 34 | 104 | | if (!outboundTransitions.Any()) |
| | | 105 | | { |
| | 4 | 106 | | await context.CompleteActivityAsync(); |
| | 4 | 107 | | return; |
| | | 108 | | } |
| | | 109 | | |
| | 119 | 110 | | foreach (var transition in outboundTransitions.Where(x => x.Trigger == null)) |
| | | 111 | | { |
| | 11 | 112 | | if (await TryTakeTransitionAsync(context, transition, schedulingContext)) |
| | 9 | 113 | | return; |
| | | 114 | | } |
| | | 115 | | |
| | 58 | 116 | | var triggeredTransitions = outboundTransitions.Where(x => x.Trigger != null).ToList(); |
| | | 117 | | |
| | 21 | 118 | | if (!triggeredTransitions.Any()) |
| | 1 | 119 | | return; |
| | | 120 | | |
| | 110 | 121 | | foreach (var transition in triggeredTransitions) |
| | 35 | 122 | | await ScheduleAsync(context, transition.Trigger!, OnTriggerCompletedAsync, GetTransitionKey(transition), sch |
| | 34 | 123 | | } |
| | | 124 | | |
| | | 125 | | private async ValueTask OnTriggerCompletedAsync(ActivityCompletedContext context) |
| | | 126 | | { |
| | 15 | 127 | | var targetContext = context.TargetContext; |
| | 15 | 128 | | var transition = FindTransitionByKey(targetContext, GetCompletionTag(context)) ?? FindTransitionByTrigger(target |
| | | 129 | | |
| | 15 | 130 | | if (transition == null || !IsCurrentSource(targetContext, transition) || FindState(transition.To) == null) |
| | 0 | 131 | | return; |
| | | 132 | | |
| | 15 | 133 | | if (!await TryTakeTransitionAsync(targetContext, transition, context.ChildContext)) |
| | | 134 | | { |
| | 2 | 135 | | if (transition.Trigger != null) |
| | 2 | 136 | | await ScheduleAsync(targetContext, transition.Trigger, OnTriggerCompletedAsync, GetTransitionKey(transit |
| | | 137 | | } |
| | 15 | 138 | | } |
| | | 139 | | |
| | | 140 | | private async ValueTask<bool> TryTakeTransitionAsync( |
| | | 141 | | ActivityExecutionContext context, |
| | | 142 | | Transition transition, |
| | | 143 | | ActivityExecutionContext? schedulingContext) |
| | | 144 | | { |
| | 26 | 145 | | var canTransition = transition.Condition == null || await EvaluateConditionAsync(context, transition.Condition); |
| | | 146 | | |
| | 26 | 147 | | if (!canTransition) |
| | 4 | 148 | | return false; |
| | | 149 | | |
| | 22 | 150 | | await CancelCompetingTriggersAsync(context, transition, schedulingContext); |
| | 22 | 151 | | await ExitStateAsync(context, transition, schedulingContext); |
| | 22 | 152 | | return true; |
| | 26 | 153 | | } |
| | | 154 | | |
| | | 155 | | private async ValueTask RunTransitionActionAsync(ActivityExecutionContext context, Transition transition, ActivityEx |
| | | 156 | | { |
| | 18 | 157 | | if (!IsCurrentSource(context, transition)) |
| | 0 | 158 | | return; |
| | | 159 | | |
| | 18 | 160 | | if (transition.Action != null) |
| | | 161 | | { |
| | 7 | 162 | | await ScheduleTransitionActivityAsync(context, transition.Action, transition, OnTransitionActionCompletedAsy |
| | 7 | 163 | | return; |
| | | 164 | | } |
| | | 165 | | |
| | 11 | 166 | | await CompleteTransitionAsync(context, transition, schedulingContext); |
| | 18 | 167 | | } |
| | | 168 | | |
| | | 169 | | private async ValueTask OnTransitionActionCompletedAsync(ActivityCompletedContext context) |
| | | 170 | | { |
| | 6 | 171 | | var targetContext = context.TargetContext; |
| | 6 | 172 | | var transition = FindTransitionByKey(targetContext, GetCompletionTag(context)); |
| | | 173 | | |
| | 6 | 174 | | if (transition == null || !IsCurrentSource(targetContext, transition)) |
| | 1 | 175 | | return; |
| | | 176 | | |
| | 5 | 177 | | await CompleteTransitionAsync(targetContext, transition, context.ChildContext); |
| | 6 | 178 | | } |
| | | 179 | | |
| | | 180 | | private async ValueTask ExitStateAsync(ActivityExecutionContext context, Transition transition, ActivityExecutionCon |
| | | 181 | | { |
| | 22 | 182 | | var sourceState = FindState(transition.From); |
| | | 183 | | |
| | 22 | 184 | | if (sourceState?.Exit != null) |
| | | 185 | | { |
| | 10 | 186 | | await ScheduleTransitionActivityAsync(context, sourceState.Exit, transition, OnStateExitCompletedAsync, sche |
| | 10 | 187 | | return; |
| | | 188 | | } |
| | | 189 | | |
| | 12 | 190 | | await RunTransitionActionAsync(context, transition, schedulingContext); |
| | 22 | 191 | | } |
| | | 192 | | |
| | | 193 | | private async ValueTask OnStateExitCompletedAsync(ActivityCompletedContext context) |
| | | 194 | | { |
| | 7 | 195 | | var targetContext = context.TargetContext; |
| | 7 | 196 | | var transition = FindTransitionByKey(targetContext, GetCompletionTag(context)); |
| | | 197 | | |
| | 7 | 198 | | if (transition == null || !IsCurrentSource(targetContext, transition)) |
| | 1 | 199 | | return; |
| | | 200 | | |
| | 6 | 201 | | await RunTransitionActionAsync(targetContext, transition, context.ChildContext); |
| | 7 | 202 | | } |
| | | 203 | | |
| | | 204 | | private async ValueTask CompleteTransitionAsync(ActivityExecutionContext context, Transition transition, ActivityExe |
| | | 205 | | { |
| | 16 | 206 | | SetCurrentState(context, transition.To); |
| | | 207 | | |
| | | 208 | | // Automatic transitions are normally evaluated inline after entering a state. If the |
| | | 209 | | // target is part of a triggerless cycle, queue the next evaluation instead. This keeps |
| | | 210 | | // the WF4 ordering (the transition has completed and the target state is current) while |
| | | 211 | | // allowing the workflow scheduler to unwind the current call stack between iterations. |
| | 16 | 212 | | if (HasAutomaticCycle(GetCurrentState(context))) |
| | | 213 | | { |
| | 6 | 214 | | await ScheduleAsync(context, _automaticTransitionContinuation, OnAutomaticTransitionContinuationCompletedAsy |
| | 6 | 215 | | return; |
| | | 216 | | } |
| | | 217 | | |
| | 10 | 218 | | await EnterStateAsync(context, schedulingContext); |
| | 16 | 219 | | } |
| | | 220 | | |
| | | 221 | | private async ValueTask OnAutomaticTransitionContinuationCompletedAsync(ActivityCompletedContext context) |
| | | 222 | | { |
| | 3 | 223 | | await EnterStateAsync(context.TargetContext, context.ChildContext); |
| | 3 | 224 | | } |
| | | 225 | | |
| | | 226 | | private async ValueTask ScheduleTransitionActivityAsync( |
| | | 227 | | ActivityExecutionContext context, |
| | | 228 | | IActivity activity, |
| | | 229 | | Transition transition, |
| | | 230 | | ActivityCompletionCallback callback, |
| | | 231 | | ActivityExecutionContext? schedulingContext) |
| | | 232 | | { |
| | 17 | 233 | | await ScheduleAsync(context, activity, callback, GetTransitionKey(transition), schedulingContext); |
| | 17 | 234 | | } |
| | | 235 | | |
| | | 236 | | private static async ValueTask ScheduleAsync( |
| | | 237 | | ActivityExecutionContext context, |
| | | 238 | | IActivity activity, |
| | | 239 | | ActivityCompletionCallback callback, |
| | | 240 | | string tag, |
| | | 241 | | ActivityExecutionContext? schedulingContext) |
| | | 242 | | { |
| | 80 | 243 | | var options = new ScheduleWorkOptions |
| | 80 | 244 | | { |
| | 80 | 245 | | CompletionCallback = callback, |
| | 80 | 246 | | Tag = tag, |
| | 80 | 247 | | SchedulingActivityExecutionId = schedulingContext?.Id |
| | 80 | 248 | | }; |
| | | 249 | | |
| | 80 | 250 | | await context.ScheduleActivityAsync(activity, options); |
| | 80 | 251 | | } |
| | | 252 | | |
| | | 253 | | private async Task CancelCompetingTriggersAsync(ActivityExecutionContext context, Transition winningTransition, Acti |
| | | 254 | | { |
| | 22 | 255 | | var competingTriggerIds = GetOutboundTransitions(winningTransition.From) |
| | 37 | 256 | | .Where(x => !ReferenceEquals(x, winningTransition)) |
| | 15 | 257 | | .Select(x => x.Trigger?.Id) |
| | 15 | 258 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 14 | 259 | | .Select(x => x!) |
| | 22 | 260 | | .ToHashSet(); |
| | | 261 | | |
| | 22 | 262 | | var competingTriggerContexts = context.WorkflowExecutionContext.ActivityExecutionContexts |
| | 35 | 263 | | .Where(x => x.ParentActivityExecutionContext == context && !ReferenceEquals(x, winningTriggerContext) && com |
| | 22 | 264 | | .ToList(); |
| | | 265 | | |
| | 52 | 266 | | foreach (var competingTriggerContext in competingTriggerContexts) |
| | 4 | 267 | | await competingTriggerContext.CancelActivityAsync(); |
| | | 268 | | |
| | 22 | 269 | | RemoveScheduledCompetingTriggers(context, competingTriggerIds); |
| | 22 | 270 | | RemoveCompetingTriggerCallbacks(context, competingTriggerIds); |
| | 22 | 271 | | } |
| | | 272 | | |
| | | 273 | | private static void RemoveScheduledCompetingTriggers(ActivityExecutionContext context, HashSet<string> competingTrig |
| | | 274 | | { |
| | 22 | 275 | | var scheduler = context.WorkflowExecutionContext.Scheduler; |
| | 61 | 276 | | scheduler.RemoveWhere(x => IsCompetingTriggerWorkItem(context, competingTriggerIds, x)); |
| | 22 | 277 | | } |
| | | 278 | | |
| | | 279 | | private static bool IsCompetingTriggerWorkItem(ActivityExecutionContext context, HashSet<string> competingTriggerIds |
| | 39 | 280 | | workItem.Owner == context && competingTriggerIds.Contains(workItem.Activity.Id); |
| | | 281 | | |
| | | 282 | | private static void RemoveCompetingTriggerCallbacks(ActivityExecutionContext context, HashSet<string> competingTrigg |
| | | 283 | | { |
| | 22 | 284 | | var competingTriggerCallbacks = context.WorkflowExecutionContext.CompletionCallbacks |
| | 13 | 285 | | .Where(x => x.Owner == context && competingTriggerIds.Contains(x.Child.Activity.Id)) |
| | 22 | 286 | | .ToList(); |
| | | 287 | | |
| | 22 | 288 | | context.WorkflowExecutionContext.RemoveCompletionCallbacks(competingTriggerCallbacks); |
| | 22 | 289 | | } |
| | | 290 | | |
| | 209 | 291 | | private string? GetCurrentState(ActivityExecutionContext context) => context.GetProperty<string>(CurrentStatePropert |
| | | 292 | | |
| | | 293 | | private IEnumerable<IActivity> GetActivities() |
| | | 294 | | { |
| | 361 | 295 | | foreach (var stateActivity in States.SelectMany(x => new[] { x.Entry, x.Exit }).Where(x => x != null)) |
| | 51 | 296 | | yield return stateActivity!; |
| | | 297 | | |
| | 26 | 298 | | var seenTriggerInstances = new HashSet<IActivity>(ReferenceEqualityComparer.Instance); |
| | 26 | 299 | | var seenTriggerIds = new HashSet<string>(StringComparer.Ordinal); |
| | | 300 | | |
| | 184 | 301 | | foreach (var transition in Transitions) |
| | | 302 | | { |
| | 66 | 303 | | if (transition.Trigger != null && seenTriggerInstances.Add(transition.Trigger) && |
| | 66 | 304 | | (string.IsNullOrWhiteSpace(transition.Trigger.Id) || seenTriggerIds.Add(transition.Trigger.Id))) |
| | 54 | 305 | | yield return transition.Trigger; |
| | | 306 | | |
| | 66 | 307 | | if (transition.Action != null) |
| | 19 | 308 | | yield return transition.Action; |
| | 66 | 309 | | } |
| | | 310 | | |
| | 26 | 311 | | yield return _automaticTransitionContinuation; |
| | 26 | 312 | | } |
| | | 313 | | |
| | | 314 | | private void EnsureSupportedTriggerIdentities() |
| | | 315 | | { |
| | 148 | 316 | | var triggers = Transitions.Where(x => x.Trigger != null).Select(x => x.Trigger!).ToList(); |
| | 26 | 317 | | var seenInstances = new HashSet<IActivity>(ReferenceEqualityComparer.Instance); |
| | 26 | 318 | | var seenIds = new HashSet<string>(StringComparer.Ordinal); |
| | | 319 | | |
| | 158 | 320 | | foreach (var trigger in triggers) |
| | | 321 | | { |
| | 54 | 322 | | var sharesInstance = !seenInstances.Add(trigger); |
| | 54 | 323 | | var duplicatesId = !string.IsNullOrWhiteSpace(trigger.Id) && !seenIds.Add(trigger.Id); |
| | | 324 | | |
| | 54 | 325 | | if (sharesInstance || duplicatesId) |
| | 2 | 326 | | throw new InvalidOperationException("StateMachine transitions cannot share a Trigger activity in Elsa 3. |
| | | 327 | | } |
| | 24 | 328 | | } |
| | | 329 | | |
| | | 330 | | private void SetCurrentState(ActivityExecutionContext context, string? state) |
| | | 331 | | { |
| | 40 | 332 | | CurrentState = state; |
| | | 333 | | |
| | 40 | 334 | | if (state == null) |
| | 0 | 335 | | context.RemoveProperty(CurrentStateProperty); |
| | | 336 | | else |
| | 40 | 337 | | context.SetProperty(CurrentStateProperty, state); |
| | 40 | 338 | | } |
| | | 339 | | |
| | 46 | 340 | | private bool IsCurrentSource(ActivityExecutionContext context, Transition transition) => string.Equals(transition.Fr |
| | | 341 | | |
| | | 342 | | private static async Task<bool> EvaluateConditionAsync(ActivityExecutionContext context, Input<bool> condition) |
| | | 343 | | { |
| | 15 | 344 | | var evaluator = context.GetRequiredService<IExpressionEvaluator>(); |
| | 15 | 345 | | return await evaluator.EvaluateAsync(condition, context.ExpressionExecutionContext); |
| | 15 | 346 | | } |
| | | 347 | | |
| | | 348 | | private StateMachineState? FindState(string? name) => |
| | 154 | 349 | | string.IsNullOrWhiteSpace(name) |
| | 154 | 350 | | ? null |
| | 403 | 351 | | : States.FirstOrDefault(x => string.Equals(x.Name, name, StringComparison.Ordinal)); |
| | | 352 | | |
| | | 353 | | private IEnumerable<Transition> GetOutboundTransitions(string? sourceState) => |
| | 102 | 354 | | string.IsNullOrWhiteSpace(sourceState) |
| | 102 | 355 | | ? [] |
| | 312 | 356 | | : Transitions.Where(x => string.Equals(x.From, sourceState, StringComparison.Ordinal)); |
| | | 357 | | |
| | | 358 | | private bool HasAutomaticCycle(string? startingState) |
| | | 359 | | { |
| | 16 | 360 | | if (string.IsNullOrWhiteSpace(startingState)) |
| | 0 | 361 | | return false; |
| | | 362 | | |
| | 16 | 363 | | var visitedStates = new HashSet<string>(StringComparer.Ordinal); |
| | 16 | 364 | | var statesToVisit = new Stack<string>([startingState]); |
| | | 365 | | |
| | 28 | 366 | | while (statesToVisit.TryPop(out var state)) |
| | | 367 | | { |
| | 62 | 368 | | foreach (var transition in GetOutboundTransitions(state).Where(x => x.Trigger == null && FindState(x.To) != |
| | | 369 | | { |
| | 8 | 370 | | if (string.Equals(transition.To, startingState, StringComparison.Ordinal)) |
| | 6 | 371 | | return true; |
| | | 372 | | |
| | 2 | 373 | | if (visitedStates.Add(transition.To!)) |
| | 2 | 374 | | statesToVisit.Push(transition.To!); |
| | | 375 | | } |
| | | 376 | | } |
| | | 377 | | |
| | 10 | 378 | | return false; |
| | 6 | 379 | | } |
| | | 380 | | |
| | | 381 | | private Transition? FindTransitionByTrigger(ActivityExecutionContext context, IActivity trigger) => |
| | 0 | 382 | | GetOutboundTransitions(GetCurrentState(context)).FirstOrDefault(x => ReferenceEquals(x.Trigger, trigger)); |
| | | 383 | | |
| | | 384 | | private Transition? FindTransitionByKey(ActivityExecutionContext context, string? key) |
| | | 385 | | { |
| | 28 | 386 | | if (string.IsNullOrWhiteSpace(key)) |
| | 0 | 387 | | return null; |
| | | 388 | | |
| | 28 | 389 | | var currentState = GetCurrentState(context); |
| | 59 | 390 | | return GetOutboundTransitions(currentState).FirstOrDefault(x => string.Equals(GetTransitionKey(x), key, StringCo |
| | 30 | 391 | | ?? Transitions.FirstOrDefault(x => string.Equals(GetTransitionKey(x), key, StringComparison.Ordinal)); |
| | | 392 | | } |
| | | 393 | | |
| | | 394 | | private string GetTransitionKey(Transition transition) |
| | | 395 | | { |
| | 87 | 396 | | var index = 0; |
| | 339 | 397 | | foreach (var current in Transitions) |
| | | 398 | | { |
| | 126 | 399 | | if (ReferenceEquals(current, transition)) |
| | 87 | 400 | | return $"{index}:{GetTransitionDisplayKey(transition)}"; |
| | | 401 | | |
| | 39 | 402 | | index++; |
| | | 403 | | } |
| | | 404 | | |
| | 0 | 405 | | return GetTransitionDisplayKey(transition); |
| | 87 | 406 | | } |
| | | 407 | | |
| | | 408 | | private static string GetTransitionDisplayKey(Transition transition) => |
| | 87 | 409 | | string.IsNullOrWhiteSpace(transition.Name) |
| | 87 | 410 | | ? $"{transition.From}->{transition.To}" |
| | 87 | 411 | | : transition.Name; |
| | | 412 | | |
| | | 413 | | private static string? GetCompletionTag(ActivityCompletedContext context) => |
| | 28 | 414 | | context.TargetContext.Tag as string ?? context.ChildContext.Tag as string; |
| | | 415 | | |
| | | 416 | | } |