forked from elsa-workflows/elsa-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WorkflowDefinitionActivity.cs
186 lines (152 loc) · 8.51 KB
/
WorkflowDefinitionActivity.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
using System.ComponentModel;
using Elsa.Common.Models;
using Elsa.Extensions;
using Elsa.Workflows.Core;
using Elsa.Workflows.Core.Activities;
using Elsa.Workflows.Core.Contracts;
using Elsa.Workflows.Core.Memory;
using Elsa.Workflows.Core.Models;
using Elsa.Workflows.Core.Signals;
using Elsa.Workflows.Management.Contracts;
using Elsa.Workflows.Management.Entities;
using Elsa.Workflows.Management.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Elsa.Workflows.Management.Activities.WorkflowDefinitionActivity;
/// <summary>
/// Loads and executes an <see cref="WorkflowDefinition"/>.
/// </summary>
[Browsable(false)]
public class WorkflowDefinitionActivity : Composite, IInitializable
{
/// <summary>
/// The definition ID of the workflow to schedule for execution.
/// </summary>
public string WorkflowDefinitionId { get; set; } = default!;
/// <summary>
/// The specific version ID of the workflow to schedule for execution. If not set, the <see cref="Version"/> number will be considered.
/// </summary>
public string? WorkflowDefinitionVersionId { get; set; }
/// <summary>
/// The latest published version number set by the provider. This is used by tooling to let the user know that a newer version is available.
/// </summary>
public int LatestAvailablePublishedVersion { get; set; }
/// <summary>
/// The latest published version ID set by the provider. This is used by tooling to let the user know that a newer version is available.
/// </summary>
public string? LatestAvailablePublishedVersionId { get; set; }
/// <inheritdoc />
protected override async ValueTask ExecuteAsync(ActivityExecutionContext context)
{
CopyInputOutputToVariables(context);
await context.ScheduleActivityAsync(Root, OnChildCompletedAsync);
}
private async ValueTask OnChildCompletedAsync(ActivityCompletedContext context)
{
var activityExecutionContext = context.TargetContext;
// Do we have a "complete composite" signal that triggered the completion?
var completeCompositeSignal = context.WorkflowExecutionContext.TransientProperties.TryGetValue(nameof(CompleteCompositeSignal), out var signal) ? (CompleteCompositeSignal)signal : default;
// If we do, make sure to remove it from the transient properties.
if (completeCompositeSignal != null)
{
var logger = context.GetRequiredService<ILogger<WorkflowDefinitionActivity>>();
logger.LogDebug("Received a complete composite signal and removing it from the transient properties");
context.WorkflowExecutionContext.TransientProperties.Remove(nameof(CompleteCompositeSignal));
}
// Copy any collected outputs into the synthetic properties.
foreach (var outputDescriptor in activityExecutionContext.ActivityDescriptor.Outputs)
{
var output = (Output?)outputDescriptor.ValueGetter(activityExecutionContext.Activity);
var value = activityExecutionContext.Get(output);
if (value == null)
{
// If direct output mapping is used, we can read the output value directly from the memory.
value = activityExecutionContext.Get(outputDescriptor.Name);
// Make sure to select a parent scope to avoid naming collisions between outputs defined on the current scope and outputs defined on parent scopes.
var parentActivityExecutionContext = activityExecutionContext.ParentActivityExecutionContext ?? activityExecutionContext;
parentActivityExecutionContext.Set(output, value, outputDescriptor.Name);
}
else
{
activityExecutionContext.Set(output, value, outputDescriptor.Name);
}
}
// Complete this activity with the signal value.
await activityExecutionContext.CompleteActivityAsync(completeCompositeSignal?.Value);
}
private void CopyInputOutputToVariables(ActivityExecutionContext context)
{
var serviceProvider = context.GetRequiredService<IServiceProvider>();
DeclareInputAsVariables(serviceProvider, (descriptor, variable) =>
{
var inputName = descriptor.Name;
var input = SyntheticProperties.TryGetValue(inputName, out var inputValue) ? (Input?)inputValue : default;
var evaluatedExpression = input != null ? context.Get(input.MemoryBlockReference()) : default;
context.ExpressionExecutionContext.Memory.Declare(variable);
variable.Set(context, evaluatedExpression);
});
DeclareOutputAsVariables(serviceProvider, (descriptor, variable) => context.ExpressionExecutionContext.Memory.Declare(variable));
}
private void DeclareInputAsVariables(IServiceProvider serviceProvider, Action<InputDescriptor, Variable> configureVariable)
{
var activityRegistry = serviceProvider.GetRequiredService<IActivityRegistry>();
var activityDescriptor = activityRegistry.Find(Type, Version)!;
foreach (var inputDescriptor in activityDescriptor.Inputs)
{
var inputName = inputDescriptor.Name;
var unsafeInputName = PropertyNameHelper.GetUnsafePropertyName(typeof(WorkflowDefinitionActivity), inputName);
var variableType = typeof(Variable<>).MakeGenericType(inputDescriptor.Type);
var variable = (Variable)Activator.CreateInstance(variableType)!;
variable.Id = unsafeInputName;
variable.Name = unsafeInputName;
variable.StorageDriverType = inputDescriptor.StorageDriverType;
configureVariable(inputDescriptor, variable);
}
}
private void DeclareOutputAsVariables(IServiceProvider serviceProvider, Action<OutputDescriptor, Variable> configureVariable)
{
var activityRegistry = serviceProvider.GetRequiredService<IActivityRegistry>();
var activityDescriptor = activityRegistry.Find(Type, Version)!;
foreach (var outputDescriptor in activityDescriptor.Outputs)
{
var outputName = outputDescriptor.Name;
var unsafeOutputName = PropertyNameHelper.GetUnsafePropertyName(typeof(WorkflowDefinitionActivity), outputName);
var variable = new Variable
{
Id = unsafeOutputName,
Name = unsafeOutputName
};
configureVariable(outputDescriptor, variable);
}
}
private async Task<WorkflowDefinition?> FindWorkflowDefinitionAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken)
{
var workflowDefinitionStore = serviceProvider.GetRequiredService<IWorkflowDefinitionStore>();
var filter = new WorkflowDefinitionFilter { DefinitionId = WorkflowDefinitionId };
if (!string.IsNullOrWhiteSpace(WorkflowDefinitionVersionId))
filter.Id = WorkflowDefinitionVersionId;
else
filter.VersionOptions = VersionOptions.SpecificVersion(Version);
var workflowDefinition =
await workflowDefinitionStore.FindAsync(filter, cancellationToken)
?? (await workflowDefinitionStore.FindAsync(new WorkflowDefinitionFilter { DefinitionId = WorkflowDefinitionId, VersionOptions = VersionOptions.Published }, cancellationToken)
?? await workflowDefinitionStore.FindAsync(new WorkflowDefinitionFilter { DefinitionId = WorkflowDefinitionId, VersionOptions = VersionOptions.Latest }, cancellationToken));
return workflowDefinition;
}
async ValueTask IInitializable.InitializeAsync(InitializationContext context)
{
var serviceProvider = context.ServiceProvider;
var cancellationToken = context.CancellationToken;
var workflowDefinition = await FindWorkflowDefinitionAsync(serviceProvider, cancellationToken);
if (workflowDefinition == null)
throw new Exception($"Could not find workflow definition with ID {WorkflowDefinitionId}.");
// Construct the root activity stored in the activity definitions.
var materializer = serviceProvider.GetRequiredService<IWorkflowMaterializer>();
var root = await materializer.MaterializeAsync(workflowDefinition, cancellationToken);
// Declare input and output variables.
DeclareInputAsVariables(serviceProvider, (inputDescriptor, variable) => Variables.Declare(variable));
DeclareOutputAsVariables(serviceProvider, (outputDescriptor, variable) => Variables.Declare(variable));
// Set the root activity.
Root = root;
}
}