elsa-core/src/modules/Elsa.Http/ShellFeatures/HttpFeature.cs
Sipke Schoorstra 11fec1c85d
Add shell middleware, call‑stack tracking, and workflow reference graph APIs (#7333)
* refactor(deps): use local CShells project refs

Replace CShells NuGet package references with direct project references to the local CShells source to enable developing and testing against local changes and simplify build integration across modules.

* Handle assembly load errors in feature discovery

Added error handling for assembly load failures in feature discovery to improve resilience. Also updated configuration for identity token options and removed unused service bus consumer dependencies. Simplified project structure by moving and cleaning up `Directory.Build.targets` files.

* Refactor configuration and service extension methods.

Moved `ShellSettingsExtensions` and `ShellConfiguration` to `CShells.Abstractions` for better modularity. Added new `ServiceCollectionFeatureExtensions` to improve options registration. Updated appsettings and references to support these changes.

* Introduce ManagementServiceCollectionExtensions to streamline activity and variable registration

Added `ManagementServiceCollectionExtensions` for registering Elsa activity types and variable descriptors, providing a modular and shell-feature-compatible approach to configuration. Updated relevant features to utilize these new extension methods, enhancing code modularity and reducing redundancy.

* Add resilience strategy registration to HTTP feature

Introduced `ResilienceServiceCollectionExtensions` to register resilience strategies within the `Elsa.Resilience.Core` module. Updated `HttpFeature` to incorporate resilience strategies, enhancing HTTP-related resilience configuration leveraging the new extension methods.

* Add new configuration options to JavaScriptFeature

Implemented multiple properties in `JavaScriptFeature` to enhance JavaScript execution: `AllowClrAccess`, `AllowConfigurationAccess`, `ScriptCacheTimeout`, `DisableWrappers`, and `DisableVariableCopying`. These additions enable more flexible and secure configuration of the Jint JavaScript engine.

* refactor(workflows): unify graph caching

Resolve workflow definitions first and store graphs under stable per-version-ID cache keys so different lookup paths share entries.
Centralize cache creation and change-token registration to remove duplicated caching logic.
Skip materializer-unavailable definitions to avoid caching null graphs and simplify flow.

* refactor(tests): centralize default IDs and materializer setup

Introduce constants for default definition and version IDs, and materializer name. Refactor tests to use these constants, streamline graph and definition resolution, and improve cache key creation by sharing logic across tests. Extend tests to check scenarios with unavailable materializers, ensuring caching only occurs for valid cases.

* extend(tests): enhance cache key verification in AutoUpdateTests

Added checks for both workflow definition and version cache keys in AutoUpdateTests to ensure comprehensive cache validation, improving test reliability and coverage.

* refactor(projects): update CShells project paths and solution configuration

Revised project reference paths in `Elsa.ModularServer.Web.csproj` for CShells projects and updated `Elsa.sln` to include new CShells projects, streamlining project organization and build configuration.

* Add `IWorkflowReferenceGraphBuilder` to `WorkflowManagementFeature`; rename `ResilienceShellFeature` to `ResilienceFeature`.

* Refactor `HttpFeature` to use `IMiddlewareShellFeature`, include `HttpWorkflowsMiddleware`, and update `HttpActivityOptions` defaults.

* Add `AddTypeAlias` and `AddVariableTypeAndAlias` extension methods to service collections

- Introduced `AddTypeAlias<T>` method in `ServiceCollectionExtensions.cs` for adding type aliases.
- Added `AddVariableTypeAndAlias<T>` method in `ManagementServiceCollectionExtensions.cs` to add variable types with aliases.

* Update CShells package versions to 0.0.11 and replace ProjectReferences with PackageReferences in project files
2026-02-28 21:16:04 +01:00

243 lines
10 KiB
C#

using CShells.AspNetCore.Features;
using CShells.Features;
using Elsa.Expressions.Options;
using Elsa.Extensions;
using Elsa.Http.Bookmarks;
using Elsa.Http.ContentWriters;
using Elsa.Http.DownloadableContentHandlers;
using Elsa.Http.FileCaches;
using Elsa.Http.Handlers;
using Elsa.Http.Middleware;
using Elsa.Http.Options;
using Elsa.Http.Parsers;
using Elsa.Http.PortResolvers;
using Elsa.Http.Resilience;
using Elsa.Http.Selectors;
using Elsa.Http.Services;
using Elsa.Http.Tasks;
using Elsa.Http.TriggerPayloadValidators;
using Elsa.Http.UIHints;
using Elsa.Resilience.Extensions;
using Elsa.Workflows;
using Elsa.Workflows.Management.Extensions;
using FluentStorage;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
namespace Elsa.Http.ShellFeatures;
/// <summary>
/// Installs services related to HTTP services and activities.
/// </summary>
[ShellFeature(
DisplayName = "HTTP",
Description = "Provides HTTP-related activities and services for workflow execution",
DependsOn = ["HttpJavaScript", "Resilience"])]
[UsedImplicitly]
public class HttpFeature : IMiddlewareShellFeature
{
/// <summary>
/// The <see cref="HttpActivityOptions"/> to configure.
/// </summary>
public HttpActivityOptions HttpActivityOptions { get; set; } = new();
/// <summary>
/// A delegate to configure <see cref="HttpFileCacheOptions"/>.
/// </summary>
public Action<HttpFileCacheOptions>? ConfigureHttpFileCacheOptions { get; set; }
/// <summary>
/// A delegate that is invoked when authorizing an inbound HTTP request.
/// </summary>
public Func<IServiceProvider, IHttpEndpointAuthorizationHandler> HttpEndpointAuthorizationHandler { get; set; } = sp => sp.GetRequiredService<AuthenticationBasedHttpEndpointAuthorizationHandler>();
/// <summary>
/// A delegate that is invoked when an HTTP workflow faults.
/// </summary>
public Func<IServiceProvider, IHttpEndpointFaultHandler> HttpEndpointWorkflowFaultHandler { get; set; } = sp => sp.GetRequiredService<DefaultHttpEndpointFaultHandler>();
/// <summary>
/// A delegate to configure the <see cref="IContentTypeProvider"/>.
/// </summary>
public Func<IServiceProvider, IContentTypeProvider> ContentTypeProvider { get; set; } = _ => new FileExtensionContentTypeProvider();
/// <summary>
/// A delegate to configure the <see cref="IFileCacheStorageProvider"/>.
/// </summary>
public Func<IServiceProvider, IFileCacheStorageProvider> FileCache { get; set; } = sp =>
{
var options = sp.GetRequiredService<IOptions<HttpFileCacheOptions>>().Value;
var blobStorage = StorageFactory.Blobs.DirectoryFiles(options.LocalCacheDirectory);
return new BlobFileCacheStorageProvider(blobStorage);
};
/// <summary>
/// A delegate to configure the <see cref="HttpClient"/> used when by the <see cref="FlowSendHttpRequest"/> and <see cref="SendHttpRequest"/> activities.
/// </summary>
public Action<IServiceProvider, HttpClient> HttpClient { get; set; } = (_, _) => { };
/// <summary>
/// A delegate to configure the <see cref="HttpClientBuilder"/> for <see cref="HttpClient"/>.
/// </summary>
public Action<IHttpClientBuilder> HttpClientBuilder { get; set; } = _ => { };
/// <summary>
/// A list of <see cref="IHttpCorrelationIdSelector"/> types to register with the service collection.
/// </summary>
public ICollection<Type> HttpCorrelationIdSelectorTypes { get; } = new List<Type>
{
typeof(HeaderHttpCorrelationIdSelector),
typeof(QueryStringHttpCorrelationIdSelector)
};
/// <summary>
/// A list of <see cref="IHttpWorkflowInstanceIdSelector"/> types to register with the service collection.
/// </summary>
public ICollection<Type> HttpWorkflowInstanceIdSelectorTypes { get; } = new List<Type>
{
typeof(HeaderHttpWorkflowInstanceIdSelector),
typeof(QueryStringHttpWorkflowInstanceIdSelector)
};
public void ConfigureServices(IServiceCollection services)
{
// Register HTTP activities.
services.AddActivitiesFrom<HttpFeature>();
// Register HTTP variable types.
services.AddVariableDescriptors([
new(typeof(HttpRouteData), "HTTP", null),
new(typeof(HttpRequest), "HTTP", null),
new(typeof(HttpResponse), "HTTP", null),
new(typeof(HttpResponseMessage), "HTTP", null),
new(typeof(HttpHeaders), "HTTP", null),
new(typeof(IFormFile), "HTTP", null),
new(typeof(HttpFile), "HTTP", null),
new(typeof(Downloadable), "HTTP", null),
]);
// Register the HTTP resilience strategy.
services.AddResilienceStrategy<HttpResilienceStrategy>();
var configureFileCacheOptions = ConfigureHttpFileCacheOptions ?? (options => { options.TimeToLive = TimeSpan.FromDays(7); });
services.Configure<HttpActivityOptions>(options =>
{
options.BasePath = HttpActivityOptions.BasePath;
options.BaseUrl = HttpActivityOptions.BaseUrl;
options.AvailableContentTypes = HttpActivityOptions.AvailableContentTypes;
options.WriteHttpResponseSynchronously = HttpActivityOptions.WriteHttpResponseSynchronously;
});
services.Configure(configureFileCacheOptions);
var httpClientBuilder = services.AddHttpClient<SendHttpRequestBase>(HttpClient);
HttpClientBuilder(httpClientBuilder);
services
.AddScoped<IRouteMatcher, RouteMatcher>()
.AddScoped<IRouteTable, RouteTable>()
.AddScoped<IAbsoluteUrlProvider, DefaultAbsoluteUrlProvider>()
.AddScoped<IRouteTableUpdater, DefaultRouteTableUpdater>()
.AddScoped<IHttpWorkflowLookupService, HttpWorkflowLookupService>()
.AddScoped(ContentTypeProvider)
.AddHttpContextAccessor()
// Handlers.
.AddNotificationHandler<UpdateRouteTable>()
// Content parsers.
.AddSingleton<IHttpContentParser, JsonHttpContentParser>()
.AddSingleton<IHttpContentParser, XmlHttpContentParser>()
.AddSingleton<IHttpContentParser, PlainTextHttpContentParser>()
.AddSingleton<IHttpContentParser, TextHtmlHttpContentParser>()
.AddSingleton<IHttpContentParser, FileHttpContentParser>()
// HTTP content factories.
.AddScoped<IHttpContentFactory, TextContentFactory>()
.AddScoped<IHttpContentFactory, JsonContentFactory>()
.AddScoped<IHttpContentFactory, XmlContentFactory>()
.AddScoped<IHttpContentFactory, FormUrlEncodedHttpContentFactory>()
// Activity property options providers.
.AddScoped<IPropertyUIHandler, HttpContentTypeOptionsProvider>()
.AddScoped<IPropertyUIHandler, HttpEndpointPathUIHandler>()
// Default providers.
.AddScoped<DefaultHttpEndpointBasePathProvider>()
.AddScoped<IHttpEndpointBasePathProvider>(sp => sp.GetRequiredService<DefaultHttpEndpointBasePathProvider>())
// Port resolvers.
.AddScoped<IActivityResolver, SendHttpRequestActivityResolver>()
// HTTP endpoint handlers.
.AddScoped<AuthenticationBasedHttpEndpointAuthorizationHandler>()
.AddScoped<AllowAnonymousHttpEndpointAuthorizationHandler>()
.AddScoped<DefaultHttpEndpointFaultHandler>()
.AddScoped<DefaultHttpEndpointRoutesProvider>()
.AddScoped(HttpEndpointWorkflowFaultHandler)
.AddScoped(HttpEndpointAuthorizationHandler)
.AddScoped<IHttpEndpointRoutesProvider>(sp => sp.GetRequiredService<DefaultHttpEndpointRoutesProvider>())
// Startup tasks.
.AddStartupTask<UpdateRouteTableStartupTask>()
// Downloadable content handlers.
.AddScoped<IDownloadableManager, DefaultDownloadableManager>()
.AddScoped<IDownloadableContentHandler, MultiDownloadableContentHandler>()
.AddScoped<IDownloadableContentHandler, BinaryDownloadableContentHandler>()
.AddScoped<IDownloadableContentHandler, StreamDownloadableContentHandler>()
.AddScoped<IDownloadableContentHandler, FormFileDownloadableContentHandler>()
.AddScoped<IDownloadableContentHandler, DownloadableDownloadableContentHandler>()
.AddScoped<IDownloadableContentHandler, UrlDownloadableContentHandler>()
.AddScoped<IDownloadableContentHandler, StringDownloadableContentHandler>()
.AddScoped<IDownloadableContentHandler, HttpFileDownloadableContentHandler>()
//Trigger payload validators.
.AddTriggerPayloadValidator<HttpEndpointTriggerPayloadValidator, HttpEndpointBookmarkPayload>()
// File caches.
.AddScoped(FileCache)
.AddScoped<ZipManager>()
// AuthenticationBasedHttpEndpointAuthorizationHandler requires Authorization services.
.AddAuthorization();
// HTTP clients.
services.AddHttpClient<IFileDownloader, HttpClientFileDownloader>();
// Add selectors.
foreach (var httpCorrelationIdSelectorType in HttpCorrelationIdSelectorTypes)
services.AddScoped(typeof(IHttpCorrelationIdSelector), httpCorrelationIdSelectorType);
foreach (var httpWorkflowInstanceIdSelectorType in HttpWorkflowInstanceIdSelectorTypes)
services.AddScoped(typeof(IHttpWorkflowInstanceIdSelector), httpWorkflowInstanceIdSelectorType);
services.Configure<ExpressionOptions>(options =>
{
options.AddTypeAlias<HttpRequest>("HttpRequest");
options.AddTypeAlias<HttpResponse>("HttpResponse");
options.AddTypeAlias<HttpResponseMessage>("HttpResponseMessage");
options.AddTypeAlias<HttpHeaders>("HttpHeaders");
options.AddTypeAlias<HttpRouteData>("RouteData");
options.AddTypeAlias<IFormFile>("FormFile");
options.AddTypeAlias<IFormFile[]>("FormFile[]");
options.AddTypeAlias<HttpFile>("HttpFile");
options.AddTypeAlias<HttpFile[]>("HttpFile[]");
options.AddTypeAlias<Downloadable>("Downloadable");
options.AddTypeAlias<Downloadable[]>("Downloadable[]");
});
}
/// <inheritdoc />
public void UseMiddleware(IApplicationBuilder app, IHostEnvironment? environment)
{
app.UseWorkflows();
}
}