| | | 1 | | using Elsa.Extensions; |
| | | 2 | | using Elsa.Http.Bookmarks; |
| | | 3 | | using Elsa.Http.Options; |
| | | 4 | | using Elsa.Workflows.Runtime.Filters; |
| | | 5 | | using JetBrains.Annotations; |
| | | 6 | | using Microsoft.AspNetCore.Http; |
| | | 7 | | using Microsoft.Extensions.DependencyInjection; |
| | | 8 | | using Microsoft.Extensions.Options; |
| | | 9 | | using System.Net; |
| | | 10 | | using System.Net.Mime; |
| | | 11 | | using System.Text.Json; |
| | | 12 | | using Elsa.Workflows.Activities; |
| | | 13 | | using Elsa.Workflows.Runtime.Entities; |
| | | 14 | | using FastEndpoints; |
| | | 15 | | using System.Diagnostics.CodeAnalysis; |
| | | 16 | | using Elsa.Workflows; |
| | | 17 | | using Elsa.Workflows.Management; |
| | | 18 | | using Elsa.Workflows.Management.Entities; |
| | | 19 | | using Elsa.Workflows.Models; |
| | | 20 | | using Elsa.Workflows.Options; |
| | | 21 | | using Elsa.Workflows.Runtime; |
| | | 22 | | using Open.Linq.AsyncExtensions; |
| | | 23 | | |
| | | 24 | | namespace Elsa.Http.Middleware; |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// An ASP.NET middleware component that tries to match the inbound request path to an associated workflow and then run |
| | | 28 | | /// </summary> |
| | | 29 | | [PublicAPI] |
| | 1 | 30 | | public class HttpWorkflowsMiddleware(RequestDelegate next, IOptions<HttpActivityOptions> options) |
| | | 31 | | { |
| | | 32 | | /// <summary> |
| | | 33 | | /// Attempts to match the inbound request path to an associated workflow and then run that workflow. |
| | | 34 | | /// </summary> |
| | | 35 | | [RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Serialize<TValue>(TValue, JsonSerializerOptions)")] |
| | | 36 | | public async Task InvokeAsync(HttpContext httpContext, IServiceProvider serviceProvider) |
| | | 37 | | { |
| | 236 | 38 | | var path = httpContext.Request.Path.Value!.NormalizeRoute(); |
| | 236 | 39 | | var matchingPath = GetMatchingRoute(serviceProvider, path).Route; |
| | 236 | 40 | | var basePath = options.Value.BasePath?.ToString().NormalizeRoute(); |
| | | 41 | | |
| | | 42 | | // If the request path does not match the configured base path to handle workflows, then skip. |
| | 236 | 43 | | if (!string.IsNullOrWhiteSpace(basePath)) |
| | | 44 | | { |
| | 236 | 45 | | if (!path.StartsWith(basePath, StringComparison.OrdinalIgnoreCase)) |
| | | 46 | | { |
| | 21 | 47 | | await next(httpContext); |
| | 21 | 48 | | return; |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | // Strip the base path. |
| | 215 | 52 | | matchingPath = matchingPath[basePath.Length..]; |
| | | 53 | | } |
| | | 54 | | |
| | 215 | 55 | | matchingPath = matchingPath.NormalizeRoute(); |
| | | 56 | | |
| | 215 | 57 | | var input = new Dictionary<string, object> |
| | 215 | 58 | | { |
| | 215 | 59 | | [HttpEndpoint.HttpContextInputKey] = true, |
| | 215 | 60 | | [HttpEndpoint.PathInputKey] = path |
| | 215 | 61 | | }; |
| | | 62 | | |
| | 215 | 63 | | var cancellationToken = httpContext.RequestAborted; |
| | 215 | 64 | | var request = httpContext.Request; |
| | 215 | 65 | | var method = request.Method.ToLowerInvariant(); |
| | 215 | 66 | | var httpWorkflowLookupService = serviceProvider.GetRequiredService<IHttpWorkflowLookupService>(); |
| | 215 | 67 | | var workflowInstanceId = await GetWorkflowInstanceIdAsync(serviceProvider, httpContext, cancellationToken); |
| | 215 | 68 | | var correlationId = await GetCorrelationIdAsync(serviceProvider, httpContext, cancellationToken); |
| | 215 | 69 | | var bookmarkHash = ComputeBookmarkHash(serviceProvider, matchingPath, method); |
| | 215 | 70 | | var lookupResult = await httpWorkflowLookupService.FindWorkflowAsync(bookmarkHash, cancellationToken); |
| | | 71 | | |
| | 215 | 72 | | if (lookupResult != null) |
| | | 73 | | { |
| | 212 | 74 | | var triggers = lookupResult.Triggers; |
| | | 75 | | |
| | 212 | 76 | | if (triggers.Count > 1) |
| | | 77 | | { |
| | 0 | 78 | | await HandleMultipleWorkflowsFoundAsync(httpContext, () => triggers.Select(x => new |
| | 0 | 79 | | { |
| | 0 | 80 | | x.WorkflowDefinitionId |
| | 0 | 81 | | }), cancellationToken); |
| | 0 | 82 | | return; |
| | | 83 | | } |
| | | 84 | | |
| | 212 | 85 | | var trigger = triggers.FirstOrDefault(); |
| | 212 | 86 | | if (trigger != null) |
| | | 87 | | { |
| | 212 | 88 | | var workflowGraph = lookupResult.WorkflowGraph!; |
| | 212 | 89 | | await StartWorkflowAsync(httpContext, trigger, workflowGraph, input, workflowInstanceId, correlationId); |
| | 212 | 90 | | return; |
| | | 91 | | } |
| | | 92 | | } |
| | | 93 | | |
| | 3 | 94 | | var bookmarks = await FindBookmarksAsync(serviceProvider, bookmarkHash, workflowInstanceId, correlationId, cance |
| | | 95 | | |
| | 3 | 96 | | if (bookmarks.Count > 1) |
| | | 97 | | { |
| | 0 | 98 | | await HandleMultipleWorkflowsFoundAsync(httpContext, () => bookmarks.Select(x => new |
| | 0 | 99 | | { |
| | 0 | 100 | | x.WorkflowInstanceId |
| | 0 | 101 | | }), cancellationToken); |
| | 0 | 102 | | return; |
| | | 103 | | } |
| | | 104 | | |
| | 3 | 105 | | var bookmark = bookmarks.SingleOrDefault(); |
| | | 106 | | |
| | 3 | 107 | | if (bookmark != null) |
| | | 108 | | { |
| | 2 | 109 | | await ResumeWorkflowAsync(httpContext, bookmark, input, correlationId); |
| | 2 | 110 | | return; |
| | | 111 | | } |
| | | 112 | | |
| | | 113 | | // If a base path was configured, the requester tried to execute a workflow that doesn't exist. |
| | 1 | 114 | | if (basePath != null) |
| | | 115 | | { |
| | 1 | 116 | | await httpContext.Response.SendNotFoundAsync(cancellation: cancellationToken); |
| | 1 | 117 | | return; |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | // If no base path was configured, the request should be handled by subsequent middlewares. |
| | 0 | 121 | | await next(httpContext); |
| | 236 | 122 | | } |
| | | 123 | | |
| | | 124 | | private async Task<WorkflowGraph?> FindWorkflowGraphAsync(IServiceProvider serviceProvider, StoredTrigger trigger, C |
| | | 125 | | { |
| | 0 | 126 | | var workflowDefinitionService = serviceProvider.GetRequiredService<IWorkflowDefinitionService>(); |
| | 0 | 127 | | var workflowDefinitionId = trigger.WorkflowDefinitionVersionId; |
| | 0 | 128 | | return await workflowDefinitionService.FindWorkflowGraphAsync(workflowDefinitionId, cancellationToken); |
| | 0 | 129 | | } |
| | | 130 | | |
| | | 131 | | private async Task<IEnumerable<StoredTrigger>> FindTriggersAsync(IServiceProvider serviceProvider, string bookmarkHa |
| | | 132 | | { |
| | 0 | 133 | | var triggerStore = serviceProvider.GetRequiredService<ITriggerStore>(); |
| | 0 | 134 | | var triggerFilter = new TriggerFilter |
| | 0 | 135 | | { |
| | 0 | 136 | | Hash = bookmarkHash |
| | 0 | 137 | | }; |
| | 0 | 138 | | return await triggerStore.FindManyAsync(triggerFilter, cancellationToken); |
| | 0 | 139 | | } |
| | | 140 | | |
| | | 141 | | private async Task<IEnumerable<StoredBookmark>> FindBookmarksAsync(IServiceProvider serviceProvider, string bookmark |
| | | 142 | | { |
| | 3 | 143 | | var bookmarkStore = serviceProvider.GetRequiredService<IBookmarkStore>(); |
| | 3 | 144 | | var bookmarkFilter = new BookmarkFilter |
| | 3 | 145 | | { |
| | 3 | 146 | | Hash = bookmarkHash, |
| | 3 | 147 | | WorkflowInstanceId = workflowInstanceId, |
| | 3 | 148 | | CorrelationId = correlationId, |
| | 3 | 149 | | TenantAgnostic = true |
| | 3 | 150 | | }; |
| | 3 | 151 | | return await bookmarkStore.FindManyAsync(bookmarkFilter, cancellationToken); |
| | 3 | 152 | | } |
| | | 153 | | |
| | | 154 | | private async Task StartWorkflowAsync(HttpContext httpContext, StoredTrigger trigger, WorkflowGraph workflowGraph, I |
| | | 155 | | { |
| | 212 | 156 | | var bookmarkPayload = trigger.GetPayload<HttpEndpointBookmarkPayload>(); |
| | 212 | 157 | | var workflowOptions = new RunWorkflowOptions |
| | 212 | 158 | | { |
| | 212 | 159 | | Input = input, |
| | 212 | 160 | | CorrelationId = correlationId, |
| | 212 | 161 | | TriggerActivityId = trigger.ActivityId, |
| | 212 | 162 | | WorkflowInstanceId = workflowInstanceId |
| | 212 | 163 | | }; |
| | | 164 | | |
| | 212 | 165 | | await ExecuteWorkflowAsync(httpContext, workflowGraph, workflowOptions, bookmarkPayload, null, input); |
| | 212 | 166 | | } |
| | | 167 | | |
| | | 168 | | private async Task ResumeWorkflowAsync(HttpContext httpContext, StoredBookmark bookmark, IDictionary<string, object> |
| | | 169 | | { |
| | 2 | 170 | | var serviceProvider = httpContext.RequestServices; |
| | 2 | 171 | | var cancellationToken = httpContext.RequestAborted; |
| | 2 | 172 | | var bookmarkPayload = bookmark.GetPayload<HttpEndpointBookmarkPayload>(); |
| | 2 | 173 | | var workflowInstanceStore = serviceProvider.GetRequiredService<IWorkflowInstanceStore>(); |
| | 2 | 174 | | var workflowInstance = await workflowInstanceStore.FindAsync(bookmark.WorkflowInstanceId, cancellationToken); |
| | | 175 | | |
| | 2 | 176 | | if (workflowInstance == null) |
| | | 177 | | { |
| | 0 | 178 | | await httpContext.Response.SendNotFoundAsync(cancellation: cancellationToken); |
| | 0 | 179 | | return; |
| | | 180 | | } |
| | | 181 | | |
| | 2 | 182 | | var workflowDefinitionService = serviceProvider.GetRequiredService<IWorkflowDefinitionService>(); |
| | 2 | 183 | | var workflowGraph = await workflowDefinitionService.FindWorkflowGraphAsync(workflowInstance.DefinitionVersionId, |
| | | 184 | | |
| | 2 | 185 | | if (workflowGraph == null) |
| | | 186 | | { |
| | 0 | 187 | | await httpContext.Response.SendNotFoundAsync(cancellation: cancellationToken); |
| | 0 | 188 | | return; |
| | | 189 | | } |
| | | 190 | | |
| | 2 | 191 | | var runWorkflowParams = new RunWorkflowOptions |
| | 2 | 192 | | { |
| | 2 | 193 | | WorkflowInstanceId = workflowInstance.Id, |
| | 2 | 194 | | Input = input, |
| | 2 | 195 | | CorrelationId = correlationId, |
| | 2 | 196 | | ActivityHandle = bookmark.ActivityInstanceId != null ? ActivityHandle.FromActivityInstanceId(bookmark.Activi |
| | 2 | 197 | | BookmarkId = bookmark.Id |
| | 2 | 198 | | }; |
| | | 199 | | |
| | 2 | 200 | | await ExecuteWorkflowAsync(httpContext, workflowGraph, runWorkflowParams, bookmarkPayload, workflowInstance, inp |
| | 2 | 201 | | } |
| | | 202 | | |
| | | 203 | | private async Task ExecuteWorkflowAsync(HttpContext httpContext, WorkflowGraph workflowGraph, RunWorkflowOptions wor |
| | | 204 | | { |
| | 214 | 205 | | var serviceProvider = httpContext.RequestServices; |
| | 214 | 206 | | var cancellationToken = httpContext.RequestAborted; |
| | 214 | 207 | | var workflow = workflowGraph.Workflow; |
| | | 208 | | |
| | 214 | 209 | | if (!await AuthorizeAsync(serviceProvider, httpContext, workflow, bookmarkPayload, cancellationToken)) |
| | | 210 | | { |
| | 0 | 211 | | httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; |
| | 0 | 212 | | return; |
| | | 213 | | } |
| | | 214 | | |
| | 214 | 215 | | var workflowRunner = serviceProvider.GetRequiredService<IWorkflowRunner>(); |
| | 214 | 216 | | var result = await ExecuteWithinTimeoutAsync(async ct => |
| | 214 | 217 | | { |
| | 214 | 218 | | if (workflowInstance == null) |
| | 212 | 219 | | return await workflowRunner.RunAsync(workflowGraph, workflowOptions, ct); |
| | 2 | 220 | | return await workflowRunner.RunAsync(workflow, workflowInstance.WorkflowState, workflowOptions, ct); |
| | 428 | 221 | | }, bookmarkPayload.RequestTimeout, httpContext); |
| | 214 | 222 | | await HandleWorkflowFaultAsync(serviceProvider, httpContext, result, cancellationToken); |
| | 214 | 223 | | } |
| | | 224 | | |
| | | 225 | | private async Task<T> ExecuteWithinTimeoutAsync<T>(Func<CancellationToken, Task<T>> action, TimeSpan? requestTimeout |
| | | 226 | | { |
| | | 227 | | // If no request timeout is specified, execute the action without any timeout. |
| | 214 | 228 | | if (requestTimeout == null) |
| | 214 | 229 | | return await action(httpContext.RequestAborted); |
| | | 230 | | |
| | | 231 | | // Create a combined cancellation token that cancels when the request is aborted or when the request timeout is |
| | 0 | 232 | | using var requestTimeoutCancellationTokenSource = new CancellationTokenSource(); |
| | 0 | 233 | | requestTimeoutCancellationTokenSource.CancelAfter(requestTimeout.Value); |
| | 0 | 234 | | using var combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(httpContext.RequestAborted, requ |
| | 0 | 235 | | var originalCancellationToken = httpContext.RequestAborted; |
| | | 236 | | |
| | | 237 | | // Replace the original cancellation token with the combined one. |
| | 0 | 238 | | httpContext.RequestAborted = combinedTokenSource.Token; |
| | | 239 | | |
| | | 240 | | // Execute the action. |
| | 0 | 241 | | var result = await action(httpContext.RequestAborted); |
| | | 242 | | |
| | | 243 | | // Restore the original cancellation token. |
| | 0 | 244 | | httpContext.RequestAborted = originalCancellationToken; |
| | | 245 | | |
| | 0 | 246 | | return result; |
| | 214 | 247 | | } |
| | | 248 | | |
| | | 249 | | private HttpRouteData GetMatchingRoute(IServiceProvider serviceProvider, string path) |
| | | 250 | | { |
| | 236 | 251 | | var routeMatcher = serviceProvider.GetRequiredService<IRouteMatcher>(); |
| | 236 | 252 | | var routeTable = serviceProvider.GetRequiredService<IRouteTable>(); |
| | | 253 | | |
| | 236 | 254 | | var matchingRouteQuery = |
| | 236 | 255 | | from routeData in routeTable |
| | 857 | 256 | | let routeValues = routeMatcher.Match(routeData.Route, path) |
| | 857 | 257 | | where routeValues != null |
| | 451 | 258 | | select new |
| | 451 | 259 | | { |
| | 451 | 260 | | route = routeData, |
| | 451 | 261 | | routeValues |
| | 451 | 262 | | }; |
| | | 263 | | |
| | 236 | 264 | | var matchingRoute = matchingRouteQuery.FirstOrDefault(); |
| | 236 | 265 | | var routeTemplate = matchingRoute?.route ?? new HttpRouteData(path); |
| | | 266 | | |
| | 236 | 267 | | return routeTemplate; |
| | | 268 | | } |
| | | 269 | | |
| | | 270 | | private async Task<string?> GetCorrelationIdAsync(IServiceProvider serviceProvider, HttpContext httpContext, Cancell |
| | | 271 | | { |
| | 215 | 272 | | var correlationIdSelectors = serviceProvider.GetServices<IHttpCorrelationIdSelector>(); |
| | | 273 | | |
| | 215 | 274 | | var correlationId = default(string); |
| | | 275 | | |
| | 1716 | 276 | | foreach (var selector in correlationIdSelectors.OrderByDescending(x => x.Priority)) |
| | | 277 | | { |
| | 430 | 278 | | correlationId = await selector.GetCorrelationIdAsync(httpContext, cancellationToken); |
| | | 279 | | |
| | 430 | 280 | | if (correlationId != null) |
| | | 281 | | break; |
| | | 282 | | } |
| | | 283 | | |
| | 215 | 284 | | return correlationId; |
| | 215 | 285 | | } |
| | | 286 | | |
| | | 287 | | private async Task<string?> GetWorkflowInstanceIdAsync(IServiceProvider serviceProvider, HttpContext httpContext, Ca |
| | | 288 | | { |
| | 215 | 289 | | var workflowInstanceIdSelectors = serviceProvider.GetServices<IHttpWorkflowInstanceIdSelector>(); |
| | | 290 | | |
| | 215 | 291 | | var workflowInstanceId = default(string); |
| | | 292 | | |
| | 1716 | 293 | | foreach (var selector in workflowInstanceIdSelectors.OrderByDescending(x => x.Priority)) |
| | | 294 | | { |
| | 430 | 295 | | workflowInstanceId = await selector.GetWorkflowInstanceIdAsync(httpContext, cancellationToken); |
| | | 296 | | |
| | 430 | 297 | | if (workflowInstanceId != null) |
| | | 298 | | break; |
| | | 299 | | } |
| | | 300 | | |
| | 215 | 301 | | return workflowInstanceId; |
| | 215 | 302 | | } |
| | | 303 | | |
| | | 304 | | [RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Serialize<TValue>(TValue, JsonSerializerOptions)")] |
| | | 305 | | private static async Task WriteResponseAsync(HttpContext httpContext, CancellationToken cancellationToken) |
| | | 306 | | { |
| | 0 | 307 | | var response = httpContext.Response; |
| | | 308 | | |
| | 0 | 309 | | if (!response.HasStarted) |
| | | 310 | | { |
| | 0 | 311 | | response.ContentType = MediaTypeNames.Application.Json; |
| | 0 | 312 | | response.StatusCode = StatusCodes.Status200OK; |
| | | 313 | | |
| | 0 | 314 | | var model = new |
| | 0 | 315 | | { |
| | 0 | 316 | | workflowInstanceIds = Array.Empty<string>(), |
| | 0 | 317 | | }; |
| | | 318 | | |
| | 0 | 319 | | var json = JsonSerializer.Serialize(model); |
| | 0 | 320 | | await response.WriteAsync(json, cancellationToken); |
| | | 321 | | } |
| | 0 | 322 | | } |
| | | 323 | | |
| | | 324 | | [RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Serialize<TValue>(TValue, JsonSerializerOptions)")] |
| | | 325 | | private async Task<bool> HandleMultipleWorkflowsFoundAsync(HttpContext httpContext, Func<IEnumerable<object>> workfl |
| | | 326 | | { |
| | 0 | 327 | | httpContext.Response.ContentType = "application/json"; |
| | 0 | 328 | | httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; |
| | | 329 | | |
| | 0 | 330 | | var responseContent = JsonSerializer.Serialize(new |
| | 0 | 331 | | { |
| | 0 | 332 | | errorMessage = "The call is ambiguous and matches multiple workflows.", |
| | 0 | 333 | | workflows = workflowMatches().ToArray() |
| | 0 | 334 | | }); |
| | | 335 | | |
| | 0 | 336 | | await httpContext.Response.WriteAsync(responseContent, cancellationToken); |
| | 0 | 337 | | return true; |
| | 0 | 338 | | } |
| | | 339 | | |
| | | 340 | | private async Task<bool> HandleWorkflowFaultAsync(IServiceProvider serviceProvider, HttpContext httpContext, RunWork |
| | | 341 | | { |
| | 214 | 342 | | if (!workflowExecutionResult.WorkflowState.Incidents.Any() || httpContext.Response.HasStarted) |
| | 214 | 343 | | return false; |
| | | 344 | | |
| | 0 | 345 | | var httpEndpointFaultHandler = serviceProvider.GetRequiredService<IHttpEndpointFaultHandler>(); |
| | 0 | 346 | | var workflowInstanceManager = serviceProvider.GetRequiredService<IWorkflowInstanceManager>(); |
| | 0 | 347 | | var workflowState = (await workflowInstanceManager.FindByIdAsync(workflowExecutionResult.WorkflowState.Id, cance |
| | 0 | 348 | | await httpEndpointFaultHandler.HandleAsync(new(httpContext, workflowState.WorkflowState, cancellationToken)); |
| | 0 | 349 | | return true; |
| | 214 | 350 | | } |
| | | 351 | | |
| | | 352 | | private async Task<bool> AuthorizeAsync( |
| | | 353 | | IServiceProvider serviceProvider, |
| | | 354 | | HttpContext httpContext, |
| | | 355 | | Workflow workflow, |
| | | 356 | | HttpEndpointBookmarkPayload bookmarkPayload, |
| | | 357 | | CancellationToken cancellationToken) |
| | | 358 | | { |
| | 214 | 359 | | var httpEndpointAuthorizationHandler = serviceProvider.GetRequiredService<IHttpEndpointAuthorizationHandler>(); |
| | | 360 | | |
| | 214 | 361 | | if (bookmarkPayload.Authorize == false) |
| | 214 | 362 | | return true; |
| | | 363 | | |
| | 0 | 364 | | return await httpEndpointAuthorizationHandler.AuthorizeAsync(new(httpContext, workflow, bookmarkPayload.Policy)) |
| | 214 | 365 | | } |
| | | 366 | | |
| | | 367 | | private string ComputeBookmarkHash(IServiceProvider serviceProvider, string path, string method) |
| | | 368 | | { |
| | 215 | 369 | | var bookmarkPayload = new HttpEndpointBookmarkPayload(path, method); |
| | 215 | 370 | | var bookmarkHasher = serviceProvider.GetRequiredService<IStimulusHasher>(); |
| | 215 | 371 | | return bookmarkHasher.Hash(HttpStimulusNames.HttpEndpoint, bookmarkPayload); |
| | | 372 | | } |
| | | 373 | | } |