# Synapse Pipelines & Behaviors > Pipeline behaviors, validation, authorization, and error handling. > > Version: Synapse 3.x This file contains all documentation content in a single document following the llmstxt.org standard. ## Authorization `UnambitiousFx.Synapse.Authorization` authorizes requests inside the pipeline, so the same rules apply whether a request comes from an HTTP endpoint, an MCP tool, a background job or a CLI. Endpoint-level ASP.NET Core policies do not cover those other transports. ```bash dotnet add package UnambitiousFx.Synapse.Authorization ``` :::info HTTP status codes Denials are the typed `UnauthenticatedFailure` and `UnauthorizedFailure` from `UnambitiousFx.Functional`, so [`IHttpInvoker` / `IMvcInvoker`](./aspnetcore) answer **401** for an anonymous caller and **403** for an authenticated caller who lacks access, never a 500. To change a status, configure Functional's mapper with `AddResultHttp` before `AddSynapseAspNetCore`: ```csharp builder.Services.AddResultHttp(o => o.AddMapper(StatusCodes.Status401Unauthorized)); builder.Services.AddSynapseAspNetCore(); // TryAddSingleton: keeps the mapper above ``` ::: ### Setup Register an `ICurrentPrincipal` for your caller's identity, then call `AddSynapseAuthorization`. In ASP.NET Core, `AddSynapseClaimsPrincipal` registers the ready-made `ClaimsCurrentPrincipal` over `HttpContext.User`: ```csharp services.AddHttpContextAccessor(); services.AddSynapseClaimsPrincipal(sp => sp.GetRequiredService().HttpContext?.User); services.AddSynapse(cfg => cfg.AddRegisterGroup(new RegisterGroup())); services.AddSynapseAuthorization(o => { o.QueryScope = "read"; // default o.CommandScope = "write"; // default o.Policy(); // IResourceAccessPolicy, scoped o.DenialRecorder(); // IAuthorizationDenialRecorder, scoped, optional }); ``` `ClaimsCurrentPrincipal` handles the usual claim traps: - **Scopes** come from `scope`, `scp` (Microsoft Entra ID) and the long name ASP.NET Core maps `scp` to. Each claim is split on spaces (`"read write"`), and scopes are compared case-sensitively. - **Roles** go through `ClaimsPrincipal.IsInRole`, so the authentication handler's `RoleClaimType` applies. Add more types (`role`, `roles`) with `RoleClaimTypes`. - **`Id`** is `sub`, then `ClaimTypes.NameIdentifier`. - **`IsAuthenticated`** comes from `User.Identity.IsAuthenticated`, not from the presence of claims. Change the claim types with the second argument: `AddSynapseClaimsPrincipal(accessor, o => o.ScopeClaimTypes = ["permissions"])`. Outside HTTP (a background job, an MCP session), create `new ClaimsCurrentPrincipal(claimsPrincipal)` yourself, or implement `ICurrentPrincipal` directly. You can call `AddSynapseAuthorization` more than once, for example from a shared module and then from the host. Every call configures the same options, so a later call's `QueryScope` / `CommandScope` replace the earlier ones, and each call's policy and recorders are registered. An empty or whitespace default scope throws `ArgumentException`; use `null` to turn it off. ### Anonymous requests Once authorization is registered, **every request needs an authenticated caller**. Mark the requests that must work without one, such as sign-in, sign-up or password reset, with `IAllowAnonymous`: ```csharp public sealed record SignIn(string Email, string Password) : ICommand, IAllowAnonymous; ``` An `IAllowAnonymous` request: - **passes the actor check**, whoever the caller is; - **is exempt from the default scope rule**, because an anonymous caller has no `write` scope to give; - **still gets the checks it declares itself.** `IRequiresRole`, `IRequiresScope` and `IResourceScoped` apply as usual. A request that combines them with `IAllowAnonymous` therefore needs a caller who has them, which in practice means an authenticated one. Keep public requests free of those markers. ### The checks Five behaviors run on every `Result` and `Result` request, in a fixed order. The first one that denies the request short-circuits the pipeline: the handler and the later checks do not run. | Order | Behavior | Applies to | Denial | |---|---|---|---| | `AuthorizationBehaviorOrder.Actor` | `ActorAuthorizationBehavior` | every request except `IAllowAnonymous` | `UnauthenticatedFailure` when `ICurrentPrincipal.IsAuthenticated` is false | | `AuthorizationBehaviorOrder.Role` | `RoleAuthorizationBehavior` | `IRequiresRole` | `UnauthorizedFailure` when the caller is not in `Role` | | `AuthorizationBehaviorOrder.Scope` | `ScopeAuthorizationBehavior` | queries, commands, `IRequiresScope` | `UnauthorizedFailure` when the caller lacks the scope | | `AuthorizationBehaviorOrder.RequestPolicy` | `RequestPolicyAuthorizationBehavior` | request types with an `IRequestAccessPolicy` | `UnauthorizedFailure` when the policy says no | | `AuthorizationBehaviorOrder.Resource` | `ResourceAuthorizationBehavior` | `IResourceScoped`, `IOptionallyResourceScoped` with a resource | `UnauthorizedFailure` when the policy says no | All five run in `PipelineStage.Authorization`: their `Order` values sit in that stage's band (`PipelineStages.StartOf(PipelineStage.Authorization) + 1000`, `+ 2000`, ...). Observability behaviors (tracing, logging) therefore wrap them, and validation and transactions run inside them. See [pipeline stages](./pipelines). Place your own behaviors by stage rather than by number: ```csharp // tracing wraps authorization [PipelineBehavior(Stage = PipelineStage.Observability)] public sealed class TracingBehavior : IResultPipelineBehavior { ... } // auditing runs once every check has passed [PipelineBehavior(Stage = PipelineStage.Authorization, After = typeof(ResourceAuthorizationBehavior<,>))] public sealed class AuditBehavior : IResultPipelineBehavior { ... } ``` Use `cfg.ConfigureBehaviorOrdering(...)` for a behavior the source generator does not see. :::warning Putting a behavior between two checks `Before` / `After` only order the two behaviors they name. A behavior declared `After = Actor, Before = Role` runs before `Role`, but `Scope` and `Resource`, which it does not name, can then run before `Role` too. To sit between two checks, use the numeric gaps instead, which keep the checks in order: `Order => AuthorizationBehaviorOrder.Resource - 1` loads a tenant just before the resource check. ::: #### Stream requests `AddSynapseAuthorization()` also authorizes stream requests (`IStreamRequest`), with no extra registration. `StreamAuthorizationBehavior` runs the same checks in the same order, at `AuthorizationBehaviorOrder.Actor`. The markers, the resource and request policies, the denial recorders and the denial failure all apply. A stream counts as a query, so it needs `QueryScope` unless it implements `IRequiresScope`. The checks run once, before the handler starts. A denied stream yields a single failed item (`UnauthenticatedFailure` or `UnauthorizedFailure`), and the handler never runs: ```csharp await foreach (var item in invoker.InvokeStreamAsync(new ExportLoans(householdId), ct)) { if (item.TryGetFailure(out var failure)) { // denied: this is the only item break; } // ... } ``` Over HTTP, `IHttpInvoker.InvokeStreamAsync` turns that denied first item into the matching `401` or `403` Problem Details response instead of streaming an empty `200`. The checks share one behavior on streams, so a behavior of your own cannot sit between two of them. ### Markers ```csharp // Default scope: a query needs QueryScope ("read"). public sealed record GetLoan(Guid Id) : IQuery, IResourceScoped { public string ResourceId => Id.ToString(); public string Access => "read"; } // Default scope: a command needs CommandScope ("write"), plus the admin role. public sealed record PurgeLoans : ICommand, IRequiresRole { public string Role => "admin"; } // Its own scope instead of "read". public sealed record ExportLoans : IQuery, IRequiresScope { public string Scope => "loans:export"; } ``` A request that targets a resource only for some arguments implements `IOptionallyResourceScoped` instead: ```csharp // All the caller's loans, or one account's. public sealed record ListLoans(Guid? AccountId) : IQuery, IOptionallyResourceScoped { public string? OptionalResourceId => AccountId?.ToString(); public string Access => "read"; } ``` When `OptionalResourceId` is `null`, the resource check is skipped and the policy is not called. Otherwise the policy receives the request as usual, with `ResourceId` equal to `OptionalResourceId`. The actor, role and scope checks run either way. - **Scopes.** A request that implements `IRequiresScope` needs its `Scope`. Otherwise an `IQuery` needs `QueryScope` and an `ICommand` / `ICommand` needs `CommandScope`. A plain `IRequest` that declares no scope needs none. - **Turning the default off.** `o.DisableDefaultScopes()` (or setting `QueryScope` / `CommandScope` to `null`) stops the query / command rule. Requests that implement `IRequiresScope` are still checked. - **Roles.** `IRequiresRole.Role` is checked with `ICurrentPrincipal.IsInRole`. - **Blank values are bugs.** An `IRequiresScope.Scope` or `IRequiresRole.Role` that is null, empty or whitespace, or an `IOptionallyResourceScoped.OptionalResourceId` that is empty or whitespace, throws `InvalidOperationException` naming the request type when the request is dispatched. It is not treated as "no requirement" (that would fail open), and it is not a silent denial of every caller (that would hide the bug behind ordinary 401/403s). Recorders are not called for it, because no caller was denied. ### Resource policy Only the policy is application-specific: who may access which resource. ```csharp public sealed class LoanAccessPolicy(LoansDbContext db) : IResourceAccessPolicy { public async ValueTask IsAllowedAsync(ICurrentPrincipal principal, IResourceScoped request, CancellationToken cancellationToken = default) { var loanId = Guid.Parse(request.ResourceId); return await db.Loans.AnyAsync(l => l.Id == loanId && l.OwnerId == principal.Id, cancellationToken); } } ``` `request` is the request itself, so you can pattern-match it to read more than `ResourceId` and `Access`. Without a registered policy, every `IResourceScoped` request is denied: the behavior fails closed. #### Hiding a resource the caller cannot see A denied resource answers `403`, which tells the caller the resource exists. To answer as if it did not exist, so that probing identifiers tells nothing, override `CheckAsync` and return `ResourceAccess.Hidden`: ```csharp public sealed class LoanAccessPolicy(LoansDbContext db) : IResourceAccessPolicy { public ValueTask IsAllowedAsync(ICurrentPrincipal principal, IResourceScoped request, CancellationToken cancellationToken = default) => throw new NotSupportedException(); // CheckAsync is overridden, so the behaviors never call it public async ValueTask CheckAsync(ICurrentPrincipal principal, IResourceScoped request, CancellationToken cancellationToken = default) { var loan = await db.Loans.FindAsync([Guid.Parse(request.ResourceId)], cancellationToken); if (loan is null || !loan.IsVisibleTo(principal.Id)) { return ResourceAccess.Hidden; // 404, same as a missing loan } return request.Access == "read" || loan.OwnerId == principal.Id ? ResourceAccess.Allowed : ResourceAccess.Denied; // 403: the caller can read it, so it knows it exists } } ``` | `CheckAsync` returns | Failure | HTTP | Denial reason | |---|---|---|---| | `Allowed` | none, the request goes on | | | | `Denied` | `UnauthorizedFailure` (`UNAUTHORIZED`) | 403 | `ResourceAccessDenied` | | `Hidden` | `NotFoundFailure` (`NOT_FOUND`), fixed message | 404 | `ResourceHidden` | By default `CheckAsync` maps `IsAllowedAsync` to `Allowed` or `Denied`, so existing policies are unchanged. Keep `Denied` for a caller who can read the resource but not do what the request asks: a `404` would look like a bug to someone who just read it. `default(ResourceAccess)` is `Denied`, so a value that was never set fails closed. :::warning The behaviors call `CheckAsync`, not `IsAllowedAsync`. A mocked policy (`Substitute.For()`) set up on `IsAllowedAsync` alone now denies every request, because the mock's `CheckAsync` returns `Denied`: configure `CheckAsync` instead. ::: ### Request policies A request that creates a resource has no resource to check yet, but often still needs a check on what it asks for: an invoice for a customer the caller may bill, an account in a branch the caller belongs to, a booking in an open period. Write a policy for that request type: ```csharp public sealed class InvoiceCreationPolicy(IBillingRights rights) : IRequestAccessPolicy { public ValueTask IsAllowedAsync(ICurrentPrincipal principal, CreateInvoice request, CancellationToken cancellationToken = default) => rights.MayBillAsync(principal.Id!, request.CustomerId, cancellationToken); } services.AddSynapseAuthorization(o => o.RequestPolicy()); ``` `RequestPolicy()` registers it as a scoped service, replacing any policy already registered for that request type. Registering `IRequestAccessPolicy` in the container yourself works too. - **It runs after the scope check and before the resource check**, for requests and streams. A request type without a policy is not checked: no marker is needed. - **A denial** is an `UnauthorizedFailure`, reported to the recorders with the reason `RequestDenied`. ### Recording denials Every denial is passed to each registered `IAuthorizationDenialRecorder` before the failure is returned: ```csharp public sealed class AuditDenials(ILogger logger) : IAuthorizationDenialRecorder { public ValueTask RecordAsync(AuthorizationDenial denial, CancellationToken cancellationToken = default) { logger.LogWarning("{Request} denied for {Principal}: {Reason} {Requirement} {Resource}", denial.Request.GetType().Name, denial.PrincipalId, denial.Reason, denial.Requirement, denial.ResourceId); return ValueTask.CompletedTask; } } ``` `AuthorizationDenial` carries the request, the `Reason` (`Unauthenticated`, `MissingRole`, `MissingScope`, `ResourceAccessDenied`, `RequestDenied`, `ResourceHidden`), the caller's `Id`, the missing role, scope or access in `Requirement`, and the `ResourceId` for resource denials. ### Background work Jobs, schedulers, migrations and outbox handlers send requests through the same pipeline as users, but run as a technical identity that belongs to no user. Run them as `SystemPrincipal.Instance` instead of faking a principal that every policy must special-case: ```csharp // the worker host's container services.AddSingleton(SystemPrincipal.Instance); ``` A principal whose `ICurrentPrincipal.IsSystem` is `true` skips the checks that `SystemBypass` names. A skipped check calls no policy and records no denial: | `o.SystemBypass` | Actor, role, scope | Request policy, resource | |---|---|---| | `SystemBypass.All` (default) | skipped | skipped | | `SystemBypass.ResourceChecks` | checked as for any caller | skipped | | `SystemBypass.None` | checked as for any caller | checked as for any caller | `SystemPrincipal.Instance` is authenticated, holds every scope and role, and its `Id` is `system`. For a system identity that should keep its role and scope checks, implement `ICurrentPrincipal` with `IsSystem => true` and only the scopes and roles it needs, and set `o.SystemBypass = SystemBypass.ResourceChecks`. `IsSystem` is a default interface member that returns `false`, so existing `ICurrentPrincipal` implementations are unaffected. ### Denial failures By default a denial returns an `UnauthenticatedFailure` (code `UNAUTHENTICATED`) or an `UnauthorizedFailure` (code `UNAUTHORIZED`) with a fixed English message such as `Requires role 'admin'.`. To give clients a domain code to branch on, and a message the application shows or translates, set `DenialFailure`: ```csharp services.AddSynapseAuthorization(o => o.DenialFailure = denial => denial.Reason switch { AuthorizationDenialReason.MissingRole => new UnauthorizedFailure("This action is reserved to administrators.") { Code = "core.admin_required" }, AuthorizationDenialReason.MissingScope => new UnauthorizedFailure($"The '{denial.Requirement}' scope is required.") { Code = "core.scope_required" }, _ => null // the default failure }); ``` It receives the same `AuthorizationDenial` as the recorders, for requests and streams alike, and runs only when a request is denied. The recorders are still called. The failure keeps its type, since transports map it to `401` / `403` / `404` and the MCP invoker hides existence behind it. Return an `UnauthenticatedFailure` for `Unauthenticated`, a `NotFoundFailure` for `ResourceHidden` and an `UnauthorizedFailure` for every other reason. Any other type throws `InvalidOperationException`, so a denial cannot become a `404` or a `422` by mistake: only the resource policy decides to hide a resource (see [Hiding a resource the caller cannot see](#hiding-a-resource-the-caller-cannot-see)). ### Limits - Events are not authorized. - The behaviors are registered closed for each request type, so the package works with Native AOT, value-type requests included. - `AddSynapse` and `AddSynapseAuthorization` must be called on the same `IServiceCollection`. A request registered in another collection (a child or tenant container, a collection built by copying descriptors) is not authorized. --- ## Error Handling Synapse embraces the principle that **errors are values**. Handlers return `Result` / `Result` from `UnambitiousFx.Functional` rather than throwing exceptions for domain errors. Exceptions are reserved for genuine programming errors (misconfiguration, missing handlers). ### Result at the call site Every `IInvoker.InvokeAsync` call returns a `Result` or `Result`. Use whichever consumption pattern fits the context: #### `TryGet` — out-variable style ```csharp var result = await invoker.InvokeAsync(new CreateTaskCommand("Buy milk"), ct); if (result.TryGet(out var id, out var error)) return Results.Created($"/tasks/{id}", id); else return Results.Problem(error.ToString()); ``` #### `Match` — functional style ```csharp return result.Match( success: id => Results.Created($"/tasks/{id}", id), failure: error => Results.Problem(error.ToString())); ``` #### `IsSuccess` guard `Result` / `Result` expose no `Value` or `Error` property — pull both out with `TryGet`, or use `IsSuccess` / `IsFailure` purely as a boolean check: ```csharp if (!result.TryGet(out var id, out var error)) { logger.LogError("Create task failed: {Error}", error); return; } Process(id); ``` ### Returning failures from handlers Return a failure directly from a handler — do not throw: ```csharp public async ValueTask> HandleAsync(CreateTaskCommand cmd, CancellationToken ct) { if (string.IsNullOrWhiteSpace(cmd.Title)) return Result.Failure("Title is required."); // ← return, not throw var id = Guid.NewGuid(); await _repo.SaveAsync(id, cmd.Title, ct); return Result.Success(id); } ``` #### Failure types and codes `Result.Failure` carries a `Failure` with a `Code`, a message and optional metadata. The `UnambitiousFx.Functional` package provides typed variants that set a default code: | Failure type | Default code | | --- | --- | | `ValidationFailure` | `VALIDATION` | | `NotFoundFailure` | `NOT_FOUND` | | `UnauthorizedFailure` | `UNAUTHORIZED` | | `UnauthenticatedFailure` | `UNAUTHENTICATED` | | `TimeoutFailure` | `TIMEOUT` | | any other `Failure` | the code you pass, or `ERROR` | Codes are plain strings, so you can define your own (for example `orders.quantity_invalid`) and map them in one place, such as the HTTP mapper described in [ASP.NET Core](./aspnetcore). Prefixing custom codes with the module name keeps them unambiguous. ### Combining multiple results Combine a collection of `Result` / `Result` values into a single result. It succeeds only when all inputs succeed; otherwise all failures are aggregated: ```csharp var results = new[] { validator1.ValidateAsync(cmd), validator2.ValidateAsync(cmd), }; // Combine over ValueTask awaits all of them and returns ValueTask var combined = await results.Combine(); if (!combined.IsSuccess) return combined; // all individual failures merged ``` ### Propagation through pipelines Failures propagate transparently through the pipeline without any special handling: - A behavior that calls `next()` and gets back `Result.Failure(...)` can inspect it, transform it, or return it unchanged. - A behavior can short-circuit by returning `Result.Failure(...)` without calling `next()` at all (e.g., a validation behavior). ```csharp public async ValueTask> HandleAsync( TRequest request, RequestHandlerDelegate next, CancellationToken ct) { // Short-circuit example if (!IsAllowed(request)) return Result.Failure("Access denied."); return await next(); } ``` ### Exceptions Exceptions are thrown only for programming errors — situations that indicate misconfiguration, not expected domain failures: | Exception | When thrown | | -------------------------------- | ------------------------------------------------------------------------------------------- | | `MissingHandlerException` | No handler registered for the request type. This is a startup/configuration error. | | `CqrsBoundaryViolationException` | A command was dispatched from inside a query (or vice versa) with CQRS enforcement enabled. | | `MissingContextFeatureException` | `IContext.MustGetFeature()` called but the feature was never set. | These should never appear in normal application flow. If they do, fix the configuration rather than catching them. ### See also - `UnambitiousFx.Functional` — full `Result` API: `Bind`, `Map`, `Ensure`, `Recover`, LINQ support. - [Validation](./validation) — validation failures surface as `Result.Failure` before the handler runs. - [Pipeline Behaviors](./pipelines) — behaviors can inspect and transform failures. --- ## Pipeline Behaviors Pipeline behaviors let you wrap request, event, or stream handling with cross-cutting logic — logging, tracing, validation, or CQRS enforcement — without touching handler code. They follow the **chain-of-responsibility** (Russian-doll) pattern: each behavior calls `next(...)` to forward to the next behavior or to the handler. All Synapse pipeline behaviors are **typed**: a behavior is bound to a specific request/response (or event, or stream-item) type through the generic interface it implements. The non-generic `HandleAsync(...)` style does not exist — `HandleAsync` is a plain method and `next` is a strongly-typed delegate that takes the request and a `CancellationToken`. ### How the pipeline works ```mermaid flowchart LR Invoker["IInvoker"] B1["Behavior 1\n(outermost)"] B2["Behavior 2"] B3["Behavior N"] Handler["Handler\n(innermost)"] Invoker --> B1 B1 -- next() --> B2 B2 -- next() --> B3 B3 -- next() --> Handler Handler -- Result --> B3 B3 -- Result --> B2 B2 -- Result --> B1 B1 -- Result --> Invoker ``` Each behavior can inspect or modify the request and the result on both sides of `next(...)`. Order is controlled explicitly by [`IOrderedPipelineBehavior`](#ordering) and [stages and `Before`/`After` constraints](#stages-and-relative-ordering) — not by registration order. ### Request pipeline behaviors A request behavior implements one of two typed interfaces: - `IRequestPipelineBehavior` — for requests that return a value (`IRequest`). - `IRequestPipelineBehavior` — for fire-and-forget requests (`IRequest`). ```csharp public sealed class AuditCreateTaskBehavior : IRequestPipelineBehavior { public async ValueTask> HandleAsync( CreateTaskCommand request, RequestHandlerDelegate next, CancellationToken cancellationToken = default) { var result = await next(request, cancellationToken); if (result.TryGetValue(out var id)) Audit.Log($"Task created: {id}"); return result; } } // Register the behavior for its request/response pair cfg.RegisterRequestPipelineBehavior(); ``` For a fire-and-forget command, implement `IRequestPipelineBehavior` and register with the two-type-argument overload: ```csharp public sealed class AuditDeleteTaskBehavior : IRequestPipelineBehavior { public ValueTask HandleAsync( DeleteTaskCommand request, RequestHandlerDelegate next, CancellationToken cancellationToken = default) => next(request, cancellationToken); } cfg.RegisterRequestPipelineBehavior(); ``` ### One behavior for both request shapes Cross-cutting logic that does not depend on the response type (validation, authorization, mapping exceptions to failures, logging) would otherwise be written twice, once per interface above. Implement `IResultPipelineBehavior` instead: Synapse closes it with `TResult = Result` for `IRequest` requests and `TResult = Result` for `IRequest` requests. ```csharp [PipelineBehavior] public sealed class ValidationBehavior(IEnumerable> validators) : IResultPipelineBehavior, IOrderedPipelineBehavior where TResult : IResult { public uint Order => IOrderedPipelineBehavior.Middle; public async ValueTask HandleAsync( TRequest request, RequestNext next, CancellationToken cancellationToken = default) { if (Validate(request) is { } failure) return next.Fail(failure); // Result.Failure(...) or Result.Failure(...) var result = await next.InvokeAsync(request, cancellationToken); // result.IsSuccess / result.TryGetFailure(...) are available here return result; } } ``` - `next.InvokeAsync` runs the rest of the pipeline; `next.Fail` builds a failure of the request's shape without calling it. - `[PipelineBehavior]` and `[assembly: SynapseGlobalBehavior(typeof(ValidationBehavior<,>))]` register it for every handler, AOT-safe. Without the generator: `cfg.AddOpenGenericResultPipelineBehavior(typeof(ValidationBehavior<,>))`, or the closed `cfg.RegisterResultPipelineBehavior()` / `()`. - Close `TResult` yourself to target one shape only: `IResultPipelineBehavior` applies to requests without response, `IResultPipelineBehavior>` to requests with one. - Result behaviors and typed behaviors share one chain ordered by `IOrderedPipelineBehavior`. On equal `Order`, typed behaviors run first. - To unit-test one, build the continuation by hand: `new RequestNext((r, ct) => ..., Result.Failure)`. ### Applying a behavior to every handler Naming each request/response pair is fine for one-off behaviors, but cross-cutting concerns (logging, tracing, auth) usually apply to *all* handlers. Make the behavior **open-generic** and mark it `[PipelineBehavior]` — the Synapse source generator discovers it, infers the kind/arity from the implemented interface, and emits one closed (Native-AOT-safe) registration per matching handler: ```csharp [PipelineBehavior] public sealed class TimingBehavior : IRequestPipelineBehavior where TRequest : IRequest where TResponse : notnull { private readonly ILogger> _logger; public TimingBehavior(ILogger> logger) => _logger = logger; public async ValueTask> HandleAsync( TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken = default) { var sw = Stopwatch.StartNew(); var result = await next(request, cancellationToken); _logger.LogInformation("{Request} completed in {Ms}ms", typeof(TRequest).Name, sw.ElapsedMilliseconds); return result; } } ``` By default an assembly's `[PipelineBehavior]` classes are applied to handlers in **referenced** assemblies too. Apply `[assembly: DisableSynapseCrossAssemblyBehaviors]` to limit the cross-product to handlers declared in the same assembly. :::note Native AOT Registering an open-generic behavior at runtime (`AddOpenGenericRequestPipelineBehavior(typeof(...))`) is supported but is **not** Native-AOT safe for value-type responses. Prefer `[PipelineBehavior]` so the generator emits closed registrations. ::: #### Registering a behavior you don't own (e.g. from a NuGet package) `[PipelineBehavior]` requires decorating the behavior class, so it only works for behaviors whose source you control. When a behavior ships in a referenced package — for example a company's shared pipeline library — opt into it from the composition root with `[assembly: SynapseGlobalBehavior(typeof(...))]`. The generator treats it exactly like a `[PipelineBehavior]` open generic: it closes the behavior over every matching handler and emits one closed, Native-AOT-safe registration per match. ```csharp [assembly: SynapseGlobalBehavior(typeof(CompanyShared.LoggingBehavior<,>))] ``` Pass the **unbound** generic definition (`typeof(Foo<,>)`) — a non-generic `typeof` is the only way to hand an open generic to an attribute. The behavior type must be `public` and implement one of the pipeline interfaces; its open-generic constraints (named-type and `class`/`struct`/`unmanaged`/`notnull`/`new()`) are honoured, and pipeline position is controlled by the behavior implementing `IOrderedPipelineBehavior`, or by the `Stage`/`Before`/`After` of a `[PipelineBehavior]` on the packaged behavior itself, which the generator reads from the reference (see [Stages and relative ordering](#stages-and-relative-ordering)). The same cross-assembly and `[assembly: DisableSynapseCrossAssemblyBehaviors]` rules apply. #### Sharing behaviors across projects `[PipelineBehavior]` propagates **downward** through the reference graph: the generator of the assembly that declares the behavior closes it over handlers in that assembly and in the assemblies it *references*. In a layered or modular solution the shared behaviors usually live in a library that the handler assemblies reference, so the library's generator never sees those handlers and the behavior is not applied to them. Wire the shared behaviors from the composition root (the host) instead: ```csharp // Host project (references the shared library and every module; runs the generator) [assembly: SynapseGlobalBehavior(typeof(Shared.AccessBehavior<,>))] [assembly: SynapseGlobalBehavior(typeof(Shared.ValidationBehavior<,>))] ``` ```csharp services.AddSynapse(cfg => { cfg.AddRegisterGroup(new Host.RegisterGroup()); // required: carries the global behaviors cfg.AddRegisterGroup(new ModuleA.RegisterGroup()); cfg.AddRegisterGroup(new ModuleB.RegisterGroup()); }); ``` :::warning The host's own group must be registered `[assembly: SynapseGlobalBehavior]` is emitted into the host assembly's generated `RegisterGroup` (or your `[RegisterGroup]` partial class). If that group is never passed to `AddRegisterGroup`, the attributes are accepted, **nothing fails, and the behaviors never run** ([`ValidateSynapse`](#validating-the-configuration) cannot detect this either — the [`SYN105`](./source-generator#diagnostics) analyzer catches it at build time instead). This matters most for security behaviors such as authorization. Add a test that dispatches one request from each module and asserts that the expected behaviors ran. ::: Ordering is unaffected by where a behavior is declared or registered: it is decided at runtime by [`IOrderedPipelineBehavior`](#ordering). See [Modular monoliths](./modular-monolith) for a complete layout. ### Applying a behavior to commands or queries only Constrain the open-generic behavior on a marker interface and it applies only to the requests that implement it. A behavior with `where TRequest : ICommand` (and `where TResponse : notnull`) runs for commands only: ```csharp [PipelineBehavior] public sealed class CommandAuditBehavior : IRequestPipelineBehavior where TRequest : ICommand where TResponse : notnull { public async ValueTask> HandleAsync( TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken = default) { // audit the command, call next return await next(request, cancellationToken); } } ``` The same works with `[assembly: SynapseGlobalBehavior(typeof(MyBehavior<,>))]` (source generator, Native-AOT safe) and with the runtime `AddOpenGenericRequestWithResponsePipelineBehavior(typeof(MyBehavior<,>))`: DI skips the closings whose constraints do not hold. (The built-in `TransactionBehavior<,>` has no such constraint: it checks `ITransactional` at run time. See [Transactions](./transactions.mdx).) The runtime path is not Native-AOT safe for value-type responses, so prefer `[PipelineBehavior]` under AOT. For requests without a response, use `where TRequest : ICommand` on an `IRequestPipelineBehavior`. There are no dedicated `AddCommandPipelineBehavior` helpers: the generic constraint is the scoping mechanism. The generator matches such a constraint against the handler's request type, so it works for any interface or base class, not only the markers. :::note Limit The `SYN102` analyzer does not evaluate constraints that reference the behavior's own type parameters (such as `ICommand`). A marker-scoped behavior that matches no handler is therefore silently never wired, and `SYN102` does not report it. ::: ### Built-in behaviors #### `SimpleLoggingBehavior` / `SimpleLoggingEventBehavior` Logs the request or event name and elapsed time. Register the closed pair for each handler (`SimpleLoggingBehavior` for void requests): ```csharp cfg.RegisterRequestPipelineBehavior< SimpleLoggingBehavior, CreateTaskCommand, Guid>(); cfg.RegisterEventPipelineBehavior< SimpleLoggingEventBehavior, TaskCreatedEvent>(); ``` #### `LoggingEnrichmentBehavior` Enriches the `ILogger` scope with the context's [flow identity](./context.mdx#flow-identity) and its [baggage](./context.mdx#baggage) so every log line emitted during the request automatically includes them: ```csharp cfg.RegisterRequestPipelineBehavior< LoggingEnrichmentBehavior, CreateTaskCommand, Guid>(); ``` #### CQRS boundary enforcement `CqrsBoundaryEnforcementBehavior` / `CqrsBoundaryEnforcementBehavior` detect when a command is dispatched from inside a query handler (or vice versa) and throw `CqrsBoundaryViolationException`. The behavior runs outermost (`Order => IOrderedPipelineBehavior.First`). Enable it per request type: ```csharp cfg.RegisterCqrsBoundaryEnforcement(); cfg.RegisterCqrsBoundaryEnforcement(); ``` Or turn it on for the whole assembly by registering the built-in behavior globally — the source generator emits the closed (AOT-safe) registrations for every handler: ```csharp [assembly: SynapseGlobalBehavior(typeof(CqrsBoundaryEnforcementBehavior<>))] [assembly: SynapseGlobalBehavior(typeof(CqrsBoundaryEnforcementBehavior<,>))] ``` Both attributes are needed: the one-parameter form covers requests with no response, the two-parameter form those that return one. `SynapseGlobalBehavior` is the general mechanism — see [Registering a behavior you don't own](#registering-a-behavior-you-dont-own-eg-from-a-nuget-package). :::note v1's `[assembly: EnableSynapseCqrsBoundaryEnforcement]` and `cfg.EnableCqrsBoundaryEnforcement()` were removed in v2 — see [Migrating to v2](./migration-v2.mdx#7-the-deprecated-cqrs-enforcement-opt-ins-are-removed). ::: #### Outbox discard on failure `OutboxDiscardOnFailureBehavior` / `OutboxDiscardOnFailureBehavior` take back the outbox events a request stored when it fails or throws. It is opt-in and also runs outermost; see [Discard the events of a failed request](./outbox.mdx#discard-the-events-of-a-failed-request). #### Transactions `TransactionBehavior` runs every `ITransactional` request inside a transaction that commits on a successful `Result` and rolls back on a failure or an exception, with savepoints for nested commands. Wire it with `cfg.AddTransactions()`; see [Transactions](./transactions.mdx). ### Event pipeline behaviors Implement `IEventPipelineBehavior` for a specific event type: ```csharp public sealed class EventLoggingBehavior : IEventPipelineBehavior { private readonly ILogger _logger; public EventLoggingBehavior(ILogger logger) => _logger = logger; public ValueTask HandleAsync( TaskCreatedEvent @event, EventHandlerDelegate next, CancellationToken cancellationToken = default) { _logger.LogInformation("Dispatching event {Event}", typeof(TaskCreatedEvent).Name); return next(@event, cancellationToken); } } cfg.RegisterEventPipelineBehavior(); ``` To cover every event, make the behavior open-generic (`EventLoggingBehavior : IEventPipelineBehavior`) and mark it `[PipelineBehavior]`. ### Stream pipeline behaviors Implement `IStreamRequestPipelineBehavior`. The `next` delegate (`StreamRequestHandlerDelegate`) is parameterless and returns the downstream `IAsyncEnumerable>`: ```csharp public sealed class StreamLoggingBehavior : IStreamRequestPipelineBehavior { public IAsyncEnumerable> HandleAsync( StreamTasksQuery request, StreamRequestHandlerDelegate next, CancellationToken cancellationToken = default) { Console.WriteLine($"Stream started: {typeof(StreamTasksQuery).Name}"); return next(); } } cfg.RegisterStreamRequestPipelineBehavior(); ``` ### Ordering Behaviors run in the order given by `IOrderedPipelineBehavior` — **not** registration order. A behavior opts in by implementing the interface and exposing an `Order` (a `uint`); **lower values run first (outermost)**, higher run last (innermost, closest to the handler). A behavior that does not implement `IOrderedPipelineBehavior` is treated as `Last`. Ties are broken by registration order (stable). ```csharp public sealed class LoggingBehavior : IRequestPipelineBehavior, IOrderedPipelineBehavior where TRequest : IRequest where TResponse : notnull { public uint Order => IOrderedPipelineBehavior.First; // outermost public ValueTask> HandleAsync( TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken = default) => next(request, cancellationToken); } ``` `IOrderedPipelineBehavior` exposes three convenience positions: `First` (`uint.MinValue`), `Middle` (`uint.MaxValue / 2`), and `Last` (`uint.MaxValue`). For example, register logging at `First` so it captures the full round-trip, and validation closer to the handler. #### Stages and relative ordering Raw numbers do not compose across modules and packages: a behavior shipped in a package cannot know the numbers an application picked. A behavior can instead declare a **stage** and **`Before`/`After` constraints** on other behaviors: ```csharp [PipelineBehavior(Stage = PipelineStage.Authorization, After = typeof(ActorBehavior<,>))] public sealed class AuditBehavior : IRequestPipelineBehavior where TRequest : IRequest where TResponse : notnull { // ... } ``` `PipelineStage` lists well-known stages, outermost first: `Observability`, `Authentication`, `Authorization`, `Validation`, `Transaction`, `Handler`. `Before`/`After` take the open-generic definition (`typeof(ActorBehavior<,>)`, matching every closed form) or a concrete type (matching only it). A constraint naming a behavior that is not in a given pipeline is ignored for that pipeline. The source generator reads these properties and emits the matching registration. Without the generator (a behavior registered by hand, or a package's behavior), declare the same thing at runtime; calling it again for the same behavior adds constraints: ```csharp services.AddSynapse(cfg => { cfg.RegisterRequestPipelineBehavior, CreateTask, TaskId>(); cfg.ConfigureBehaviorOrdering(typeof(AuditBehavior<,>), PipelineStage.Authorization, after: typeof(ActorBehavior<,>)); }); ``` The attribute alone is not read at runtime: without the generator, use `ConfigureBehaviorOrdering`. Declarations for an open-generic definition and for one of its closed forms both apply to that closed form: their constraints add up, and two different stages are an error (`SYN006`). ##### How the order is resolved 1. **Group by stage.** A behavior belongs to the stage it declares. A behavior that declares none belongs to the stage whose `Order` band contains its `Order` (below). Stages run in enum order. 2. **Apply `Before`/`After`.** Within a stage, constraints are edges of a stable topological sort. Across stages, a constraint must agree with the stage order: `Before` an earlier stage is impossible and reported. 3. **Break ties** with `Order` (a behavior without one counts as `Last`), then registration order. Each stage owns a contiguous band of `Order` values, exposed by `PipelineStages.StartOf(stage)` and `PipelineStages.Of(order)`: | Stage | `Order` band | Holds | |---|---|---| | `Observability` | `0` to `0x1FFF_FFFF` | `First` | | `Authentication` | `0x2000_0000` to `0x3FFF_FFFF` | | | `Authorization` | `0x4000_0000` to `0x5FFF_FFFF` | | | `Validation` | `0x6000_0000` to `0x7FFF_FFFF` | `Middle` | | `Transaction` | `0x8000_0000` to `0x9FFF_FFFF` | | | `Handler` | `0xA000_0000` to `0xFFFF_FFFF` | `Last` | Because the bands are contiguous and increasing, **a pipeline in which no behavior declares a stage or a constraint runs in exactly the order `Order` alone gives**, ties included: existing behaviors keep their position. Behaviors that only set `Order` also interleave predictably with staged ones; for example `Order = 10` runs in `Observability`, before any `Authorization` behavior. A package that prefers numbers can still target a stage with `PipelineStages.StartOf(PipelineStage.Transaction) + 10`. The order is resolved once per pipeline, when it is first built, and cached; dispatching a request does not pay for it. A cycle or an impossible constraint throws `PipelineOrderingException` when that pipeline is built, and is reported earlier: - at build time by the generator, when it can see the declarations: `MDG018` for a `Before`/`After` cycle, `MDG019` for a constraint that contradicts two declared stages or names the behavior itself; - at startup by [`ValidateSynapse()`](#validating-the-configuration) otherwise (`SYN005`, `SYN006`). ### Validating the configuration `ValidateSynapse()` inspects the registrations and reports mistakes that would otherwise surface only at the first request (or never). It never throws on findings (it throws `ArgumentNullException` for a null provider and `InvalidOperationException` if `AddSynapse` was never called): it returns a `SynapseValidationReport` and you decide what to do with it. | Code | Severity | What it catches | Fix | |---|---|---|---| | `SYN001` | Error | A closed pipeline behavior is registered for a request or event type that has no handler. | Register the handler, or remove the behavior. | | `SYN002` | Error | Two or more handlers are registered for one request type. Only the last registered one runs; the others are silently ignored. Events are exempt: several handlers per event is normal. | Keep one handler per request. | | `SYN003` | Error | The pipeline of a registered handler or event cannot be resolved (missing dependency, throwing constructor). The exception message is included. | Register the missing dependency or fix the constructor. | | `SYN004` | Warning | Two behaviors in one pipeline share a stage and an `Order`, and no `Before`/`After` constraint orders them. Legal, they keep registration order. Only behaviors that declare an `Order` through `IOrderedPipelineBehavior` can tie, and ties made solely of Synapse's own built-in behaviors are not reported. | Give them distinct `Order` values, or a `Before`/`After` constraint, if the relative position matters. | | `SYN005` | Error | The `Before`/`After` constraints of a pipeline's behaviors form a cycle. | Remove one of the constraints. | | `SYN006` | Error | An ordering declaration cannot be satisfied: a constraint contradicts the stages (a `Validation` behavior declared `Before` an `Observability` one), or one behavior is declared in two stages. | Change a stage or drop the constraint. | Warnings do not make `report.IsValid` false. Assert on it in a test: ```csharp using UnambitiousFx.Synapse; // ValidateSynapse() using UnambitiousFx.Synapse.Abstractions; // SynapseValidationReport var report = provider.ValidateSynapse(); Assert.True(report.IsValid, report.ToString()); ``` Or fail the host at startup instead of at the first request. `ValidateOnStart()` registers a hosted service that logs every warning and throws `SynapseValidationException` when the report has errors: ```csharp services.AddSynapse(cfg => { cfg.AddRegisterGroup(new Host.RegisterGroup()); cfg.ValidateOnStart(); }); ``` #### What it cannot catch - A request with neither a handler nor a behavior: nothing is registered, so there is nothing to inspect. - `[assembly: SynapseGlobalBehavior]` when the host's generated group is never registered (`cfg.AddRegisterGroup(new Host.RegisterGroup())`). The behaviors never reach the container, so the validator sees a valid configuration. The build-time [`SYN105`](./source-generator#diagnostics) analyzer catches this instead. - Stream requests: stream pipelines are not inspected yet. - An `IRequestPipelineBehavior` (void flavour) registered for an `IRequest` request: it never runs and is not reported. - Behaviors added to the `IServiceCollection` after `AddSynapse` returns. - Open-generic behaviors: DI closes them lazily over any request, so whether one applies to nothing is not decidable at runtime. Validation also resolves every registered handler and its behaviors once at startup (one throwaway scope per pipeline), so constructor side effects run at startup. ### See also - [Validation](./validation) — `RequestValidationBehavior`, the built-in validation pipeline. - [Observability](./observability) — `SimpleLoggingBehavior` and `LoggingEnrichmentBehavior` in detail. - [Source Generator](./source-generator) — `[PipelineBehavior]` discovery and closed-registration emission. - [Error Handling](./error-handling) — behaviors can short-circuit by returning `Result.Failure(...)` instead of calling `next(...)`. ### Inspecting a pipeline `IPipelineDescriber` reports which handler(s) and behaviors a request or event type resolves to, in the order they execute. Use it in an architecture test to prove a behavior can never be skipped: ```csharp var describer = provider.GetRequiredService(); var pipeline = describer.Describe(); Assert.NotNull(pipeline); Assert.Equal(typeof(PurgeCompletedTasksCommandHandler), Assert.Single(pipeline.Handlers)); Assert.Contains(pipeline.Behaviors, b => b.Type.IsGenericType && b.Type.GetGenericTypeDefinition() == typeof(AuthorizationBehavior<,>)); ``` `Behaviors` is outermost first, in the resolved order; each entry carries the concrete behavior type, the `Order` it declared (`IOrderedPipelineBehavior.Last` when it declares none), and the `Stage` it runs in (declared, or implied by its `Order`). `Describe` returns `null` when nothing handles the message. To check every request in an assembly, use the non-generic overloads. `IsRequest` stands for your own predicate for request types (for example, concrete types that implement `IRequest` or `IRequest<>`). `Describe` returns `null` for a request nothing handles, so decide what that means for your test instead of suppressing it: ```csharp foreach (var requestType in typeof(PurgeCompletedTasksCommand).Assembly.GetTypes().Where(IsRequest)) { var pipeline = describer.Describe(requestType); Assert.NotNull(pipeline); // or skip request types that are deliberately unhandled Assert.Contains(pipeline.Behaviors, b => b.Type.IsGenericType && b.Type.GetGenericTypeDefinition() == typeof(AuthorizationBehavior<,>)); } ``` `PipelineDescription` has structural equality, so two descriptions with the same handlers and behaviors in the same order are equal, and `ToString()` prints them as `Stage Order Name`. :::note `Describe(Type)` and `DescribeEvent(Type)` are served from the registrations Synapse recorded, without reflection, so they are Native-AOT safe like the generic overloads. A type that was not registered through Synapse returns `null`, since the invoker cannot dispatch it either. A type registered with both `IRequest` and `IRequest` is described by its `IRequest` pipeline. ::: :::caution Describing resolves the handler and the behaviors from a fresh DI scope, because `Order` is an instance property, then disposes the scope. The handler's constructor dependencies are constructed too (a `DbContext`, an `HttpClient`, any warm-up side effect). A handler or behavior whose constructor needs something that only exists inside a real request (for example an `HttpContext`) can throw there, and a handler that only implements `IAsyncDisposable` makes disposing that scope throw. ::: --- ## Validation Synapse provides a first-class validation mechanism that runs validators before the handler is invoked. If any validator fails, the handler is never called and the failure is returned to the caller. ### Define a validator Implement `IRequestValidator` and return `Result.Failure(...)` when the request is invalid: ```csharp using UnambitiousFx.Functional; using UnambitiousFx.Synapse.Abstractions; public class CreateTaskCommandValidator : IRequestValidator { public ValueTask ValidateAsync(CreateTaskCommand command, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(command.Title)) return ValueTask.FromResult(Result.Failure("Title is required.")); if (command.Title.Length > 200) return ValueTask.FromResult(Result.Failure("Title must be 200 characters or fewer.")); return ValueTask.FromResult(Result.Success()); } } ``` ### Register the validator and the validation behavior Validation is implemented as a pipeline behavior, so you register both the validator and the behavior: ```csharp services.AddSynapse(cfg => { cfg.AddValidator(); cfg.RegisterRequestPipelineBehavior< RequestValidationBehavior, CreateTaskCommand, Guid>(); }); ``` `AddValidator` registers `IRequestValidator` in DI. `RequestValidationBehavior` resolves all registered validators for the request type at runtime. :::tip If any validator returns `Result.Failure`, the **handler is never called** and the failure is returned directly to the caller. ::: ### Validation flow ```mermaid flowchart TD Request["Request arrives at pipeline"] Validators["IRequestValidator<TRequest> ×N\n(run in order)"] Combine["Combine results"] Pass{All valid?} Handler["IRequestHandler\n.HandleAsync()"] Failure["Return Result.Failure\n(handler never called)"] Success["Return Result from handler"] Request --> Validators Validators --> Combine Combine --> Pass Pass -- Yes --> Handler Pass -- No --> Failure Handler --> Success ``` ### Multiple validators You can register as many validators as you like for the same request type. All validators run and their results are combined via `.Combine()`. If any fail, all failures are aggregated: ```csharp cfg.AddValidator(); cfg.AddValidator(); // Both run; both failures are reported if both fail ``` ### FluentValidation `UnambitiousFx.Synapse.FluentValidation` runs every `IValidator` registered in the container, for both `Result` and `Result` requests. Nothing to write per request. ```bash dotnet add package UnambitiousFx.Synapse.FluentValidation ``` ```csharp services.AddValidatorsFromAssemblyContaining(); // FluentValidation.DependencyInjectionExtensions services.AddSynapse(cfg => cfg.AddRegisterGroup(new RegisterGroup())); services.AddSynapseFluentValidation(o => o.Order = IOrderedPipelineBehavior.Middle); // order is optional ``` When a validator fails, the handler is not called and the result holds one `ValidationFailure` with every error of every validator. Each `ValidationError` keeps the property name (`Field`, `null` for object-level rules), the message and the FluentValidation error code. By default the behavior runs at the start of `PipelineStage.Validation` (`PipelineStages.StartOf(PipelineStage.Validation)`): after authorization and before transactions, so an invalid request never opens a transaction. Set `Order` to move it, for example to `IOrderedPipelineBehavior.Last` to run closest to the handler, like the built-in validation behavior. The behaviors are registered closed, once per request type that `AddSynapse` registers a handler for (value-type requests included), so this package is Native-AOT compatible and trimming-safe on our side. Call `AddSynapse` and `AddSynapseFluentValidation` on the same `IServiceCollection`, in either order: a collection that never gets `AddSynapse` has no request type to validate. Your own `AbstractValidator` rules are expression-based, so they remain subject to whatever FluentValidation itself supports under NativeAOT. ### External validation libraries `IRequestValidator` is just an interface — you can adapt any validation library. Here is an example adapting FluentValidation by hand: ```csharp public class FluentCreateTaskValidator : IRequestValidator { private readonly IValidator _validator; public FluentCreateTaskValidator(IValidator validator) => _validator = validator; public async ValueTask ValidateAsync(CreateTaskCommand cmd, CancellationToken ct = default) { var validation = await _validator.ValidateAsync(cmd, ct); return validation.IsValid ? Result.Success() : Result.Failure(string.Join("; ", validation.Errors.Select(e => e.ErrorMessage))); } } ``` ### See also - [Pipeline Behaviors](./pipelines) — validation is a pipeline behavior; understand registration order. - [Error Handling](./error-handling) — how validation failures surface as `Result` at the call site.