| | | 1 | | using Bpmn.Model; |
| | | 2 | | using Bpmn.Semantics; |
| | | 3 | | using Elsa.Bpmn.Activities; |
| | | 4 | | using Elsa.Bpmn.Exceptions; |
| | | 5 | | using Elsa.Bpmn.Signals; |
| | | 6 | | using Elsa.Extensions; |
| | | 7 | | using Elsa.Workflows; |
| | | 8 | | using Elsa.Workflows.Activities.Flowchart.Models; |
| | | 9 | | using Elsa.Workflows.Signals; |
| | | 10 | | |
| | | 11 | | namespace Elsa.Bpmn.Hosting; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// The host side of the <c>Bpmn.Semantics</c> port for one BPMN scope: it feeds the interpreter's four entry points |
| | | 15 | | /// and applies what comes back onto the scope's <see cref="ActivityExecutionContext"/>. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <remarks> |
| | | 18 | | /// <para> |
| | | 19 | | /// Every entry point is synchronous and returns a value; the interpreter never calls back. The host's job is to say |
| | | 20 | | /// what its world looks like — a snapshot — and then to do what it is told, in the order it is told. |
| | | 21 | | /// </para> |
| | | 22 | | /// <para> |
| | | 23 | | /// A host instance is a view over one scope's context and is created per call. Everything durable lives in |
| | | 24 | | /// <see cref="BpmnScopeMemory"/>, everything derived lives in the context's transient properties, and everything |
| | | 25 | | /// ordering-related lives in the instance-wide <see cref="BpmnScopeDispatcher"/>. |
| | | 26 | | /// </para> |
| | | 27 | | /// </remarks> |
| | | 28 | | internal sealed class BpmnScopeHost |
| | | 29 | | { |
| | | 30 | | /// <summary> |
| | | 31 | | /// What this host promises it can do. |
| | | 32 | | /// </summary> |
| | | 33 | | /// <remarks> |
| | | 34 | | /// Each capability is a claim, honoured elsewhere in this module: subtree cancellation by |
| | | 35 | | /// <see cref="BpmnWorkTeardown"/>, scope signalling by <see cref="BpmnScopeSignal"/>, iteration scopes by the |
| | | 36 | | /// applier's per-instance variables, and <see cref="BpmnHostCapabilities.ScopeVariables"/> by |
| | | 37 | | /// <see cref="BpmnScopeVariables"/>. Defined in terms of <see cref="BpmnRuntimeCapabilities.Declared"/> — see its |
| | | 38 | | /// remarks for why the set is spelled out there rather than written as <c>BpmnHostCapabilities.Full</c>, and for |
| | | 39 | | /// why that type exists at all. The same set goes to <see cref="BpmnGraph.Build"/> and to every snapshot, which |
| | | 40 | | /// the port requires. |
| | | 41 | | /// </remarks> |
| | | 42 | | public const BpmnHostCapabilities Capabilities = BpmnRuntimeCapabilities.Declared; |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// The property key under which a nested scope's invocation correlation is carried on its own context. |
| | | 46 | | /// </summary> |
| | | 47 | | public const string InvocationCorrelationPropertyKey = "Bpmn:InvocationCorrelation"; |
| | | 48 | | |
| | | 49 | | private const string GraphTransientPropertyKey = "Bpmn:Graph"; |
| | | 50 | | |
| | | 51 | | // The interpreter is a pure function of its request: it holds no per-instance state, so one instance serves the |
| | | 52 | | // whole process. Creating one per evaluation would only re-register the built-in element behaviors. |
| | 2 | 53 | | private static readonly BpmnInterpreter Interpreter = BpmnInterpreter.CreateDefault(); |
| | | 54 | | |
| | 2 | 55 | | private static readonly object DispatcherKey = new(); |
| | 2 | 56 | | private static readonly IReadOnlyDictionary<string, string> NoCorrelation = new Dictionary<string, string>(StringCom |
| | | 57 | | |
| | | 58 | | private readonly ActivityExecutionContext _context; |
| | | 59 | | private readonly BpmnProcess _process; |
| | | 60 | | |
| | 142 | 61 | | private BpmnScopeHost(ActivityExecutionContext context) |
| | | 62 | | { |
| | 142 | 63 | | _context = context; |
| | 142 | 64 | | _process = (BpmnProcess)context.Activity; |
| | 142 | 65 | | } |
| | | 66 | | |
| | | 67 | | /// <summary>Returns the host for the given BPMN scope context.</summary> |
| | 142 | 68 | | public static BpmnScopeHost For(ActivityExecutionContext context) => new(context); |
| | | 69 | | |
| | | 70 | | /// <summary>The evaluation queue shared by every BPMN scope in this workflow instance.</summary> |
| | | 71 | | public static BpmnScopeDispatcher DispatcherOf(WorkflowExecutionContext context) => |
| | 189 | 72 | | context.TransientProperties.GetOrAdd(DispatcherKey, () => new BpmnScopeDispatcher()); |
| | | 73 | | |
| | | 74 | | /// <summary>The built graph for this scope. Derived from the definition, the bound work and the capabilities, none |
| | 135 | 75 | | public BpmnGraph Graph => _context.TransientProperties.GetOrAdd(GraphTransientPropertyKey, BuildGraph); |
| | | 76 | | |
| | | 77 | | // --- The interpreter's four entry points --------------------------------------------------------- |
| | | 78 | | |
| | | 79 | | /// <summary>The scope is beginning.</summary> |
| | 38 | 80 | | public ValueTask StartAsync() => EvaluateAsync(memory => |
| | 76 | 81 | | Interpreter.Start(new BpmnStartRequest(Graph, memory.State, Snapshot(memory)))); |
| | | 82 | | |
| | | 83 | | /// <summary>A unit of work finished, reporting zero or more outcome names.</summary> |
| | 90 | 84 | | public ValueTask OnWorkCompletedAsync(ActivityExecutionContext childContext, object? result) => EvaluateAsync(memory |
| | 90 | 85 | | { |
| | 90 | 86 | | // Keyed on the child's own context id. A completion for work this scope no longer holds is absorbed rather |
| | 90 | 87 | | // than faulted: an interrupting boundary tears its host down while the host's work is still in flight, and a |
| | 90 | 88 | | // late completion for work that was torn down is an ordinary BPMN race. |
| | 90 | 89 | | if (memory.Work.FindByChildContextId(childContext.Id) is not { } record) |
| | 1 | 90 | | return null; |
| | 90 | 91 | | |
| | 90 | 92 | | // The completing work must ALREADY be gone from LiveWork when the interpreter is asked. |
| | 89 | 93 | | memory.Work.Remove(record); |
| | 89 | 94 | | memory.SaveWork(); |
| | 90 | 95 | | |
| | 89 | 96 | | var outcomeNames = result is Outcomes outcomes ? outcomes.Names : []; |
| | 90 | 97 | | |
| | 89 | 98 | | return Interpreter.OnWorkCompleted(new BpmnWorkCompletedRequest( |
| | 89 | 99 | | Graph, memory.State, Snapshot(memory), record.BindingRef, record.Handle, outcomeNames, record.IterationId)); |
| | 90 | 100 | | }); |
| | | 101 | | |
| | | 102 | | /// <summary>A nested scope this one invoked signalled outward.</summary> |
| | | 103 | | public ValueTask OnScopeSignalledAsync(BpmnScopeSignal signal, SignalContext signalContext) |
| | | 104 | | { |
| | 6 | 105 | | var sender = signalContext.SenderActivityExecutionContext; |
| | | 106 | | |
| | | 107 | | // The channel delivers to the sender before walking its ancestors, and a scope never signals itself. |
| | 6 | 108 | | if (string.Equals(sender.Id, _context.Id, StringComparison.Ordinal)) |
| | 3 | 109 | | return default; |
| | | 110 | | |
| | | 111 | | // A scope signal is for the immediate enclosing scope, which is the one that started the sender's work. Any |
| | | 112 | | // other receiver lets it keep bubbling; that is also how an unrelated container in between composes. |
| | 3 | 113 | | if (BpmnScopeMemory.Load(_context).Work.FindByChildContextId(sender.Id) is not { } signalling) |
| | 0 | 114 | | return default; |
| | | 115 | | |
| | 3 | 116 | | signalContext.StopPropagation(); |
| | | 117 | | |
| | 3 | 118 | | return EvaluateAsync(memory => |
| | 3 | 119 | | { |
| | 3 | 120 | | // Unlike a completion, the signalling work stays in the ledger: an escalating activity keeps running, and |
| | 3 | 121 | | // removing it makes the interpreter believe it has already gone. |
| | 3 | 122 | | if (memory.Work.FindByHandle(signalling.Handle) is not { } record) |
| | 0 | 123 | | return null; |
| | 3 | 124 | | |
| | 3 | 125 | | return Interpreter.OnWorkSignalled(new BpmnWorkSignalledRequest( |
| | 3 | 126 | | Graph, memory.State, Snapshot(memory), record.BindingRef, record.Handle, signal.Code, signal.Payload, re |
| | 3 | 127 | | }); |
| | | 128 | | } |
| | | 129 | | |
| | | 130 | | /// <summary> |
| | | 131 | | /// A unit of work failed. Rides the <see cref="FaultSignal"/> seam: handle the signal, ask the interpreter what |
| | | 132 | | /// BPMN makes of the fault, and claim it only when a catcher took it. |
| | | 133 | | /// </summary> |
| | | 134 | | /// <remarks> |
| | | 135 | | /// The disposition has to be decided before this handler returns, so the interpreter is asked inline; only the |
| | | 136 | | /// commands are applied through the dispatcher. A <c>Propagated</c> disposition is left strictly alone — no |
| | | 137 | | /// <c>StopPropagation</c>, nothing terminalized — so the fault reaches the enclosing scope, which is how BPMN |
| | | 138 | | /// error propagation crosses a scope boundary, or the incident strategy, which is how it surfaces at the root. |
| | | 139 | | /// </remarks> |
| | | 140 | | public async ValueTask OnWorkFaultedAsync(FaultSignal signal, SignalContext signalContext) |
| | | 141 | | { |
| | 8 | 142 | | var memory = BpmnScopeMemory.Load(_context); |
| | | 143 | | |
| | 8 | 144 | | if (ResolveFaultedWork(memory, signal.FaultedContext) is not { } record) |
| | 3 | 145 | | return; |
| | | 146 | | |
| | | 147 | | // As with a completion, the failed work must ALREADY be removed before the interpreter is asked. |
| | 5 | 148 | | memory.Work.Remove(record); |
| | 5 | 149 | | memory.SaveWork(); |
| | | 150 | | |
| | 5 | 151 | | var evaluation = Interpreter.OnWorkFaulted(new BpmnWorkFaultedRequest( |
| | 5 | 152 | | Graph, memory.State, Snapshot(memory), record.BindingRef, record.Handle, signal.Exception.Message)); |
| | | 153 | | |
| | 5 | 154 | | memory.State = evaluation.State.Prune(); |
| | 5 | 155 | | memory.SaveState(); |
| | | 156 | | |
| | 5 | 157 | | if (evaluation.Disposition is not BpmnErrorDisposition.Caught) |
| | 2 | 158 | | return; |
| | | 159 | | |
| | 3 | 160 | | signalContext.StopPropagation(); |
| | | 161 | | |
| | | 162 | | // A handler that claims a fault owns terminalizing the failed activity, and BPMN terminalizes the whole unit of |
| | | 163 | | // work rather than the one activity that threw: when the failure came from inside a nested scope, this scope's |
| | | 164 | | // failing work is that scope. Cancelling it recursively covers the activity that actually threw. The interprete |
| | | 165 | | // issues no teardown for failed work — it treats it as already terminal — so this is the host's own doing and |
| | | 166 | | // not a command out of order. RecoverFromFault stays the middleware's alone: it decrements every ancestor's |
| | | 167 | | // fault count, so a second call drives them negative. |
| | 3 | 168 | | if (BpmnWorkTeardown.FindContext(_context.WorkflowExecutionContext, record.ChildContextId) is { } failedWorkCont |
| | 3 | 169 | | await BpmnWorkTeardown.CancelSubtreeAsync(failedWorkContext, $"element '{record.ElementId}' failed"); |
| | | 170 | | |
| | 6 | 171 | | await DispatcherOf(_context.WorkflowExecutionContext).PostAsync(() => ApplyAsync(memory, evaluation)); |
| | 8 | 172 | | } |
| | | 173 | | |
| | | 174 | | // --- Plumbing ------------------------------------------------------------------------------------ |
| | | 175 | | |
| | | 176 | | private ValueTask EvaluateAsync(Func<BpmnScopeMemory, BpmnEvaluation?> evaluate) => |
| | 131 | 177 | | DispatcherOf(_context.WorkflowExecutionContext).PostAsync(async () => |
| | 131 | 178 | | { |
| | 131 | 179 | | var memory = BpmnScopeMemory.Load(_context); |
| | 131 | 180 | | var evaluation = evaluate(memory); |
| | 131 | 181 | | |
| | 131 | 182 | | if (evaluation is null) |
| | 1 | 183 | | return; |
| | 131 | 184 | | |
| | 131 | 185 | | // Persist the state before acting on the commands: a command applied against a state that was never |
| | 131 | 186 | | // recorded is how a crash produces work with no token behind it. |
| | 130 | 187 | | memory.State = evaluation.State.Prune(); |
| | 130 | 188 | | memory.SaveState(); |
| | 131 | 189 | | |
| | 130 | 190 | | await ApplyAsync(memory, evaluation); |
| | 260 | 191 | | }); |
| | | 192 | | |
| | | 193 | | private async ValueTask ApplyAsync(BpmnScopeMemory memory, BpmnEvaluation evaluation) |
| | | 194 | | { |
| | 133 | 195 | | await new BpmnCommandApplier(_context, _process, memory).ApplyAsync(evaluation.Commands); |
| | | 196 | | |
| | 132 | 197 | | switch (evaluation.Continuation) |
| | | 198 | | { |
| | | 199 | | case BpmnContinuation.Complete complete: |
| | | 200 | | // The scope completes because the interpreter said so, never because it ran out of children. |
| | 30 | 201 | | await _context.CompleteActivityAsync(new Outcomes(complete.Outcome)); |
| | 30 | 202 | | break; |
| | | 203 | | case BpmnContinuation.Defer: |
| | | 204 | | break; |
| | | 205 | | case BpmnContinuation.Fault fault: |
| | 1 | 206 | | throw new BpmnScopeFaultException(fault.Code, fault.Message); |
| | | 207 | | default: |
| | 0 | 208 | | throw new NotSupportedException($"The BPMN continuation '{evaluation.Continuation.GetType().Name}' is no |
| | | 209 | | } |
| | 131 | 210 | | } |
| | | 211 | | |
| | | 212 | | /// <summary> |
| | | 213 | | /// Finds the unit of work this scope started that the failing activity belongs to, walking outward from the |
| | | 214 | | /// failure. |
| | | 215 | | /// </summary> |
| | | 216 | | /// <remarks> |
| | | 217 | | /// A fault raised deep inside a nested scope is, to this scope, its own subprocess work failing. The nested scope |
| | | 218 | | /// sees the signal first and claims it if it has a catcher; if it does not, the signal arrives here and this walk |
| | | 219 | | /// is what turns "some activity failed" into "the work I started failed", which is exactly what BPMN error |
| | | 220 | | /// propagation across a scope boundary means. |
| | | 221 | | /// </remarks> |
| | | 222 | | private BpmnWorkRecord? ResolveFaultedWork(BpmnScopeMemory memory, ActivityExecutionContext faultedContext) |
| | | 223 | | { |
| | 24 | 224 | | for (var current = faultedContext; current is not null && !string.Equals(current.Id, _context.Id, StringComparis |
| | | 225 | | { |
| | 9 | 226 | | if (memory.Work.FindByChildContextId(current.Id) is { } record) |
| | 5 | 227 | | return record; |
| | | 228 | | } |
| | | 229 | | |
| | 3 | 230 | | return null; |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | private BpmnHostSnapshot Snapshot(BpmnScopeMemory memory) |
| | | 234 | | { |
| | 135 | 235 | | var invocationCorrelation = InvocationCorrelation; |
| | | 236 | | |
| | 135 | 237 | | return new BpmnHostSnapshot( |
| | 135 | 238 | | ScopeInstanceId: _context.Id, |
| | 135 | 239 | | // A scope has an enclosing one exactly when another scope started it, which is what the carried |
| | 135 | 240 | | // correlation records. A root process has none, so an unhandled escalation is a documented no-op. |
| | 135 | 241 | | HasEnclosingScope: invocationCorrelation.Count > 0, |
| | 135 | 242 | | LiveWork: memory.Work.ToLiveWork(), |
| | 135 | 243 | | InvocationCorrelation: invocationCorrelation, |
| | 135 | 244 | | Variables: new BpmnScopeVariables(_context), |
| | 135 | 245 | | Capabilities: Capabilities); |
| | | 246 | | } |
| | | 247 | | |
| | | 248 | | /// <summary> |
| | | 249 | | /// The correlation of the work that started this scope. It belongs to the scope and is fixed for its lifetime; |
| | | 250 | | /// a completing unit of work's correlation is never written here, because the event-subprocess start hint is read |
| | | 251 | | /// from this same dictionary. |
| | | 252 | | /// </summary> |
| | | 253 | | private IReadOnlyDictionary<string, string> InvocationCorrelation => |
| | 135 | 254 | | BpmnScopeMemory.Read<Dictionary<string, string>>(_context, InvocationCorrelationPropertyKey) ?? NoCorrelation; |
| | | 255 | | |
| | | 256 | | private BpmnGraph BuildGraph() |
| | | 257 | | { |
| | 71 | 258 | | var definition = _process.Process |
| | 71 | 259 | | ?? throw new InvalidOperationException($"BPMN process activity '{_process.Id}' has no process d |
| | | 260 | | |
| | | 261 | | // Every binding the definition declares, with the nested definition attached where the bound activity is |
| | | 262 | | // itself a BPMN scope. The graph validator reads that for an event subprocess body's start trigger. |
| | 256 | 263 | | var boundWork = BpmnBoundWork.Derive(definition, bindingRef => (_process.FindWorkActivity(bindingRef) as BpmnPro |
| | | 264 | | |
| | 71 | 265 | | return BpmnGraph.Build(definition, boundWork, Capabilities); |
| | | 266 | | } |
| | | 267 | | } |