elsa-core/src/modules/Elsa.Persistence.EFCore.Common/PersistenceShellFeatureBase.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

153 lines
6.4 KiB
C#

using System.Reflection;
using CShells.Features;
using Elsa.Common.Entities;
using Elsa.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
// ReSharper disable once CheckNamespace
namespace Elsa.Persistence.EFCore;
public abstract class PersistenceShellFeatureBase<TDbContext> : IShellFeature
where TDbContext : DbContext
{
/// <summary>
/// Gets or sets a value indicating whether to use context pooling.
/// When not explicitly set, falls back to shared settings if available.
/// </summary>
public bool? UseContextPooling { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to run migrations.
/// When not explicitly set, falls back to shared settings if available, defaulting to true.
/// </summary>
public bool? RunMigrations { get; set; }
/// <summary>
/// Gets or sets the lifetime of the <see cref="IDbContextFactory{TContext}"/>.
/// When not explicitly set, falls back to shared settings if available, defaulting to <see cref="ServiceLifetime.Scoped"/>.
/// </summary>
public ServiceLifetime? DbContextFactoryLifetime { get; set; }
/// <summary>
/// Gets or sets the connection string to use for the database.
/// When not explicitly set, falls back to shared settings if available.
/// </summary>
public string? ConnectionString { get; set; }
/// <summary>
/// Gets or sets additional options to configure the database context.
/// When not explicitly set, falls back to shared settings if available.
/// </summary>
public ElsaDbContextOptions? DbContextOptions { get; set; }
/// <summary>
/// Gets or sets the callback used to configure the <see cref="DbContextOptionsBuilder"/>.
/// </summary>
protected virtual Action<IServiceProvider, DbContextOptionsBuilder> DbContextOptionsBuilder { get; set; } = (_, _) => { };
public void ConfigureServices(IServiceCollection services)
{
// Capture feature-specific settings
var featureConnectionString = ConnectionString;
var featureDbContextOptions = DbContextOptions;
var featureUseContextPooling = UseContextPooling;
var featureRunMigrations = RunMigrations;
var featureDbContextFactoryLifetime = DbContextFactoryLifetime;
// Resolve effective settings at runtime, falling back to shared settings
Action<IServiceProvider, DbContextOptionsBuilder> setup = (sp, opts) =>
{
var sharedSettings = sp.GetService<IOptions<SharedPersistenceSettings>>()?.Value;
var connectionString = featureConnectionString
?? sharedSettings?.ConnectionString
?? throw new InvalidOperationException(
$"Connection string not configured for {GetType().Name}. " +
$"Either configure the feature directly or provide shared settings via the combined persistence feature.");
var dbContextOptions = featureDbContextOptions ?? sharedSettings?.DbContextOptions;
opts.ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning));
// Configure the database provider
var migrationsAssembly = GetMigrationsAssembly();
ConfigureProvider(opts, migrationsAssembly, connectionString, dbContextOptions);
// Allow derived classes to further configure
DbContextOptionsBuilder(sp, opts);
};
// Resolve pooling and lifetime settings with fallback
// Note: These are resolved at configuration time, not runtime, but they'll use defaults if not set
var useContextPooling = featureUseContextPooling ?? false;
var dbContextFactoryLifetime = featureDbContextFactoryLifetime ?? ServiceLifetime.Scoped;
var runMigrations = featureRunMigrations ?? true;
if (useContextPooling)
services.AddPooledDbContextFactory<TDbContext>(setup);
else
services.AddDbContextFactory<TDbContext>(setup, dbContextFactoryLifetime);
services.Decorate<IDbContextFactory<TDbContext>, TenantAwareDbContextFactory<TDbContext>>();
services.Configure<MigrationOptions>(options =>
{
options.RunMigrations[typeof(TDbContext)] = runMigrations;
});
services.AddStartupTask<RunMigrationsStartupTask<TDbContext>>();
OnConfiguring(services);
}
/// <summary>
/// Gets the assembly containing migrations for this provider.
/// By default, returns the assembly of the concrete feature type.
/// </summary>
protected virtual Assembly GetMigrationsAssembly() => GetType().Assembly;
/// <summary>
/// Configures the database provider for the specified <see cref="DbContextOptionsBuilder"/>.
/// </summary>
/// <param name="builder">The options builder to configure.</param>
/// <param name="migrationsAssembly">The assembly containing migrations.</param>
/// <param name="connectionString">The connection string to use.</param>
/// <param name="options">Additional options to configure the database context.</param>
protected abstract void ConfigureProvider(
DbContextOptionsBuilder builder,
Assembly migrationsAssembly,
string connectionString,
ElsaDbContextOptions? options);
protected virtual void OnConfiguring(IServiceCollection services)
{
}
/// <summary>
/// Adds a store to the service collection.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <typeparam name="TStore">The type of the store.</typeparam>
protected void AddStore<TEntity, TStore>(IServiceCollection services) where TEntity : class, new() where TStore : class
{
services
.AddScoped<Store<TDbContext, TEntity>>()
.AddScoped<TStore>()
;
}
/// <summary>
/// Adds an entity store to the service collection.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <typeparam name="TStore">The type of the store.</typeparam>
protected void AddEntityStore<TEntity, TStore>(IServiceCollection services) where TEntity : Entity, new() where TStore : class
{
services
.AddScoped<EntityStore<TDbContext, TEntity>>()
.AddScoped<TStore>()
;
}
}