elsa-core/src/activities/Elsa.Activities.Http/Middleware/HttpRequestMiddleware.cs

68 lines
2.4 KiB
C#
Raw Normal View History

2020-10-17 10:49:41 +00:00
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Elsa.Activities.Http.Extensions;
2020-10-17 10:49:41 +00:00
using Elsa.Activities.Http.Triggers;
using Elsa.Repositories;
2020-10-17 10:49:41 +00:00
using Elsa.Services;
using Elsa.Triggers;
using Microsoft.AspNetCore.Http;
using Open.Linq.AsyncExtensions;
namespace Elsa.Activities.Http.Middleware
{
2020-10-17 10:49:41 +00:00
public class ReceiveHttpRequestMiddleware
{
private readonly RequestDelegate _next;
2020-10-17 10:49:41 +00:00
public ReceiveHttpRequestMiddleware(RequestDelegate next)
{
_next = next;
}
2020-12-11 20:14:57 +00:00
public async Task InvokeAsync(HttpContext httpContext, IWorkflowSelector workflowSelector, IWorkflowRunner workflowRunner, IWorkflowInstanceStore workflowInstanceStore)
{
2020-10-17 10:49:41 +00:00
var path = httpContext.Request.Path;
var method = httpContext.Request.Method;
var cancellationToken = httpContext.RequestAborted;
httpContext.Request.TryGetCorrelationId(out var correlationId);
2020-10-17 13:38:27 +00:00
2020-10-17 10:49:41 +00:00
var results = await workflowSelector.SelectWorkflowsAsync<ReceiveHttpRequestTrigger>(
x => (x.Path == path) && (x.Method == null || x.Method == method) && (x.CorrelationId == null || x.CorrelationId == correlationId),
cancellationToken)
.ToList();
if (!results.Any())
{
2020-10-17 10:49:41 +00:00
await _next(httpContext);
return;
}
if (results.Count > 1)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
await httpContext.Response.WriteAsync("Request matches multiple workflows.", cancellationToken);
return;
}
var result = results.Single();
if (result.WorkflowInstanceId == null)
{
await workflowRunner.RunWorkflowAsync(result.WorkflowBlueprint, result.ActivityId, cancellationToken: cancellationToken);
}
2020-10-17 10:49:41 +00:00
else
{
2020-12-11 20:14:57 +00:00
var workflowInstance = await workflowInstanceStore.GetByIdAsync(result.WorkflowInstanceId, cancellationToken);
if (workflowInstance == null)
{
httpContext.Response.StatusCode = 404;
return;
}
await workflowRunner.RunWorkflowAsync(result.WorkflowBlueprint, workflowInstance, result.ActivityId, cancellationToken: cancellationToken);
}
}
}
}