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

44 lines
1.9 KiB
C#
Raw Normal View History

using System.Threading.Tasks;
using Elsa.Activities.Http.Bookmarks;
using Elsa.Activities.Http.Extensions;
using Elsa.Dispatch;
using MediatR;
using Microsoft.AspNetCore.Http;
namespace Elsa.Activities.Http.Middleware
{
public class HttpEndpointMiddleware
{
// TODO: Design multi-tenancy.
2021-05-03 10:55:22 +00:00
private const string? TenantId = default;
private readonly RequestDelegate _next;
public HttpEndpointMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext httpContext, IMediator mediator, IWorkflowInstanceDispatcher workflowInstanceDispatcher)
{
var path = httpContext.Request.Path.Value.ToLowerInvariant();
var method = httpContext.Request.Method!.ToLowerInvariant();
var cancellationToken = httpContext.RequestAborted;
httpContext.Request.TryGetCorrelationId(out var correlationId);
var useDispatch = httpContext.Request.GetUseDispatch();
2020-10-17 13:38:27 +00:00
const string activityType = nameof(HttpEndpoint);
var trigger = new HttpEndpointBookmark(path, method, null);
var bookmark = new HttpEndpointBookmark(path, method, correlationId?.ToLowerInvariant());
var triggerRequest = new TriggerWorkflowsRequest(activityType, bookmark, trigger, default, correlationId, default, TenantId, Execute: !useDispatch);
var response = await mediator.Send(triggerRequest, cancellationToken);
if (useDispatch)
{
// We created workflow instances but haven't scheduled them for execution yet. Use the dispatcher to schedule them for execution.
workflowInstanceDispatcher.DispatchAsync(new ExecuteWorkflowInstanceRequest())
}
if (response.WorkflowInstanceIds.Count == 0)
{
2020-10-17 10:49:41 +00:00
await _next(httpContext);
}
}
}
}