PM> Install-Package Shuttle.Middleware
Typed, composable middleware with named insertion points.
A composite middleware (Middleware<TState>) invokes an ordered chain of middleware (IMiddleware<TState>). Each middleware wraps everything downstream of it: it does its work, calls next to run the remainder of the chain, and can do more work after next returns.
Each middleware type is also a named anchor, so another middleware can be inserted before or after it, can replace it, or can remove it, without changing the composite middleware or the other middleware.
Every invocation receives a new instance of the state type, so nothing carries over between invocations:
public class LaunchState(bool cryogenic = false, bool weatherClear = true) : IVehicleState, IPayloadState
{
public bool WeatherClear { get; } = weatherClear;
public bool Cryogenic { get; } = cryogenic;
public bool Fuelled { get; set; }
public bool TanksPressurized { get; set; }
public bool Ignited { get; set; }
public bool PayloadDeployed { get; set; }
}
public interface ILaunchMiddleware : IMiddleware<LaunchState>
{
Task<bool> InvokeAsync(LaunchState state, CancellationToken cancellationToken = default);
}
public class LaunchMiddleware(IServiceProvider serviceProvider) : Middleware<LaunchState>(serviceProvider), ILaunchMiddleware;Middleware<TState> is itself an IMiddleware<TState>, and InvokeAsync(TState, CancellationToken) runs it as the outermost middleware. A composite middleware's own interface declares the members that its callers use: usually InvokeAsync for one that is invoked directly, and nothing beyond IMiddleware<TState> for one that is only nested.
IMiddleware<in TState> is contravariant and IMiddlewareContext<out TState> is covariant. A middleware therefore only declares the state it needs, through a capability interface, and can be used in any composite middleware whose state implements that interface:
public interface IVehicleState
{
bool WeatherClear { get; }
bool Cryogenic { get; }
bool Fuelled { get; set; }
bool TanksPressurized { get; set; }
bool Ignited { get; set; }
}
public interface ILoadFuelMiddleware : IMiddleware<IVehicleState>;
public class LoadFuelMiddleware : ILoadFuelMiddleware
{
public async Task InvokeAsync(IMiddlewareContext<IVehicleState> context, MiddlewareDelegate next, CancellationToken cancellationToken = default)
{
context.State.Fuelled = true;
await next(cancellationToken);
}
}A middleware written against object (IMiddleware<object>) can be used in every composite middleware.
Data that is not part of the state, such as data added by an extension, goes into features. context.Features is the IFeatureCollection from Microsoft.Extensions.Features, the same type that ASP.NET Core exposes as HttpContext.Features, keyed by type. Every invocation starts with an empty collection:
using Microsoft.AspNetCore.Http.Features;
context.Features.Set(new LaunchTelemetry(...)); // Set<T>(null) removes it
var telemetry = context.Features.Get<LaunchTelemetry>(); // null when not set
var telemetry = context.Features.GetRequiredFeature<LaunchTelemetry>(); // throws when not setservices.AddMiddleware()
.AddMiddlewareFrom(typeof(LaunchMiddleware).Assembly) // registers each middleware (scoped) against its `I{Name}` interface
.AddMiddleware<LaunchMiddleware>(definition => definition
.Add<ICheckWeatherMiddleware>()
.Add<ILoadFuelMiddleware>()
.Add<IIgniteMiddleware>()
.Add<IDeployPayloadMiddleware>());AddMiddleware<TMiddleware>(define) registers the composite middleware (scoped), its I{Name} interface if it has one, and its base definition. AddMiddleware<TService, TImplementation>() registers a single middleware.
Say the vehicle now uses cryogenic fuel, which cannot be ignited until the tanks are pressurized, so a PressurizeTanks middleware is needed after LoadFuel:
public interface IPressurizeTanksMiddleware : IMiddleware<IVehicleState>;
public class PressurizeTanksMiddleware : IPressurizeTanksMiddleware
{
public async Task InvokeAsync(IMiddlewareContext<IVehicleState> context, MiddlewareDelegate next, CancellationToken cancellationToken = default)
{
context.State.TanksPressurized = true;
await next(cancellationToken);
}
}
services.ConfigureMiddleware<LaunchMiddleware>(definition => definition.InsertAfter<ILoadFuelMiddleware, IPressurizeTanksMiddleware>());LaunchMiddleware now runs CheckWeather → LoadFuel → PressurizeTanks → Ignite → DeployPayload.
Supported modifications on a MiddlewareDefinition:
| Method | Effect |
|---|---|
Add<TMiddleware>() |
Appends the middleware. |
InsertBefore<TAnchor, TMiddleware>() |
Inserts the middleware immediately before the anchor. |
InsertAfter<TAnchor, TMiddleware>() |
Inserts the middleware immediately after the anchor. |
Replace<TExisting, TReplacement>() |
Puts the replacement in the existing middleware's position. |
Remove<TMiddleware>() |
Removes the middleware. |
Contains<TMiddleware>() |
Checks whether the middleware is part of the definition. |
Rules:
- A middleware type appears only once per definition. A class that should take part at more than one point is registered under a separate interface for each point.
- The anchor has to exist. Called directly on a
MiddlewareDefinition, a missing anchor or a duplicate middleware throws anInvalidOperationException; withinAddMiddleware/ConfigureMiddlewarethe error is recorded and reported by validation. ConfigureMiddlewareis applied usingPostConfigureof named options. Modifications therefore always run after the base definition, whatever the registration order, so an extension package may be registered before the package that defines the composite middleware. Modifications run in registration order.
Every middleware definition is validated (MiddlewareDefinitionValidator, an IValidateOptions<MiddlewareDefinition>):
- the
AddMiddleware/ConfigureMiddlewareactions applied without errors (e.g. a missing anchor, or a middleware added twice); - the type derives from
Middleware<TState>; - the definition contains at least one middleware (a
ConfigureMiddlewarefor a composite middleware that was never added is reported here); - each middleware implements
IMiddleware<TState>for the composite middleware's state, directly or through variance; - each middleware has been registered (when the container provides
IServiceProviderIsService, as the default container does).
All the errors of a definition are reported together in one OptionsValidationException, whose OptionsName is the composite middleware type's full name.
AddMiddleware and ConfigureMiddleware register their definitions for validation on startup (ValidateOnStart), so a host (Host, WebApplication) validates all middleware definitions when it starts and fails to start if any is invalid; several invalid definitions are reported together in an AggregateException. Without a host, validate explicitly after building the service provider:
serviceProvider.GetRequiredService<IStartupValidator>().Validate();Startup validation is not required for correctness: a definition is also validated when it is first used, so an invalid composite middleware is never invoked. Startup validation only moves the failure to the earliest point.
A composite middleware is also a middleware, so composite middleware can be nested. This replaces the "stages" of Shuttle.Pipelines: each stage becomes a standalone composite middleware, and an outer composite middleware runs them in order:
public interface IPreLaunchMiddleware : IMiddleware<IVehicleState>;
public class PreLaunchMiddleware(IServiceProvider serviceProvider) : Middleware<IVehicleState>(serviceProvider), IPreLaunchMiddleware;
public interface IAscentMiddleware : IMiddleware<IVehicleState>;
public class AscentMiddleware(IServiceProvider serviceProvider) : Middleware<IVehicleState>(serviceProvider), IAscentMiddleware;
public interface IOrbitMiddleware : IMiddleware<IPayloadState>;
public class OrbitMiddleware(IServiceProvider serviceProvider) : Middleware<IPayloadState>(serviceProvider), IOrbitMiddleware;
public interface IMissionMiddleware : IMiddleware<LaunchState>
{
Task<bool> InvokeAsync(LaunchState state, CancellationToken cancellationToken = default);
}
public class MissionMiddleware(IServiceProvider serviceProvider) : Middleware<LaunchState>(serviceProvider), IMissionMiddleware;
services.AddMiddleware()
.AddMiddlewareFrom(typeof(MissionMiddleware).Assembly)
.AddMiddleware<PreLaunchMiddleware>(definition => definition
.Add<ICheckWeatherMiddleware>()
.Add<ILoadFuelMiddleware>())
.AddMiddleware<AscentMiddleware>(definition => definition
.Add<IIgniteMiddleware>())
.AddMiddleware<OrbitMiddleware>(definition => definition
.Add<IDeployPayloadMiddleware>())
.AddMiddleware<MissionMiddleware>(definition => definition
.Add<IPreLaunchMiddleware>()
.Add<IAscentMiddleware>()
.Add<IOrbitMiddleware>());A nested composite middleware:
- Shares the outer context: the same state, features and abort status. A middleware that aborts inside a nested composite middleware (a weather scrub in
PreLaunch, say) stops the outer chain. - Only needs a compatible state type: a composite middleware over a capability interface (
Middleware<IVehicleState>) can be nested in any composite middleware whose state implements that interface. It can also be invoked on its own. - Runs its own middleware as a self-contained chain, then continues the outer chain:
- Ambient context set up by a middleware inside a nested composite middleware is scoped to it.
- To wrap a nested composite middleware and everything after it, insert the middleware before it in the outer definition:
ConfigureMiddleware<MissionMiddleware>(definition => definition.InsertBefore<IPreLaunchMiddleware, ITransactionScopeMiddleware>()).
- Is a normal anchor: middleware can be inserted into a nested composite middleware (
ConfigureMiddleware<PreLaunchMiddleware>(...)) or between nested composite middleware (ConfigureMiddleware<MissionMiddleware>(definition => definition.InsertAfter<IPreLaunchMiddleware, IPressurizeTanksMiddleware>())). - Raises middleware events like any other middleware: for itself (by the outer chain) and for each of its own middleware.
- Is not protected against recursion: as with any middleware that invokes other middleware, a composite middleware that contains itself, directly or indirectly, recurses until the stack overflows. Avoiding that is up to the definitions.
All downstream middleware run inside the call to next. Ambient context that a middleware sets up before next (TransactionScope with TransactionScopeAsyncFlowOption.Enabled, Activity, logging scopes, any AsyncLocal) is therefore visible to every downstream middleware. A using around next also disposes it once they complete, even if one of them fails:
public interface ITransactionScopeMiddleware : IMiddleware<object>;
public class TransactionScopeMiddleware : ITransactionScopeMiddleware
{
public async Task InvokeAsync(IMiddlewareContext<object> context, MiddlewareDelegate next, CancellationToken cancellationToken = default)
{
using var scope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);
await next(cancellationToken);
scope.Complete();
}
}
services.ConfigureMiddleware<LaunchMiddleware>(definition => definition.InsertBefore<IIgniteMiddleware, ITransactionScopeMiddleware>());A middleware may pass a different (e.g. linked) CancellationToken to next; downstream middleware receive that token. A middleware may also call next more than once, e.g. to retry the remainder of the chain.
- A middleware either calls
nextor callscontext.Abort()to stop the invocation. A middleware that returns having done neither causes anInvalidOperationException, so a forgottennextnever silently skips the rest of the chain.InvokeAsyncreturnsfalsewhen the invocation was aborted. - Exceptions propagate through the chain, so a middleware can handle downstream failures with an ordinary
try/catcharoundnext. An exception that is not handled is rethrown fromInvokeAsync. - An
OperationCanceledExceptionraised because the invocation's token was cancelled is not reported as a failure.
MiddlewareOptions exposes lifecycle events for every middleware invocation, including the outermost middleware that InvokeAsync runs, so observability needs no changes to any middleware. MiddlewareEventArgs carries the Context and the MiddlewareType: the type as it appears in the definition, or the concrete type for the outermost middleware.
services.AddMiddleware(options =>
{
options.MiddlewareStarting += (args, cancellationToken) => ...;
});| Event | Raised |
|---|---|
MiddlewareStarting |
Before a middleware is invoked. |
MiddlewareCompleted |
After a middleware has returned, which includes the downstream middleware it wraps. |
MiddlewareAborted |
For the outermost middleware, in place of MiddlewareCompleted, when the invocation was aborted. |
MiddlewareFailed |
For the middleware that threw an unhandled exception, and for each middleware that the exception passed through, up to the outermost middleware. |