# App passwords (/docs/capabilities/app-passwords) Calendar apps (iOS, macOS, Thunderbird, DAVx5) cannot run an OIDC or cookie sign-in: they send a user name and a password over HTTP Basic on every request. Outlook and Google Calendar subscribe to a URL and send nothing at all. An **app password** is the credential for both: a person creates one in the application ("iPhone"), types it into the calendar app once, and revokes it when the phone is gone. A **feed token** is an app password bound to one published calendar and carried in the path of its feed URL (ADR-0111). | Package | Role | | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Elarion.AppPasswords` | `IAppPasswords` (create, list, revoke, verify), `AppPasswordScope`, `AppPasswordOptions`, the `IAppPasswordStore` seam and an in-memory store for tests. NativeAOT-safe. | | `Elarion.AppPasswords.EntityFrameworkCore` | The `elarion_app_passwords` table on the application's `DbContext` (`[GenerateElarionAppPasswords]`). | | `Elarion.AppPasswords.AspNetCore` | The authentication scheme: HTTP Basic and feed tokens, its events, and `AddElarionIdentityAppPasswordPrincipals()`. | Management is the application's: it writes the own-account handlers that create, list and revoke, and the page that shows a new secret once. Elarion stores, checks and signs in. ## Wiring [#wiring] ```csharp // The DbContext maps the table: [GenerateDbSets] [GenerateElarionAppPasswords] public partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } builder.Services.AddElarionAppPasswordsEntityFrameworkCore( builder.Configuration.GetSection(AppPasswordOptions.SectionName)); builder.Services.AddElarionIdentityAppPasswordPrincipals(); // or set Events.OnCreatePrincipal builder.Services.AddAuthentication() // the browser's scheme stays the default .AddElarionAppPasswordAuthentication(o => o.Realm = "Example"); ``` The scheme is not the default scheme. Name it on the routes calendar apps use, and only there: ```csharp app.MapGroup("/dav").RequireAuthorization(new AuthorizeAttribute { AuthenticationSchemes = AppPasswordAuthenticationDefaults.AuthenticationScheme, }); ``` An app password then authenticates nothing else (not `/rpc`, not `[HttpEndpoint]` routes), and the browser's cookie or proxy token authenticates nothing under `/dav`. The DAV host of the CalDAV packages applies this to its route group itself. **No calendar feeds? Turn the feed-token reader off.** The scheme reads a feed token from `{/dav}/feeds/{token}.ics` by default, for CalDAV's ICS feeds. Only an app password of scope `calendar-feed` verifies there, so an application that issues none is not exposed, but one that serves no feeds (CardDAV only, or no DAV at all) should say so: ```csharp builder.Services.AddAuthentication().AddElarionAppPasswordAuthentication(o => o.FeedTokenReader = null); ``` ## Creating, listing and revoking [#creating-listing-and-revoking] ```csharp [Handler] // an own-account handler: it acts only on the signed-in user's passwords public sealed class CreateAppPassword(IAppPasswords appPasswords, ICurrentUser user) : IHandler> { public sealed record Command([property: StringLength(AppPasswordOptions.MaxNameLength, MinimumLength = 1)] string Name); public sealed record Created(Guid Id, string Secret); public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var issued = await appPasswords.CreateAsync(user.UserId, command.Name, AppPasswordScope.Dav, ct); if (!issued.IsSuccess) return issued.Error; // app_password.limit_reached return new Created(issued.Value.Password.Id, issued.Value.Secret); // the only time the secret is readable } } ``` * `CreateAsync(userId, name, scope)` returns `Result`: the listing data and the secret. A user who already holds `MaxPerUser` app passwords gets a conflict with the code `AppPasswordErrorCodes.LimitReached` (`app_password.limit_reached`) whose `Data` is an `AppPasswordLimitReachedData` with `MaxPerUser`, so the message in the user's language needs no options: branch on the code, word the payload. A handler that returns the error over JSON-RPC declares `[ProducesError(AppPasswordErrorCodes.LimitReached, ErrorKind.Conflict, typeof(AppPasswordLimitReachedData))]`, which puts the payload into its error contract and serializer context. The password is stored when the call returns, independent of the caller's transaction. A user id is at most 256 characters (`AppPasswordOptions.MaxUserIdLength`, the stored column's length); a longer one throws. * `ListAsync(userId)` returns `AppPasswordInfo`s (id, name, scope, creation, last use), never a secret, **oldest first** (by creation). A page that shows the newest first reverses the list; it holds at most `MaxPerUser` rows. * `RevokeAsync(userId, id)` deletes the row; the next request with it is refused. Another user's id or an unknown one is a not-found with `AppPasswordErrorCodes.NotFound` (`app_password.not_found`). * `VerifyAsync(secret, scope)` is what the scheme calls; it records the last use at most once per `LastUseInterval`. ### Scopes and feed tokens [#scopes-and-feed-tokens] `AppPasswordScope.Dav` (`dav`) is a calendar app's account. `AppPasswordScope.CalendarFeed(source, key)` (`calendar-feed:{source}.{key}`, each part 1 to 64 ASCII letters, digits, `-` or `_`) binds a feed token to one published calendar. The scheme accepts a `dav` password only over HTTP Basic and a feed token only in a feed URL, `{prefix}/feeds/{token}.ics` (`AppPasswordFeedPaths`), and answers a refused feed token with `404` rather than a challenge, because the URL itself is the credential. Which calendar a feed token may read is checked by the DAV host against the token's scope; see [CalDAV feeds](/docs/capabilities/caldav#feeds-for-outlook-and-google-calendar), where `AppPasswordScope.CalendarFeed(CalDavAddress)` and `CalDavLinks.FeedUrl` create the scope and the URL. ### The secret [#the-secret] A secret is `SecretPrefix` (default `elap_`) and 256 bits from `RandomNumberGenerator`, base64url without padding. Only its hash is stored: SHA-256 over the UTF-8 bytes of the whole secret as the client sends it, prefix included, as standard Base64 with padding (`AppPasswordSecrets.ComputeHash`), under a unique index. A machine-generated secret of this entropy needs no slow hash and no lockout; a rate limiter on the route can still guard it. ## The scheme and its events [#the-scheme-and-its-events] For HTTP Basic the header is split at the first colon (the user name cannot contain one, the password can). Then four events run, each a `Func>` on `AppPasswordAuthenticationEvents`. Every context carries `HttpContext`, `Services` (the request scope), `Scheme`, `CredentialKind`, `UserName` (Basic only) and `CancellationToken`. | Event | Default | Returning | | -------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `OnVerifyCredential` | `IAppPasswords.VerifyAsync`: scope `dav` for Basic, any calendar-feed scope for a feed token | the `AppPasswordMatch` (id, user id, scope), or `null` to refuse | | `OnValidateUserName` | not checked (the secret identifies the credential); not run for feeds | `false` to refuse | | `OnCreatePrincipal` | none: the registered `IAppPasswordPrincipalFactory`, else the host fails to start | the `ClaimsPrincipal`, or `null` to refuse | | `OnAuthenticated` | nothing | — (audit, metrics) | The principal is created on **every** request, so a deleted or deactivated account stops syncing at once. `AddElarionIdentityAppPasswordPrincipals()` does it through ASP.NET Core Identity: `UserManager.FindByIdAsync`, a refusal when the user is missing or locked out, when a registered `SignInManager` would not sign the user in (`CanSignInAsync`: a required confirmed e-mail, phone number or account through `IUserConfirmation`, or the application's override), or when the application's own rule says no, and `IUserClaimsPrincipalFactory`: ```csharp builder.Services.AddElarionIdentityAppPasswordPrincipals( (user, ctx) => ValueTask.FromResult(user.IsActive && (user.EndsAt is null || user.EndsAt > DateTimeOffset.UtcNow))); ``` An application on proxy identity or OIDC sets the delegate over its own user service: ```csharp builder.Services.AddAuthentication().AddElarionAppPasswordAuthentication(o => { o.Events.OnCreatePrincipal = async ctx => { var accounts = ctx.Services.GetRequiredService(); return await accounts.CreatePrincipalAsync(ctx.Match.UserId, ctx.CancellationToken); // null refuses }; }); ``` The scheme adds the claims `elarion:app_password_id` and `elarion:app_password_scope` (`AppPasswordClaimTypes`), so `ICurrentUser.HasClaim` and the DAV host can tell an app-password request apart. Whatever `OnVerifyCredential` returns, a match of the wrong kind is refused: a feed token never works as a Basic password. A missing or refused credential is answered `401` with `WWW-Authenticate: Basic realm="{Realm}", charset="UTF-8"` (iOS sends unauthenticated requests during discovery and gives up on a `403`); an authenticated request the policy refuses is answered `403` without a challenge. Instead of setting delegates, an application can subclass `AppPasswordAuthenticationEvents`, override `VerifyCredential`, `ValidateUserName`, `CreatePrincipal` or `Authenticated`, register the subclass and set `o.EventsType`, as with `JwtBearerEvents`. The scheme is hand-written over `AuthenticationHandler` with no reflection and publishes with NativeAOT without warnings. ## Adopting existing app passwords [#adopting-existing-app-passwords] An application that already issues its own Basic credentials to DAV clients moves to this scheme without asking anyone to create a new password and type it into every device. It has two paths. **1. Keep its own store.** It registers no `Elarion.AppPasswords.EntityFrameworkCore` (and need not call `AddElarionAppPasswords`), and points the events at what it has: `OnVerifyCredential` at its existing check, `OnValidateUserName` at its user-name rule, and `OnCreatePrincipal` at its principal construction, with any account checks of its own. `IAppPasswords` and `IAppPasswordStore` are then never resolved. Only the handler class changes; the table, the management handlers and the page stay. No data migration. ```csharp builder.Services.AddAuthentication().AddElarionAppPasswordAuthentication(o => { o.Events.OnVerifyCredential = async ctx => { var tokens = ctx.Services.GetRequiredService(); var token = await tokens.FindAsync(ctx.Secret, ctx.CancellationToken); return token is null ? null : new AppPasswordMatch { Id = token.Id.ToString(), UserId = token.UserId, Scope = AppPasswordScope.Dav }; }; o.Events.OnValidateUserName = async ctx => { // "the e-mail of the owning account" var accounts = ctx.Services.GetRequiredService(); var email = await accounts.GetEmailAsync(ctx.Match.UserId, ctx.CancellationToken); return string.Equals(email, ctx.UserName, StringComparison.OrdinalIgnoreCase); }; o.Events.OnCreatePrincipal = async ctx => { var accounts = ctx.Services.GetRequiredService(); return await accounts.CreateActivePrincipalAsync(ctx.Match.UserId, ctx.CancellationToken); }; }); ``` **2. Move the rows into Elarion's store.** This works without the secrets when the old store kept SHA-256 over the UTF-8 secret as standard Base64 — the encoding above. A migration step copies each row into `elarion_app_passwords` with `scope = 'dav'`, the user id as a string, the name, the creation and last-use times, and the hash unchanged; then the application drops its own table and handlers and uses `IAppPasswords`. The hash covers the whole secret as typed, so secrets with the old prefix keep verifying; `SecretPrefix` affects only new ones. A store that kept SHA-256 as hex converts in SQL (`encode(decode(hash_hex, 'hex'), 'base64')` on PostgreSQL); one with another hash function stays on path 1, or its users re-create their passwords. ```sql INSERT INTO elarion_app_passwords (id, user_id, name, scope, hash, created_at, last_used_at) SELECT id, user_id::text, name, 'dav', token_hash, created_at, last_used_at FROM legacy_app_passwords; ``` The cap per user (10), the last-use interval (15 minutes) and revoking by deleting match what such stores usually do, so neither path changes what a user notices. What does not carry over is a user-name rule: path 2 still sets `OnValidateUserName` when the application wants one. ## Options [#options] | Option | Default | Meaning | | -------------------------------------------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `AppPasswords:SecretPrefix` | `elap_` | The start of every new secret, so secret scanners recognise a leaked one. | | `AppPasswords:MaxPerUser` | `10` | How many app passwords one user may hold. | | `AppPasswords:LastUseInterval` | `00:15:00` | The shortest time between two writes of the last use; a polling client causes no write within it. | | `AppPasswordAuthenticationOptions.Realm` | `DAV` | The realm of the Basic challenge. | | `AppPasswordAuthenticationOptions.FeedTokenReader` | `{/dav}/feeds/{token}.ics` | Reads a feed token from a request; `AppPasswordFeedPaths.CreateReader(prefix)` for another prefix, `null` for no feeds. | See [configuration](/docs/reference/configuration#app-passwords) and the [decision](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0111-caldav.md). # Archive & restore (/docs/capabilities/archive-restore) "Delete" in a product UI is usually not `DELETE` in SQL: the user wants the record out of the way, and someone else wants it back next quarter. That is a reversible **domain state** — *archived* — not a deletion, and modeling it honestly is the whole trick. There is deliberately no `Elarion.SoftDelete` package or `[SoftDelete]` attribute: the pattern is a **recipe** composed from pieces you already have — an entity property, a partial unique index, two small command handlers, a [scheduled job](/docs/capabilities/scheduling) — and a shipped convention could only hide the two decisions that actually matter (what each query returns, and what *delete* means in your domain). This page is the recommended shape, and — because every team has met `IsDeleted` and `HasQueryFilter` before — [why the usual alternatives are rejected](#alternatives-this-recipe-rejects). ## 1. The state is a nullable timestamp [#1-the-state-is-a-nullable-timestamp] One property: `ArchivedAt`, `null` while active. A timestamp costs the same as an `IsArchived` boolean and answers *when* for free — which the purge job below needs anyway. Add `ArchivedBy` only if the archived-items screen displays it; the [audit trail](/docs/concepts/auditing) already records who executed the command. ```csharp public sealed class Customer : IArchivable { public Guid Id { get; set; } public required string Name { get; set; } public required string Email { get; set; } public DateTimeOffset? ArchivedAt { get; set; } } [EntityConfiguration] public sealed class CustomerConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { builder.HasKey(c => c.Id); // Partial unique index: only ACTIVE customers reserve an email, so archiving one // frees the address for a new registration. Make this a per-key decision — an // invoice *number* must stay reserved forever, so its index would have no filter. builder.HasIndex(c => c.Email) .IsUnique() .HasFilter("\"ArchivedAt\" IS NULL"); // Partial index over the archived minority: serves the archived-items screen and // the purge probe without taxing writes to active rows. builder.HasIndex(c => c.ArchivedAt) .HasFilter("\"ArchivedAt\" IS NOT NULL"); } } ``` `IArchivable` is a one-property interface in your shared persistence layer; its only job is to let a named, reusable predicate exist: ```csharp public interface IArchivable { DateTimeOffset? ArchivedAt { get; set; } } public static class ArchivableQueryExtensions { public static IQueryable WhereActive(this IQueryable query) where T : IArchivable => query.Where(e => e.ArchivedAt == null); public static IQueryable WhereArchived(this IQueryable query) where T : IArchivable => query.Where(e => e.ArchivedAt != null); } ``` Archive at the **aggregate root**. Line items, addresses, and other owned children are only reached through their root's queries, so they need no flag of their own; a flag on every child row is a sign the aggregate boundary — not the archive pattern — needs work. ## 2. Every query says what it returns [#2-every-query-says-what-it-returns] Filtering is **explicit at the call site**, and each read surface decides deliberately: ```csharp // Lists, pickers, lookups, assignment targets: active only — visible in the query. var rows = await db.Customers.WhereActive() .OrderBy(c => c.Name) .Select(c => new Row(c.Id, c.Name)) .ToListAsync(ct); // The archived-items screen is just the other predicate. var archived = await db.Customers.WhereArchived() .OrderByDescending(c => c.ArchivedAt) .Select(c => new Row(c.Id, c.Name)) .ToListAsync(ct); ``` The **detail query deliberately has no filter**: a bookmarked link or a reference from an old invoice should land on the record with its state showing — "this customer is archived", with a restore action — not a bewildering 404. Return `ArchivedAt` in the response and let the client render the state. (Contrast [feature gates](/docs/concepts/feature-flags), where a generic `NotFound` is the point because the feature's existence must not leak; an archived record is a user-visible state, not a secret.) ### Why not a global `HasQueryFilter` [#why-not-a-global-hasqueryfilter] EF Core's model-level filter looks like the safer choice — "nobody can forget the predicate" — and is the most common way teams do this. This recipe rejects it, for three reasons that compound: * **It makes queries stop saying what SQL runs.** The same posture that rejects repositories and `IAppDbContext` ([the database is application logic](/docs/why-elarion#the-database-is-application-logic-not-an-abstraction)) applies to rows: a handler reading `db.Customers.ToListAsync()` should mean *customers*, not *customers minus whatever the model silently subtracts*. `WhereActive()` is six characters of honesty per query. * **The "can't forget" guarantee is false exactly where Elarion sends you.** Query filters apply to LINQ queries only. `SqlQuery` rollups, provider functions, [bulk COPY](/docs/capabilities/bulk-operations), and the [AOT SQL tier](/docs/capabilities/sql-mapping) never see the filter — and raw SQL is an *intended path* here, not an escape hatch. You end up with two classes of query that silently disagree about which rows exist, which is worse than one class that states its predicate. * **Filtered navigations make rows vanish far from the cause.** The filter applies wherever the entity appears, including joins and `Include`s: an active order referencing an archived customer reads as "customer missing", and the resulting bug report never mentions archiving. The all-or-nothing `IgnoreQueryFilters()` escape hatch drops *every* filter at once (EF 10's named filters soften this one point), but the first two objections stand regardless. A global filter earns its keep when the predicate is a **security boundary** that must hold even when a developer forgets — multi-tenancy is the classic case, and the one place Elarion does use a global filter ([multi-tenancy](/docs/capabilities/multi-tenancy)). Archive visibility is not a security boundary; it is per-screen UX, and per-screen decisions belong at the call site. ## 3. Archive and restore are ordinary commands [#3-archive-and-restore-are-ordinary-commands] Two handlers, nothing exotic: the [`TransactionDecorator`](/docs/concepts/persistence-and-transactions) owns the unit of work, the state change and the [integration event](/docs/capabilities/events) commit together, and both transitions are **naturally idempotent** — archiving an archived customer converges to success with no `[Idempotent]` machinery needed. ```csharp [Handler("crm.customers.archive")] public sealed class ArchiveCustomer(AppDbContext db, TimeProvider clock, IIntegrationEventBus events) : IHandler { public sealed record Command(Guid Id) : ICommand; public async ValueTask HandleAsync(Command command, CancellationToken ct) { var customer = await db.Customers.FirstOrDefaultAsync(c => c.Id == command.Id, ct); if (customer is null) { return AppError.NotFound($"Customer {command.Id} was not found."); } if (customer.ArchivedAt is not null) { return Result.Success(); // already archived — converged, not a conflict } customer.ArchivedAt = clock.GetUtcNow(); await events.PublishAsync(new CustomerArchived { CustomerId = customer.Id }, ct); await db.SaveChangesAsync(ct); return Result.Success(); } } ``` Restore is symmetric, plus the one check archiving created: the partial unique index freed the natural key, so someone may have taken it. The in-transaction check produces the friendly error; the index remains the authority if a race slips past it ([business checks run inside the transaction](/docs/concepts/validation)): ```csharp [Handler("crm.customers.restore")] public sealed class RestoreCustomer(AppDbContext db, IIntegrationEventBus events) : IHandler { public sealed record Command(Guid Id) : ICommand; public async ValueTask HandleAsync(Command command, CancellationToken ct) { var customer = await db.Customers.FirstOrDefaultAsync(c => c.Id == command.Id, ct); if (customer is null) { return AppError.NotFound($"Customer {command.Id} was not found."); } if (customer.ArchivedAt is null) { return Result.Success(); // already active } var emailTaken = await db.Customers.WhereActive() .AnyAsync(c => c.Email == customer.Email, ct); if (emailTaken) { return AppError.Conflict( $"Cannot restore: the email {customer.Email} is now used by an active customer."); } customer.ArchivedAt = null; await events.PublishAsync(new CustomerRestored { CustomerId = customer.Id }, ct); await db.SaveChangesAsync(ct); return Result.Success(); } } ``` **Archived means read-only, enforced in handlers.** Every mutating command on the aggregate guards the state itself — the frontend hiding an Edit button is a [UX projection, never the enforcement](/docs/concepts/client-capabilities): ```csharp if (customer.ArchivedAt is not null) { return AppError.Conflict($"Customer {command.Id} is archived; restore it before editing."); } ``` The integration events are the projection seam: other modules react after commit, and a consumer can push a [client event](/docs/capabilities/events/client-events) hint so open list screens re-query — the same shape as the [time-series dashboard](/docs/capabilities/time-series#5-live-dashboards-client-events). Tag the two handlers [`[Auditable]`](/docs/concepts/auditing) if archiving is a compliance-relevant action; the trail then records who archived what, when, with no extra columns on the entity. ## 4. Delete is still delete [#4-delete-is-still-delete] The flag never replaces `DELETE`; it *schedules* it. Two forms remain, both real: * **Retention purge** — a scheduled job hard-deletes rows archived beyond your retention window. The window lives in configuration or [runtime settings](/docs/concepts/settings); on a cluster the [per-occurrence claims](/docs/capabilities/scheduling/multi-node) make exactly one node run it. ```csharp public sealed class CustomerPurgeJob(AppDbContext db, TimeProvider clock) { [ScheduledJob("crm.customers.purge", Cron = "0 0 3 * * *")] public async ValueTask RunAsync(CancellationToken ct) { var cutoff = clock.GetUtcNow().AddDays(-180); await db.Customers .Where(c => c.ArchivedAt != null && c.ArchivedAt < cutoff) .ExecuteDeleteAsync(ct); } } ``` * **Erasure on request** — a GDPR-style erasure obligation is a hard delete (or anonymization) executed *now*, as its own command. An `ArchivedAt` flag does not satisfy it, and neither does waiting for the purge window. Naming the state *archived* rather than *deleted* is what keeps these honest: the UI can say "Archive" and "Delete" and mean two different, truthfully described operations. ## Alternatives this recipe rejects [#alternatives-this-recipe-rejects] * **A global `HasQueryFilter`** — the closest call, argued [above](#why-not-a-global-hasqueryfilter): it hides the predicate from the call site, silently doesn't cover the raw-SQL and bulk paths Elarion treats as first-class, and makes filtered navigations drop rows far from the cause. * **An `IsDeleted` flag ("soft delete" proper)** — the name lies in both directions: the user reads *deleted* and believes the data is gone (it isn't — a compliance problem), while the code treats it as retained state (so *actual* deletion never gets designed — the purge and erasure paths above simply don't exist). Name the state what the domain means — archived, deactivated, closed — and reserve *delete* for `DELETE`. * **Folding archive into a lifecycle enum** — adding `Archived` to `Status { Draft, Active, Paid }` conflates two axes: archive is orthogonal to the domain lifecycle (a *paid* invoice gets archived and must still read as paid after restore). One nullable timestamp beside the enum keeps both axes; one merged enum multiplies states and loses the pre-archive value. * **Moving rows to an `_archive` table** — twice the schema to migrate, foreign keys that dangle or duplicate, and restore becomes a cross-table insert racing the unique indexes. Row volume is not a problem this pattern needs to solve at [Elarion's target tier](/docs/why-elarion); when cold-data volume is genuinely the concern, that is retention/partitioning (see [time-series](/docs/capabilities/time-series)), not archive semantics. * **Hard delete now, restore from the audit trail** — the [audit trail](/docs/concepts/auditing) records *actions with diffs* for compliance; point-in-time reconstruction is an explicit non-goal. "Undelete" via audit forensics means reassembling a row (and its children, and its foreign keys) by hand under pressure. If restore is a product feature, the restorable state must stay a row. # Blob storage (/docs/capabilities/blob-storage) Elarion's blob packages give application handlers a small, provider-neutral storage contract while keeping database-specific concerns in the host or infrastructure layer. Application code depends on `Elarion.Blobs`; the host chooses a provider such as `Elarion.Blobs.PostgreSql`. Use blob storage for files that should be addressed by reference from your domain model: generated documents, uploads, exports, attachments, and other binary content. Store the returned `BlobRef.Value` on your own entities rather than embedding file bytes in handler responses or domain rows. To **accept uploads from a browser** — pre-upload a file, reference it when creating an entity, and reclaim it automatically if the entity is never created — see [Blob uploads](/docs/capabilities/blob-uploads), which adds the pending/commit/TTL lifecycle and the tus and direct-upload HTTP transports on top of this storage contract. ## Package split [#package-split] | Package | Use it in | Contains | | -------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Elarion.Blobs` | Application code | `IBlobStore`, `BlobRef`, `BlobUploadRequest`, `BlobDownload`, `BlobMetadata`, `BlobContent`, listing (`BlobListRequest`/`BlobListing`), and `BlobStoreExtensions`. No provider dependency. | | `Elarion.Blobs.PostgreSql` | Infrastructure / host | `PostgreSqlBlobStore`, DI registration, and EF Core model configuration for PostgreSQL. | ```xml ``` If your solution separates application and infrastructure projects, put `Elarion.Blobs` in the application project and `Elarion.Blobs.PostgreSql` only where the concrete `DbContext` is configured. ## Application contract [#application-contract] `IBlobStore` is **streaming-first**: content flows in and out as a `Stream`, so neither callers nor backends are forced to buffer a whole blob in memory. The shape mirrors the major blob SDKs (AWS S3, Azure Blob, Google Cloud Storage) so an alternative backend slots in cleanly. Inject `IBlobStore` into handlers or services that need binary storage: ```csharp using Elarion.Abstractions; using Elarion.Blobs; public sealed class UploadAttachment(IBlobStore blobs) : IHandler> { public sealed record Command(string FileName, string ContentType, byte[] Data); public sealed record Response(string BlobId); public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var blobRef = await blobs.SaveAsync( new BlobUploadRequest { Container = "attachments", Name = command.FileName, ContentType = command.ContentType }, command.Data, ct); return new Response(blobRef.Value); } } ``` The identity and metadata of a blob ride in a `BlobUploadRequest` (mirroring S3 `PutObjectRequest` / Azure `BlobUploadOptions`), and the content is supplied separately. The core interface takes a `Stream`; the `byte[]` overload above is one of the conveniences in `BlobStoreExtensions`. When you already hold a stream — an incoming upload, for example — pass it straight to the core method: ```csharp await blobs.SaveAsync(request, uploadStream, ct); ``` `BlobUploadRequest.ContentLength` is an optional hint; the recorded `BlobMetadata.Size` is always the actual number of bytes written, so you can leave it `null` for unknown-length sources. A store may use the hint to optimize the write — the PostgreSQL store streams a non-seekable source straight into `bytea` when the hint is present (verifying it against the actual bytes), and only buffers to learn the length when it is absent. The core `IBlobStore` is intentionally small: | Method | Purpose | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `SaveAsync(BlobUploadRequest, Stream)` | Streams content in and returns a `BlobRef`. | | `OpenReadAsync` | Opens a disposable `BlobDownload` carrying metadata plus an open content stream. | | `GetMetadataAsync` | Loads metadata without content. | | `ExistsAsync` | Checks whether a reference exists. | | `DeleteAsync` | Deletes a referenced blob. | | `ListAsync(BlobListRequest)` | Lists one page of blobs — optionally rolled up into virtual directories by a delimiter (see [Listing](#listing-prefixes-as-virtual-directories)). | | `ListContainersAsync` | Lists the containers known to the store. | `BlobStoreExtensions` layers the ergonomic call styles over those primitives, so every backend gets them for free: | Extension | Purpose | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `SaveAsync(BlobUploadRequest, byte[])` | Stores an in-memory byte array. | | `SaveFromFileAsync` | Stores content from a local file path (opened as a stream, no backend file assumption). | | `DownloadContentAsync` | Loads metadata plus bytes into a `BlobContent`. | | `ReadAllBytesAsync` | Loads just the content bytes. | | `DownloadToAsync` | Copies content to a destination stream (for example an HTTP response body). | | `ListAllAsync` | Enumerates every blob under a prefix as an `IAsyncEnumerable`, walking `ListAsync` page by page — the flat enumeration migration/backup tooling wants. | | `GetContentSha256Async` | The SHA-256 of a blob's content: the [recorded one](#content-hash), or computed by reading the content once when none is recorded. | The PostgreSQL implementation replaces an existing blob when `container` and `name` match, preserving the blob id while updating content type, size, timestamp, and bytes. ### Content hash [#content-hash] The stores compute the SHA-256 of the content while `SaveAsync` streams it and record it with the blob: `BlobMetadata.ContentSha256` holds 64 lower-case hex characters. Finding the same file uploaded twice, or using the hash as a download's entity tag, then needs no second read of the content: ```csharp var metadata = await blobs.GetMetadataAsync(blobRef, ct); var duplicate = await db.Documents.AnyAsync(d => d.ContentSha256 == metadata!.ContentSha256, ct); ``` Copy the hash into your own entity when you query by it, as above: the store is not a query model, and `stored_blobs` has no index on the column. `ContentSha256` is `null` for a blob without a recorded hash: one stored before your Elarion version recorded them, one written to an Azure container by another producer, and one the Azure staged-upload store completes by a server-side copy (the bytes never pass the application). Where one code path must serve every blob, call `blobs.GetContentSha256Async(blobRef, ct)`: it answers from the metadata, and reads the content once only when nothing is recorded. | Store | Where the hash lives | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | PostgreSQL | `stored_blobs.content_sha256`, written in the same transaction as the content. | | Azure Blob Storage | the blob metadata `elarion_content_sha256`. A save reads the content in 4 MiB blocks and hashes them on the way: up to one block is one Put Blob, more is staged block by block and committed with the hash. | ## Listing: prefixes as virtual directories [#listing-prefixes-as-virtual-directories] Listing follows the industry model shared by S3 (`ListObjectsV2`), Azure (`GetBlobsByHierarchy`), and GCS: a **flat namespace with prefix + delimiter emulation of hierarchy**. Pass a `Delimiter` (typically `"/"`) and names containing it beyond the `Prefix` roll up into `BlobListing.Prefixes` — one delimiter-inclusive entry per virtual directory — while only blobs at the current level appear in `BlobListing.Blobs`: ```csharp var root = await blobs.ListAsync(new BlobListRequest { Container = "uploads", Delimiter = "/" }, ct); // root.Prefixes: ["user-1/", "user-2/"] root.Blobs: blobs directly in the container var level = await blobs.ListAsync( new BlobListRequest { Container = "uploads", Prefix = "user-1/", Delimiter = "/" }, ct); ``` Entries come back in lexicographic (ordinal) name order, paged via an opaque, store-specific `ContinuationToken` (`null` = exhausted). A missing container yields an empty page. `BlobMetadata` carries the blob's lifecycle `State`, and `BlobListRequest.State` filters on it, so a browse surface can hide half-finished pending uploads — on Azure that filter is applied per page after listing (metadata cannot be filtered server-side), so a filtered page may hold fewer than `PageSize` items while more remain; loop on the token, not on page fill. Directories are never real objects — there are no empty folders and no subtree renames. An application that needs true folder semantics (rename, per-folder permissions) models folders as entities in its own database and keeps blobs flat. Listing is a **browse/ops surface** (admin UIs, migration and backup tooling): an application answers "which files belong to this contract" from its own tables, which hold the `BlobRef`s — it does not enumerate the store. For the same reason, never derive ownership from a name prefix (names are client-influenced); ownership is the exact-match `BlobMetadata.OwnerId`. ## PostgreSQL setup [#postgresql-setup] Configure the provider in the concrete EF Core context: ```csharp using Elarion.Blobs.PostgreSql; using Microsoft.EntityFrameworkCore; public sealed class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.UseElarionBlobStorage(); } } ``` Then register the store in the host: ```csharp using Elarion.Blobs.PostgreSql; var connectionString = builder.Configuration.GetConnectionString("Database")!; builder.Services.AddDbContext(options => options.UseNpgsql(connectionString)); builder.Services.AddElarionPostgreSqlBlobStore(); ``` The context registration is the only connection wiring. The store's **streaming reads** — each `OpenReadAsync` draws a dedicated connection whose lifetime is owned by the returned `BlobDownload`, which the scoped `DbContext` connection cannot provide — clone that dedicated connection from the context's own connection, so it comes from the same pool, with the same type mapping and auth callbacks, and targets the same database by construction. Every EF connection shape works unchanged: `UseNpgsql(connectionString)`, `UseNpgsql(dataSource)`, or `AddNpgsqlDataSource` + `UseNpgsql()` (ADR-0041). ### One shared connection pool [#one-shared-connection-pool] The blob registrations take **no connection argument at all** — not `AddElarionPostgreSqlBlobStore()`, not `AddElarionPostgreSqlBlobLifecycle(configure?)`, not `AddElarionPostgreSqlStagedUploads(configureGc?, configureBlobGc?)`. Every one of them draws from the context's own connection, so they add no pool of their own. What *does* multiply pools is the company blobs keep: several Elarion PostgreSQL registrations accept a connection string and open connections from a source of their own — `AddElarionPostgreSql(connectionString)` on the EF-free SQL tier `TryAddSingleton`s an `NpgsqlDataSource`, and `AddElarionPostgreSqlClientEvents(connectionString)`, `AddElarionPostgreSqlSettingsChanges(connectionString)`, and `AddElarionPostgreSqlHandlerCaching(connectionString)` each build one for themselves. Pair any of those with an `AddDbContext(o => o.UseNpgsql(connectionString))` and the host runs **two pools against one database** — each sized independently, each counting separately against `max_connections`. Build one data source, register it, and hand it explicitly to everything that would otherwise pool for itself: ```csharp using Npgsql; var connectionString = builder.Configuration.GetConnectionString("Database")!; // One pool for the whole host. Registered through a factory delegate, so the container disposes it. var dataSource = NpgsqlDataSource.Create(connectionString); builder.Services.AddSingleton(_ => dataSource); // The parameterless UseNpgsql() resolves the registered NpgsqlDataSource — no second pool. builder.Services.AddDbContext(options => options.UseNpgsql()); // Blob registrations need no connection argument: they draw from the context's connection. builder.Services.AddElarionPostgreSqlBlobLifecycle(); builder.Services.AddElarionPostgreSqlStagedUploads(); // These would each build their own pool from a connection string — pass the shared source instead. builder.Services.AddElarionPostgreSqlClientEvents(dataSource); builder.Services.AddElarionPostgreSqlSettingsChanges(dataSource); builder.Services.AddElarionPostgreSqlHandlerCaching(options => options.DataSource = dataSource); ``` Sharing is **not** uniform across the packages, so read the registration you are calling: | Registration | Connection-string form | How it shares the host's pool | | ----------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | `AddElarionPostgreSql` (EF-free SQL tier) | `TryAddSingleton`s an `NpgsqlDataSource` built from the string | Automatically — a source the host registered first wins, because `TryAdd` does not overwrite it. | | `AddElarionPostgreSqlClientEvents` | Calls `NpgsqlDataSource.Create(connectionString)` inside its factory | Only through the explicit `NpgsqlDataSource` overload; the string form never consults DI. | | `AddElarionPostgreSqlSettingsChanges` | Calls `NpgsqlDataSource.Create(connectionString)` inside its factory | Only through the explicit `NpgsqlDataSource` overload; the string form never consults DI. | | `AddElarionPostgreSqlHandlerCaching` | Sets the cache's `ConnectionString` option, and the cache builds its own source | Only through the options overload, setting `options.DataSource`. | | `AddElarionPostgreSql*Blob*` / `*StagedUploads` | No connection argument at all | Always — they clone from the `DbContext` connection. | If your host only pairs EF with the blob packages, `builder.Services.AddNpgsqlDataSource(connectionString)` is the shorter equivalent of the first two lines: nothing else needs the instance in hand. The `NpgsqlDataSource`/options overloads all **borrow** the source you pass and never dispose it, which is why the container has to own it. Weigh the `LISTEN/NOTIFY` pair deliberately, though: a listen connection is held open for the life of the process, so pointing client events or settings changes at the application pool permanently consumes one of its connections — size the pool for it, or leave those two on their own source. Register the data source **through a factory delegate** — `AddNpgsqlDataSource(connectionString)`, or `services.AddSingleton(_ => dataSource)` as in the recipe above — and never through the instance overload (`services.AddSingleton(NpgsqlDataSource.Create(connectionString))`). The container disposes what it hands out from a factory, but never an instance it was simply given, so an instance-registered source survives its host's shutdown and leaks its entire pool. One long-lived process hides that; an integration suite does not — a `WebApplicationFactory` per test class leaks one pool per host until PostgreSQL answers `53300: too many clients already`. ### Model and tables [#model-and-tables] `UseElarionBlobStorage()` adds two tables to the EF Core model: | Table | Purpose | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `stored_blobs` | Metadata: id, container, name, content type, size, created timestamp, the [content hash](#content-hash), and the lifecycle state, expiry, and owner id used by [blob uploads](/docs/capabilities/blob-uploads). | | `blob_contents` | Content bytes keyed by blob id, with cascade delete from `stored_blobs`. | `UseElarionBlobStorage` takes optional `tableName` and `contentTableName` parameters to rename either table, a `schema`, and a `snakeCase` toggle (default `true`; `false` switches to PascalCase names — the defaults become `StoredBlobs`/`BlobContents`), for example `modelBuilder.UseElarionBlobStorage("app_blobs", "app_blob_contents", "app")`. The blob entities are plain EF Core types configured by `UseElarionBlobStorage()`; they are **not** part of Elarion's `[EntityConfiguration]` / `[GenerateDbSets]` source generation. Because the configuration runs inside your own `OnModelCreating`, the tables become part of your context's model and ride along with your normal migrations — there is no separate "blob migration" to manage. On a `[GenerateDbSets]` context you can skip the hand-written call: annotate the context with `[GenerateElarionBlobStorage]` (optionally with `SnakeCase`/`TableName`/`ContentTableName`/`Schema`) and the bundled generator emits the `DbSet` (the content row type is `internal` — mapped, but no `DbSet`) and applies the same model configuration through the EF generator's model-config seam (`ELBLB001` if `[GenerateDbSets]` is missing). ### Schema migration [#schema-migration] After adding `UseElarionBlobStorage()` to your context, create and apply a migration the usual way: ```bash dotnet ef migrations add AddBlobStorage dotnet ef database update ``` The generated migration includes `stored_blobs`, `blob_contents`, the unique `(container, name)` index, and the cascade foreign key. For throwaway or test databases you can call `dbContext.Database.EnsureCreated()` instead of migrating, but use migrations for any schema that will evolve. When an Elarion release adds a column to these tables, the model changes with the package: add a migration after upgrading (`dotnet ef migrations add UpgradeBlobStorage`), or every query of `stored_blobs` fails on the missing column ([CHANGELOG](https://github.com/swimmesberger/Elarion/blob/main/CHANGELOG.md) names each such change). The [content hash](#content-hash) added the nullable `content_sha256 varchar(64)`; existing rows keep `null`, which `GetContentSha256Async` covers. The store talks to PostgreSQL directly for content bytes (it casts the context's connection to `NpgsqlConnection`), so the owning context must be configured with `UseNpgsql` — see the registration above. That raw SQL is built from the EF model (`ISqlGenerationHelper` plus the resolved table/column names), so table, schema, and naming overrides apply to the raw Npgsql content path too. Writes stream a seekable source (a file, an in-memory buffer) straight into the `bytea` column without buffering. Reads stream too: `OpenReadAsync` opens a dedicated connection cloned from the context's connection and reads through `CommandBehavior.SequentialAccess` + `NpgsqlDataReader.GetStream`, so the content flows from the wire without materializing the blob in memory; the reader, command, and connection are owned by the returned `BlobDownload` and released on its disposal (double-dispose safe). The one exception is a read inside a caller-owned ambient transaction, which must share that transaction's connection to see the caller's own uncommitted writes and therefore stays buffered. ## Reading and deleting [#reading-and-deleting] Store only blob ids in your own entities or DTOs, then reconstruct `BlobRef` at read time. When the whole blob fits comfortably in memory, `DownloadContentAsync` buffers metadata plus bytes in one call: ```csharp var blob = await blobs.DownloadContentAsync(new BlobRef { Value = attachment.BlobId }, ct); if (blob is null) { return AppError.NotFound($"Attachment {attachment.Id} was not found."); } return new DownloadAttachment.Response( blob.Name, blob.ContentType, blob.Data); ``` To avoid materializing large content, stream instead. `DownloadToAsync` copies straight to a destination such as the HTTP response body — the store opens, copies, and disposes the source for you: ```csharp response.ContentType = "application/octet-stream"; var found = await blobs.DownloadToAsync(blobRef, response.Body, ct); if (!found) { return Results.NotFound(); } ``` `OpenReadAsync` is the lower-level pull primitive: it hands you the open stream plus metadata. You own the `BlobDownload`, so dispose it once you have finished reading — keep the read inside the `using` scope so the stream is not disposed out from under a lazy consumer: ```csharp await using var download = await blobs.OpenReadAsync(blobRef, ct); if (download is null) { return; } response.ContentType = download.Metadata.ContentType; await download.Content.CopyToAsync(response.Body, ct); ``` Use `GetMetadataAsync` when you only need filename, content type, or size for a listing. Use `DeleteAsync` when the owning record is removed and the blob should not be retained. ## Boundaries [#boundaries] `Elarion.Blobs` deliberately does not mention PostgreSQL, EF Core, ASP.NET Core, HTTP uploads, or any application-specific file categories. Provider packages own storage schema and I/O details; handlers should depend only on `IBlobStore` unless they are part of infrastructure composition. # Blob uploads (/docs/capabilities/blob-uploads) A common requirement is to **create an entity (say a `Contract`) and attach files to it**. Over a JSON transport (JSON-RPC) the entity and its files cannot travel together — JSON cannot carry binary. So the file is uploaded *separately*, the upload returns a reference, and the entity-creation call carries that reference. This is the same shape S3 apps use: **pre-upload, then reference**. The hard part is the orphan: if the user uploads a file but never finishes creating the entity (they cancel, or the browser closes), there is **no backend signal**. Elarion answers this the way S3 lifecycle rules do — with **time plus an explicit promote**: **Upload** produces a `Pending` blob with a time-to-live. **Commit** promotes it to `Committed` inside the same transaction that creates the referencing entity — atomic with the entity insert. **Garbage collection** deletes any `Pending` blob whose TTL elapses without a commit. A referenced upload is kept forever; an abandoned one is reclaimed. The TTL *is* the missing signal. This builds directly on [blob storage](/docs/capabilities/blob-storage) and stays S3-free — the upload protocol lives only at the HTTP layer. ## Package split [#package-split] | Package | Use it in | Contains | | -------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.Blobs` | Application | `BlobLifecycleState`, `IBlobLifecycle` (`CommitAsync`/`DeleteExpiredPendingAsync`), the additive `BlobUploadRequest.InitialState`/`ExpiresAt`, the protocol-neutral **staged-upload seam** (`IStagedUploadStore`) with its in-memory default and the garbage collectors, and the owner-checked reader behind the [`UploadedFile`](#passing-an-upload-to-a-handler) handler parameter (`AddElarionUploadedFiles`). | | `Elarion.Blobs.PostgreSql` | Infrastructure / host | The lifecycle on the PostgreSQL store (`state`/`expires_at` columns with a partial index, `AddElarionPostgreSqlBlobLifecycle`) and durable staged-upload staging (`UseElarionStagedUploads`, `AddElarionPostgreSqlStagedUploads`) so in-progress uploads survive restarts. | | `Elarion.Blobs.Azure` | Infrastructure / host | The same two roles on Azure Blob Storage: blob store + lifecycle over blob metadata, and native staging over append blobs (`AddElarionAzureBlobLifecycle`, `AddElarionAzureStagedUploads`). | | `Elarion.Blobs.Tus` | Host | The tus 1.0 resumable transport (`MapElarionResumableBlobUploads`, `AddElarionResumableBlobUploads`) — a pure protocol adapter over the staging seam. | | `Elarion.Blobs.AspNetCore` | Host | The minimal direct-upload endpoint (`MapElarionBlobUploads`, `AddElarionBlobUploads`) and the owner-scoped streaming download endpoint (`MapElarionBlobDownloads`). | ```xml ``` ## The lifecycle [#the-lifecycle] The lifecycle is a small capability over `IBlobStore`, provider-neutral and S3-free. `BlobUploadRequest` gains `InitialState` (defaults to `Committed`, so a plain `SaveAsync` stays permanent) and `ExpiresAt`; upload transports save with `InitialState = Pending` and an `ExpiresAt`. `IBlobLifecycle` adds two operations: | Method | Purpose | | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CommitAsync(blobRef, ct)` | Promotes a `Pending` blob to `Committed` and clears its expiry. Idempotent; participates in the **caller's** transaction (it mutates within the ambient transaction and persists on the caller's `SaveChangesAsync`), so the commit and the entity insert are atomic. Returns `false` when the blob no longer exists. | | `DeleteExpiredPendingAsync(olderThanUtc, batchSize, ct)` | The garbage-collection entry point. | A `Pending` blob has two fates. Either an application **commits** it — the pre-upload-then-reference pattern [below](#attaching-a-file-to-an-entity), which keeps it forever — or it is **discarded**: a consumed temp file is deleted explicitly (`IBlobStore.DeleteAsync`) and anything left over is reclaimed by the collector after its TTL (see [temp-file flows](#streaming-downloads-and-temp-file-flows)). A blob is never both. Register the PostgreSQL lifecycle and its background collector: ```csharp services.AddElarionPostgreSqlBlobLifecycle(); // store + lifecycle + GC sweeper // (streaming reads clone the context's connection — no other wiring, ADR-0041) // in OnModelCreating: modelBuilder.UseElarionBlobStorage(); ``` This adds `state` and `expires_at` columns plus a partial index over pending rows; create a migration (or `EnsureCreated` for throwaway databases) as for any model change. ### Attaching a file to an entity [#attaching-a-file-to-an-entity] The command carries the upload as an [`UploadedFile`](#passing-an-upload-to-a-handler), and the handler keeps it through `IUploadedFiles`, which commits only the caller's own pending upload: ```csharp [Handler] [ProducesError(ErrorCodes.UploadNotFound, ErrorKind.Validation)] [ProducesError(ErrorCodes.UploadContentType, ErrorKind.Validation)] public sealed class CreateContract(AppDbContext db, IUploadedFiles uploads) : IHandler> { public sealed record Command : ICommand { public required string Title { get; init; } public required UploadedFile Attachment { get; init; } // the id the upload endpoint answered } public async ValueTask> HandleAsync(Command command, CancellationToken ct) { // Promote the pre-uploaded blob in the same transaction as the entity insert. var kept = await uploads.CommitAsync( command.Attachment, new UploadConstraints { ContentTypes = ["application/pdf"] }, ct); if (!kept.IsSuccess) return kept.Error; var contract = new Contract { Title = command.Title, AttachmentBlobId = kept.Value.BlobId, // read it later through IBlobStore AttachmentName = kept.Value.FileName, }; db.Contracts.Add(contract); await db.SaveChangesAsync(ct); // commit + insert are atomic return new CreateContractResponse(contract.Id); } } ``` If the handler rolls back, the blob stays `Pending` and the collector reclaims it after `Ttl + SafetyMargin`. The collector deletes only rows still pending, so a commit that lands first wins the race and a never-committed upload is always reclaimed. The blob store is registered against your `DbContext` as a scoped service, so `CommitAsync` shares the same `DbContext` and transaction as your handler — no extra wiring. Wrap the handler in a transaction decorator (or rely on `SaveChangesAsync`'s implicit transaction) so the promote and the insert commit together. ## Upload transports [#upload-transports] The lifecycle is transport-neutral. Two open transports produce `Pending` blobs over it; both stay S3-free. Pick by client needs. ### tus — the resumable standard [#tus--the-resumable-standard] [tus 1.0](https://tus.io) is the open, resumable upload protocol built by the Uppy authors and the basis of the IETF *Resumable Uploads* draft. It is **resumable, handles large files, and survives a browser close mid-upload**, and is supported natively by Uppy (`@uppy/tus`) and `tus-js-client`. This is the recommended transport for new frontends. ```csharp services.AddElarionResumableBlobUploads(); // in-memory staging by default app.MapElarionResumableBlobUploads().RequireAuthorization(); ``` `MapElarionResumableBlobUploads` implements Creation, Core, Expiration, and Termination: `OPTIONS` advertises capabilities, `POST` creates an upload (baking the current user's id), `PATCH`/`HEAD` stream and resume, `DELETE` aborts. When an upload completes, the staged bytes are written as a `Pending` blob and its reference is returned in the `Elarion-Blob-Ref` response header (also available on `HEAD`) — the handle the client passes to entity creation. Under the endpoints sits the protocol-neutral **`IStagedUploadStore`** seam: offset-guarded appends, an explicit idempotent completion (so a crash between the last chunk and completion self-heals on the next status probe), and deferred-length sessions — the shape of the IETF *Resumable Uploads* draft ("tus 2.0"), which will be a second adapter over the same seam. All policy (upload expiry, pending-blob TTL, completed- session retention) lives in `ResumableBlobUploadOptions` and reaches the store as data, so staging backends are protocol-free and interchangeable. The default in-memory staging keeps in-progress uploads in process. For resumability **across restarts and instances**, add the durable PostgreSQL staging store — it persists staged bytes and reaps both incomplete sessions (the analog of S3's *abort incomplete multipart upload*) and completed sessions once past a retention window: ```csharp services.AddElarionResumableBlobUploads(); services.AddElarionPostgreSqlStagedUploads(); modelBuilder.UseElarionBlobStorage(); // blob tables, in OnModelCreating modelBuilder.UseElarionStagedUploads(); // staging table, in OnModelCreating ``` `AddElarionPostgreSqlStagedUploads` also wires the PostgreSQL **blob lifecycle** and its `BlobGarbageCollector` (idempotently, via `AddElarionPostgreSqlBlobLifecycle`) — a completed upload produces a *pending* blob, so without that collector an abandoned upload would leak its blob forever. Map the blob tables with `UseElarionBlobStorage()` alongside the staging table. Both wiring methods take optional `tableName` (plus `contentTableName` on the blob side) and `schema` parameters and a `snakeCase` toggle (default `true`; `false` switches to PascalCase names — `StagedUploads`, `StoredBlobs`/`BlobContents`); the stores' raw Npgsql SQL (content streaming and the staging conditional append) is built from the EF model, so the overrides apply there too. On a `[GenerateDbSets]` context, `[GenerateElarionBlobStorage]` and `[GenerateElarionStagedUploads]` (each with optional `SnakeCase`/`TableName`/`Schema` — the blob attribute also takes `ContentTableName`) replace the hand-written calls: the bundled generators emit the `DbSet`s and apply the same configuration through the EF generator's model-config seam (`ELBLB001`/`ELBLB002` if `[GenerateDbSets]` is missing). A completed session row is retained for `ResumableBlobUploadOptions.CompletedSessionRetention` (default 1 hour) so a client `HEAD` can still fetch the reference, then reclaimed; the session collector applies a `StagedUploadGcOptions.SafetyMargin` (default 1 minute) to the expiry cutoff, mirroring the blob collector. Prefer Azure Blob Storage? `AddElarionAzureStagedUploads(connectionString)` stages each session as an **append blob** — the offset guard is Azure's server-side `If-Append-Position-Equal` precondition, and completion is a server-side copy into the final pending blob, so bytes never round-trip through the application. The matching `AzureBlobStore` serves reads and the commit lifecycle over blob metadata (commit takes effect immediately rather than joining a caller transaction — the documented delta from the PostgreSQL tier). Cross-origin frontends must expose the reference header via CORS: `Access-Control-Expose-Headers: Upload-Offset, Location, Upload-Expires, Elarion-Blob-Ref`. Behind a reverse proxy, enable `UseForwardedHeaders` so the `Location` header reflects the public scheme and host rather than the internal one. ### Direct upload — minimal endpoint [#direct-upload--minimal-endpoint] For FilePond's `process`/`revert` and plain `fetch`/`
` clients, a single "accept bytes, return a reference" endpoint is the smallest path. It is not a new protocol. ```csharp services.AddElarionBlobUploads(o => o.MaxContentLength = 25 * 1024 * 1024); app.MapElarionBlobUploads().RequireAuthorization(); ``` `POST` (multipart or raw body) writes a `Pending` blob and returns its id as `text/plain`; `DELETE /{id}` cancels an owner's pending upload (a committed blob answers `404`: it belongs to the record that kept it). Both enforce authentication, the configured size cap, and an optional content-type allow-list. Ownership is recorded as a dedicated `BlobUploadRequest.OwnerId` (surfaced as `BlobMetadata.OwnerId`) and compared **exactly** on cancel — not parsed from the stored name — so an id containing the naming separator cannot be forged, and a blob with no recorded owner is denied to everyone. The tus transport applies the same owner-exact, fail-closed check to its `HEAD`/`PATCH`/`DELETE`. When the server's body-size limit is lower than `MaxContentLength`, the endpoint raises it for that request, so a cap above the server's default (Kestrel: about 28.6 MB) works for this route without raising it for every route. It never lowers a higher server limit: it enforces the cap itself, and a multipart file part over the cap is refused while it is read. `AddElarionBlobUploads` and `AddElarionResumableBlobUploads` register their options through the options pattern, so a later `services.Configure(…)` reaches the endpoints too, and code that needs the configured values — the route prefix, the container — reads `IOptions` (or `IOptions`) and gets exactly what the endpoints use. Every response of the direct upload, cancel and download endpoints carries `X-Content-Type-Options: nosniff`. Both transports bake the current user's id into the upload, so the host must register an `ICurrentUser` (via `AddElarionCurrentUser` or the optional Identity integration) and opt the route group into `.RequireAuthorization(...)`. Per-endpoint authorization is the host's job, as for all generated routes. ### Upload policies: a larger limit for one kind of upload [#upload-policies-a-larger-limit-for-one-kind-of-upload] Some uploads are larger than the rest: imported e-mail messages up to 100 MB where 20 MB is enough for everything else. Raising the endpoint's cap would let every signed-in user stage 100 MB. An **upload policy** raises it for the uploads that name it, and can check the record an upload is for **before its bytes arrive**: ```csharp services.AddElarionBlobUploads(o => o.MaxContentLength = 20L * 1024 * 1024); // the default for every upload services.AddElarionUploadPolicy("mail.eml", policy => { policy.MaxBytes = 100L * 1024 * 1024; policy.ContentTypes = ["message/rfc822", "application/octet-stream"]; // The draft exists and is the caller's — asked before the body is read. policy.Authorize = static async (context, ct) => Guid.TryParse(context.ResourceId, out var draftId) && await context.Services.GetRequiredService().Drafts .AnyAsync(d => d.Id == draftId && d.OwnerId == context.User.UserId, ct); }); ``` The client names the policy, and the record it is for, when it uploads: | Transport | Names the policy with | | --------------------------- | ---------------------------------------------------------------------------------------------- | | Direct endpoint | `POST /_elarion/blobs?policy=mail.eml&resourceId=` | | tus | the `policy` and `resourceId` keys of `Upload-Metadata` (Uppy: `meta: { policy, resourceId }`) | | Generated TypeScript client | `rpc.$uploadFile(file, { policy: 'mail.eml', resourceId: draftId })` | * **Its limits replace the endpoint's** for that upload: `MaxBytes` the cap (`MaxContentLength`, tus `MaxSize`), `ContentTypes` the allow-list (tus checks it against the declared `filetype`). A limit left `null` is the endpoint's; an upload without a policy gets the endpoint's limits. * **`Authorize` runs before the body is read**, with the caller, the request's services, the declared length and the client's `resourceId` — untrusted input, parse it. A refusal answers `404`, so it does not confirm that the record exists; an unknown policy name answers `400`. * **It decides what may be staged, not what a handler accepts.** The staged file is an ordinary pending upload. The handler that takes it declares the larger limit (`[UploadLimits(MaxBytes = 100L * 1024 * 1024)]`) and checks the draft again inside its transaction; a handler with a smaller limit refuses the file. * **A tus `PATCH` may carry all the bytes the upload still lacks**: its body-size limit is raised to that when the server's is lower, so a 100 MB upload may arrive in one `PATCH` without raising the server's limit for every route. ### Client adapters [#client-adapters] * **Uppy** — `@uppy/tus` against `MapElarionResumableBlobUploads` (recommended), or `@uppy/aws-s3`'s `getUploadParameters` / `@uppy/xhr-upload` against the direct endpoint. * **FilePond** — `server.process` → `POST` the direct endpoint (the response body is the file id); `server.revert` → `DELETE /{id}`. FilePond's chunked mode is tus-derived but not identical, so its resumable path needs a small client adapter. ## Passing an upload to a handler [#passing-an-upload-to-a-handler] A handler takes an upload as an **`UploadedFile`** member: on every JSON surface (JSON-RPC, MCP, HTTP bodies) a plain string, the blob id the upload endpoint answered with. It reads, keeps or discards the file only through **`IUploadedFiles`**, never by handing that id to `IBlobStore` itself: ```csharp services.AddElarionPostgreSqlBlobLifecycle(); services.AddElarionBlobUploads(o => o.Ttl = TimeSpan.FromHours(2)); // and/or AddElarionResumableBlobUploads services.AddElarionUploadedFiles(); // IUploadedFiles app.MapElarionBlobUploads().RequireAuthorization(); ``` ```csharp [Handler] // [UploadLimits] puts upload.not_found and the code of each declared limit into the error contract public sealed class AnalyzeStatement(IUploadedFiles uploads, StatementParser parser) : IHandler> { public sealed record Command : ICommand { [UploadLimits(MaxBytes = 50L * 1024 * 1024, ContentTypes = ["text/csv", "application/xml"])] public required UploadedFile Statement { get; init; } } public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var opened = await uploads.OpenAsync(command.Statement, cancellationToken: ct); // the declared limits apply if (!opened.IsSuccess) return opened.Error; await using var file = opened.Value; // Content, ContentType, FileName, Length, ContentSha256 return await parser.AnalyzeAsync(file.Content, ct); } } ``` `IUploadedFiles` has three operations: | Method | Does | | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `OpenAsync(file, constraints?, ct)` | Opens the content for reading. The upload stays pending, so the next step of a flow opens it again. Dispose the result. | | `CommitAsync(file, constraints?, ct)` | Keeps it: promotes the pending blob inside the caller's transaction ([above](#attaching-a-file-to-an-entity)) and answers a `CommittedUpload` (`BlobId`, `FileName`, `ContentType`, `Length`, `ContentSha256`) for the record. Needs an `IBlobLifecycle`. | | `DeleteAsync(file, ct)` | Discards it now instead of after its TTL. Idempotent; `false` when there was nothing of the caller's to delete. On the PostgreSQL store it saves the `DbContext` it shares with the handler: call it after the handler's own save ([below](#streaming-downloads-and-temp-file-flows)). | Every operation answers only an upload that is **still pending**, whose recorded owner is **exactly the current user**, and that lies in an **upload container** (`UploadedFilesOptions.Containers`, default `uploads`, the container of both endpoints; list a renamed endpoint container there). A missing, expired, already kept, someone else's, unowned or foreign-container blob, and any call by an anonymous caller, all answer the same error, so a caller cannot tell which ids exist. A kept blob belongs to its record from then on: the record's own authorization guards it, and the reference no longer opens it. | Code | When | `data` | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | `upload.not_found` | No pending upload of the caller has that id. The caller uploads again. | none | | `upload.too_large` | The file is larger than `UploadConstraints.MaxBytes`. | `UploadTooLargeData`: `maxBytes`, the file's `length` | | `upload.content_type` | The declared content type is not in `UploadConstraints.ContentTypes` (exact, case-insensitive, parameters such as `; charset` ignored). | `UploadContentTypeData`: the accepted `contentTypes`, the file's `contentType` | | `upload.file_extension` | The stored file name does not end in one of `UploadConstraints.FileExtensions` (case-insensitive; a file uploaded without a name is stored as `upload`). | `UploadFileExtensionData`: the accepted `fileExtensions`, the file's `fileName` | The limits are checked in that order, and the first one the file breaks answers. All four are `Validation` errors (JSON-RPC `-32602`, HTTP `400`) the handler returns. A request that [declares its limits](#declaring-the-limits-on-the-member) has `upload.not_found` and the code of each declared limit, with its payload, in its error contract already. A handler that only passes `UploadConstraints` declares the codes it can produce with their payload: ```csharp [ProducesError(ErrorCodes.UploadNotFound, ErrorKind.Validation)] [ProducesError(ErrorCodes.UploadTooLarge, ErrorKind.Validation, typeof(UploadTooLargeData))] ``` A declaration of an upload code with another payload, or none, is the warning `ELERR004`: it would hide the typed data from the schema and the client. The `message` is an English fallback with the limit in bytes. To say it in the user's language, branch on the code and word the payload: the [generated client](/docs/capabilities/transports/typescript-client#uploaded-files) types `data` per code, and its own check before the upload reports the same codes and data. ```ts catch (error) { if (isRpcMethodError('statements.analyze', error) && error.code === 'upload.too_large') showError(t('upload.tooLarge', { max: formatBytes(error.data.maxBytes) })) } ``` The limits are the handler's per operation; the endpoints' `MaxContentLength`/`MaxSize` and `AllowedContentTypes`, or the [upload policy](#upload-policies-a-larger-limit-for-one-kind-of-upload) the client named, still cap what can be uploaded at all. The content type and the file name are the ones the client declared, not sniffed: treat the content as untrusted input. An upload lives until it is committed, deleted, or collected after the endpoint's `Ttl` (`BlobUploadEndpointOptions.Ttl`, `ResumableBlobUploadOptions.Ttl`, default 30 minutes). A multi-step flow (analyze, preview, commit) passes the same `UploadedFile` to every step, so raise the `Ttl` to the longest time a user may spend in it. ### Declaring the limits on the member [#declaring-the-limits-on-the-member] `[UploadLimits(MaxBytes = …, ContentTypes = […], FileExtensions = […])]` on the request member declares the limits once, where every side reads them. Before the handler runs, the pipeline declares them for the request's files to the scoped `IDeclaredUploadConstraints` (the same `AddElarionUploadedFiles` registration), and every `OpenAsync` and `CommitAsync` of those files checks them — the handler passes no constraints and declares no upload error. The schema exports them next to the marker, and the generated client rejects a file that breaks them before uploading it. ```csharp public sealed record Command : ICommand { [UploadLimits(MaxBytes = 50L * 1024 * 1024, ContentTypes = ["text/csv", "application/xml"])] public required UploadedFile Statement { get; init; } // On a collection the limits apply to every file; [MaxLength] bounds how many there are. [MaxLength(10), UploadLimits(MaxBytes = 5L * 1024 * 1024, ContentTypes = ["application/pdf"])] public IReadOnlyList Receipts { get; init; } = []; // Browsers declare a spreadsheet's type differently per system, often as application/octet-stream. [UploadLimits(MaxBytes = 10L * 1024 * 1024, FileExtensions = [".xlsx", ".xls"])] public UploadedFile? Workbook { get; init; } } ``` | Rule | | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Members | `UploadedFile`, `UploadedFile?`, or a collection of them (array, list, read-only collection), on the handler's request type, its own or inherited. On a positional record, target the property (`[property: UploadLimits(…)]`) or the parameter. | | Limits | `MaxBytes` (`0` = none), `ContentTypes` (empty = any) and `FileExtensions` (empty = any), compared as `UploadConstraints` compares them. At least one; every one declared must hold. | | Types or extensions | The content type is what the browser declared, and for `.xlsx`, `.vcf` or `.ics` that varies between systems or is missing (sent as `application/octet-stream`). Accept such formats by `FileExtensions` (each with its leading dot, compared case-insensitively against the end of the stored file name), not `ContentTypes`; declaring both requires both. | | Error contract | `upload.not_found`, and `upload.too_large`, `upload.content_type` or `upload.file_extension` for each kind of limit the request declares, with its payload — the handler declares none of them. | | Several | Constraints a call still passes to `IUploadedFiles` apply too; a file declared by two members must satisfy both. Declarations only tighten. | | Build errors | `ELUPL001` for a member that holds no uploaded file, an extension that is not a dot followed by a name (`"xlsx"`, `".x ls"`), or a declaration without a valid limit; `ELUPL002` for a member of a type that is not a handler's request in the assembly — a declaration the pipeline would not enforce is never accepted. | | Fail closed | A handler with declared limits needs an `IDeclaredUploadConstraints` (registered by `AddElarionUploadedFiles`); without one its pipeline does not build. A singleton handler cannot declare limits (`ELSG013`). | The exported schema marks the member `x-elarion-upload` (a string), with the declared limits as `x-elarion-max-bytes`, `x-elarion-content-types` and `x-elarion-file-extensions` (on the items of a collection), and the [generated TypeScript client](/docs/capabilities/transports/typescript-client#uploaded-files) takes a `File` there, checks it against those limits and uploads it before the call; `rpc.$uploadFile(file, { method, member })` uploads once for a multi-step flow after the same check, and `rpcLimits` shows the limits to the user (an `` from `fileExtensions`). An MCP tool caller passes the id. The [OpenAPI document](/docs/capabilities/transports/openapi) carries the same marker and limits. See [ADR-0105](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0105-uploaded-files-are-handler-parameters.md) and [ADR-0100](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0100-the-schema-exports-constants-presets-and-limits.md). ## Streaming downloads and temp-file flows [#streaming-downloads-and-temp-file-flows] The staging area is also the framework's answer for **large files in handler flows** — the tier above the in-memory [`ElarionFile` payload](/docs/capabilities/transports/http-endpoints#files-downloads-and-uploads) (which buffers and is the right default only up to a few megabytes). Handlers never carry big payloads; they carry **pointers into the staging area**, and the pending state doubles as temp-file semantics: what is never committed is garbage-collected after its TTL. The read side is the owner-scoped streaming download endpoint: ```csharp app.MapElarionBlobDownloads().RequireAuthorization(); // GET {prefix}/{blobId}; requires AddElarionBlobUploads ``` `GET /{blobId}` streams the blob with its content type and leaf file name (`Content-Disposition: attachment`), applying the same exact-owner, fail-closed check as cancel — a missing, foreign-container, unowned, committed, or someone else's blob is `404`, so ownership is never leaked. Once a handler commits a blob to a record, the record's own (authorized) download path serves it; the uploader cannot keep reading it here after losing access to the record. **Import (large upload → processing handler):** 1. The client uploads via tus (or the direct endpoint) into the staging area → gets a pending blob reference. 2. It calls the processing handler (any transport) with that reference as an [`UploadedFile`](#passing-an-upload-to-a-handler) member. 3. The handler streams it from `IUploadedFiles.OpenAsync(...)`, processes it, and disposes of the temp file. A consumed import is the mirror image of [attaching a file to an entity](#attaching-a-file-to-an-entity): you never keep it, so **do not `CommitAsync` it** — commit means "promote to permanent and clear the expiry," the opposite of what a throwaway import wants. There are two ways to reclaim it: * **Explicitly — delete it the moment you are done**, so a large temp file is not left occupying storage for the whole TTL: ```csharp public async ValueTask> HandleAsync(ImportRows.Command command, CancellationToken ct) { var opened = await uploads.OpenAsync(command.File, new UploadConstraints { ContentTypes = ["text/csv"] }, ct); if (!opened.IsSuccess) { return opened.Error; // upload.not_found: expired, consumed or not the caller's } await using (var file = opened.Value) { await importer.IngestAsync(file.Content, ct); // stream and process } await db.SaveChangesAsync(ct); // the handler's own save first (see below) await uploads.DeleteAsync(command.File, ct); // reclaim now — no waiting for the GC return Unit.Value; } ``` * **Implicitly — do nothing**, and the [blob garbage collector](#the-lifecycle) reclaims the pending blob once its `ExpiresAt` passes. This is also the safety net if the process crashes before the explicit delete. Whether that delete is transactional depends on the backend. On a **same-database store (PostgreSQL)** it joins the caller's unit of work: inside a command's transaction the reclaim commits atomically with the imported rows and **rolls back with them** if the import fails, leaving the file in place to retry — so calling `DeleteAsync` inside the handler is safe. On an **external store (Azure Blob Storage)** the delete is an immediate side effect, not part of your database transaction, so delete only **after** the import transaction commits — or skip the explicit delete and let the garbage collector reclaim it. On the PostgreSQL store, `DeleteAsync` removes the blob row through the scoped `DbContext` it shares with the handler and calls `SaveChangesAsync` on it. That save writes **everything the handler still tracks** at that moment, not only the delete. Call `DeleteAsync` **after** the handler's own `SaveChangesAsync`, as the example does, never between changing tracked entities and saving them: a delete in between would save half-made changes before the handler validated or finished them. Note the handler works with the **pending blob** the upload produced, never the staging *session*: by the time it runs, the resumable upload has already been sealed into that blob (the session is cleaned up separately by the staged-upload collector, and must outlive the client's completion probe). "Removing it from staging" therefore means deleting the pending blob, exactly as above. **Export (handler-produced artifact → streaming download):** ```csharp public async ValueTask> HandleAsync(Command command, CancellationToken ct) { await using var artifact = await _exporter.BuildAsync(command.List, ct); // a stream, never buffered var blobRef = await _blobs.SaveAsync(new BlobUploadRequest { Container = "uploads", // the download endpoint's configured container Name = $"{_currentUser.UserId}/{Guid.CreateVersion7():N}/{command.List}.xlsx", ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", InitialState = BlobLifecycleState.Pending, // temp: GC reclaims it if never downloaded/committed ExpiresAt = _timeProvider.GetUtcNow() + TimeSpan.FromMinutes(30), OwnerId = _currentUser.UserId, // only the requesting user may download it }, artifact, ct); return new ExportPointer(blobRef.Value); // the client GETs {prefix}/{id} to stream it } ``` The response DTO carries only the blob id — small, cacheable, schema-friendly — and the actual bytes move once, streamed, over the download endpoint. ### Streaming a ZIP archive into the response body [#streaming-a-zip-archive-into-the-response-body] "Download all of these as one file" is the one export shape the single-blob download endpoint cannot serve: the archive is assembled per request from several stored blobs and never exists as a blob of its own. An HTTP-only handler builds it while it is sent: an `[HttpEndpoint]` without `[Handler]` returns a [streamed file](/docs/capabilities/transports/http-endpoints#streamed-files-http-only-endpoints) whose writer gets the response body, so nothing is buffered in memory or staged in the database, and authorization and the module's feature gate guard it like every handler: ```csharp [HttpEndpoint("exports/{id}/bundle")] [RequirePermission("exports", "read")] public sealed class DownloadBundle(IExportParts parts, IBlobStore blobs, ILogger logger) : IHandler> { public sealed record Query : IQuery { public required Guid Id { get; init; } } public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var members = await parts.ListAsync(query.Id, ct); if (members.Count == 0) return AppError.NotFound("Nothing to bundle."); return ElarionStreamedFile.FromWriter(async (body, ct) => { await using var archive = await ZipArchive.CreateAsync( body, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, ct); foreach (var member in members) { await using var download = await blobs.OpenReadAsync(new BlobRef { Value = member.BlobId }, ct); if (download is null) { // Expired or reclaimed: leave it out, but say so — a listing may name it. logger.LogWarning("Bundle member {BlobId} has vanished.", member.BlobId); continue; } var entry = archive.CreateEntry(member.FileName, CompressionLevel.Fastest); await using var entryStream = await entry.OpenAsync(ct); await download.Content.CopyToAsync(entryStream, ct); } }, "application/zip") with { FileName = $"bundle-{query.Id}.zip" }; } } ``` Two things the framework takes care of here: * **The synchronous trailer write.** `System.IO.Compression` has async APIs (`ZipArchive.CreateAsync`, `ZipArchiveEntry.OpenAsync`, `ZipArchive.DisposeAsync`), but the entry stream from `OpenAsync` does not override `DisposeAsync`: `await using` falls through to the synchronous `Dispose()`, which writes the entry's compressed trailer and data descriptor synchronously, even with `CompressionLevel.NoCompression`. Kestrel and `TestServer` refuse synchronous body writes (`AllowSynchronousIO` is `false`), and by then the `200` and its headers are sent, so a host route would hang with a download that never finishes. The body a streamed file's writer receives holds those few synchronous bytes and sends them with the next asynchronous write, so the handler needs no `AllowSynchronousIO`. The member bytes still copy asynchronously and unbuffered. This is a BCL gap, worth an upstream fix in `dotnet/runtime` (the entry stream should write its trailer in `DisposeAsync`). * **A mid-stream failure aborts.** Once the status line is sent, an exception in the writer aborts the connection, the only honest signal: the client sees a failed download, not a truncated archive with a valid-looking central directory. A route you map yourself outside the handler tier needs the same care: scope `IHttpBodyControlFeature.AllowSynchronousIO = true` to that one response (never `KestrelServerOptions` globally, which gives every endpoint a thread-blocking write path), and call `HttpContext.Abort()` on a failure after the headers. ## Not S3 on the wire [#not-s3-on-the-wire] Elarion deliberately does **not** implement the S3 wire protocol (SigV4, `aws-chunked` streaming signatures, multipart XML). That is the interop-fragile, expensive part of S3, and upload widgets never need it — Uppy treats every upload URL as opaque. The S3 wire protocol is only required for real AWS SDK / CLI interoperability, which is a non-goal. The abstraction stays S3-free — `Elarion.Blobs.Azure` is exactly such a direct-to-storage backend behind the neutral seams, and a presigned-URL capability could be added the same way without changing the lifecycle. # Bulk operations (/docs/capabilities/bulk-operations) `SaveChanges` is the right write path for handlers — change-tracked, batched, transactional. It is the wrong tool for *volume*: importing files, seeding, backfills, or projecting large event streams pushes tens of thousands of rows through a tracker that was built for tens. Elarion's bulk operations add one verb for that case: ```csharp await context.Orders.ExecuteInsertAsync(orders, cancellationToken: ct); ``` On PostgreSQL this streams the entities through binary `COPY … FROM STDIN` — the database's native ingestion path. Measured against comparable libraries (see [ADR-0051](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0051-postgresql-bulk-insert.md) for the full table): \~12× faster than `SaveChanges` at 100k rows with \~0.5% of its allocations, at parity with a hand-written `NpgsqlBinaryImporter` loop. The API deliberately follows the design sketched for EF Core itself ([dotnet/efcore#27333](https://github.com/dotnet/efcore/issues/27333), [#29897](https://github.com/dotnet/efcore/issues/29897)): it joins the `ExecuteUpdateAsync` / `ExecuteDeleteAsync` family — set-based, non-tracking, bypasses the change tracker — so if EF ships the native API, migrating is a rename. ## Package split [#package-split] | Package | Use it in | Contains | | -------------------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.EntityFrameworkCore.BulkOperations` | Application code | `ExecuteInsertAsync` extensions on `DbSet`, `BulkInsertOptions`, the `IBulkInsertProvider` seam, and the shared column-selection rules. Depends on EF Core relational APIs only. | | `Elarion.BulkOperations.PostgreSql` | Infrastructure / host | The binary-COPY provider and its `UseElarionPostgreSqlBulkOperations()` options-builder registration. | ## Setup [#setup] The provider registers on the context options — the same composition point as `UseNpgsql` itself, no service-collection call: ```csharp services.AddDbContext(options => options .UseNpgsql(connectionString) .UseElarionPostgreSqlBulkOperations()); ``` Calling `ExecuteInsertAsync` without a registered provider fails with the registration hint. ## Usage [#usage] ```csharp // Materialized input long written = await context.Orders.ExecuteInsertAsync(orders, cancellationToken: ct); // Streaming input — rows are written as they are produced, nothing is materialized await context.Orders.ExecuteInsertAsync(ReadRowsAsync(file, ct), cancellationToken: ct); // Options bag await context.Orders.ExecuteInsertAsync(orders, new BulkInsertOptions { Timeout = TimeSpan.FromMinutes(5) }, ct); ``` ### Upsert [#upsert] Conflict handling is opt-in per call — the default streams straight into the table (fastest, any conflict aborts all-or-nothing); the upsert behaviors stage through a temporary table and merge with PostgreSQL's native `ON CONFLICT`: ```csharp // Skip rows that already exist (any unique constraint) await context.Counters.ExecuteInsertAsync(counters, new BulkInsertOptions { OnConflict = BulkInsertConflictBehavior.DoNothing }, ct); // Overwrite existing rows (conflict target = primary key) await context.Counters.ExecuteInsertAsync(counters, new BulkInsertOptions { OnConflict = BulkInsertConflictBehavior.Update }, ct); // Overwrite matched on an alternate unique index await context.Counters.ExecuteInsertAsync(counters, new BulkInsertOptions { OnConflict = BulkInsertConflictBehavior.Update, ConflictProperties = [nameof(Counter.Key)], }, ct); ``` `Update` sets every insertable non-target column to the incoming value. The conflict target must match a declared key or unique index — a mismatch throws before the database is touched. The staged path joins the ambient transaction like the direct path, and the returned count is the number of rows inserted or updated. ### Transactions [#transactions] The COPY runs on the context's own connection, so an open transaction contains it — inside a handler, the framework unit of work already provides one and a failure rolls the bulk rows back together with every other write. COPY itself is all-or-nothing: any error (e.g. a unique violation) aborts the whole stream; partial rows are never left behind. ### Semantics to know [#semantics-to-know] * **Non-tracking.** Inserted entities are not attached; nothing is written back to them. * **Store-generated columns stay store-generated.** Identity/serial keys, computed columns, and on-add store defaults are omitted from the insert and filled by the database — and deliberately **not fetched back** (the bulk-import tradeoff, same as the EF sketch). Client-side value generators do not run either: callers assign keys, which Elarion entities do anyway (client-assigned v7 Guids, ADR-0038). * **Value converters are honored** — enum-to-string, strongly-typed ids, and friends convert exactly as `SaveChanges` would, compiled into the write path once per model. * **Complex properties (value objects) flatten**, including nesting; a null anywhere along an optional chain nulls the columns. Entities without complex properties pay nothing for the capability. * **TPH works** (the discriminator constant is written per set); a derived instance passed through a base-type set throws instead of silently dropping its columns. * **Fail-loud shapes**: TPT / entity splitting, owned types, JSON-mapped complex collections, and non-discriminator shadow properties are not supported and throw before touching the database. * **RETURNING is out of scope** for now — fetching database-generated values back mirrors how the EF team splits plain import from `ExecuteInsertReturning`, and client-assigned v7 Guid keys make it rarely needed. ## When to use which write path [#when-to-use-which-write-path] | Rows | Path | | ------------------------------------ | --------------------------------------------------------------------------- | | A handful, as part of domain work | `Add`/`AddRange` + `SaveChanges` — tracking, events, interceptors all apply | | Thousands to millions, import-shaped | `ExecuteInsertAsync` | Note that bulk-inserted rows bypass everything that hangs off the change tracker: audit change capture (`SaveChangesInterceptor`), [tenant stamping](/docs/capabilities/multi-tenancy) (set the tenant on each entity yourself), domain events raised from tracked entities, and concurrency tokens. That is the point — but it means bulk insert is for *ingestion*, not for domain mutations that other machinery must observe. ## Benchmarks [#benchmarks] `tests/Elarion.Benchmarks` contains the comparison suite (real PostgreSQL via Testcontainers): ```bash dotnet run --project tests/Elarion.Benchmarks -c Release -- --filter "*BulkInsert*" ``` It compares `SaveChanges`, Elarion, EFCore.BulkExtensions (MIT fork), linq2db, PhenX, and a raw `NpgsqlBinaryImporter` ceiling. # Caching (/docs/capabilities/caching) Elarion can cache handler results declaratively. Mark a read handler with `[Cacheable]` and the generator wraps it in a cache decorator; mark a write handler with `[CacheInvalidate]` and it clears the matching entries. Caching is opt-in per handler and integrates with the same [decorator pipeline](/docs/concepts/decorator-pipelines) as everything else. Only **successful** `Result` responses are cached. Validation and domain failures are returned to the caller but never stored, so a transient failure cannot become sticky. ## Caching a read handler [#caching-a-read-handler] ```csharp using Elarion.Abstractions; using Elarion.Abstractions.Caching; using Microsoft.EntityFrameworkCore; [Cacheable("clients", DurationSeconds = 120)] [Handler("clients.get")] public sealed class GetClient(AppDbContext db) : IHandler> { public sealed record Query(Guid Id); public sealed record Response(Guid Id, string Name); public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var client = await db.Clients .Where(c => c.Id == query.Id) .Select(c => new Response(c.Id, c.Name)) .FirstOrDefaultAsync(ct); return client is null ? AppError.NotFound($"Client {query.Id} was not found.") : client; } } ``` The generator emits an `IHandlerCachePolicy` from the attribute metadata and inserts a `CacheDecorator<,>` into the handler's pipeline. The decorator computes a key from the request, looks it up, and only runs the handler on a miss. ### `[Cacheable]` properties [#cacheable-properties] | Property | Default | Meaning | | -------------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `tags` (constructor) | none | Logical cache tags for grouping and invalidation. | | `DurationSeconds` | `60` | Entry lifetime, applied to both the distributed and local cache layers. | | `Scope` | `CurrentUser` | Whether keys and tags are isolated per user or shared globally. | | `KeyProperties` | all public request properties | Which request properties contribute to the key. An unknown name is reported at build time ([`ELCACHE007`](/docs/reference/diagnostics)). | Use `KeyProperties` when only some request fields affect the response: ```csharp [Cacheable("reports", DurationSeconds = 300, KeyProperties = new[] { "Year", "Month" })] ``` Every property that participates in the key must have a stable, injective string formatting: a primitive, `string`, `char`, `bool`, `Guid`, an enum, `DateTime`/`DateTimeOffset`/`DateOnly`/`TimeOnly`/ `TimeSpan`, `decimal`, or a `Nullable` of those. A property of any other type (a collection, array, or custom object) would fall back to `object.ToString()` — colliding every value into one key and risking a cross-request cache leak — so the generator rejects it at build time ([`ELCACHE006`](/docs/reference/diagnostics)). Narrow the key with `KeyProperties` to exclude such a property. ## Cache scope [#cache-scope] `HandlerCacheScope` controls isolation: | Scope | Behavior | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `CurrentUser` (default) | Entries and tags are isolated by the authenticated user. Requires an [`ICurrentUser`](/docs/capabilities/current-user) with a user id; the id is hashed before it enters the physical cache key. | | `Global` | Entries are shared across all users. Use only for data that is not user-specific and carries no authorization context. | Both scopes sit inside the tenant when [tenant scoping](#tenant-isolation) is registered: `Global` then means every user *of the tenant in scope*. `CurrentUser` is the default precisely so that one user's cached response is never served to another. Switch to `Global` deliberately, only for non-personalized data. ## Invalidating with tags [#invalidating-with-tags] A command handler clears cached entries by tag with `[CacheInvalidate]`. Invalidation is tag-based, so the writer does not need to know the concrete keys produced by read handlers: ```csharp [CacheInvalidate("clients")] [Handler("clients.update")] public sealed class UpdateClient(AppDbContext db) : IHandler> { public sealed record Command(Guid Id, string Name); public sealed record Response(Guid Id); public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var client = await db.Clients.FirstOrDefaultAsync(c => c.Id == command.Id, ct); if (client is null) { return AppError.NotFound($"Client {command.Id} was not found."); } client.Name = command.Name; await db.SaveChangesAsync(ct); // The decorator invalidates the "clients" tag on success. return new Response(client.Id); } } ``` `[CacheInvalidate]` takes the same `tags` and `Scope` as `[Cacheable]`. The scopes compose precisely: * A **`Global`** invalidation (the default) evicts the globally shared entries **and** every user's `CurrentUser`-scoped entries for the listed tags. User-scoped entries are deliberately also stamped with the global tag namespace so the default `[Cacheable]` (`CurrentUser`) / default `[CacheInvalidate]` (`Global`) pairing works out of the box. * A **`CurrentUser`** invalidation clears only the *invoking* user's entries for the listed tags — never another user's, and never the globally shared entries. `[CacheInvalidate]`'s `Scope` defaults to **`Global`** — unlike `[Cacheable]`, whose default is `CurrentUser`. Invalidation is a mutation reacting to a state change, and the caller performing it is usually *not* the user whose cached read must be evicted (an admin editing another user's record). A `CurrentUser`-scoped invalidation would clear only the mutator's own tag and leave every affected user permanently stale, so the safe default is over-invalidation (`Global` — it evicts the tag across all users). Set `Scope = HandlerCacheScope.CurrentUser` explicitly only for a genuinely per-user cache the mutating caller also owns. ## Tenant isolation [#tenant-isolation] A cache hit never runs the handler, so it never runs the [tenant read filter](/docs/capabilities/multi-tenancy#reads--a-named-model-level-filter) either. Once tenant scoping is registered (`AddElarionTenantScoping()`), the default cache therefore puts the tenant in scope into every key and tag, whatever the `Scope`. A `[Cacheable(Scope = HandlerCacheScope.Global)]` query over tenant-scoped rows caches one entry per tenant, and a user who belongs to several tenants gets one `CurrentUser` entry per tenant. Nothing changes on the handler or its attributes. | In scope | Reads | `[CacheInvalidate]` evicts | | ------------------ | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | A tenant | Cached for that tenant only. | That tenant's entries, every user's at the `Global` default, plus entries cached under a system scope. Other tenants keep theirs. | | `SystemScope()` | Cached in a namespace of its own, never served to a tenant. | The listed tags in every tenant. | | No tenant resolved | Not cached: the handler runs on every call. | The listed tags in every tenant. | A tenant's id is hashed before it enters a key or tag, like a user id. A host without tenant scoping keeps exactly the keys and tags it had before. **No tenant means no cache.** This fails closed, the same way the read filter matches no rows when the tenant is unresolved. A shared namespace for every caller without a tenant would be keyed on a missing value: a handler that enters a tenant itself, with `ITenantContext.Scope` in its body, would store that tenant's result there and serve it to the next caller without a tenant. Bypassing gives up caching for those callers instead, typically anonymous visitors when the tenant comes from a claim. To cache their reads, resolve a tenant for them before the pipeline runs (from the host name, say). **Invalidation stays inside the tenant.** A tenant's writes are guarded to its own rows, so its `[CacheInvalidate]` leaves other tenants' entries alone, and one busy tenant cannot keep flushing everyone else's cache. A system scope and a scope with no tenant are not confined to one tenant's rows, so their invalidations reach every tenant. The cache cannot tell what a handler reads, so data that is not tenant-scoped is cached per tenant as well. When such data changes inside a tenant — a user's own profile, cached in each of their tenants — only that tenant's copy is evicted, and the other copies stay until they expire. Dispatch a command that changes shared data inside a system scope, which evicts every tenant, or keep `DurationSeconds` short for reads of such data. ## Registering the cache runtime [#registering-the-cache-runtime] The attributes and generated policies are runtime-neutral. The host chooses the implementation. The default is backed by [`HybridCache`](https://learn.microsoft.com/aspnet/core/performance/caching/hybrid): ```csharp // dotnet add package Elarion.Caching builder.Services.AddElarionHandlerCaching(); ``` `Elarion.Caching` is an opt-in sibling package — referencing it is what pulls `Microsoft.Extensions.Caching.Hybrid`, so the core stays dependency-light ([ADR-0017](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0017-dependency-light-core.md)). This registers `HybridCache` and the default `IHandlerCache` (`HybridHandlerCache`). There are three ways to change the backing store, from least to most invasive: * **Add an L2 distributed cache** so entries survive restarts and are shared across instances — see [Adding an L2 distributed cache](#adding-an-l2-distributed-cache) below. The recommended default for most applications is a PostgreSQL `UNLOGGED` table; Redis, SQL Server, and others work too. * **Swap the `HybridCache` implementation itself.** `HybridCache` is the abstraction, and `HybridHandlerCache` simply resolves whatever `HybridCache` is in the container. Register your own `HybridCache` *before* `AddElarionHandlerCaching()` — its `AddHybridCache()` call uses `TryAddSingleton`, so it adds the default only when one is not already registered, and your implementation wins. * **Replace `IHandlerCache` entirely** when you want to bypass `HybridCache` and own the whole caching contract. A replacement then owns [tenant isolation](#tenant-isolation) as well: the generated policies' keys contain only request values. ## Adding an L2 distributed cache [#adding-an-l2-distributed-cache] `HybridCache` is two-tier. The **L1** is an in-process `MemoryCache` that absorbs the hot path and is lost on restart; the **L2** is an optional `IDistributedCache` that `HybridCache` auto-discovers from DI and uses for cross-instance coherence, warm-restart survival, and stampede coordination. With no L2 registered, caching is L1-only — fine for a single instance, but each instance keeps its own copy and a restart starts cold. For most applications the recommended L2 is **a PostgreSQL `UNLOGGED` table** — reuse the database you already run instead of standing up a separate Redis tier. `Elarion.Caching.PostgreSql` wires it in one call: ```csharp // dotnet add package Elarion.Caching.PostgreSql using Elarion.Caching.PostgreSql; builder.Services.AddElarionPostgreSqlHandlerCaching( builder.Configuration.GetConnectionString("CacheDb")!); ``` That registers the official `Microsoft.Extensions.Caching.Postgres` distributed cache as the L2 — an auto-created `UNLOGGED` table named `elarion_cache` in the `public` schema — and calls `AddElarionHandlerCaching()` for you, so `HybridCache` picks the table up automatically. The optional `configure` delegate overrides any default (it runs last, so it always wins): ```csharp builder.Services.AddElarionPostgreSqlHandlerCaching( builder.Configuration.GetConnectionString("CacheDb")!, options => { options.SchemaName = "cache"; options.TableName = "handler_cache"; }); ``` An `UNLOGGED` table skips the write-ahead log, so cache writes are cheap and produce no WAL or replication traffic (this is the package's `UseWAL = false`, which Elarion defaults on). The tradeoff — the table is **truncated on a crash or unclean shutdown** and is **not present on physical standby replicas** — is exactly right for a cache: its contents are always reconstructible from the source of truth, so the worst case is a cold repopulate, never data loss. Why this fits most apps: `HybridCache`'s in-process L1 carries the high-frequency reads, so the L2 mostly handles cross-instance coherence and warm restarts — a load Postgres serves comfortably. Reach for a dedicated tier such as Redis when the cache itself must be a very high-throughput, independently scaled, or multi-region store, where routing all cache traffic through your primary Postgres (and the "not on replicas" limitation of `UNLOGGED`) would make the database the bottleneck. Any `IDistributedCache` works as the L2: register Redis (`AddStackExchangeRedisCache`), SQL Server, or another provider before `AddElarionHandlerCaching()` and `HybridCache` uses it just the same. ## How it composes [#how-it-composes] `CacheDecorator` and `CacheInvalidationDecorator` are ordinary handler decorators inserted by the `[Cacheable]` / `[CacheInvalidate]` attributes. They sit in the generated pipeline alongside your application decorators, so caching composes deterministically with logging, validation, and transactions. Cache operations are also [trace-visible](/docs/capabilities/telemetry): get/create spans report the precise outcome — `miss-factory-executed`, `miss-non-cacheable`, `cached-or-coalesced`, or `bypass-no-tenant` — and invalidation emits its own spans, all without leaking full keys, raw user ids, or tenant ids into tags. # CalDAV (/docs/capabilities/caldav) People see the application's shifts, bookings and deadlines in the calendar app they already use. A module publishes calendar objects in the handler that changes its data; the framework keeps them in a store with a change journal and answers the calendar apps' WebDAV requests from it, so sync is exact on every node and after every restart. | Package | Role | | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Elarion.WebDav` | The WebDAV core without a wire: the hardened XML reader, the `DavDispatcher`, `sync-collection`, the store seam `IDavCollectionStore`. NativeAOT-safe. | | `Elarion.WebDav.EntityFrameworkCore` | The store and its journal on the application's `DbContext`: `[GenerateElarionDavStore]`. PostgreSQL. | | `Elarion.CalDav` | Calendar sources, `ICalDavPublisher`, the calendar properties and reports. NativeAOT-safe. | | `Elarion.WebDav.AspNetCore` | The host: `MapElarionDav()`, `/.well-known/caldav`, the app-password scheme on the DAV routes only. | | `Elarion.AppPasswords` (+ `.EntityFrameworkCore`, `.AspNetCore`) | The credential calendar apps send: see [App passwords](/docs/capabilities/app-passwords). | Address books are served from the same packages and host by [CardDAV](/docs/capabilities/carddav). Why it is shaped this way, and what was rejected, is in [ADR-0111](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0111-caldav.md). ## Getting started [#getting-started] ```bash dotnet add package Elarion.CalDav dotnet add package Elarion.WebDav.EntityFrameworkCore ``` ```bash dotnet add package Elarion.WebDav.AspNetCore dotnet add package Elarion.AppPasswords.EntityFrameworkCore dotnet add package Elarion.AppPasswords.AspNetCore ``` ```csharp builder.Services.AddElarionWebDavEntityFrameworkCore(builder.Configuration.GetSection("WebDav")); builder.Services.AddElarionCalDav(builder.Configuration.GetSection("CalDav")); builder.Services.AddElarionAppPasswordsEntityFrameworkCore(builder.Configuration.GetSection("AppPasswords")); builder.Services.AddAuthentication() .AddElarionAppPasswordAuthentication(); // plus AddElarionIdentityAppPasswordPrincipals() or OnCreatePrincipal var app = builder.Build(); app.UseElarionCrossOriginProtection(); app.UseAuthentication(); app.UseAuthorization(); app.MapElarionDav(); // /dav, /.well-known/caldav, feeds ``` A person creates an app password in the application (the application's own-account handler calls `IAppPasswords`), then adds a CalDAV account on iOS, macOS, Thunderbird, DAVx5 or Evolution with the host name, their e-mail and that password. The calendars of their home appear, read-only. ## The host [#the-host] `MapElarionDav()` maps one route group under `WebDav:Prefix` for every registered DAV protocol and returns it, so the application can add conventions such as a rate limiter: * **Methods.** `OPTIONS`, `GET`, `HEAD`, `PROPFIND`, `REPORT`, and the write methods, which the dispatcher answers `403`. * **Authentication.** The group requires an authenticated user of the schemes in `WebDavHostOptions.AuthenticationSchemes`, by default only the app-password scheme (`ElarionAppPassword`): the application's browser credential (a cookie, a proxy token) never authenticates a DAV request, and an app password no other endpoint. A request without a credential answers `401` with `WWW-Authenticate: Basic realm="DAV", charset="UTF-8"` (iOS sends anonymous requests during discovery and gives up on a `403`); a forbidden one `403` without a challenge. * **The dispatch scope** is seeded with the DAV principal after authentication, so `ICurrentUser` in the calendar sources is the calendar app's user, whatever ran before. * **Cross-origin protection.** The group carries `CrossOriginProtectionExemptMetadata` with its prefix, so `UseElarionCrossOriginProtection` leaves it alone, before routing as well as after: its only credential is one a browser never attaches by itself. * **Well-known.** `/.well-known/caldav` at the application root answers every method with `301` to the prefix (`WebDavHostOptions.MapWellKnown`). * **The prefix is the group's.** It maps `{prefix}/{**path}` for every protocol. An endpoint the application maps under the prefix with a more specific template wins by route precedence, and then runs outside the dispatcher, the group's authentication schemes and its scope seeding; give it those conventions yourself, or serve it under another prefix. A DAV protocol of your own is an `IDavProtocol`; a first path segment no protocol's home owns reaches `IDavProtocol.HandleOtherAsync`. * **No collection, no DAV.** `WebDav:RefuseWhenNoCollections` answers `403` to every request but `OPTIONS` of a user who sees no collection of any protocol, for an application whose DAV access used to be one permission. By default such a user discovers empty homes. Serve CalDAV over HTTPS: Apple clients may send no credentials over plain HTTP. When the prefix is not `/dav`, set the scheme's `FeedTokenReader` to `AppPasswordFeedPaths.CreateReader(prefix)`. ## Calendar sources: who sees which calendar [#calendar-sources-who-sees-which-calendar] A module declares a **calendar source**: a query request implementing `ICalDavSource`, whose static `SourceName` names it, and an ordinary handler that returns the calendars of the source the current user may see. ```csharp public sealed record MyShiftCalendars : ICalDavSource { public static string SourceName => "shifts"; } [RequirePermission("shifts", Verbs.Read)] public sealed class ListMyShiftCalendars(ICurrentUser user) : IHandler> { public ValueTask> HandleAsync(MyShiftCalendars query, CancellationToken ct) => ValueTask.FromResult(Result.Success(new CalDavSourceListing([ new PublishedCalendarInfo(Key: $"u-{user.UserId}", DisplayName: "My shifts") { Color = "#2E7D32", Components = CalendarComponentKinds.Event, TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Vienna"), }, ]))); } // in the module's ConfigureServices, so a disabled module registers no source services.AddElarionCalDavSource(); ``` Every DAV request invokes every registered source's handler through the handler pipeline as the authenticated user, so `[RequirePermission]`, resource rules with `WhereAuthorized` and `[FeatureGate]` decide what a calendar app shows exactly as they decide what the application shows. A source that answers not-found (a closed feature gate), forbidden or unauthorized shows no calendars; any other failure answers `500`. A calendar no source returns, and a principal or home of another user, answer `404`, never `403`. Leave `[Handler]` off a source's handler unless you also want it on JSON-RPC: it is invoked in process. A source name and a key are 1 to 64 ASCII letters, digits, `-` and `_`; a calendar's URL segment is `{source}.{key}` unless `PublishedCalendarInfo.Segment` names another (1 to 128 ASCII letters, digits, `-`, `_`, `.`, `~` or `@`, not `.` or `..`, unique among the calendars a user sees). Segments, the home segment `calendars` and the prefix are a URL contract: apps store the URLs they discovered, so set `Segment` to keep the URLs of a server you replace, and never change one once devices synced. A segment is matched exactly; it does not change the store address or the sync token. Two sources with one name fail when the second is registered; an invalid or repeated key fails when it is returned, naming the source. A source whose handler is not registered (the class is outside the module, or the module that holds it is not enabled) stops the host from starting, with a message naming the source. Access is decided per calendar, not per object. A calendar whose content differs between viewers is published as one calendar per viewer (`u-{user}` above); losing access to a calendar needs no log, because the calendar leaves the home. ## Publishing calendar objects [#publishing-calendar-objects] The handler that changes the application's data publishes the calendar objects it changes, in its own transaction: ```csharp public sealed class CreateShift(AppDbContext db, ICalDavPublisher calendars) : IHandler> { public async ValueTask> HandleAsync(Command command, CancellationToken ct) { // ... write the shift await calendars.PublishAsync(new CalDavAddress("shifts", $"u-{shift.UserId}"), ToEvent(shift), ct); return shift.Id; } } ``` | Call | Does | | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `PublishAsync(address, calendarObject)` | Adds or replaces the object of its UID; `false` when the written bytes equal the stored ones. | | `RemoveAsync(address, uid)` | Removes it; clients syncing receive it as removed. | | `ReplaceAsync(address, objects)` | Makes the set the calendar's whole content: the repair for a drifted calendar, or a nightly re-projection. Only what differs is recorded. | A `CalendarObject` (from `Elarion.Calendars`) is an event, a to-do, or a series' master and its overrides under one UID; it converts implicitly from a `CalendarEvent` or `CalendarTodo`. The publisher writes it with `CalendarWriter` and one `VTIMEZONE` per `TZID`, under the name `{uid}.ics` (a hash for a UID with other characters), and its strong ETag is a hash of the bytes. No clock value is passed to the writer, so every item needs a `Timestamp` (`DTSTAMP`) or `LastModified`: publishing an item with neither throws `CalendarWriteException`, because a clock value would change the bytes, and every client would refetch, on every re-publish. Publishing an object with a `METHOD` property, or into a source that is not registered, throws too. The store records the time span each object's occurrences cover (open for an endless series), so a `calendar-query` selects its candidates without reading the calendar. A handler that forgets to publish leaves the calendar stale. Publishing from a domain-event consumer, which shares the command's transaction, keeps every handler that changes a shift covered; `ReplaceAsync` repairs what drifted. ## Calendars as calendar apps see them [#calendars-as-calendar-apps-see-them] Every calendar answers the properties the surveyed clients read: `resourcetype` with `calendar`, `displayname`, `calendar-description`, Apple's `calendar-color`, `supported-calendar-component-set`, `calendar-timezone` (a `VTIMEZONE` DAVx5 uses as the Android calendar's zone), `supported-report-set`, `sync-token` and `getctag`, `owner`, and a `current-user-privilege-set` of `read` and `read-current-user-privilege-set` only, which Thunderbird, DAVx5 and Evolution read as read-only. The principal answers `calendar-home-set` and `calendar-user-address-set` (`mailto:` the user's e-mail, which DAVx5 asks for otherwise). | Report | Answer | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `calendar-multiget` | The named objects in the order of their `href`s; one that does not exist as `404`. At most `MaxMultigetHrefs`. | | `calendar-query` | The objects matching the filter: `comp-filter`, `prop-filter`, `param-filter`, `text-match` (`i;ascii-casemap` by default, `i;unicode-casemap`, `i;octet`, `negate-condition`), `is-not-defined`, and `time-range` by the table of RFC 4791 §9.9 for events, to-dos, journals, free-busy and alarms, over every occurrence of a series. Floating times and dates are placed in the calendar's time zone. | | `free-busy-query` | One `VFREEBUSY` of the opaque, not cancelled events in the range, merged, tentative ones as `BUSY-TENTATIVE`. | `calendar-data` may ask for `expand` (every instance in UTC, without rules), `limit-recurrence-set`, or a partial `comp`/`prop` selection; `CalDAV-Timezones: F` (RFC 7809) leaves standard `VTIMEZONE`s out. `CalendarExpandOptions` in `CalDavOptions.CalendarExpand` caps every expansion. `CalDavFilterEvaluator.Matches` evaluates a filter on its own. ## Feeds for Outlook and Google Calendar [#feeds-for-outlook-and-google-calendar] Outlook and Google Calendar cannot add a CalDAV account; they subscribe to a URL, which cannot carry a password. Every published calendar is also served as one `.ics` document at `{prefix}/feeds/{token}.ics`, where the token is an [app password](/docs/capabilities/app-passwords) bound to that calendar: ```csharp var address = new CalDavAddress("shifts", $"u-{user.UserId}"); var feed = await appPasswords.CreateAsync(user.UserId, "Outlook", AppPasswordScope.CalendarFeed(address), ct); if (!feed.IsSuccess) return feed.Error; Uri url = links.FeedUrl(new Uri("https://app.example.com"), feed.Value); // CalDavLinks; show it once ``` * The URL is the credential: revoking the app password ends the feed, and each feed is revoked on its own. * On every request the feed runs the calendar's source as the token's user: a feed of a calendar the user no longer sees, an unknown or revoked token, and a CalDAV (`dav`) app password in the URL all answer `404`, without a challenge. * The document holds the calendar's name, description and color, each `VTIMEZONE` once, and the same objects as the calendar. It streams from the store; its `ETag` follows the calendar's sync token, so `If-None-Match` answers `304` until something changed. * `CalDav:FeedsEnabled` turns feeds off. A feed token is never accepted as a Basic password, nor the reverse. Outlook.com refreshes subscriptions about every three hours, Google Calendar less often; calendar apps on CalDAV see a change within their polling interval. ## Syncing an external calendar: the client [#syncing-an-external-calendar-the-client] `CalDavClient` brings calendars from iCloud, Nextcloud, Fastmail, Google or any CalDAV server into the application, one step at a time. The application stores each step's state where it keeps the rest of the account, and schedules the steps with its own job. ```csharp var http = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = false }); // the client follows redirects itself var client = new CalDavClient(http, new CalDavClientOptions { Authorization = ct => ValueTask.FromResult( new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{appPassword}")))), }); CalDavResult account = await client.DiscoverAsync(new Uri("https://caldav.example.com"), ct); if (!account.HasValue) return account.Error; // caldav.unauthorized, caldav.not_found, … CalDavResult step = await client.SyncAsync(account.Value.Calendars[0], stored.State, ct); if (!step.HasValue) return step.Error; // keep the previous state foreach (var changed in step.Value.Changed) { /* changed.Name, changed.ETag, changed.Data (a CalendarReadResult) */ } foreach (var name in step.Value.Removed) { /* … */ } stored.State = step.Value.State; // a string; step.Value.HasMore: run another step ``` * **Discovery** asks the URL for `current-user-principal`, then `/.well-known/caldav`, then `calendar-home-set` on the principal at depth 0 (iCloud refuses depth 1 there), then lists the calendars of every home (`HomeUrls`) with their names, colors, component kinds, whether they are writable, and whether they offer `sync-collection`. A URL that answers without `current-user-principal` but names a home (Synology) is the principal; a principal without `calendar-home-set` (a Nextcloud share) is its own home. * **A sync step** uses `sync-collection` when the calendar offers it, and compares the ETags of a full listing when it does not (after a `getctag` check) or when the server refuses the token (`400`, `403`, `409`, `412`; a `500` stays an error). Changed objects are fetched with `calendar-multiget` in batches of `MultigetBatchSize`, by the href the server listed; an object a multiget answers `404` for (Zimbra) or leaves out (sabre-based servers) is a removal. A truncated answer sets `HasMore` only while its token moves. At most `MaxObjectsPerStep` objects are fetched per step; the rest follow in the next. A name can appear in `Removed` again in a later step; removing is idempotent. * **Credentials** come from the `Authorization` delegate per request: an app password as Basic, or an OAuth bearer token the application refreshes (Google's CalDAV endpoint accepts only that). * **Writes**: `PutAsync(calendar, name, calendarObject, ifMatch)` sends `If-Match`, or `If-None-Match: *` to create; `DeleteAsync` sends `If-Match`. A failed precondition (`412`) or a conflict (`409`) is `caldav.conflict`, and a `207` that reports a failed member fails the write. The new ETag is returned when the server sends a strong one (a bare or percent-encoded one is quoted), else `null` and the next step fetches it. Redirects from https to http are not followed. * **What the server sends is input.** A refused credential (`caldav.unauthorized`), a refused request (`caldav.forbidden`), a missing calendar (`caldav.not_found`), another error status (`caldav.server_error`), an answer that is not WebDAV (`caldav.invalid_response`) or over a limit (`caldav.too_large`, with the limit) is a result with a `CalDavError` (code, message, status, URL), never an exception; an object that is not valid iCalendar comes back with the `calendar.*` errors of its read result. Only cancellation, misconfiguration (an option out of range, a state from elsewhere) and transport failures throw. | `CalDavClientOptions` | Default | Meaning | | --------------------- | ------------------------------ | ------------------------------------------------------------------------- | | `Authorization` | none | The `Authorization` header of each request. | | `MaxResponseBytes` | 32 MiB | The largest answer read. | | `MaxXmlDepth` | `32` | The deepest nesting of an answer. | | `MaxXmlElements` | `500000` | The most elements of an answer. | | `MaxObjectsPerStep` | `5000` | The most objects one step fetches. | | `MultigetBatchSize` | `100` | The objects per `calendar-multiget`. | | `MaxRedirects` | `5` | The redirects one request follows, with its method, body and credentials. | | `RequestTimeout` | the `HttpClient`'s | How long one request may take (`TimeoutException`). | | `CalendarRead` | `CalendarReadOptions` defaults | How calendar data is read. | ## The published-collection store [#the-published-collection-store] Calendar apps poll. They ask "what changed since my token?" (RFC 6578 `sync-collection`), and the answer must name every changed and every removed object, on every node, after every restart. The store keeps, per published collection, the objects as written, a counter, and a journal of changes: | Table | Holds | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `elarion_dav_collections` | One row per published collection: kind, source, key, the counter `sync_seq` and the journal's `low_water` mark. | | `elarion_dav_objects` | The objects: name, `uid`, strong `etag`, `content`, `content_type`, the time span they cover (`range_start`, `range_end`). | | `elarion_dav_changes` | One row per change: the counter it was given, the object name, added/changed/removed, and when. | Map the tables onto the application's context and register the store: ```csharp [GenerateDbSets] [GenerateElarionDavStore] // or modelBuilder.UseElarionDavStore() in OnModelCreating public partial class AppDbContext(DbContextOptions options) : DbContext(options); builder.Services.AddElarionWebDavEntityFrameworkCore(builder.Configuration.GetSection("WebDav")); ``` Then create the tables with a migration. The store is scoped over the request's context: a publish joins the context's transaction, so a published object becomes visible exactly when the handler commits and disappears with a rollback. Without a transaction, a write runs in a transaction of its own. * **No change, no write.** Publishing bytes equal to the stored ones compares the entity tag and writes nothing, so a handler may re-publish after every save, and a nightly re-projection costs no client a refetch. * **Every change counts.** Any other change takes the collection's row lock, increments the counter and appends one journal row per changed object, so tokens strictly increase across nodes. * **The journal prunes itself.** Each change also removes the collection's journal rows beyond `MaxJournalRowsPerCollection` or older than `JournalRetention` and raises the low-water mark. A client holding an older token gets `403` with `valid-sync-token` and resyncs in full. No job has to run. * **The sync token** is `urn:elarion:sync:{collection id}:{counter}`: a URI (Evolution reads anything else as a CTag), bound to its collection, and valid on every node. A collection's id is derived from its kind, source and key, so a calendar nothing was published to yet has a stable token at `0`. The same value serves as `getctag`. `AddElarionInMemoryDavStore()` keeps the same counters and journal in memory, for tests and single-node development. ## The WebDAV dispatcher [#the-webdav-dispatcher] `DavDispatcher.HandleAsync(DavRequest, IServiceProvider, CancellationToken)` answers a request without a wire, so it runs in tests without a server. It serves the current user's principal `{prefix}/principals/{user}/`, a home per protocol such as `{prefix}/calendars/{user}/`, each collection `{prefix}/calendars/{user}/{segment}/` and its objects; another user's principal or home answers `404`. The principal also resolves without its trailing slash. A collection is published (its members in the store, with sync tokens) or live (its members read per request through `DavCollection.Live`, answered by a CTag only; see [live address books](/docs/capabilities/carddav#live-address-books-contacts-filtered-per-viewer)). | Request | Answer | | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `OPTIONS` | `200`, `DAV: 1, 3` and the protocols' classes (`calendar-access`), an `Allow` header without a write method. | | `PROPFIND` depth `0` or `1` | The live properties of RFC 4918, RFC 3744, RFC 5397 and RFC 6578 and the protocol's, an unknown one in a `404` propstat; `Prefer: return=minimal` leaves those out. A missing `Depth` is read as `1`; `0,noroot` and `1,noroot` answer without the requested resource itself. A `PROPFIND` that names `calendar-data` carries each object's data, as a report would. `getcontentlength` is answered where the length is known. | | `PROPFIND` depth `infinity` | `403` with `propfind-finite-depth`. | | `REPORT sync-collection` | On a published collection (a live one answers `403` with `supported-report`), level `1`: the changed objects and the removed ones (as `404`) since the token, with a new token; a `limit` lower than the changes answers the first ones and a `507` on the collection, and the client continues from the token; an expired or foreign token `403` with `valid-sync-token`. | | `GET`, `HEAD` on an object | Its bytes, `Content-Type` and `ETag`; `If-None-Match` answers `304`. | | `PUT`, `DELETE`, `PROPPATCH`, `MKCALENDAR`, `MOVE`, `COPY`, … | `403` with `need-privileges`, nothing changes. Every collection grants `read` and `read-current-user-privilege-set` only. | Request bodies are read with DTDs and external entities refused and with `MaxBodyBytes`, `MaxXmlDepth` and `MaxXmlElements`: a larger body answers `413` without reading the rest, a deeper or malformed one `400`. ## Configuration [#configuration] | Key | Default | Meaning | | -------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------- | | `CalDav:CalendarRead:…` | the `CalendarReadOptions` defaults | How published objects and server answers are read (`MaxBytes`, `MaxComponents`, …). | | `CalDav:CalendarExpand:MaxOccurrences` | `10000` | The most occurrences one expansion yields. | | `CalDav:CalendarExpand:MaxIterations` | `100000` | The most candidates a rule examines. | | `CalDav:FeedsEnabled` | `true` | Whether calendars are also served as ICS feeds. | | `CalDav:ProductId` | `-//Elarion//Elarion.Calendars//EN` | The `PRODID` of published objects; changing it changes every ETag once. | | `WebDav:Prefix` | `/dav` | The path the DAV routes are served under. | | `WebDav:MaxBodyBytes` | `1048576` | The largest request body. | | `WebDav:MaxXmlDepth` | `32` | The deepest element nesting of a request body. | | `WebDav:MaxXmlElements` | `10000` | The most elements in a request body. | | `WebDav:MaxMultigetHrefs` | `1000` | The most objects one multiget names. | | `WebDav:JournalRetention` | `90.00:00:00` | How long the journal keeps a change. | | `WebDav:MaxJournalRowsPerCollection` | `10000` | The most changes one collection's journal keeps. | | `WebDav:RefuseWhenNoCollections` | `false` | Whether a user who sees no collection gets `403` on the whole DAV surface. | # Calendars (/docs/capabilities/calendars) Applications import calendars people upload (waste collection, school holidays, an export from Outlook or Google) and publish their own dates as files and feeds that calendar programs subscribe to. `Elarion.Calendars` reads and writes iCalendar (RFC 5545) without a third-party library and without reflection, so an application keeps publishing with NativeAOT. | Piece | Role | | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `CalendarReader` | Reads an `.ics` stream leniently into a `CalendarReadResult`: every event and to-do with its typed value, its component and its located errors. | | `CalendarEvent`, `CalendarTodo`, `CalendarAlarm` | The typed model, a view over the component that keeps every property it does not model. | | `CalendarComponent`, `CalendarProperty`, `CalendarParameter` | The lossless component tree: everything the file states, in order, with line numbers; built and changed in code too. | | `CalendarDateTime` | A date, a floating time, a UTC time or a time in a zone, with the zone's `TimeZoneInfo` and the `TZID` as written. | | `CalendarRecurrence` | Expands items into occurrences within a window: rules, extra and excluded dates, overrides, bounded by caps. | | `CalendarTimeZones` | Resolves `TZID`s, converts `VTIMEZONE` to `TimeZoneInfo` and back. | | `CalendarWriter` | Writes calendars to a stream, an `ElarionFile` or an `ElarionStreamedFile`, deterministically. | Why it is shaped this way, and what was rejected, is in [ADR-0109](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0109-icalendar-model-reader-and-writer.md). ## Getting started [#getting-started] ```bash dotnet add package Elarion.Calendars ``` ```csharp builder.Services.AddElarionCalendars(builder.Configuration.GetSection(CalendarOptions.SectionName)); ``` ## Importing an uploaded calendar [#importing-an-uploaded-calendar] A handler reads the uploaded file's stream. Reading never throws because of what the file contains: it returns every item, so the handler can show a preview and commit what the person confirms. ```csharp [Handler] public sealed class PreviewImport(CalendarReader reader) : IHandler> { public sealed record Command([property: UploadLimits(FileExtensions = [".ics"])] UploadedFile File); public async ValueTask> HandleAsync(Command command, CancellationToken ct) { await using var stream = command.File.OpenReadStream(); var result = await reader.ReadAsync(stream, cancellationToken: ct); if (result.FileErrors.Count > 0) return result.ToAppError("file"); foreach (var entry in result.Events.Where(e => e.HasValue && e.Value!.Start!.Value.Date < today)) entry.AddError("import.date_in_past", "The event lies in the past.", "DTSTART"); return new ImportPreview([.. result.Events.Select(e => new Row(e.Index, e.Value?.Summary, e.Value?.Start, e.Errors))]); } } ``` * `HasValue` says whether an entry has a typed item. Only a time that cannot be read (`DTSTART`, `DTEND`, `DURATION`, `DUE`, `RRULE`, `RDATE`, `EXDATE`, `RECURRENCE-ID` or its zone), a missing `DTSTART` on an event, or a per-item limit clears it. Any other unreadable property is reported as `calendar.invalid_value`, left out of the value and kept in the component. * `AddError(code, message, property?, lineNumber?)` adds the application's own errors, under its own prefix; they are located like the package's and appear in `Errors` and in `ToAppError`. * `ToAppError(fieldPath, format?, maxMessages)` converts to a validation `AppError` with at most 100 messages by default and one that counts the rest. Pass a formatter to word each error from its `Code` and data in the application's language; the package's messages are English, and it ships no translations, as the other file-format packages do not: ```csharp static string German(CalendarError e) => e.Code switch { CalendarErrorCodes.UnknownTimeZone => $"Zeile {e.LineNumber}: Zeitzone „{e.TimeZoneId}“ ist unbekannt.", CalendarErrorCodes.InvalidValue => $"Zeile {e.LineNumber}: {e.Property} ist kein gültiger Wert ({e.ExpectedKind}).", _ => e.ToString(), }; return result.ToAppError("file", German); ``` * Reading is lenient (see below). An application that refuses broken files instead refuses when `CalendarErrorCodes.IsStructural(error.Code)` holds for an error: the file is not a calendar or past a file limit, a line is malformed, too long or holds a control character, a component ends unexpectedly or exceeds a per-item limit. An application that imports leniently instead skips the entries that have errors and keeps the rest: where an error is reported says what it affects (`FileErrors` the file, an entry's `Errors` only that item, which has no value when a per-item limit stopped it). `CalendarErrorCodes.IsLimit(error.Code)` tells a configured limit (`too_large`, `line_too_long`, `too_many_*`, `nesting_too_deep`, `recurrence_limit`) apart from a broken file, to word it as "too large" rather than "broken". `Strict = true` in the read options also reports what the lenient reader accepts silently: a rule with both `COUNT` and `UNTIL` (`calendar.invalid_value`, the item has no value) and a value with a control character other than tab (`calendar.control_character`, the line is skipped). * Reading and expanding are CPU-bound and run synchronously on the calling thread once the stream is buffered. An application that imports uploads under load passes a token with a time budget to both, and may run them on a bounded number of worker threads rather than the request thread. ### Files as producers write them [#files-as-producers-write-them] The reader accepts a byte-order mark, also at the start of a later line of files concatenated from several exports, UTF-16, lines that were never folded, LF and CR line ends, folds with a tab, quoted and vendor-prefixed `TZID`s (`/mozilla.org/…/Europe/Berlin`, `"W. Europe Standard Time"`), dates where date-times belong, truncated or doubled time suffixes, and Exchange's all-day flag. A line that is not valid UTF-8 is decoded with the fallback encoding (Windows-1252 by default, `FallbackEncoding` to change it); `UsedFallbackEncoding` says when that happened. The code pages are held by the package, never registered process-wide. ## Time zones [#time-zones] A `TZID` resolves through the system's zones first, as an IANA or a Windows id, and otherwise through the file's `VTIMEZONE` of that id. Legacy ids such as `US/Eastern` or `Asia/Calcutta` resolve to the zone they link to, also on hosts that ship them separately (Debian's and Ubuntu's `tzdata-legacy`). An id neither knows is `calendar.unknown_time_zone` on each item that uses it. A vendor prefix is removed by trying the id's last few segments, so resolution is linear in the id's length; an id longer than `MaxTimeZoneIdLength` (128 characters) is not resolved at all, and a `VTIMEZONE` or `X-WR-TIMEZONE` with such an id is not used. Only zones the system knows are cached process-wide; an id from a file that does not resolve leaves nothing behind. A floating time stays floating; it converts to UTC only in a zone the caller passes (`CalendarExpandOptions.FloatingTimeZone`). `X-WR-TIMEZONE` is reported as `CalendarHeader.SuggestedTimeZone`. Resolution depends on the host's tzdata. Slim and NativeAOT container images often lack it: install `tzdata`. A `VTIMEZONE` converts to a `TimeZoneInfo` with one adjustment rule per year. `TimeZoneInfo` evaluates rules per calendar year, so two historical shapes are approximate: the New Year hour of a zone's first year that ends in daylight time, and a year with three different offsets. ## Recurrences [#recurrences] ```csharp var week = result.Expand(monday, monday.AddDays(7), new CalendarExpandOptions { FloatingTimeZone = vienna }); foreach (var occurrence in week.Occurrences) Console.WriteLine($"{occurrence.StartUtc}–{occurrence.EndUtc}: {occurrence.Item.Summary}"); ``` Expansion implements RFC 5545 recurrence for the Gregorian calendar: every `FREQ` and `BY` part, `BYSETPOS`, `WKST`, `COUNT`, `UNTIL`, `RDATE`, `EXDATE` and overrides matched by `UID` and `RECURRENCE-ID`. A local time in a daylight-saving gap moves forward by the gap, and the occurrence shows the wall-clock time it resolves to while its `RecurrenceId` keeps the time the rule named; an ambiguous one takes its first offset. `COUNT` counts the local times a rule names, before a gap moves them: on the spring day `BYHOUR=2,3` names 02:00 and 03:00, which are one instant, so they use two of the count and give one occurrence, and the series has one occurrence fewer than `COUNT`. An item may have several rules (`RecurrenceRules`): its occurrences are the union of theirs, each rule counting its own `COUNT`, and an instance two rules share is one occurrence. Hourly and shorter rules step in elapsed time. A repeated value of a `BY` list counts once, as RFC 5545 allows repeats: `BYMONTH=1,1,1` is January, however many items the list has. Parsing is linear in the rule's length, which the line limit bounds (`calendar.line_too_long`). * **Overrides** match their instance exactly, as RFC 5545 says: an override whose recurrence id is no instance (the right day at another time, say) is an extra occurrence, as the major clients treat it. A date `RECURRENCE-ID` against date-time instances matches the day's instance. `RANGE=THISANDFUTURE` is read as an override of its one instance. * **Updates sent again**: of several overrides of one instance, only the latest counts (the highest `SEQUENCE`, then the latest `DTSTAMP`, then the later one), as calendar clients do. `ResolveOverrideVersions = false` keeps them all. `CalendarRecurrence.LatestVersions(result.Items)` returns the items without the versions that lose, by the same rule, for an application that stores or shows items rather than occurrences. * **Cancelled items**: by default an item with `STATUS:CANCELLED` is an occurrence like any other, because the expansion reports what the file states. `SkipCancelled = true` leaves them out: a cancelled override removes its instance, a cancelled master its series. An application that shows a calendar turns it on. * **`EXRULE`** (RFC 2445, deprecated by RFC 5545 but still written by older producers) is read into `ExceptionRules`, written back, and applied: its instances are excluded, `DTSTART` never. | Cap | Default | Exceeded | | ---------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `MaxOccurrences` | 10,000 | The expansion stops with `calendar.too_many_occurrences` and the occurrences found. | | `MaxIterations` | 100,000 | A series whose rule finds no instance in that many periods stops with `calendar.recurrence_limit`. | | `MaxCandidates` | 1,000,000 | A series whose rule builds that many candidates stops with `calendar.recurrence_limit`, counted as they are built within a period. | A rule without `COUNT` starts a few periods before the window, whatever its frequency, so a rule from a distant `DTSTART` costs only the periods near the window. A rule with `COUNT` must be counted from `DTSTART`; `MaxCandidates` bounds that. `Expand` takes a cancellation token, checked per series and per period of a rule. Each occurrence says where its end comes from (`EndKind`: stated, from a duration, a default day or no time). Alarms resolve their trigger times per occurrence with `CalendarAlarm.GetTriggerTimes(occurrence)`. ## Publishing a calendar or a feed [#publishing-a-calendar-or-a-feed] ```csharp // A small export to any transport: return await CalendarWriter.ToFileAsync(events, "shifts.ics", new CalendarHeader { Name = "Shifts" }, cancellationToken: ct); // A feed an HTTP endpoint streams: return CalendarWriter.ToStreamedFile(db.Shifts.AsNoTracking().AsAsyncEnumerable().Select(ToEvent), "shifts.ics", new CalendarHeader { Name = "Shifts", RefreshInterval = TimeSpan.FromHours(6) }); ``` * Output is UTF-8 without a byte-order mark, CRLF, lines folded at 75 octets, served as `text/calendar; charset=utf-8`. * One `VTIMEZONE` per zone is written before the first item that uses it; `IncludeTimeZones = false` leaves out those of zones with an IANA id. A zone is written with its IANA id where the system can name one. * The writer never reads a clock: `DTSTAMP` comes from the item, else its `LAST-MODIFIED`, else `CalendarWriteOptions.Timestamp`. The same input writes the same bytes; a change in the written bytes between package versions is noted in the changelog. * An item without `UID` or timestamp, one that ends before it starts, or a zone without an id fails with a `CalendarWriteException` naming the item and the property. * Name and refresh interval are written as `NAME` and `X-WR-CALNAME`, `REFRESH-INTERVAL` and `X-PUBLISHED-TTL`. Properties and components the model does not cover (`X-APPLE-*`, `X-MICROSOFT-*`, unknown components) are kept on the typed item and written back unchanged. The model is mutable: `Clone()` on an event, a to-do, an alarm or an attendee copies it deeply, where assigning another item's lists would share them. The component tree can be pruned or built in code and written with `CalendarWriter.WriteAsync(stream, root)`. ## Limits and options [#limits-and-options] | Option | Default | Exceeded | | --------------------------- | --------- | --------------------------------------------------------------------------------------------------------- | | `MaxBytes` | 16 MiB | One `calendar.too_large` error; nothing past the limit is read. | | `MaxComponents` | 50,000 | Reading stops with `calendar.too_many_components`; the items before it are kept. | | `MaxLineBytes` | 4 MiB | The line is dropped with `calendar.line_too_long`; the item keeps its value. | | `MaxPropertiesPerComponent` | 1,000 | The item has no value (`calendar.too_many_properties`); reading continues. | | `MaxDepth` | 8 | The item has no value (`calendar.nesting_too_deep`); reading continues. | | `MaxLines` | 1,000,000 | Reading stops with `calendar.too_many_lines`; the items before it are kept. | | `MaxItems` | 50,000 | Reading stops with `calendar.too_many_items`; the items before it are kept. Only events and to-dos count. | | `MaxTimeZoneIdLength` | 128 | A longer `TZID` is `calendar.unknown_time_zone` without a lookup. | | `Strict` | `false` | Reports `COUNT` with `UNTIL` and control characters (see above). | The cancellation token of `ReadAsync` is checked every 1,024 lines while the file is parsed, and per item while items are mapped. The keys are listed in the [configuration reference](/docs/reference/configuration#calendars). ## Error codes [#error-codes] `calendar.unreadable`, `calendar.too_large`, `calendar.line_too_long`, `calendar.too_many_components`, `calendar.too_many_properties`, `calendar.nesting_too_deep`, `calendar.malformed_line`, `calendar.unexpected_end`, `calendar.required`, `calendar.invalid_value`, `calendar.unknown_time_zone`, `calendar.duplicate_uid`, `calendar.too_many_occurrences`, `calendar.recurrence_limit`, `calendar.too_many_lines`, `calendar.too_many_items`, `calendar.control_character` — constants of `CalendarErrorCodes`, whose `IsStructural(code)` says which are about the file's form and `IsLimit(code)` which report a configured limit. Each error carries the item's index and line, the component and `UID`, the property, its line and value, and the expected kind, the limit or the time-zone id where they apply. # CardDAV (/docs/capabilities/carddav) People see the application's customers, colleagues and suppliers in the contacts app they already use. A module publishes contacts in the handler that changes its data; the framework keeps them in the same store, journal and host as [CalDAV](/docs/capabilities/caldav), so sync is exact on every node and after every restart, and one app password serves calendars and address books alike. | Package | Role | | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `Elarion.CardDav` | Address-book sources, `ICardDavPublisher`, the address-book properties and reports. NativeAOT-safe. | | `Elarion.WebDav`, `Elarion.WebDav.EntityFrameworkCore`, `Elarion.WebDav.AspNetCore` | The WebDAV core, the store and the host, shared with CalDAV: see [CalDAV](/docs/capabilities/caldav#the-host). | | `Elarion.AppPasswords` (+ `.EntityFrameworkCore`, `.AspNetCore`) | The credential contacts apps send: see [App passwords](/docs/capabilities/app-passwords). | | `Elarion.Contacts` | The contact model, reader and writer: see [Contacts](/docs/capabilities/contacts). | Why it is shaped this way, and what was left out, is in [ADR-0113](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0113-carddav-address-books.md), on top of [ADR-0111](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0111-caldav.md). ## Getting started [#getting-started] ```bash dotnet add package Elarion.CardDav dotnet add package Elarion.WebDav.EntityFrameworkCore dotnet add package Elarion.WebDav.AspNetCore ``` ```csharp builder.Services.AddElarionWebDavEntityFrameworkCore(builder.Configuration.GetSection("WebDav")); builder.Services.AddElarionCardDav(builder.Configuration.GetSection("CardDav")); // app passwords and MapElarionDav() as on the CalDAV page; nothing else changes on the host ``` `MapElarionDav()` serves every registered DAV protocol: with `AddElarionCardDav` it also answers `/dav/addressbooks/{user}/…` and `/.well-known/carddav`, and `OPTIONS` names `addressbook` beside `calendar-access`. A person adds a CardDAV account with the host name, their e-mail and an app password of scope `dav`; DAVx5 and Evolution find calendars and address books in one account, iOS, macOS and Thunderbird add contacts as an account of its own with the same credentials. ## Address-book sources: who sees which address book [#address-book-sources-who-sees-which-address-book] A module declares an **address-book source**: a query request implementing `ICardDavSource`, whose static `SourceName` names it, and an ordinary handler that returns the address books of the source the current user may see. ```csharp public sealed record CustomerAddressBooks : ICardDavSource { public static string SourceName => "customers"; } [RequirePermission("customers", Verbs.Read)] public sealed class ListCustomerAddressBooks : IHandler> { public ValueTask> HandleAsync(CustomerAddressBooks query, CancellationToken ct) => ValueTask.FromResult(Result.Success(new CardDavSourceListing([ new PublishedAddressBookInfo(Key: "all", DisplayName: "Customers") { Description = "Every active customer" }, ]))); } // in the module's ConfigureServices, so a disabled module registers no source services.AddElarionCardDavSource(); ``` Sources behave as calendar sources do: every DAV request invokes them through the handler pipeline as the authenticated user, so `[RequirePermission]`, resource rules and `[FeatureGate]` apply; a source that answers not-found, forbidden or unauthorized shows no address books; an address book no source returns, and another user's home, answer `404`. Leave `[Handler]` off the handler. Names and keys are 1 to 64 ASCII letters, digits, `-` and `_`, and a source whose handler is not registered stops the host from starting. An address-book source and a calendar source may share a name; they share nothing else. ### URL segments [#url-segments] An address book is served at `/dav/addressbooks/{user}/{segment}/`, where the segment is `{source}.{key}` unless the source names one: ```csharp new PublishedAddressBookInfo(Key: "all", DisplayName: "Contacts") { Segment = "default" } ``` The segment, the home segment `addressbooks` and the prefix are a **URL contract**: contacts apps store the URLs they discovered, and changing one makes every synced device download the address book anew (or lose it, on some clients). Set `Segment` to keep the URLs of a server you replace. It is 1 to 128 ASCII letters, digits, `-`, `_`, `.`, `~` or `@`, never `.` or `..`, matched exactly (case-sensitive), and unique among the address books a user sees; a duplicate or an invalid one throws as the application's mistake. It does not change the store address, so published contacts keep their sync token. The principal answers at `/dav/principals/{user}/` and also without the trailing slash. ### One address book per account on Apple devices [#one-address-book-per-account-on-apple-devices] macOS Contacts downloads one address book of an account, and which one is not predictable; iOS at best merges them into one list. Thunderbird, DAVx5 and Evolution list every address book and let the person choose. If your users are on Apple devices, publish **one address book per user** that holds every contact they may see, for example a source that returns a single "Contacts" book keyed by the user, beside or instead of finer ones: ```csharp new PublishedAddressBookInfo(Key: $"u-{user.UserId}", DisplayName: "Contacts") ``` Publishing then writes a contact into the books of every user who may see it, as per-viewer calendars do. ## Publishing contacts [#publishing-contacts] The handler that changes the application's data publishes the contacts it changes, in its own transaction: ```csharp public sealed class CreateCustomer(AppDbContext db, ICardDavPublisher addressBooks) : IHandler> { public async ValueTask> HandleAsync(Command command, CancellationToken ct) { // ... write the customer await addressBooks.PublishAsync(new CardDavAddress("customers", "all"), new Contact { Uid = customer.Id.ToString(), FormattedName = customer.Name, Emails = [new ContactEmail(customer.Email) { Types = ContactTypes.Work }], }, ct); return customer.Id; } } ``` | Call | Does | | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `PublishAsync(address, contact)` | Adds or replaces the contact of its UID; `false` when the written bytes equal the stored ones. | | `RemoveAsync(address, uid)` | Removes it; clients syncing receive it as removed. | | `ReplaceAsync(address, contacts)` | Makes the set the address book's whole content, recording only what differs; two contacts of one UID throw before anything changes. | The publisher writes the `Contact` with `ContactWriter` as **vCard 3.0**, the version Apple asks for and every client reads, under the name `{uid}.vcf` (a hash for a UID with other characters); the strong ETag is a hash of the bytes. The writer writes no clock value, so publishing an unchanged contact changes nothing, not even the sync token. A contact without `Uid`, or with nothing to show as its name (`DisplayName` empty: no formatted name, name, organization, e-mail or phone), throws: Apple drops a card without `FN`. Keep photos under 224 KiB, the largest iCloud accepts; DAVx5 shrinks photos over 1 MB. ## Live address books: contacts filtered per viewer [#live-address-books-contacts-filtered-per-viewer] A published address book holds the same contacts for everyone who sees it. When what a person sees depends on rules that change without any contact changing (restricted contacts, sharing groups, a permission, a role), publishing one address book per viewer would mean re-publishing every viewer's book on every such change. A **live address book** reads the contacts per request instead, as the current user, with the same rules the application's own list queries use: ```csharp // the source's handler still decides which address books the user sees services.AddElarionCardDavLiveSource(); internal sealed class VisibleContacts(AppDbContext db) : ICardDavLiveAddressBooks { // name and ETag of every contact the current user sees; no card is written for a listing public IAsyncEnumerable ListAsync(string key, CancellationToken ct) => db.Contacts.WhereAuthorized(Verbs.Read) .Select(c => new CardDavLiveMember(c.Id + ".vcf", c.Version.ToString())) .AsAsyncEnumerable(); // the named contacts the user sees (all of them for a query), as Contacts public async IAsyncEnumerable GetAsync(string key, IReadOnlyCollection? names, DavContentPurpose purpose, [EnumeratorCancellation] CancellationToken ct) { var ids = names?.Select(n => Guid.Parse(n[..^4])).ToList(); await foreach (var c in db.Contacts.WhereAuthorized(Verbs.Read) .Where(c => ids == null || ids.Contains(c.Id)).AsAsyncEnumerable().WithCancellation(ct)) yield return new CardDavLiveContact(c.Id + ".vcf", c.Version.ToString(), ToContact(c, withPhoto: purpose != DavContentPurpose.Query)); } } ``` `TAddressBooks` is resolved from the request's scope, so it takes the `DbContext` and `ICurrentUser`. The framework writes each `Contact` as vCard 3.0 with the rules of published contacts (a UID and a name to show), under the member name and ETag you give. An application that pins its own card bytes (its property order, the spelling of a parameter, a property of its own) gives the card's property list instead of a `Contact`: `new CardDavLiveContact(name, etag, properties)`. It is written as `ContactWriter.AddAsync(properties)` writes it, as vCard 3.0, in that order and spelling; it needs a `UID` and an `FN`, and its values are escaped as a read entry's are. `contact.ToProperties(ContactFormatVersion.V3_0)` is the writer's own list to start from. An application whose address books are all live needs no store: `AddElarionCardDav()` and its live sources are all it registers, without `AddElarionWebDavEntityFrameworkCore` and its tables. `ICardDavPublisher` still resolves, and says which store to register if it is used for a published source. * **Answered by a CTag, without sync tokens.** A live address book answers `getctag`, has no `sync-token`, and does not offer `sync-collection` (a `sync-collection` answers `403` with `supported-report`). Every contacts app falls back to the CTag: when it changed, the app lists the names and ETags (`PROPFIND Depth: 1`) and fetches the changed contacts with `addressbook-multiget`. Removals and contacts the person no longer may see disappear at the next listing. * **The CTag** is by default a hash over the listing, so it changes exactly when the listing does, including when visibility changes; override `GetCTagAsync` with something cheaper only if it changes at least as often. * **The ETag is yours to keep right**: the same in the listing and with the contact, changing exactly when the card does. Derive it from a row version or a hash of the fields the card is written from (including a per-viewer photo fallback, if the card differs by viewer). One that never changes keeps stale cards on devices; one that changes on every request makes every poll a full download. * **The purpose** (`DavContentPurpose.Get`, `Multiget` or `Query`) says why the contacts are asked for. A query reads every contact the user sees, so leave photos out of it; one `GetAsync` call answers one response, so a byte budget for photos is kept inside it. * **Member names** are the last URL segment (1 to 128 ASCII letters, digits, `-`, `_`, `.`, `~`, `@`), a URL contract like the address book's segment; `CardDavAddress.MemberNameOf(uid)` gives the name a published contact would have. A listing does not know a card's length, so `getcontentlength` answers `404` for listed members. A listing that names `address-data` (some clients fetch the cards that way) asks for every card with `DavContentPurpose.Multiget` and carries them, as for a published address book. * **Nothing is published into a live source**: `ICardDavPublisher` throws for one. A source is either published or live; an application can register both kinds. A change costs every client a listing (names and ETags) after the CTag changed, and the default CTag costs a listing per poll: one indexed query, fine for the few thousand contacts per book of the tier Elarion targets. Published address books stay the choice when the content is the same for every viewer. ## Address books as contacts apps see them [#address-books-as-contacts-apps-see-them] * **Properties.** The principal answers `addressbook-home-set`; address books answer `resourcetype` with `addressbook`, `displayname`, `addressbook-description`, `supported-address-data` (vCard 3.0 and 4.0), `supported-collation-set`, `sync-token` and `getctag`. Properties Apple asks about and the server does not keep (`me-card`, `max-image-size`, `directory-gateway`) answer `404` inside the `multistatus`, which Apple tolerates. * **Reports.** `sync-collection` (published address books), `addressbook-multiget` and `addressbook-query`. * **Versions.** `address-data` without a version answers the stored vCard 3.0; `version="4.0"` answers the same contact written as 4.0 (DAVx5 and Evolution prefer it), with the same ETag; another version or content type answers `403` with `supported-address-data`. `GET` answers 3.0 unless `Accept` ranks `text/vcard; version=4.0` higher. `address-data` naming properties answers only those, plus `VERSION`, `UID` and `FN`. A `PROPFIND` that names `address-data` carries each card too, at depth 1 for every contact of the address book and at depth 0 for one. * **Depth.** `PROPFIND` answers depth `0` and `1` (also `0,noroot` and `1,noroot`); `infinity` answers `403` with `propfind-finite-depth`. A `PROPFIND` without a `Depth` header is answered as depth `1`, as sabre/dav answers it: RFC 4918 reads a missing header as `infinity`, which would refuse a client that leaves it out. * **Search.** `addressbook-query` matches `prop-filter`, `param-filter` and `text-match` (`equals`, `contains`, `starts-with`, `ends-with`; collations `i;unicode-casemap` by default, `i;ascii-casemap`, `i;octet`; `negate-condition`, `is-not-defined`, `test="anyof|allof"`) against each card's properties, including `X-` properties and grouped ones such as Apple's `item1.EMAIL`. A query without a filter answers every contact, a `limit` lower than the matches answers that many and a `507`. Nothing is indexed: every card is read per query, which suits the few thousand contacts of an address book; the clients search their local copy and rarely send a query. * **Read-only.** Every address book grants `read` and `read-current-user-privilege-set` only, and `PUT`, `DELETE`, `PROPPATCH`, `MKCOL`, `MOVE` and `COPY` answer `403` with `need-privileges`. Thunderbird, DAVx5 and Evolution show the address book as read-only; DAVx5 reverts a local edit at the next sync. On iOS, editing such a contact may show an alert or copy it into the default account, and an account whose address books are all read-only cannot be iOS's default contacts account. ## Groups [#groups] A group is a contact of kind `ContactKind.Group` whose `Members` reference the contacts in it, published like any contact, usually into the same address book: ```csharp await addressBooks.PublishAsync(new CardDavAddress("customers", "all"), new Contact { Uid = $"team-{team.Id}", FormattedName = team.Name, Kind = ContactKind.Group, Members = [.. team.MemberIds.Select(id => ContactMember.FromUid(id.ToString()))], }, ct); ``` The stored card is Apple's form (`X-ADDRESSBOOKSERVER-KIND:group`, `X-ADDRESSBOOKSERVER-MEMBER`); a client asking for vCard 4.0 gets `KIND:group` with `MEMBER`, under the same ETag, and an `addressbook-query` on `KIND` or `MEMBER` finds either form. Apple's Contacts shows groups as groups, which is the only way to show subsets within the one address book it reads per account; DAVx5 does when the account uses "groups are separate vCards", and in its "categories" mode groups by `Categories`, which the application sets on the members if it wants both; Thunderbird shows a group as a plain card. Members are not checked against the address book. A group counts one property per member against `CardDav:ContactRead:MaxPropertiesPerContact` (1,000 by default): publishing a larger one throws until the limit is raised. ## What is not there [#what-is-not-there] Two-way editing, a CardDAV client, vCard feed URLs (no contacts app subscribes to a URL; Outlook and Google Contacts import a `.vcf` file, which `ContactWriter.ToStreamedFile` produces) and Apple's directory gateway. ## Configuration [#configuration] `AddElarionCardDav(configuration)` binds `CardDavOptions` from the `CardDav` section. Contact data uses `Elarion.Contacts`' own options: | Key | Default | | ------------------------------------------------------------------------------------------------------------------ | ---------- | | `CardDav:ContactRead:MaxBytes` (and the other `ContactReadOptions` keys) | `33554432` | | `CardDav:ContactRead:MaxPropertiesPerContact` (also the largest card, so the largest group, that can be published) | `1000` | The store, journal and request limits are `WebDav`'s; see [CalDAV](/docs/capabilities/caldav#configuration). # Device gateways (/docs/capabilities/connections/device-gateway) ## Keepalives and conversations [#keepalives-and-conversations] Two optional pieces cover what every device codec otherwise hand-rolls: * **The idle hook.** Set `IdleTimeout` on any adapter and the codec's `OnIdleAsync` fires per elapsed window without inbound traffic — send the protocol's poll/heartbeat there, or throw to declare the link dead. Default is off; the hook never abandons the pending read. * **Conversation helpers** (in the kernel, use only if they fit): `ConnectionPendingRequests` is the sequence-number → completion map behind a codec's `InvokeAsync` — register the key, send, await the correlated reply with a timeout, `FailAll` on teardown. `SendAndWaitAsync(key, send, …)` is the safe correlation pattern in one call: it registers **before** invoking your send (a fast reply can never race its own registration), and a failed send withdraws its own pending entry — the key is immediately reusable and nothing awaits a reply that can never come. `ConnectionInbox` serves multi-message flows: the receive path `Post`s every parsed message, flow code awaits the next message matching a predicate ("the ready frame or the abort frame"), buffered so a fast reply beats its waiter safely, and `Complete` faults everything when the connection ends. ```csharp internal sealed class DeviceCodec(TcpClientConnection connection) : IClientConnectionProtocol { private readonly ConnectionPendingRequests _pending = new(); public ValueTask OnBinaryAsync(ReadOnlyMemory message, CancellationToken ct) { var frame = DeviceFrame.Parse(message.Span); return _pending.TryComplete(frame.Sequence, frame) ? ValueTask.CompletedTask : HandleUnsolicitedAsync(frame, ct); // telemetry, events, … } public async ValueTask InvokeAsync( string name, TRequest request, ClientInvokeOptions? options, CancellationToken ct) where TRequest : class { var sequence = NextSequence(); // Register-then-send in one call: the sink already resolved the default invoke timeout into // options (a null Timeout here means the invoke is deliberately unbounded), and a send that // faults withdraws its own registration so the sequence number is immediately reusable. var reply = await _pending.SendAndWaitAsync(sequence, sendCt => connection.SendBinaryAsync(DeviceFrame.Encode(sequence, name, request), sendCt), options?.Timeout, ct); return Decode(reply); } public ValueTask OnIdleAsync(CancellationToken ct) => connection.SendBinaryAsync(DeviceFrame.Poll(), ct); // the 60 s keepalive } ``` ## Putting it together — the device-gateway loop [#putting-it-together--the-device-gateway-loop] Connections are deliberately **not a fourth invocation model** — they're a carrier with identity. Actors stay the concurrency gate for device state, handlers stay the authorization gate for anything command-shaped, client events stay the one fan-out. The whole loop, end to end: **Connect/disconnect → the twin.** An observer (the one piece of hand-written glue) routes lifecycle into the digital twin's public facade; the twin marks presence and captures the sink — an actor owning a stateful connection is exactly actor use-case #1, and the mailbox serializes a device's parallel channels against user-triggered commands for free: ```csharp internal sealed class DeviceTwinAttachment(IActorSystem actors) : IClientConnectionObserver { public ValueTask OnConnectedAsync(IClientConnectionSink connection, CancellationToken ct = default) => new(actors.Get(connection.Connection.PrincipalId!).ChannelUp(connection)); public ValueTask OnDisconnectedAsync(ClientConnection connection, CancellationToken ct = default) => new(actors.Get(connection.PrincipalId!).ChannelDown(connection.ConnectionId)); public ValueTask OnIdentityPromotedAsync(ClientConnection previous, ClientConnection current, CancellationToken ct = default) => ValueTask.CompletedTask; // links here authenticate at connect } // services.TryAddEnumerable(ServiceDescriptor.Singleton()); ``` **Inbound frames → the twin, pipeline-free.** Telemetry isn't a command; the codec parses and hands the frame to the mailbox (see the codec examples on the [WebSocket](/docs/capabilities/connections/websocket) and [TCP](/docs/capabilities/connections/tcp) pages). The codec's one routing decision is *which frames are commands* — those go through the dispatch rail instead: ```csharp // Inside a codec, for command-shaped messages: ConnectionHandlerInvoker rides the same per-call scope // rail JSON-RPC and MCP use. Bind it once per connection; every call then runs authorization, // validation, [Idempotent], transaction, and audit per message, evaluated against the connection's // captured identity snapshot (seeded as ICurrentUser by the standard initializer) — a promotion racing // a dispatch affects the next message, never the scope underneath the current one, and adapter // metadata can never overwrite the framework identity entries. var invoker = new ConnectionHandlerInvoker(services, connection); // A request with a self-typed marker (StartCommand : ICommand) infers both // generic arguments; marker-free requests use the explicit InvokeAsync form. var result = await invoker.InvokeAsync(decoded, ct); // encode the result back over the sink — your framing; a failed Result stays a value // Decoded-by-name traffic goes through the filtered named rail instead: only routes exposed with // HandlerTransports.Connection are reachable, and unknown/other-transport names return the same // generic NotFound so exposure is never leaked. var named = await invoker.InvokeNamedAsync(dispatcher, name, decodedRequest, ct); ``` **User → device.** A UI action arrives as a normal `[Handler]` (over HTTP/JSON-RPC — `[RequirePermission]`, ownership check, `[Auditable]`) and calls the twin facade; the twin talks to the device through its captured sink, serialized with everything else in its mailbox: ```csharp [Handler("robots.start")] internal sealed class StartRobot(IActorSystem actors) : IHandler> { public sealed record Command : ICommand { public required Guid RobotId { get; init; } } public async ValueTask> HandleAsync(Command request, CancellationToken ct) => await actors.Get(request.RobotId.ToString("N")).StartAsync(ct); } // inside the twin: one request/reply into the device, bounded by a timeout var ack = await _channel.InvokeAsync( "start", new StartCommand(), new ClientInvokeOptions { Timeout = TimeSpan.FromSeconds(5) }, ct); ``` **Live state → every UI.** The twin publishes client events from its hot state (the ephemeral tier), or projects committed facts via a method-form `[ConsumeEvent]`; SSE browsers and connection-carried subscribers receive identically through the bridge. Durable facts flow as integration events — which can come back *into* actors via `[ConsumeEvent]` on actor methods. The hand-written glue per app is the observer (\~10 lines) and the codec's routing decision; the handshake, registry, lifecycle, per-message scopes, mailbox, and fan-out are all framework. For the hot-path allocation profile of this loop, see [Low-allocation dispatch](/docs/capabilities/connections/low-allocation). # Client connections (/docs/capabilities/connections) Most realtime needs don't need a connection. A deferred response to one request is [request-driven streaming](/docs/capabilities/transports/server-streaming); server→client facts are [client events](/docs/capabilities/events/client-events); and producer-owned ordered outputs are [streams](/docs/capabilities/events/streams). A **connection** is a stateful, bidirectional carrier for the cases those deliberately don't cover — when the conversation itself is stateful or latency-interactive. It does not add replay, ordering, or delivery guarantees to the contract it carries: 1. **Interactive rate** — client→server messages are frequent *and* per-message latency is part of the UX (collaboration ops, live input, telemetry ingest where batching's flush window is itself too slow). 2. **The connection is the state** — device links where connect/disconnect are business events, or the link fronts a stateful device protocol (the IoT gateway shape). 3. **Server→client RPC** — the server must address one specific connected client and await a result. If a list-carrying batch command flushed every N items or M milliseconds would do, use that instead: one authorization, one validation pass, one transaction per batch, visible in the schema. ## In this section [#in-this-section] The ASP.NET Core adapter — authenticator, codec, per-connection settings. Raw-socket listeners and dialers — framing, TLS, backpressure, deterministic close. Keepalives, codec conversations, and the full device-gateway loop with actors. Socket-less simulated connections, in-memory TCP links, and the WebSocket test host. The opt-in profile (ADR-0066) that takes a dispatched message to 0 B/op. ## The kernel [#the-kernel] `Elarion.Connections` (contracts in `Elarion.Abstractions.Connections`) is transport-neutral — the same seams serve a WebSocket adapter today and a raw TCP or datagram adapter tomorrow, and nothing in them assumes a socket exists at all: | Piece | Role | | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ClientConnection` | Stable connection facts (`ConnectionId`, `Transport`, `ConnectedAt`) plus the current **immutable, revisioned identity snapshot**: principal, `PrincipalId` (user id for browsers, **device id for device links** — many connections share one principal), bounded opaque `Metadata`. Capture the snapshot once at an operation boundary. | | `IClientConnectionRegistry` | Node-local index and lifecycle broker: adapters register/unregister; consumers look up by id or principal; `PromoteAsync` performs the one-way anonymous → authenticated identity promotion. Observers run after the index mutation and are failure-isolated. | | `IClientConnectionObserver` | Connect/disconnect/identity-promotion lifecycle seam — presence projections, device registration, twin wiring hang here. | | `IClientConnectionSink` | The per-connection outbound port: fire-and-forget `SendAsync(name, payload)` and request/reply `InvokeAsync` (completes with the reply, a timeout, or `ClientConnectionClosedException` — never silently). | | `IClientConnectionProtocol` | The app-owned **codec**: complete inbound messages arrive sequentially in receive order; the sink's outbound legs delegate here so wire encoding stays the codec's decision. Legs a codec doesn't speak keep fail-loud defaults. | | `ClientConnectionEventBridge` | Makes any adapter a peer delivery leg of the SSE endpoint: same topic catalog, same fail-closed subscribe-time authorization, same `elarion.connected` greeting, same cross-node fan-out. | Register the kernel once: ```csharp builder.Services.AddElarionConnections(); // registry + client-events bridge ``` ## Identity promotion (anonymous → authenticated) [#identity-promotion-anonymous--authenticated] A connection may register **anonymously** — the shape of device protocols whose authentication is a framed exchange after connect rather than a connect-time credential — and later perform **exactly one atomic, one-way promotion** to an authenticated identity: ```csharp var status = await registry.PromoteAsync(connection.Connection.ConnectionId, new ClientConnectionIdentity { Principal = principal, PrincipalId = deviceId, Metadata = new Dictionary { ["firmware"] = version }, }, ct); // Promoted | AlreadyAuthenticated | ConnectionNotFound — demotion and user switching are rejected. ``` The rules are deliberate and security-shaped: * **Stable facts never change** (`ConnectionId`, `Transport`, `ConnectedAt`); the principal, principal id, metadata, and revision are replaced **together** as one immutable snapshot. Inputs are cloned and metadata is defensively copied and bounded — mutating what you passed in cannot alter stored identity. * Only anonymous/no-id → authenticated/non-empty-id is accepted, **exactly once** — concurrent promoters get one winner; demotion and principal switching are rejected as `AlreadyAuthenticated`. * **An in-flight dispatch keeps the snapshot it captured** at its boundary; the next dispatch observes the promoted snapshot. A failed validation or a lost race leaves the prior snapshot and revision intact; a promotion observer failure is isolated and never rolls the identity back. * **Client-event subscriptions are disposed on promotion** — the peer must resubscribe so subscribe-time authorization is reevaluated under the new identity. Observers implementing `OnIdentityPromotedAsync(previous, current, …)` see both snapshots; disconnect observers and the codec's `OnClosedAsync` always receive the final (latest) snapshot. ## Talking back to one client [#talking-back-to-one-client] Look a connection up and use its sink — from a handler, an observer, or an actor turn: ```csharp // All channels of one device (or all tabs of one user): foreach (var sink in registry.GetForPrincipal(deviceId)) { await ((WebSocketClientConnection)sink).SendTextAsync(frame, ct); // raw leg, codec-owned format } // Request/reply into a client whose codec implements InvokeAsync: var status = await sink.InvokeAsync( "status.get", new StatusQuery(), new ClientInvokeOptions { Timeout = TimeSpan.FromSeconds(5) }, ct); ``` `InvokeAsync` is deliberately the *simple* tier — one request, one reply, bounded by a timeout. Multi-message protocol conversations (sequence numbers, re-synchronisation, wait-for-any flows) are codec/actor state; the codec seam is their mounting point, not their replacement — see [device gateways](/docs/capabilities/connections/device-gateway). Every invoke is **bounded by default**: a call that carries no `ClientInvokeOptions.Timeout` gets the kernel's `DefaultInvokeTimeout` (30 s out of the box; `AddElarionConnections(o => o.DefaultInvokeTimeout = …)`), resolved by the sink before the codec sees the options — a client that never answers surfaces as a `TimeoutException`, never a silently hung await. The layering is per-call `Timeout` > `DefaultInvokeTimeout` > unbounded: a per-call value always wins (pass `Timeout.InfiniteTimeSpan` to make a single call unbounded), and only a default explicitly configured to `null` applies none. ## Client events over a connection [#client-events-over-a-connection] A connection can serve the same topics the SSE endpoint serves — same catalog, same fail-closed authorization, so a second transport can never fork the rules. The adapter parses its subscribe frame and hands the requests to the bridge; delivery framing is the adapter's choice: ```csharp var result = await bridge.SubscribeAsync(connection, requests, (envelope, ct) => connection.SendTextAsync($"event:{envelope.Topic}:{envelope.Payload}", ct), ct); ``` Delivery starts with the `elarion.connected` greeting (the same re-query contract an SSE stream opens with), and the subscription dies automatically when its connection unregisters. Statuses mirror the SSE endpoint's HTTP mapping (unauthenticated / invalid / not-found — unknown and denied topics stay indistinguishable). ## Rules of the road [#rules-of-the-road] * **Facts still travel as client events**, even over a connection — the sink is for conversation-shaped traffic (replies, control frames, RPC), not a side channel for state fan-out. * **Guarantees are unchanged**: events are at-most-once hints healed by re-query; sends are at-most-once; `InvokeAsync` faults explicitly. Commands a device may retransmit belong behind [`[Idempotent]`](/docs/concepts/idempotency). * **One device, many connections**: give every channel the same `PrincipalId` and let a [digital-twin actor](/docs/concepts/actors) keyed by device id serialize the shared state — per-connection ordering comes from the receive loop, cross-channel consistency from the actor. * **The registry is node-local by design.** Multi-node deployments co-locate device ingress with the single-homed twin (the role-holder proxy's prefix list); a replicated connection directory is the point where you adopt a clustered runtime instead. * **Telemetry**: register the `Elarion.Connections` meter — `connection.active`, `connection.opened`/`connection.closed` (tagged `elarion.connection.transport`), `connection.identity_promotions` (tagged `elarion.connection.promotion.outcome`), and `connection.event_subscriptions.active` — and, for TCP endpoints, `Elarion.Connections.Tcp`: `elarion.tcp.tls.handshake.duration` (seconds, tagged `elarion.tcp.tls.outcome`), `elarion.tcp.connection.failures` (bounded `elarion.tcp.failure.stage`), `elarion.tcp.connection.closed` (`elarion.tcp.close.mode` = `graceful`/`forced`), `elarion.tcp.outbound.pending`/`elarion.tcp.outbound.saturated`, and `elarion.tcp.idle`. Tags are fixed vocabularies only — never connection/principal ids, payloads, endpoints, operation names, or certificate data. # Low-allocation dispatch (/docs/capabilities/connections/low-allocation) A game-server-like transport — thousands of connections, each producing frequent small messages — pays for a fresh DI scope, a rebuilt decorator chain, and a context dictionary on every message. The opt-in low-allocation profile (ADR-0066) keeps the full pipeline semantics and removes the steady-state garbage. Each row below is one allocation source on the default path, the opt-in that removes it, and why that opt-in is the right lever: | Per-message allocation (default path) | Removed by | Why this lever | | -------------------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | DI scope + initializer run + `DispatchScopeContext` dictionary | `ScopeMode = PerConnection` | The scope, the initializer list, and one reusable context are per-*connection* state; re-seeding per message keeps identity promotion observable. | | Decorator chain rebuilt per resolution | `ScopeMode = PerConnection` | The chain is a scoped registration — one reused scope means one build per connection, plus an invoker-side cache that skips DI lookup per message. | | Handler scope participation | `[Handler(Scope = ServiceScope.Singleton)]` | An all-singleton-dependency handler needs no scope at all; the compile-time check (ELSG011–013) makes a captive scoped dependency unshippable. | | Enrichment context + tags + log scope (\~300 B) | `[HandlerTelemetry(HandlerTelemetryMode.None)]` | Enrichment is **not** listener-gated: its consumers are the log scope and the ambient transport span, so it runs whenever enrichers are registered (current-user support registers one by default) — and that is correct, because handler log lines should carry user context. Since virtually every host has logging configured, the honest lever for a hot handler is not a runtime gate but not generating the decorator at all. Spans and metrics were already free without listeners. | | Outbound payload buffer per send | writer-based `SendBinaryAsync` | The caller serializes into the connection's pooled framed buffer instead of materializing a payload to copy from. | | Inbound payload copy per message (WebSocket) | nothing to opt into | Fixed unconditionally: both adapters now hand `OnBinaryAsync` a call-scoped slice of a pooled per-connection buffer — the contract that always applied. | | Struct request boxed by the marker overload | explicit-generic `InvokeAsync` | C# cannot infer both generics from a constraint, so the inferred overload takes the marker interface — a hot `readonly record struct` request calls the explicit form and stays unboxed. | | Async state machines on suspension | nothing to opt into | Hot framework paths use pooled async method builders unconditionally. | Each piece stands alone and composes: **Per-connection dispatch scope.** Choose the scope mode per connection at invoker construction — never globally (`ConnectionHandlerInvoker` is introduced on the [device-gateway page](/docs/capabilities/connections/device-gateway)): ```csharp var invoker = new ConnectionHandlerInvoker(services, connection, new ConnectionHandlerInvokerOptions { ScopeMode = ConnectionDispatchScopeMode.PerConnection }); // ... dispatch as usual; then, when the connection closes: await invoker.DisposeAsync(); ``` One DI scope is created lazily on first dispatch and reused for every unary and named message; the composed handler chain is resolved once per request type and cached; one reusable context is refilled per message. Scope initializers still run per message, so **identity promotion is observed by the very next message**. The trade: scoped services live for the *connection's* lifetime — a pipeline that assumes per-message scoping (the transaction decorator's unit of work, idempotency) keeps its state across every message, and the invoker warns once per handler type when such a pipeline is dispatched in this mode. Dispatch must stay sequential (the adapter's receive loop already is), and the owner that constructed the invoker must dispose it on close. Streams keep their own scope in both modes. **Singleton handlers and telemetry opt-down.** Declare them on the handler (or the module/assembly for telemetry) — see [handlers](/docs/concepts/handlers): `[Handler(Scope = ServiceScope.Singleton)]` removes scope participation entirely (compile-time verified, `ELSG011`–`ELSG013`), and `[HandlerTelemetry(HandlerTelemetryMode.None)]` removes the observability decorator from the generated chain. **Writer-based sends.** `SendBinaryAsync(ReadOnlyMemory)` forces one materialized buffer per outbound message; the writer-based overload serializes the payload directly into the framed outbound buffer instead: ```csharp await connection.SendBinaryAsync(reply, static (reply, output) => { // serialize straight into the framed output — no per-message payload buffer MessagePackSerializer.Serialize(output, reply); }, ct); ``` Admission, backpressure (`MaxPendingSends`), oversize handling, and completed-send meaning are identical to the memory-based overload. The callback runs synchronously exactly once; a throwing callback (or a payload the framer rejects) faults only that send. `BeginMessage`/`CompleteMessage` (reserve/backfill the prologue) is the framer's only abstract emit path — every send route, including the base `WriteMessage` convenience, frames through it, so framing logic exists once. `CompleteMessage` receives the payload as a writable span, so a framer carrying negotiated cipher state can apply a same-length in-place transform — encrypt the serialized payload where it lies and backfill the tag into the prologue. **Inbound buffers are pooled and call-scoped** on every adapter: TCP and WebSocket both hand `OnBinaryAsync` a slice of a reused per-connection buffer that the next read overwrites. Copy the memory if the codec defers work — retaining it is a use-after-reuse bug. With the full profile — per-connection scope, singleton handler, telemetry `None`, writer sends — a dispatched message allocates **nothing** in steady state (the allocation gate in the test suite enforces 0 B/op), and the pipeline — decorators, `Result`, typed dispatch — is still the one every other transport runs. Simulation-rate traffic (tens of messages per second per connection for movement) still belongs outside the pipeline in actors or tick loops. # TCP endpoints (/docs/capabilities/connections/tcp) `Elarion.Connections.Tcp` runs the same handler/codec seams over raw sockets (BCL only, no ASP.NET) — the shape for devices that speak a proprietary protocol and can't do WebSockets. Because TCP has no message boundaries, the adapter owns a **framing seam** — and framing is boundaries only: pick `LengthPrefixedTcpFramer`, `DelimitedTcpFramer` (line/telegram framing — an optional start delimiter skips serial-bridge line noise), or implement `TcpMessageFramer` for the vendor's format. Bytes are bytes on TCP, so every inbound message reaches the codec's `OnBinaryAsync` as a raw slice; a text protocol's codec decodes with one `Encoding.UTF8.GetString` — the string is paid for only where it is wanted. The pipeline is benchmarked at **raw-socket parity** in both directions — receive (framer slice → codec) and send (`SendBinaryAsync` frames into a pooled, budget-capped per-connection buffer that is trimmed after oversized frames, so a proxy that forwards between links stays allocation-light and never retains its largest frame) — and an armed-but-quiet idle window costs nothing on the hot path. Sockets default to `NoDelay` (Nagle stalls serial request/reply telegrams); override per endpoint or per connection for bulk one-way streams. ## Custom framers [#custom-framers] When you implement `TcpMessageFramer` for a vendor format, the contract is **payload only on both sides** — the framer owns the header/prefix/delimiter, the codec never sees or supplies it: * `TryReadMessage` reports `consumed` = the *whole* wire span it advances past (reserved prologue + payload * any trailer), but hands back `message` = the **payload slice alone**. Don't subtract the header length from `message` — it already excludes the header; `consumed` is what accounts for it. A transforming framer (a negotiated cipher) returns the decoded payload from its own buffer instead of a slice. * Outbound there is **one emit path**: `BeginMessage` emits/reserves the frame's prologue and returns its length; the payload is then serialized in place; `CompleteMessage` backfills the prologue (length, checksum, auth tag), may transform the payload in place (same length), and appends any epilogue. The base class provides `WriteMessage(payload, output)` as a convenience over the same pair — framing and any cipher logic are written exactly once. ```csharp // A 2-byte reserved prologue (e.g. a type tag) before the body: public sealed class VendorFramer : TcpMessageFramer { private const int Prologue = 2; public override bool TryReadMessage(ReadOnlyMemory buffer, out int consumed, out ReadOnlyMemory message) { consumed = 0; message = default; if (buffer.Length < Prologue + BodyLength) return false; // need more bytes consumed = Prologue + BodyLength; // advance past prologue AND body message = buffer.Slice(Prologue, BodyLength); // payload only — prologue excluded return true; } public override int BeginMessage(IBufferWriter output) { ReserveProlog(output); // emit or zero-reserve the prologue... return Prologue; // ...and report its length for the backfill } public override void CompleteMessage(Span prologue, Span payload, IBufferWriter output) { FillProlog(prologue, payload); // the payload is serialized — backfill length/type/checksum } } ``` `LengthPrefixedTcpFramer` is the shipped reference for exactly this shape (4-byte length prefix as the prologue, backfilled in `CompleteMessage`). The codec's `OnBinaryAsync` then receives that payload slice — never the framing bytes. **Establishment order is fixed**: raw TCP → optional TLS → framer → framed application authentication → registration → `OnOpenedAsync` → messages. Frame limits count **total unconsumed wire bytes** — prefix, variable header, body, and trailer included — so `MaxInboundFrameBytes` bounds what a peer can make the endpoint buffer before a single message completes, and `MaxOutboundFrameBytes` bounds what a codec can frame outward; both are validated before allocation and apply to the handshake too. Shared endpoint framers must be stateless and thread-safe; a framer carrying negotiated state is created per connection by the session and returned via `Settings`. ## Sessions [#sessions] The handler you register is a **factory**: `CreateSessionAsync(peer, ct)` runs before any byte is exchanged, does the binding-configuration lookup (or rejects the link by returning `null` — the socket closes, nothing is registered), and creates one `TcpConnectionSession` for the connection. The session owns everything per-connection: its `Settings` override the endpoint options (and its framer governs the handshake itself), `AuthenticateAsync` runs the framed handshake, and `CreateProtocol` builds the codec. Per-connection state — the binding row, a stateful framer, key material derived during authentication — lives in typed session fields and flows into the codec's constructor; the handler stays a stateless singleton serving every connection concurrently. ## Negotiated framing state (encryption toggles) [#negotiated-framing-state-encryption-toggles] A session's framer may carry **negotiated state** — the classic case is a protocol whose handshake derives a session key and then switches the link into encrypted framing. The session creates the framer, returns it through `Settings`, and hands it (typed) to the codec it creates; the codec flips the state at the exact protocol point the wire format defines: ```csharp sealed class CipherSession : TcpConnectionSession { private readonly CipherFramer _framer = new(); public override TcpConnectionSettings? Settings => new() { Framer = _framer }; public override ValueTask AuthenticateAsync( TcpHandshakeContext handshake, CancellationToken ct) { /* challenge/response */ } public override IClientConnectionProtocol CreateProtocol(TcpClientConnection connection) => new CipherProtocol(connection, _framer); } // In the codec: public async ValueTask OnBinaryAsync(ReadOnlyMemory message, CancellationToken ct) { if (TryCompleteKeyExchange(message, out var sessionKey, out var reply)) { // A completed send means the frame was physically written, so awaiting the plaintext // mode-switch reply puts the flip exactly between it and the next outbound frame. await connection.SendBinaryAsync(reply, ct); framer.EnableEncryption(sessionKey); return; } // ... normal dispatch } ``` The adapter does not synchronize framer state: mutate inbound-affecting state only on the codec's inbound path (it runs on the receive loop, so no read is in flight) and outbound-affecting state only after the mode-switch send completed with no concurrent sends admitted. Two contract points make a cipher framer implementable: `TryReadMessage` may return **framer-owned memory** (the decrypted payload from the framer's own buffer — a slice of the receive buffer is impossible once bytes are transformed), and `CompleteMessage` receives the payload as a **writable span** for same-length in-place transforms — encrypt the serialized payload where it lies and backfill the tag into the reserved prologue. Because `WriteMessage` is a convenience over the same pair, the cipher is written once and applies on every send route. In simulated links, give the client side its own framer instance (`InMemoryTcpLink.Start(…, clientFramer: new CipherFramer())`) — the two ends of a real link never share framing state. ## Listeners and dialers [#listeners-and-dialers] ```csharp // Devices dial in: builder.Services.AddElarionTcpConnectionListener(o => { o.ListenEndPoint = new IPEndPoint(IPAddress.Any, 7010); o.Framer = new DelimitedTcpFramer(end: (byte)'>', start: (byte)'<'); o.IdleTimeout = TimeSpan.FromSeconds(60); }); // Or the gateway dials the device and keeps the link alive (jittered exponential reconnect): builder.Services.AddElarionTcpConnectionDialer(o => { o.Host = "10.0.40.17"; o.Port = 2101; o.Framer = new LengthPrefixedTcpFramer(); }); ``` Each `Add…` call is one endpoint — listen on several ports (one per device channel type) or dial several devices, each with its own handler, framer, and options. The handler subclasses `TcpConnectionHandler` and creates one session per link; device protocols with no credential exchange ticket straight from what the handler's binding-configuration lookup handed the session (which port, which peer). ## Runtime endpoint management [#runtime-endpoint-management] Bindings that live as **data** (an admin configures which device is dialed or listened for, on which port, with which framing) use the runtime manager instead of composition-time registrations: add `AddElarionTcpConnectionEndpoints()` and apply named endpoints whenever configuration changes — `Apply…` is an upsert that tears the old endpoint down first, so **changing a binding means a reconnect under the new settings**, including flipping its direction: ```csharp var endpoints = provider.GetRequiredService(); // Startup: apply every binding row; on admin change: re-apply just that row. await endpoints.ApplyDialerAsync("device-7:mgmt", o => { o.Host = row.Host; o.Port = row.Port; o.Framer = row.Protocol == "telegram" ? telegramFramer : new LengthPrefixedTcpFramer(); }, ct); // The same binding later becomes server-based (the device now dials us): await endpoints.ApplyListenerAsync("device-7:mgmt", o => { o.ListenEndPoint = new IPEndPoint(IPAddress.Any, row.Port); o.Framer = telegramFramer; }, ct); await endpoints.RemoveAsync("device-7:mgmt", ct); // unbind: connections unregister ``` Every managed endpoint **advertises its binding health**: `endpoints.Statuses` / `GetStatus(name)` answer "which bindings are serving, which failed to bind, and why" — a listener whose port couldn't be bound is `Faulted` with the reason; a dialer between attempts is `Dialing` carrying the last failure — and `endpoints.StatusChanged` fires on every transition, ready to be projected onto a client event so an admin UI shows binding state live. Settings can also vary **per connection on one endpoint**: the session's `Settings` returns `TcpConnectionSettings` (framer, size caps, send capacity, TLS policy, idle window, transport tag — nulls inherit the endpoint options). `CreateSessionAsync` runs before any byte is exchanged, so a binding-configuration lookup keyed on the peer can pick the wire framing — or the TLS certificate — that governs the handshake itself — the shape gateways need when differently-speaking device families share one ingress port. ## TLS [#tls] Set `Tls` on any TCP endpoint (or per connection) and the adapter authenticates the stream **before the framer, the application authenticator, the registry, or any observer sees a byte** — a TLS failure rejects the socket with nothing registered, and a TLS-configured dialer never falls back to plaintext. Policy stays explicit BCL configuration (`SslServerAuthenticationOptions` / `SslClientAuthenticationOptions`, minted **fresh per connection**); platform certificate validation is fail-closed and Elarion never bypasses it — a development bypass is test configuration, not a production convenience. The recommended server setup: ```csharp builder.Services.AddElarionTcpConnectionListener(o => { o.ListenEndPoint = new IPEndPoint(IPAddress.Any, 7010); o.Framer = new LengthPrefixedTcpFramer(); o.Tls = new TcpServerTlsOptions { CreateAuthenticationOptionsAsync = (peer, ct) => ValueTask.FromResult( new SslServerAuthenticationOptions { ServerCertificate = gatewayCertificate }), }; }); // Dialer side: TargetHost names the certificate identity this binding expects. builder.Services.AddElarionTcpConnectionDialer(o => { o.Host = "10.0.40.17"; o.Port = 2101; o.Framer = new LengthPrefixedTcpFramer(); o.Tls = new TcpClientTlsOptions { CreateAuthenticationOptionsAsync = (peer, ct) => ValueTask.FromResult( new SslClientAuthenticationOptions { TargetHost = "device-7.gateway.internal" }), }; }); ``` `TcpTlsOptions.HandshakeTimeout` (10 s default) bounds the TLS exchange separately from the framed application `HandshakeTimeout` that follows it. ## Outbound backpressure and send completion [#outbound-backpressure-and-send-completion] Each connection's outbound leg is a **bounded FIFO pipeline**: up to `MaxPendingSends` (256 default) sends may be admitted at once — queued *plus* in-progress — and at capacity a send fails immediately with `TcpSendQueueFullException` before any frame memory is allocated. Admitted sends are never silently dropped; saturation is always that deterministic fault, so a slow device produces visible backpressure instead of an unbounded waiter population. A send that **completes** means its complete frame was physically written to the stream — never merely queued. Under contention the drainer **coalesces queued frames into one physical write** (up to a 64 KiB flush threshold): FIFO order is unchanged, syscalls amortize, and over TLS a batch costs one record instead of one per frame — the uncontended send stays inline and allocation-free at raw-socket parity. Cancellation before a frame is picked up withdraws it (nothing is emitted, the slot frees); a frame the drainer has already activated completes regardless (the batch write is connection-owned — like bytes already on the wire); cancellation or an I/O failure *during* an inline physical write aborts the connection, because a partial frame may have corrupted stream boundaries — at-most-once covers loss, never corruption. ## Deterministic close and endpoint shutdown [#deterministic-close-and-endpoint-shutdown] One internal lifetime controller owns every connection's `Open → Closing → Closed` transition: peer EOF, `CloseAsync`, codec failures, endpoint reconfiguration, and host shutdown all funnel into one first-reason-wins close that quiesces I/O, settles every admitted send exactly once (drain on a clean close, fault on failure), runs the codec's `OnClosedAsync` once with the first reason and the latest identity, unregisters once, and disposes the transport once. Endpoint stop — hosted shutdown, `RemoveAsync`, or a reconfiguring `Apply…` — stops accepting/redialing, requests graceful close everywhere, waits the endpoint's `ShutdownGracePeriod` (5 s default), force-aborts the stragglers' raw transports, and then **awaits every connection task**: no connection is ever silently abandoned, and the registry holds none of the endpoint's connections when stop returns. # Simulation & testing (/docs/capabilities/connections/testing) `Elarion.Connections.Simulation` ships the pieces every gateway test suite — and every runnable dev/demo device simulator — otherwise hand-rolls. `SimulatedClientConnection` is an in-memory sink double — register it with the real registry and drive twins, observers, and presence logic deterministically: await its `Sent` channel for outbound messages, answer `InvokeAsync` via `InvokeResponder`, and `Close()` it to assert your code survives `ClientConnectionClosedException`. `AwaitableConnectionObserver` turns lifecycle edges into awaitable completions (with `Reset()` for reconnect scenarios). `TcpSimulatorClient` is the framed client for simulated devices/peers: connect it to a listener (or wrap the accepted side of a fake device an Elarion dialer reached) and speak whole messages through the endpoint's own framer, with text helpers for challenge/response handshakes. The default for codec/handler-level work is **fully in-memory** — no OS sockets, ports, or firewall prompts: `InMemoryTcpLink.Start(handler, registry, o => o.Framer = …)` runs the complete connection lifecycle (per-connection sessions, handshake, framing, registry, codec, idle hook) over an in-memory duplex pair, hands you the simulator-side `Client`, a deterministic `ServerConnection` await (the registered sink — no polling, no handshake races), and a `ServerCompletion` for teardown assertions. By default the client speaks the endpoint framer instance (fine for stateless framers); when the handler's sessions create a **stateful** framer (negotiated framing, encryption toggles), pass the client its **own** instance via the `clientFramer` parameter — the two ends of a real link never share framing state. Reserve real sockets (loopback TCP, Kestrel + `ClientWebSocket`) for integration tests of the adapters themselves — the separate `Elarion.Connections.AspNetCore.Simulation` package's `WebSocketTestHost` covers a real Kestrel upgrade, handshake, codec, and close path. `InMemoryDuplexStream.CreatePair()` is public for anything else that wants a socket pair without the socket. # WebSocket endpoint (/docs/capabilities/connections/websocket) `Elarion.Connections.AspNetCore` ships the first adapter, shaped for device gateways: the endpoint owns accept, message reassembly (size-capped), registry lifecycle, and teardown; the app supplies an **authenticator** and a **codec** by subclassing `WebSocketConnectionHandler`. For device links, the provisioning chain behind the authenticator — pairing codes, per-device keys, the HMAC challenge/response — is [device identity](/docs/capabilities/devices) (`Elarion.Devices`). ```csharp // HmacChallengeVerifier + DevicePrincipal come from Elarion.Devices — pairing codes, key storage, // and the constant-time verification are covered on the device identity page. The handler is a // factory: it creates one session per upgrade request; per-connection state lives on the session. public sealed class GatewaySocketHandler(IActorSystem actors, HmacChallengeVerifier verifier) : WebSocketConnectionHandler { public override ValueTask CreateSessionAsync( HttpContext context, CancellationToken ct) { return ValueTask.FromResult(new GatewaySession(actors, verifier)); } } public sealed class GatewaySession(IActorSystem actors, HmacChallengeVerifier verifier) : WebSocketConnectionSession { // In-socket challenge/response (HTTP-level token auth works too — the HttpContext is available). public override async ValueTask AuthenticateAsync( WebSocketHandshakeContext handshake, CancellationToken ct) { var nonce = HmacChallengeVerifier.CreateNonce(); await handshake.SendTextAsync($"challenge:{Convert.ToBase64String(nonce)}", ct); var answer = await handshake.ReceiveTextAsync(ct); // "deviceId:base64(mac)" if (answer?.Split(':', 2) is not [var deviceId, var mac]) { return null; // → PolicyViolation close, nothing registered } var principal = await verifier.VerifyAsync(deviceId, nonce, Convert.FromBase64String(mac), ct); if (principal is null) { return null; } return new ClientConnectionTicket { Principal = principal, PrincipalId = deviceId, // the registry indexes by this Metadata = new Dictionary { ["channel"] = "telemetry" }, }; } public override IClientConnectionProtocol CreateProtocol(WebSocketClientConnection connection) => new GatewayCodec(connection, actors); } // The codec: parse the device's frames, route into the digital-twin actor, answer over raw sends. internal sealed class GatewayCodec(WebSocketClientConnection connection, IActorSystem actors) : IClientConnectionProtocol { public async ValueTask OnTextAsync(string message, CancellationToken ct) { var frame = GatewayFrame.Parse(message); // your wire format var twin = actors.Get(connection.Connection.PrincipalId!); await twin.ApplyAsync(frame); // the actor serializes all channels + UI actions } } ``` ```csharp builder.Services.AddSingleton(); var app = builder.Build(); app.UseWebSockets(); app.MapElarionConnectionSocket("/gateway/ws", o => o.MaxMessageBytes = 64 * 1024); ``` A browser attaches its cookies to a WebSocket handshake from any site, and the Same-Origin Policy does not apply to the socket. When browser clients authenticate the handshake with a cookie (rather than a token sent in the socket, as devices do), install `app.UseElarionCrossOriginProtection()` before `UseWebSockets()`: it refuses a cross-site handshake with `403` and lets devices that send no `Origin` through — see [CSRF and cookie authentication](/docs/capabilities/hosting#csrf-and-cookie-authentication). Everything after the handshake is framework: the connection is minted (v7 id, `Transport = "websocket"`), registered, observed, pumped, and unregistered on every exit path — client close, abrupt death, oversized message (`MessageTooBig`), codec exception (logged, closed), host shutdown. ## Required opening work [#required-opening-work] `IClientConnectionObserver.OnConnectedAsync` remains best-effort: observers are deliberately failure-isolated and suit presence/client-event projections. A codec that cannot process frames until it has completed required work (for example, attaching the authenticated link to a keyed device actor) implements `IClientConnectionProtocol.OnOpenedAsync`. It runs exactly once **after registry registration and observer visibility, before the first inbound frame**. It is awaited; a failure or cancellation closes the link, calls `OnClosedAsync`, and unregisters it without delivering a frame. For tests, choose the lowest faithful tier: `SimulatedClientConnection` for kernel/observer work, `InMemoryTcpLink` (or loopback TCP) for a framed TCP lifecycle, and the separate `Elarion.Connections.AspNetCore.Simulation` package's `WebSocketTestHost` for a real Kestrel upgrade, handshake, codec, and close path — see [Simulation & testing](/docs/capabilities/connections/testing). ## Per-connection settings and bindings [#per-connection-settings-and-bindings] Settings can vary **per connection on one route**: `CreateSessionAsync(HttpContext, …)` resolves the binding configuration from the upgrade request (route values, query, headers) before the socket is accepted, and the session's `Settings` returns `WebSocketConnectionSettings` (size cap, idle window, keep-alive interval, transport tag — nulls inherit the endpoint options). And where the [TCP adapter](/docs/capabilities/connections/tcp) needs a runtime endpoint manager (ports are OS resources), WebSocket **bindings-as-data are just routing**: map one wildcard route (`/gateway/{binding}/ws`) and let `CreateSessionAsync` consult the binding row per connection — an unknown or disabled binding returns `null` and the request is rejected with `403` before the socket is even accepted; a changed binding takes effect the next time the device connects (close its current connections via the registry to force it). # Contacts (/docs/capabilities/contacts) People export their address book from a phone, Apple Contacts, Google Contacts, Outlook, Thunderbird or Nextcloud and upload it; an application hands its contacts out as a file those programs import. `Elarion.Contacts` reads and writes those `.vcf` files. It reads vCard 2.1, 3.0 and 4.0, and files that mix them, with the quirks each producer has; it writes vCard 3.0 or 4.0. It has no reflection and no third-party library, so an application that reads and writes vCards still publishes with NativeAOT. | Piece | Role | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Contact` | The fixed model: names, organization, title, phone numbers, e-mail, postal and web addresses with their types and labels, birthday, anniversary, note, categories, photo, UID, and every property it does not map. | | `ContactProperty` | One property as the file states it: the lossless layer under a contact. | | `ContactReader` | Reads a `.vcf` stream into a `ContactReadResult`: every vCard as an entry, every problem as a coded, located error. | | `ContactWriter` | Writes contacts forward-only to a stream, an `ElarionFile` or an `ElarionStreamedFile`. | | `ContactOptions` | The read limits and the fallback encoding, bound from configuration. | Why it is shaped this way, and what was rejected, is in [ADR-0110](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0110-vcard-contacts.md). The package follows the [file-format design](https://github.com/swimmesberger/Elarion/blob/main/.github/instructions/framework.instructions.md#file-formats-import-and-export) `Elarion.Spreadsheets` set: read results, codes, `ToAppError` and file tiers work the same way. ## Getting started [#getting-started] ### Reference the package [#reference-the-package] ```bash dotnet add package Elarion.Contacts ``` It depends on `Elarion.Abstractions` and the `Microsoft.Extensions` abstractions only. ### Register the reader [#register-the-reader] ```csharp builder.Services.AddElarionContacts(builder.Configuration.GetSection(ContactOptions.SectionName)); ``` `AddElarionContacts` registers `ContactReader` as a singleton and binds `ContactOptions` with the configuration-binding source generator. The writer needs no registration. ## The contact model [#the-contact-model] A vCard is a list of properties. The package keeps that list, and offers `Contact` as a view over it: the fields every address book has, in one shape for reading and writing. The application maps a contact to its own entity in plain code, where "which of three phone numbers is the mobile one" belongs. An application whose own entity is also called `Contact` aliases one of the two (`using VContact = Elarion.Contacts.Contact;`). | Member | From | | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `FormattedName`, `Name` (family, given, additional, prefix, suffix), `Nicknames` | `FN`, `N`, `NICKNAME` | | `Kind` (individual, organization or group) | `KIND:org`, Apple's `X-ABShowAs:COMPANY`; `KIND:group`, Apple's `X-ADDRESSBOOKSERVER-KIND:group` | | `Members` (a group's member references, in order) | `MEMBER`, Apple's `X-ADDRESSBOOKSERVER-MEMBER`; `ContactMember.FromUid(uid)` builds `urn:uuid:{uid}` | | `Organization`, `Department`, `Title`, `Role` | the first two components of `ORG`, `TITLE`, `ROLE` | | `Phones`, `Emails`, `Addresses`, `Urls` | `TEL`, `EMAIL`, `ADR` (seven components), `URL`, each with `Types`, `Preferred` and `Label`, and the `LineNumber` and `Group` it was read from | | `Birthday`, `Anniversary` | `BDAY`; `ANNIVERSARY`, `X-ANNIVERSARY`, `X-MS-ANNIVERSARY` or an Apple `X-ABDATE` labelled as one, in that order | | `Note`, `Categories`, `Photo`, `Uid` | the first `NOTE`, `CATEGORIES`, the first `PHOTO` that reads, `UID` | | `AdditionalProperties` | every other property, with its group, parameters and value, written back as it was read | | `DisplayName` | the formatted name, else the name, else the organization, else the first e-mail address, else the first phone number | `ContactTypes` is a set of flags (`Home`, `Work`, `Cell`, `Voice`, `Fax`, `Pager`, `Text`, `Video`, `Main`, `Internet`), read from `TYPE` parameters, bare vCard 2.1 parameters (`TEL;WORK;VOICE`) and Apple's `_$!!$_`-style labels. Any other label of an Apple `itemN.X-ABLabel` is the value's `Label`. `ContactDate` is a day of a month with an optional year: `--MMDD` and Apple's year 1604 read as a date without a year. Several values of one `N` component are joined with `", "`: `N:Huber;Anna,Maria` reads the given name `Anna, Maria`. Equality is structural and ignores where a value was read from, so a contact written and read back equals the one written. `contact.ToProperties(version)` turns a contact into its property list and `Contact.TryFromProperties` maps a list back, so an application can also prune or rewrite a card at the property level. A property the model does not map reads with `property.GetText()` (unescaped) or `GetTexts()` (a comma list), so a second `NOTE` or an `X-SOCIALPROFILE` needs no parsing of its own; a further `PHOTO` reads with `ContactPhoto.TryRead(property, maxBytes, out photo, out error)`. ## Import [#import] ### Read an upload [#read-an-upload] A handler takes the uploaded file and injects `ContactReader`. A small upload can arrive as an `ElarionFile`; a larger one arrives as an [`UploadedFile`](/docs/capabilities/blob-uploads#passing-an-upload-to-a-handler) with its limits declared, which the handler opens through `IUploadedFiles`. ```csharp using VContact = Elarion.Contacts.Contact; [Handler("people.import")] public sealed class ImportPeople(ContactReader reader, IUploadedFiles uploads, CrmDbContext db) : IHandler> { public sealed record Command : ICommand { [UploadLimits(MaxBytes = 32L * 1024 * 1024, FileExtensions = [".vcf", ".vcard"])] public required UploadedFile Contacts { get; init; } } public sealed record Response(int Imported); public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var opened = await uploads.OpenAsync(command.Contacts, cancellationToken: ct); if (!opened.IsSuccess) return opened.Error; await using var file = opened.Value; var result = await reader.ReadAsync(file.Content, cancellationToken: ct); if (result.HasErrors) return result.ToAppError("contacts"); foreach (var contact in result.Contacts) db.People.Add(ToPerson(contact)); await db.SaveChangesAsync(ct); return new Response(result.Entries.Count); } private static Person ToPerson(VContact contact) => new() { Name = contact.DisplayName, Email = contact.Emails.FirstOrDefault(static e => e.Preferred)?.Address ?? contact.Emails.FirstOrDefault()?.Address, Mobile = contact.Phones.FirstOrDefault(static p => p.Types.HasFlag(ContactTypes.Cell))?.Number, Birthday = contact.Birthday?.ToDateOnly(), }; } ``` The reader recognizes the vCards from the content, not the file name. It reads 2.1, 3.0 and 4.0, and files that mix them; names in any case; CRLF, LF and CR line ends; folded lines whatever their indentation; groups (`item1.TEL`); quoted, repeated and comma-joined parameters and RFC 6868 carets; quoted-printable values with soft line breaks; Base64 values that end at a blank line; `#` comment lines; Google's `\:` escapes; and files concatenated from several exports, with a byte-order mark before each card. Line breaks in values read as `\n` on every platform, and invisible directional marks are removed from phone numbers. vCard 2.1 escapes only the semicolon, so in a 2.1 card every other backslash is a character: Outlook's `N:C:\Daten` reads `C:\Daten`. The entry's property holds such a value in the escaping of 3.0, its backslashes doubled, so it maps, unescapes and writes like any other. ### Encodings [#encodings] A UTF-8 or UTF-16 byte-order mark, or a `BEGIN` in UTF-16 without one, decides the encoding of the whole file. Otherwise each value is decoded on its own: with its `CHARSET` parameter when the runtime knows it, else as UTF-8 when its bytes are valid UTF-8, else with `FallbackEncoding` (Windows-1252 by default). So an old Outlook export in Windows-1252 reads, and so does a file whose values mix encodings. The result says when the fallback was used (`UsedFallbackEncoding`) and which encoding a byte-order mark chose (`ByteOrderMarkEncoding`). A `CHARSET` the runtime does not know is a `contact.unknown_charset` error, and the value is decoded by the same ladder. The package holds its own code pages: it never registers an encoding provider process-wide. An application whose users export from Central European Windows sets the fallback once: ```json { "Contacts": { "ReadDefaults": { "FallbackEncoding": "windows-1250" } } } ``` ### A preview: every contact, then decide [#a-preview-every-contact-then-decide] A read never throws because of what a file contains; it throws only on cancellation and on misconfiguration. Every vCard becomes an entry, so a handler can show a preview before it saves anything. | Member | Meaning | | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `result.Entries` | Every vCard in file order, with or without a contact. | | `entry.Index`, `entry.LineNumber`, `entry.Version` | Its 1-based index, the line of its `BEGIN`, the version it states. | | `entry.Properties` | Every property in file order, with its group, parameters, value as written and line, mapped or not. | | `entry.Value`, `entry.HasValue` | The contact, and whether there is one. | | `entry.Errors` | Its errors. | | `result.FileErrors` | Problems with the file: unreadable, too large, too many contacts, lines or errors. Each but `contact.too_many_errors` means the read stopped or never started. | | `result.OmittedErrorCount` | The errors past `MaxErrors`, counted and not listed. | | `result.Errors`, `result.HasErrors`, `result.Contacts` | All errors in file order; whether there are any; the contacts of the entries that have one. | An error costs only what is broken. A birthday that reads as no date, invalid Base64, a photo over the limit, an unknown charset, a line over the limit or a line without a colon drops that property: the contact comes back without it, and the entry carries the error. An entry has no contact only when nothing usable is left (no formatted name, name, organization, e-mail address or phone number) or when the card has more lines than the limit. `HasValue` is therefore not `IsValid`: an entry with errors keeps its contact, and the application decides what an error means for it. A handler that imports what it can refuses only a read that stopped. `contact.too_many_errors` is a file error too, but the read it ends is complete: only the listing of errors stopped. So test the file errors with `ContactErrorCodes.IsStructural` rather than for being there: ```csharp // The file is not a vCard file, or the read stopped early: refuse the upload. if (result.FileErrors.Any(static e => ContactErrorCodes.IsStructural(e.Code))) return result.ToAppError("contacts"); ``` `IsStructural` is true for the errors about the file's form: `contact.unreadable`, `contact.too_large`, `contact.too_many_contacts`, `contact.too_many_properties_in_file`, `contact.too_many_properties`, `contact.too_many_parameters`, `contact.line_too_long`, `contact.malformed_line` and `contact.unexpected_end`. An application that refuses broken files tests `result.Errors` the same way. The handler adds its own errors, under its own code prefix, located like the package's: ```csharp foreach (var entry in result.Entries.Where(static entry => entry.HasValue)) { var email = entry.Value.Emails.FirstOrDefault()?.Address; if (email is not null && await db.People.AnyAsync(p => p.Email == email, ct)) entry.AddError("import.duplicate", "A person with this e-mail address is already stored.", "EMAIL"); } ``` ## Error codes and wording [#error-codes-and-wording] Every error has a stable code, the data its wording needs, and an English default `Message`. `ToString()` prefixes the location: `Contact 12 (Jane Doe), line 340: The value of BDAY is not a date.` | Code | When | Data | | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `contact.unreadable` | The upload holds no `BEGIN:VCARD` line: a PDF, an empty file, a spreadsheet. | `MediaType` when it is not text (`application/pdf`, `application/zip`, `application/octet-stream`) | | `contact.too_large` | The upload is larger than `MaxBytes`. | `Limit` | | `contact.too_many_contacts` | More vCards than `MaxContacts`; the entries before it are kept. | `Limit` | | `contact.too_many_properties` | A card has more lines than `MaxPropertiesPerContact`; its entry has no contact. | `Limit` | | `contact.too_many_properties_in_file` | The cards hold more lines and parameter values than `MaxProperties`; the entries before the card being read are kept. | `Limit` | | `contact.too_many_errors` | More errors than `MaxErrors`; the rest are counted in `OmittedErrorCount`. The read is complete; not structural. | `Limit` | | `contact.too_many_parameters` | A line has more parameter values than `MaxParametersPerProperty`; the property is dropped. | `Property`, `Limit` | | `contact.line_too_long` | An unfolded line is longer than `MaxLineBytes`; the property is dropped. | `Property`, `Limit` | | `contact.photo_too_large` | A photo is larger than `MaxPhotoBytes`; it is dropped. | `Property`, `Limit` | | `contact.invalid_value` | A value does not read as its kind: `date`, `uri`, `photo`, or `photo-format` for an image the package does not read. | `Property`, `Value`, `ExpectedKind`; `MediaType` for `photo-format` | | `contact.partial_date` | A birthday or anniversary names no month and day (`1985`, `1985-04`, `--04`, `---12`); it is dropped. | `Property`, `Value` | | `contact.unknown_charset` | A `CHARSET` the runtime does not know. | `Property`, `Charset` | | `contact.malformed_line` | A line inside a card without a name or a colon; it is skipped. | `Value` | | `contact.empty` | A card with nothing usable; its entry has no contact. | — | | `contact.unexpected_end` | A card not closed by `END:VCARD`; it is read. | — | Every error about a contact also carries `ItemIndex`, `ItemLineNumber`, `LineNumber` and the contact's `DisplayName`, the location fields the calendar errors carry too. `result.ToAppError("contacts")` converts the errors to a validation `AppError` keyed by the upload member, with at most 100 messages and one that counts the rest. Pass a formatter to word them in the application's language from the code and the data: ```csharp return result.ToAppError("contacts", static error => error.Code switch { ContactErrorCodes.InvalidValue => $"Kontakt {error.ItemIndex}, Zeile {error.LineNumber}: {error.Property} ist ungültig.", _ => error.ToString(), }); ``` ## Photos [#photos] An inline photo (vCard 2.1 and 3.0 Base64, a 4.0 `data:` URI) reads as its bytes, with the media type the bytes show (JPEG, PNG, GIF, WebP or BMP) whatever the file declared. Bytes of no known image format are dropped with `contact.invalid_value` and the expected kind `photo-format`; its `MediaType` names what the bytes are (`image/heic`, `application/pdf`) or else what the file declared, so a preview can say "the HEIC picture is not imported". A photo over `MaxPhotoBytes` is dropped with `contact.photo_too_large`, without decoding it. The first `PHOTO` that reads is the contact's photo; later ones stay additional properties, which `ContactPhoto.TryRead` reads. To build a photo from stored bytes without an exception, use `ContactPhoto.TryFromData`. A photo given as an address reads as a `Uri`, only for `http` and `https`; any other scheme (`file:`, `ftp:`) is dropped with `contact.invalid_value`. **The package never requests an address.** An upload that made the server fetch an address it names would let the uploader send requests from inside the network (server-side request forgery), so the decision to fetch is the application's: check the host against an allow list, bound the size and the time, and fetch through a client that cannot reach internal addresses. ## Export [#export] ### A small file for any transport [#a-small-file-for-any-transport] ```csharp [Handler("people.export")] public sealed class ExportPeople(CrmDbContext db) : IHandler> { public sealed record Query : IQuery; public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var people = await db.People.AsNoTracking().ToListAsync(ct); return await ContactWriter.ToFileAsync(people.Select(ToContact), "contacts.vcf", cancellationToken: ct); } private static Contact ToContact(Person person) => new() { Name = new ContactName(person.LastName, person.FirstName, null, null, null), Emails = person.Email is null ? [] : [new ContactEmail(person.Email) { Types = ContactTypes.Work }], Phones = person.Mobile is null ? [] : [new ContactPhone(person.Mobile) { Types = ContactTypes.Cell, Preferred = true }], }; } ``` The file is vCard 3.0, which Apple Contacts, Google Contacts, Android and Outlook import, served as `text/vcard; charset=utf-8` (`ContactWriter.ContentType` is `text/vcard`). Pass `new ContactWriteOptions { Version = ContactFormatVersion.V4_0 }` for vCard 4.0. vCard 2.1 is never written. ### A large file, streamed [#a-large-file-streamed] From an HTTP endpoint, return an `ElarionStreamedFile`: the contacts are written to the response body as they are produced, and the server holds one contact at a time. ```csharp return ContactWriter.ToStreamedFile( db.People.AsNoTracking().Select(p => new Contact { FormattedName = p.Name }).AsAsyncEnumerable(), "contacts.vcf"); ``` `ContactWriter.ToStreamedFile(fileName, async (writer, ct) => …)` hands the writer to a delegate, and `ContactWriter.Create(stream)` writes to any stream; `writer.AddAsync(entry.Properties)` writes a card exactly as it was read. ### A payload that is not a file [#a-payload-that-is-not-a-file] A QR code or an NFC tag carries one card, built in synchronous code, and its readers do not unfold lines: ```csharp var payload = ContactWriter.ToText(contact, new ContactWriteOptions { FoldLines = false }); ``` `ContactWriter.Write(stream, contacts, options)` writes synchronously to a stream. An application that pins its own wire format (the order of the properties, the spelling of a parameter) builds the property list itself, from `contact.ToProperties(version)` or by hand, and writes it as it is, synchronously too: ```csharp var properties = contact.ToProperties(ContactFormatVersion.V3_0).OrderBy(Rank).ToList(); var text = ContactWriter.ToText(properties); // one card ContactWriter.Write(stream, cards); // IEnumerable> ``` ### One file per contact for Outlook classic [#one-file-per-contact-for-outlook-classic] Outlook classic imports only the first card of a file. For it, write each contact to a file of its own: ```csharp var file = await ContactWriter.ToFileAsync([contact], $"{contact.DisplayName}.vcf", cancellationToken: ct); ``` ### What a written file looks like [#what-a-written-file-looks-like] UTF-8 without a byte-order mark, CRLF line ends, lines folded at 75 octets without splitting a character or an escape (unless `FoldLines` is off). Types are `TYPE=` parameters, `TYPE=INTERNET` among them; a preferred value is `PREF` among the upper-case type values in 3.0 (`TYPE=CELL,VOICE,PREF`) and `PREF=1` in 4.0; a custom label is an `itemN.X-ABLabel` property of the value's group. A photo is `ENCODING=b` with its type in 3.0 and a `data:` URI in 4.0. A date without a year is `X-APPLE-OMIT-YEAR=1604` with year 1604 in 3.0 and `--MMDD` in 4.0; an organization is `X-ABShowAs:COMPANY` in 3.0 and `KIND:org` in 4.0. A web address is a URI, written as it is (`;` and `,` unescaped), and so is a 4.0 phone number given as a `tel:` URI, with `VALUE=uri`; a tab or line break in a URI is left out, as a browser's URL parser leaves it out. Control characters other than the tab (U+0000–U+001F, U+007F–U+009F) are left out of every value: a card a CardDAV server embeds in XML must not hold one. A group is `X-ADDRESSBOOKSERVER-KIND:group` with one `X-ADDRESSBOOKSERVER-MEMBER` per member in 3.0, which Apple and DAVx5 read, and `KIND:group` with `MEMBER` in 4.0, never both; a contact that is not a group but has members fails the write. Every card has an `FN`, derived from the display name when the contact has no formatted name, and in 3.0 an `N` (a group's name when it has none). Additional properties are written as they were read. The same contacts give byte-identical files. A contact the writer cannot represent (an additional property whose name, group or parameter name is not a valid vCard name, or whose value holds a line break) fails with a `ContactWriteException` that names the contact (`ItemIndex`) and the property. The writer checks a contact before it writes any of it, so the writer takes further contacts. ## Limits and options [#limits-and-options] On top of the upload limits the handler declares, the read options bound what a file costs. A per-contact limit costs at most that contact or property, and the read continues; a file limit stops the read with one error and keeps the contacts before it. Reading is one pass, linear in the input, and nothing recurses. The bytes bound the input; the lines, their parameters and the errors bound the result. Every property of every card stays in the result, and a property costs 60 to 150 bytes however short its line, and each of its parameters up to 70 more: a 20 MB file of four-byte lines held 600 MB before `MaxProperties` existed, and a 32 MB file of lines with four empty parameters 430 MB before parameters counted against it. With the defaults a result holds at most about 200 MB, whatever the file holds; a 20 MB file of short lines now holds 26–115 MB, and one of malformed lines 2 MB. A real export of 10,000 contacts counts some 200,000 lines and 160,000 parameter values. | `ContactReadOptions` | Default | Exceeded | | -------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------- | | `MaxBytes` | 32 MiB | `contact.too_large`; the reader holds no more than the limit | | `MaxContacts` | 10,000 | `contact.too_many_contacts`; the read stops | | `MaxPropertiesPerContact` | 1,000 | `contact.too_many_properties`; the card has no contact and keeps only its `FN`, `N`, `ORG`, `EMAIL`, `TEL` and `UID` | | `MaxProperties` | 1,000,000 | `contact.too_many_properties_in_file`; the read stops. Each parameter value of a line counts as one more | | `MaxParametersPerProperty` | 100 | `contact.too_many_parameters`; the property is dropped. Each value of a list and each bare parameter counts one | | `MaxErrors` | 10,000 | `contact.too_many_errors`; the read goes on, further errors are counted | | `MaxLineBytes` | 1 MiB | `contact.line_too_long`; the property is dropped | | `MaxPhotoBytes` | 1 MiB | `contact.photo_too_large`; the photo is dropped | | `FallbackEncoding` | `windows-1252` | an unknown name throws `InvalidOperationException` | A read that passes its own options uses those instead of the defaults; derive them with `with`: ```csharp var options = contactOptions.Value.ReadDefaults with { MaxContacts = 50_000 }; // IOptions ``` The keys are listed in the [configuration reference](/docs/reference/configuration#contacts). ## Serving contacts to contacts apps [#serving-contacts-to-contacts-apps] To show the application's contacts in iOS, macOS, Thunderbird, DAVx5 or Evolution, publish them over [CardDAV](/docs/capabilities/carddav), which stores and serves them with this package's writer. ## Out of scope [#out-of-scope] * Writing vCard 2.1; jCard (RFC 7095) and xCard. * Mapping `RELATED`, `IMPP`, `GEO`, `TZ`, `SOUND`, `LOGO`, `KEY`, `LABEL`, `AGENT`, `X-SOCIALPROFILE` or phonetic names into the model; they stay additional properties. An `AGENT` value is never parsed as a vCard. * Fetching photo addresses, and resizing or re-encoding photos. * Detecting duplicates and merging contacts; that is the application's, through `AddError`. * CardDAV. # Coordination & role leases (/docs/capabilities/coordination) Elarion has four deliberately different coordination shapes. Choose the one that matches the unit being coordinated: | Need | Primitive | Coordination key | | ------------------------------------------------------------ | ----------------------------------------------------------- | -------------------------- | | Run one recurring occurrence across the cluster | [Scheduler claim](/docs/capabilities/scheduling/multi-node) | Job + due time | | Deliver one integration consumer invocation at a time | [Outbox delivery lease](/docs/capabilities/events/backends) | Message + consumer | | Work through your own queue table, one worker per row | [Leased work rows](#leased-work-rows) | Row id + lease token | | Serialize writers of one row or key inside a transaction | [Row and advisory locks](#row-and-advisory-locks) | Entity key, or scope + key | | Make exactly one instance hold a long-lived application role | **Role lease** | Role name | A role lease answers a coarse question such as “which instance is the maintenance coordinator?” It is a heartbeat-renewed row in the application's PostgreSQL database, exposed as an `IRoleLease` keyed by role name. The current holder renews; other instances keep trying; graceful shutdown releases immediately; a crashed holder fails over when its lease expires. A role lease is **not a distributed-lock API**. Do not create one per tenant, record, or work item. An application should have a handful of stable roles. Use database constraints and optimistic concurrency for rows, scheduler claims for job occurrences, outbox leases for messages, and leased work rows for your own queue tables. This default targets Elarion's normal scale: roughly 1–10 application nodes on the PostgreSQL the app already runs. Beyond that tier, replace the coordination seam with dedicated infrastructure rather than growing a membership system inside the application. ## Map the lease table [#map-the-lease-table] Add `Elarion.Coordination.PostgreSql` and opt the application's concrete `DbContext` into the model: ```csharp using Elarion.Coordination.PostgreSql; using Elarion.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; [GenerateDbSets] [GenerateElarionRoleLeases] public sealed partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); ConfigureEntities(modelBuilder); // generated, including elarion_role_leases } } ``` The hand-written model equivalent is `modelBuilder.UseElarionRoleLeases()`. Apply the resulting EF Core migration before any instance starts competing for a role. ## Register one lease per role [#register-one-lease-per-role] Each registration adds a keyed `IRoleLease` and its heartbeat worker: ```csharp builder.Services.AddElarionPostgreSqlRoleLease(options => { options.RoleName = "maintenance"; }); ``` Duplicate registration of the same role in one process fails at startup. The defaults are sized so the old holder stops acting before a successor may legitimately take over: | Option | Default | Meaning | | ------------------- | ---------------------------- | -------------------------------------------------------------------------------------------- | | `LeaseDuration` | 30 s | How long one successful acquisition remains valid; also the crash-failover bound. | | `RenewInterval` | 10 s | How often holders renew and non-holders try to acquire. | | `HeldSafetyMargin` | 5 s | How early local `IsHeld` becomes false before database expiry. | | `InstanceId` | Machine name + random suffix | Process identity written to the lease row. | | `AdvertisedAddress` | `null` | Explicit holder address for proxying; otherwise an `IInstanceAddressProvider` may supply it. | `LeaseDuration` must be greater than `RenewInterval + HeldSafetyMargin`. Role names are validated against the lease table's 128-character limit during registration. Fixed partitions validate their generated `{name}:partition-N` roles before adding any services. ## Register a fixed role partition [#register-a-fixed-role-partition] When a stable key should select one of several coarse roles without configuring process count, register a fixed partition. One process may hold several partitions; this does not add automatic balancing: ```csharp builder.Services.AddElarionPostgreSqlRolePartition(partition => { partition.Name = "devices"; partition.PartitionCount = 16; }); ``` Resolve the keyed `IRolePartition` (keyed by the partition name) and call `Resolve(key)` (or `Resolve(scope, key)`) for the locally cached role/holder/address view — no I/O on the hot path: ```csharp public sealed class DeviceRouter([FromKeyedServices("devices")] IRolePartition partition) { public bool OwnsDevice(string deviceId) { RolePartitionTarget target = partition.Resolve(deviceId); // stable hash → one of 16 roles return target.IsHeld; // this process holds the partition's role lease // target.Role is e.g. "devices:partition-7"; target.CurrentHolderAddress routes elsewhere. } } ``` Roles are named `devices:partition-0` through `devices:partition-15`. `IRoleLeaseRegistry` exposes all configured leases to infrastructure such as role-affine outbox claiming. ## Gate every cycle [#gate-every-cycle] Resolve the lease by its role name and check `IsHeld` at the start of every unit of work. `IsHeld` is local, lock-free state; it does not query PostgreSQL on the hot path. ```csharp using Elarion.Abstractions.Coordination; using Microsoft.Extensions.DependencyInjection; public sealed class MaintenanceWorker( [FromKeyedServices("maintenance")] IRoleLease lease, TimeProvider timeProvider) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { if (lease.IsHeld) { await RunOneCycleAsync(stoppingToken); } await Task.Delay(TimeSpan.FromSeconds(10), timeProvider, stoppingToken); } } } ``` Do not start a permanent leader-only loop in response to a lease-change event. There is deliberately no such event: database outages fail closed, and a holder can lose the role between any two cycles. Gate each call or polling cycle instead. `CurrentHolder` and `CurrentHolderAddress` are diagnostic/routing snapshots refreshed at heartbeat cadence. They may lag a failover by one renewal interval; correctness comes from `IsHeld`, not from comparing holder strings. ## Route HTTP to the holder [#route-http-to-the-holder] Some roles own live state or an ordered stream, so every public instance must accept the route while only the holder may execute it. `Elarion.AspNetCore` ships a small role-holder proxy for that shape: ```csharp builder.Services.AddElarionInstanceAddress(); builder.Services.AddElarionPostgreSqlRoleLease(options => { options.RoleName = "maintenance"; }); var app = builder.Build(); // Install before routing/auth so a non-holder never starts local execution. app.UseElarionRoleHolderProxy("maintenance", "/maintenance", "/maintenance-streams"); app.MapMaintenanceEndpoints(); ``` `AddElarionInstanceAddress()` advertises the server's bound address, replacing wildcard hosts with a non-loopback IPv4 address. Pass an explicit address behind NAT, a reverse proxy, or when nodes use HTTPS between themselves: ```csharp builder.Services.AddElarionInstanceAddress("https://app-03.internal:8443"); ``` The proxy forwards at most one hop and supports streaming responses such as SSE. It never retries or queues a request: an unknown/unreachable holder or a failover race returns `503` with `Retry-After`. The loop guard prevents a forwarded request from bouncing again. When the named lease is not registered (for example in single-instance development), the call installs no middleware. The prefix list is intentionally the same rule a future ingress or service mesh would own. When external routing can target the holder directly, remove the in-app proxy rather than layering both. For a key-selected role, use the partition overload before routing: ```csharp app.UseElarionPartitionHolderProxy( "devices", context => context.Request.Headers["X-Device-Id"].FirstOrDefault(), "/device-api"); ``` The resolver reads raw path/query/header state. Missing affinity keys return 400; holder failures use the same bounded 503 behavior as the coarse-role proxy. When the target subsystem uses scoped affinity, pass that same stable scope. Virtual-sharded actors hash their logical actor name (the `[Actor(Name = ...)]` value, or the class name without `Actor`) and canonical key together, so actor ingress must use the scoped overload: ```csharp app.UseElarionPartitionHolderProxy( "actors", "Order", context => context.Request.Path.Value?.Split('/').LastOrDefault(), "/orders"); ``` ## Actor home is a specialized role [#actor-home-is-a-specialized-role] `AddElarionPostgreSqlActorHome()` composes the same mechanism under the reserved `"actors"` role for `[Actor(Placement = ActorPlacementMode.SingleHome)]` actors. Calls on other instances fail rather than forwarding through the actor runtime; host-owned HTTP prefixes can use `UseElarionRoleHolderProxy("actors", ...)` to reach a single home, or `UseElarionPartitionHolderProxy("actors", actorName, ...)` for virtual-sharded ingress. See [Actors](/docs/concepts/actors) for the placement and migration boundaries. ## Failure behavior [#failure-behavior] * **Graceful shutdown:** the holder releases the row, allowing immediate takeover. * **Process or node loss:** another instance acquires after `LeaseDuration` expires. * **Database outage:** no instance considers itself holder after its safety window; coordination fails closed. * **Clock skew:** leases use application clocks. Keep node clocks synchronized; this is not a consensus protocol. * **Two processes on one machine:** the random `InstanceId` suffix keeps their identities distinct. The full rationale and proxy design are recorded in [ADR-0049](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0049-role-leases.md) and [ADR-0050](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0050-role-holder-proxy.md). ## Leased work rows [#leased-work-rows] When an application keeps its own queue-shaped table — outbound e-mail or SMS deliveries, webhook dispatches, a durable retry table — and workers on any instance must process each row one at a time, use the leased-work-row primitive from `Elarion.EntityFrameworkCore.LeasedWork`. It is the same claim the outbox delivers integration events with, packaged so a second table does not re-derive its invariants from memory: * **Claim is select → conditional stamp → re-read.** Candidates are read without locks; one `ExecuteUpdate` restating the whole eligibility predicate stamps a lease token and expiry onto the rows that are still eligible; the worker gets back only the rows carrying its token. Concurrent workers never block each other and never receive the same row for the same lease period. * **Every finalize is lease-guarded.** Completing, failing, releasing, or renewing a row only matches while the worker's token is still on it. A worker that stalled past its lease learns it lost the row (`false`) instead of overwriting the new owner. * **Recovery is by expiry.** A crashed worker releases nothing; its lease lapses and the row becomes claimable again. There is no reaper and no lock to leak. * **The claim rides a partial index** over the live rows only, so it stays fast while completed history accumulates. No statement holds a row lock or a transaction across the work itself. That matters most for outbound delivery: a slow SMTP or HTTP call never pins a database connection, and a producer can still update or withdraw a row while a worker is busy with it. `SELECT … FOR UPDATE SKIP LOCKED` held across the external call does the opposite and is deliberately not the pattern. ### Map the table [#map-the-table] The entity implements `ILeasedWorkRow` (`Id`, `LockId`, `LockedUntilUtc`) as ordinary properties. Everything else — the completion marker, the attempt counter, the error, a deadline — stays your own column: ```csharp public sealed class Delivery : ILeasedWorkRow { public required Guid Id { get; init; } public required DateTimeOffset CreatedAtUtc { get; init; } public required DateTimeOffset ExpiresAtUtc { get; init; } public byte[]? Payload { get; set; } public int Attempts { get; set; } public DateTimeOffset? CompletedAtUtc { get; set; } public string? Error { get; set; } public Guid? LockId { get; set; } public DateTimeOffset? LockedUntilUtc { get; set; } } [EntityConfiguration] public sealed class DeliveryConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder entity) { entity.ToTable("deliveries"); // Lease columns plus the partial claim index ix_deliveries_claim over the live queue. entity.HasElarionLeasedWork(d => new { d.CreatedAtUtc, d.Id }, "completed_at_utc IS NULL"); } } ``` The claim index lists the queue-order column and then `Id`, matching the claim's ordering. The filter is required. If you keep completed rows for a while, add the complementary purge index yourself. ### Claim, work, finalize [#claim-work-finalize] ```csharp private static readonly TimeSpan[] RetryLadder = [TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(15), TimeSpan.FromHours(1), TimeSpan.FromHours(12)]; public async Task DeliverBatchAsync(CancellationToken ct) { var now = time.GetUtcNow(); var lockId = Guid.CreateVersion7(); var claimed = await db.Deliveries.ClaimPendingAsync(new LeasedWorkClaim { LockId = lockId, NowUtc = now, LeaseUntilUtc = now + TimeSpan.FromMinutes(2), // well above one batch's worth of calls BatchSize = 20, Eligible = d => d.CompletedAtUtc == null && d.Attempts < 8 && d.ExpiresAtUtc > now, OrderBy = rows => rows.OrderBy(d => d.CreatedAtUtc), // Count the attempt at claim: a worker that dies mid-call still uses one up. OnClaim = s => s.SetProperty(d => d.Attempts, d => d.Attempts + 1), }, ct); foreach (var delivery in claimed) { var outcome = await transport.SendAsync(delivery, ct); // no lock, no transaction held var finished = time.GetUtcNow(); var owned = outcome.Succeeded ? await db.Deliveries.FinalizeClaimAsync(delivery.Id, lockId, s => s .SetProperty(d => d.CompletedAtUtc, finished) .SetProperty(d => d.Payload, (byte[]?)null), visibleAfterUtc: null, ct) : await db.Deliveries.FinalizeClaimAsync(delivery.Id, lockId, s => s .SetProperty(d => d.Error, outcome.Error), finished + LeasedWorkBackoff.Ladder(delivery.Attempts, RetryLadder, outcome.RetryAfter), ct); logger.LogFinalizeOutcome(owned, "delivery", delivery.Id); // warns when the claim was lost } return claimed.Count; } ``` Run the method from a [scheduled job](/docs/capabilities/scheduling) or a `BackgroundService` loop on every instance; the claim makes that safe. A failed attempt's finalize sets the retry visibility (`LeasedWorkBackoff.Exponential`, or `LeasedWorkBackoff.Ladder`, which honors a longer remote `Retry-After`), so a failing row waits instead of blocking the head of the queue. `ReleaseClaimAsync` hands back a row without bookkeeping, and `RenewClaimAsync` extends the lease for work that can outlive it. Delivery stays **at least once**: a worker that crashes after the remote side accepted but before the finalize leaves the row to be retried. Give the remote side the row `Id` as its idempotency key where it accepts one. ### Giving up, guarding the outcome, and shutting down [#giving-up-guarding-the-outcome-and-shutting-down] Four needs recur in every worker; the primitive answers each so the skeleton is not rewritten per queue: * **Give up an exhausted row at claim.** `Exhausted` names rows that have used up their attempts — evaluated right after the stamp, on the values `OnClaim` wrote, so `d => d.Attempts > MaxAttempts` also catches a row whose every previous worker died mid-call. Such a row is not returned: it is finalized at once with `GiveUp` (which must take it out of `Eligible`) and reported to `OnGivenUp` for logging. Without it, an exhausted row just sits in the table. Every given-up row is reported, even after a callback threw; a failed report fails the claim, and the won rows are released first instead of staying stamped until their lease lapses. A claim can therefore come back empty while work remains — every candidate given up or taken by another worker — so an empty claim is not "queue drained". The claim says what it saw: `Candidates` is how many rows its select found (zero means drained) and `GivenUp` how many of them it gave up, so a pass loops `while (claimed.Candidates > 0)` without counting in `OnGivenUp`. * **Write the outcome only while it still applies.** Work done without a lock can race a concurrent writer. A `LeasedWorkFinalize` with `StillEligible` applies the setters only while the row still meets that condition; otherwise the claim is ended without them. The outcome says which happened (`Finalized`, `Ineligible`, `ClaimLost`). `Ineligible` clears the lease at once and ignores `VisibleAfterUtc`: that backoff belonged to the discarded result, and the concurrent writer's values decide through `Eligible` whether the row is still work. * **Give a batch back on shutdown.** `ReleaseClaimsAsync(ids, lockId, update, ct)` ends the claims on the unfinished rows in one statement and lets the update take back the attempt the claim counted — it was never made. * **Log what a finalize could not do.** `logger.LogFinalizeOutcome(outcome, "metadata", row.Id)` writes the warning for a lost claim (the lease expired and another worker took the row, or the row was deleted meanwhile) and the information line for an `Ineligible` row, and returns whether the setters applied; the `bool` overload covers `FinalizeClaimAsync` without a guard, `ReleaseClaimAsync` and `RenewClaimAsync`. * **Read related data with the claim.** `ClaimPendingAsync(claim, select, ct)` projects the won rows in the same query (`m => new { m.Id, m.Attempts, m.Attachment.BlobId }`) instead of a second query per batch. ```csharp var claimed = await db.ImageMetadata.ClaimPendingAsync(new LeasedWorkClaim { LockId = lockId, NowUtc = now, LeaseUntilUtc = now + Lease, BatchSize = 20, Eligible = m => m.State == ReadState.Pending, OrderBy = rows => rows.OrderBy(m => m.UploadedAt), OnClaim = s => s.SetProperty(m => m.Attempts, m => m.Attempts + 1), Exhausted = m => m.Attempts > MaxAttempts, GiveUp = s => s.SetProperty(m => m.State, ReadState.Done).SetProperty(m => m.Error, "attemptsExhausted"), OnGivenUp = (m, _) => { logger.LogWarning("Metadata of {Id} given up.", m.Id); return ValueTask.CompletedTask; }, }, m => new { m.Id, m.Attempts, m.Attachment.BlobId }, ct); var finished = 0; try { foreach (var row in claimed) { var read = await ReadAsync(row.BlobId, ct); // Only while still pending: a newer upload meanwhile wrote its own values and marked the row done. var outcome = await db.ImageMetadata.FinalizeClaimAsync(row.Id, lockId, new LeasedWorkFinalize { Update = s => s.SetProperty(m => m.Width, read.Width).SetProperty(m => m.State, ReadState.Done), StillEligible = m => m.State == ReadState.Pending, }, ct); logger.LogFinalizeOutcome(outcome, "image metadata", row.Id); finished++; } } catch (OperationCanceledException) when (ct.IsCancellationRequested) { // The pass's token is cancelled: give the rest back on a fresh one, attempt uncounted. await db.ImageMetadata.ReleaseClaimsAsync(claimed.Skip(finished).Select(r => r.Id), lockId, s => s.SetProperty(m => m.Attempts, m => m.Attempts - 1), CancellationToken.None); throw; } ``` ### Rows that recur: bringing the next run forward [#rows-that-recur-bringing-the-next-run-forward] A row that is worked again and again (a mailbox fetched every ten minutes, a feed polled hourly) keeps a column of its own that says when it is due next. The claim filters on it (`Eligible = m => m.NextFetchAt <= now`), stamps the start of the attempt (`OnClaim = s => s.SetProperty(m => m.LastAttemptAt, now)`), and the finalize writes the next due time. When something outside the worker wants the row sooner, such as a command that wrote a change the worker has to carry out, call `BringForwardAsync` on the rows concerned: ```csharp // In the command's transaction: commits or rolls back with the change that caused it. await db.Mailboxes.Where(m => touched.Contains(m.Id)).BringForwardAsync(new LeasedWorkBringForward { DueAt = m => m.NextFetchAt, NowUtc = now, LastAttemptAt = m => m.LastAttemptAt, MinSpacing = TimeSpan.FromMinutes(1), BackingOff = m => m.ConsecutiveFailures > 0, }, ct); ``` It is one `UPDATE` and returns how many rows became due sooner: * A row becomes due at `NowUtc`, or `MinSpacing` after its last attempt began when that is later. A burst of requests starts one run per spacing, not one per request. Without `MinSpacing` every row becomes due at `NowUtc`. * A row already due at or before that time, including an overdue one, is not written: a request never makes a row due later. * A row whose due column is `null` counts as not scheduled, and the request schedules it. * A row matching `BackingOff` is not written. Name the rows whose retry backoff the due column itself carries (the failed finalize wrote the retry time into it). A backoff written as the finalize's `VisibleAfterUtc` needs no predicate: the lease columns are not touched, and the claim does not take the row before that deadline however soon it is due. `DueAt` and `LastAttemptAt` select `DateTimeOffset` properties of the row, nullable or not. The times are sent as parameters, so all requests share one query plan. **A row that is claimed while the request arrives is not helped by this call**: its due time lies in the past, and its worker's finalize writes the next one. Let that finalize decide from the work still waiting, in its own statement, instead of from the interval alone: ```csharp var byInterval = now + interval; var soon = now + MinSpacing < byInterval ? now + MinSpacing : byInterval; await db.Mailboxes.FinalizeClaimAsync(mailbox.Id, lockId, new LeasedWorkFinalize { Update = s => s.SetProperty(m => m.NextFetchAt, m => db.PendingChanges.Any(c => c.MailboxId == m.Id) ? soon : byInterval), }, ct); ``` The rule and what was rejected are in [ADR-0132](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0132-a-request-brings-a-leased-work-rows-next-run-forward.md). ### Testing a worker [#testing-a-worker] The claim and every finalize are `ExecuteUpdate` statements, which EF InMemory cannot run — and InMemory would hide the concurrency the primitive exists for anyway. Test a worker against PostgreSQL with a Testcontainers fixture, the way Elarion tests the primitive itself: create the schema once per fixture, give every test its own rows (a per-test marker column in `Eligible`, like a source or tenant id, keeps tests in one table apart), and pass `NowUtc` explicitly so lease expiry and backoff are exact without waiting. Two workers racing for one batch are two contexts on the same fixture. The invariants and the extraction history are recorded in [ADR-0073](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0073-leased-work-rows.md). ## Row and advisory locks [#row-and-advisory-locks] Most concurrency is the database's job — constraints, optimistic concurrency, `ON CONFLICT`. Some rules are not expressible as a constraint: "periods of one unit never overlap" across a whole set, a read-then-write that must not interleave with another writer of the same aggregate. For those, `Elarion.EntityFrameworkCore.UnitOfWork` adds **transaction-scoped** PostgreSQL row and advisory locks on `DbContext`, held until the current transaction (a command's pipeline transaction, or one you opened) commits or rolls back: ```csharp using Elarion.EntityFrameworkCore.UnitOfWork; // Lock one row; table and key column come from the EF model. False when no visible row has that key. if (!await db.LockRowAsync(command.UnitId, RowLockMode.NoKeyUpdate, ct)) return AppError.NotFound("No such unit."); // No row to lock (the account may not exist yet): lock a key instead, or try without waiting. await db.AdvisoryLockAsync("billing-account", command.AccountNumber, ct); var period = command.Period.ToString("yyyy-MM", CultureInfo.InvariantCulture); if (!await db.TryAdvisoryLockAsync("statement-run", period, ct)) return AppError.Conflict("A statement run for this period is already in progress."); ``` `LockRowAsync` looks the row up through the entity's own set first, so its query filters (tenant scoping, soft delete) and a hierarchy's discriminator apply: a row the context cannot see answers `false` and is never locked, so an id from a request cannot probe or stall another tenant's row. A strongly typed key with a value converter is converted the way EF converts it; an id of another type throws `ArgumentException`. A writer that deliberately changes rows its filters hide, such as an archived tenant, locks past them with the options overload. Every filter is skipped, tenant scoping included, so use it only for an id the handler has already authorized: ```csharp if (!await db.LockRowAsync(command.TenantId, new RowLockOptions { Mode = RowLockMode.NoKeyUpdate, IgnoreQueryFilters = true }, ct)) return AppError.NotFound("No such tenant."); ``` | `RowLockMode` | SQL | Choose it when | | ------------------ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `Update` (default) | `FOR UPDATE` | a concurrent insert of a row *referencing* this one (a foreign key) must wait too — deleting a role against a concurrent assignment of it | | `NoKeyUpdate` | `FOR NO KEY UPDATE` | only writers of the row itself must be serialized; inserts referencing it proceed | | `Share` | `FOR SHARE` | readers may share; writers wait | | `KeyShare` | `FOR KEY SHARE` | only a change of the row's key or its deletion waits | ### Several rows or keys [#several-rows-or-keys] A command that changes several records — a bulk edit, a merge — locks all of them. Two transactions that take overlapping locks in different orders can each wait for the other, a deadlock PostgreSQL breaks by failing one of them. `LockRowsAsync` and `AdvisoryLockAllAsync` take a set and lock each member once, in one stable order, so every command that locks several members of the same set waits instead of deadlocking: ```csharp // Rows: ascending key order (strings ordinally). The result holds the keys found and locked. var locked = await db.LockRowsAsync( command.Ids, new RowLockOptions { Mode = RowLockMode.NoKeyUpdate }, ct); if (locked.Count != command.Ids.Distinct().Count()) return AppError.NotFound("Some invoices do not exist."); // Advisory keys of one scope: ordinal order of the key. await db.AdvisoryLockAllAsync("invoice-family", familyIds.Select(id => id.ToString()), ct); ``` The order only protects callers that use it: lock every set of several rows of an entity, or several keys of a scope, through these methods rather than one at a time in the order a request lists them. A command that needs locks of several entities or scopes takes them in one fixed order of entities and scopes, the same in every command. Each member costs one statement (two for a row: the lookup through the entity's set, then the lock); `LockRowsAsync` applies `RowLockOptions` to every row, and orders keys with `Comparer.Default`, so a strongly typed key implements `IComparable`. Both refuse to run **outside a transaction** (PostgreSQL would release the lock at the end of its own statement) and on any provider other than PostgreSQL, so a lock never silently protects nothing. An ambient `TransactionScope` counts as a transaction because the connection enlists in it; a connection string with `Enlist=false` opts out of that, so lock inside an EF or pipeline transaction on such a connection. Tests of locking run against PostgreSQL ([Testcontainers](/docs/concepts/persistence-and-transactions#testing-persistence)). A unit test on another provider that only passes through a lock, such as a handler test on EF InMemory or SQLite, opts its own context out explicitly: ```csharp var options = new DbContextOptionsBuilder() .UseInMemoryDatabase(Guid.CreateVersion7().ToString()) .UseUnenforcedElarionLocks() // locks lock nothing; the provider and transaction checks are skipped .Options; ``` On that context the helpers still validate keys and scopes, and `LockRowAsync` still answers whether a visible row has the key, so the handler's not-found path runs as in production. A context without the opt-in still fails closed. A PostgreSQL context that carries it throws at its first lock, so a shared test options helper can't leave a real database unlocked. ### One advisory key scheme [#one-advisory-key-scheme] A database has one advisory-lock space. Every advisory lock taken through Elarion locks `hashtextextended('scope:key', 0)` — `AdvisoryLockKey.Text(scope, key)` builds the text, the same function the framework uses — so two `(scope, key)` pairs only meet when their hashes collide. A scope names what is serialized (`billing-account`) and must not contain `:`. Scopes starting with `elarion.` are reserved; the framework locks: | Scope | Key | Taken by | | ------------------------- | ------------- | --------------------------------------- | | `elarion.scheduler.job` | the job name | the multi-node scheduler's window claim | | `elarion.devices.pairing` | the device id | reissuing a device's pairing code | The migration runner's session-level lock uses its own fixed key (`PostgreSqlMigrationRunner.DefaultAdvisoryLockKey`), not a hashed text. A host on the EF-free SQL tier builds the same text with `AdvisoryLockKey.Text` and runs `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))` itself. A lock is per transaction, not per node or per process: it serializes the transactions that ask for it on the one PostgreSQL every instance shares, and it ends with the transaction. For "exactly one instance does this for a long time", use a role lease; for "one worker per queue row", use leased work rows. # Current user (/docs/capabilities/current-user) Handlers often need to know who is calling — for authorization, auditing, or [user-scoped caching](/docs/capabilities/caching). Elarion exposes this through a transport-neutral `ICurrentUser` abstraction so application code never depends on `HttpContext` or `IHttpContextAccessor`. This follows the framework's boundary rule: `Elarion.Abstractions` owns the abstraction, `Elarion` owns the transport-neutral claims-based default, and `Elarion.AspNetCore` owns the HTTP integration that fills it in. ## The abstraction [#the-abstraction] ```csharp namespace Elarion.Abstractions.Identity; public interface ICurrentUser { string UserId { get; } string? Email { get; } IReadOnlyList Roles { get; } bool IsAuthenticated { get; } bool IsInRole(string role); bool HasClaim(string type, string value); IEnumerable GetClaimValues(string type); } ``` Inject it like any other service: ```csharp [Service] public sealed class OwnershipStamp(ICurrentUser user) { // Stamp the signed-in account onto a new row, so reads can be scoped per user. public string CurrentOwnerId => user.UserId; } ``` ## Wiring it in an ASP.NET Core host [#wiring-it-in-an-aspnet-core-host] The default implementation reads claims from the authenticated principal into a scoped snapshot. Register it during service configuration and add the middleware after authentication: ```csharp using Elarion.AspNetCore.Identity; // AddElarionCurrentUser / UseElarionCurrentUser builder.Services.AddElarionCurrentUser(); var app = builder.Build(); app.UseAuthentication(); app.UseElarionCurrentUser(); // after authentication, before endpoints app.UseAuthorization(); ``` `UseElarionCurrentUser()` seeds the scoped `ClaimsPrincipalCurrentUser` with the request principal once per request. Application handlers then read the snapshot, so they never touch `HttpContext` and stay testable — in a unit test you simply register a fake `ICurrentUser`. ### Endpoints that authenticate later [#endpoints-that-authenticate-later] `UseElarionCurrentUser()` sees the principal of the default scheme. A route group that names its own scheme — `RequireAuthorization(new AuthorizeAttribute { AuthenticationSchemes = "Basic" })`, as for [app passwords](/docs/capabilities/app-passwords) — is authenticated by the authorization middleware, after the request scope was seeded, so `ICurrentUser` would still be the earlier principal. Seed the scope again at the start of such an endpoint: ```csharp app.MapGroup("/sync") .RequireAuthorization(new AuthorizeAttribute { AuthenticationSchemes = "Basic" }) .MapGet("/{id}", async (HttpContext context, Guid id, IHandlerSender sender, CancellationToken ct) => { context.SeedElarionCurrentUser(); // ICurrentUser is now the Basic-authenticated caller … }); ``` `SeedElarionCurrentUser()` runs the same dispatch-scope initializers the middleware runs, with `HttpContext.User`; the DAV host of the CalDAV and CardDAV packages does this for its group. ## Works across every transport [#works-across-every-transport] `ICurrentUser` resolves identically under plain HTTP endpoints, JSON-RPC (single and batch), and MCP — no extra wiring. This matters because the JSON-RPC and MCP dispatchers run each call in a **fresh DI child scope** for isolation, and a child scope does not inherit the request scope's scoped instances. So the snapshot the request middleware initialized is not the one a JSON-RPC/MCP handler would otherwise resolve. Elarion bridges that gap explicitly (no `IHttpContextAccessor`, no `AsyncLocal`) with one uniform path: each transport captures the authenticated principal at its boundary into a `DispatchScopeContext`, and a single initializer seeds the per-call snapshot from it. JSON-RPC captures `HttpContext.User`; MCP captures the per-message `RequestContext.User` (its per-call scope is rooted at the session/app root, so it can't reach the HTTP request scope anyway). HTTP `[HttpEndpoint]` handlers run in the request scope and read the snapshot the middleware seeds — the same `Initialize(principal)` operation. The snapshot **materializes claims lazily**, so seeding it per call costs nothing until a handler reads a claim, and each snapshot parses at most once — no duplicate work. Authorization rides the same path, since the authorizer reads `ICurrentUser`. ### Carrying your own scoped state [#carrying-your-own-scoped-state] The same rail is the extension point for other per-call state (tenant, correlation id, …). Capture it at the boundary and seed it with an `IDispatchScopeInitializer`, registered with `TryAddEnumerable`. (For tenant isolation of EF Core data specifically, prefer the built-in [ambient tenant scoping](/docs/capabilities/multi-tenancy), whose `ClaimsTenantResolver` already reads the tenant claim from `ICurrentUser`.) ```csharp internal sealed class TenantScopeInitializer : IDispatchScopeInitializer { public void Initialize(IServiceProvider callScope, DispatchScopeContext context) { if (context.TryGet(out var user) && user is not null) { callScope.GetRequiredService().TenantId = user.FindFirstValue("tenant"); } } } // services.TryAddEnumerable( // ServiceDescriptor.Singleton()); ``` ## Mapping claims [#mapping-claims] By default the middleware maps standard claim types. Override them when your identity provider uses different ones: ```csharp builder.Services.AddElarionCurrentUser(options => { options.UserIdClaimType = "sub"; options.EmailClaimType = "email"; options.RoleClaimType = ClaimTypes.Role; options.DefaultRolesWhenAuthenticated = ["user"]; }); ``` | Option | Default | Purpose | | ------------------------------- | ----------------- | --------------------------------------------- | | `UserIdClaimType` | `"sub"` | Claim used for `UserId`. | | `EmailClaimType` | `"email"` | Claim used for `Email`. | | `RoleClaimType` | `ClaimTypes.Role` | Claim used to populate `Roles`. | | `DefaultRolesWhenAuthenticated` | empty | Roles granted to any authenticated principal. | Behind an authenticating reverse proxy, [proxy identity](/docs/capabilities/proxy-identity) registers this mapping from its own claim-name settings. ### One mapping per host [#one-mapping-per-host] A host has exactly one mapping, and the **first registration wins**: `AddElarionCurrentUser` (and with it `AddElarionClaimsCurrentUser`, `AddElarionIdentity` and `AddElarionProxyIdentity`, which call it) registers the `ClaimsCurrentUserOptions` singleton with `TryAdd`, so a later call's mapping is ignored without an error. When the application builds or replaces the principal itself — a local account's principal from ASP.NET Core Identity, a hand-built one — build it under the claim types of the mapping in effect rather than registering a second mapping. `ClaimsCurrentUserOptions` is resolvable from DI for exactly that; with Identity, point `IdentityOptions.ClaimsIdentity` at it. [Replacing the principal](/docs/capabilities/proxy-identity#replacing-the-principal) shows the recipe. ## Relationship to caching [#relationship-to-caching] [`CurrentUser`-scoped caching](/docs/capabilities/caching) depends on this abstraction: the cache uses `ICurrentUser.UserId` (hashed) to isolate entries per user. If you use `CurrentUser` scope, make sure `AddElarionCurrentUser()` and `UseElarionCurrentUser()` are wired and the principal carries a user id claim. # Data-rate shaping (/docs/capabilities/data-rate-shaping) Between "something produces data many times per second" and "the database, the UI, or a single-writer loop consume it" sit small concurrency problems every gateway and simulation tier hand-rolls — each \~100 lines that are easy to get subtly wrong (flush/publish races, shutdown drains, timer and ownership lifecycles). `Elarion` core ships them once, in the `Elarion.Buffering` namespace ([ADR-0055](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0055-data-rate-shaping-helpers.md), [ADR-0069](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0069-producer-owned-hot-state-buffering.md)). Which one do I want? | Primitive | Workload shape | Contract | | ------------------------------ | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `WriteBehindBuffer` | Append-all samples — every reading is a new fact | Accumulate, flush in batches by count or interval; natural flush body: [`ExecuteInsertAsync`](/docs/capabilities/bulk-operations) | | `KeyedConflater` | Latest-per-key emits — hot values headed for the UI | At most one emit per key per interval, never ending stale; natural publish body: [`IClientEventPublisher.PublishAsync`](/docs/capabilities/events/client-events) | | `StagedBatchFlusher` | Producer-owned state snapshots — dirty-flag state where only the latest matters | Single-flight ownership handoff of one preallocated batch to a background writer | | `BoundedMpscQueue` | Commands into a single-writer loop — many producers, one consumer | Fixed-capacity lock-free struct queue; full returns `false`, the caller picks the backpressure policy | All four are BCL-only and need no DI registration (construct them wherever the data path lives — typically an [actor](/docs/concepts/actors), gateway component, or the loop that owns the state). The whole family is **loss-tolerant by contract**: a crash, a full queue, or a failed flush loses at most recent in-flight data. Data that must not be lost belongs in a handler transaction and [the outbox](/docs/capabilities/events/backends), never in these primitives. ## `WriteBehindBuffer` — batch samples to the database [#writebehindbuffert--batch-samples-to-the-database] ```csharp var buffer = new WriteBehindBuffer( async (batch, ct) => await WriteBatchAsync(batch, ct), // e.g. ExecuteInsertAsync on a fresh scope new WriteBehindBufferOptions { MaxItems = 500, // flush when the batch is full… FlushInterval = TimeSpan.FromSeconds(5), // …or when the oldest item is this old }, onFlushError: (ex, batch) => logger.LogWarning(ex, "Dropped {Count} samples", batch.Count)); buffer.Add(measurement); // any thread, never blocks on the flush target await buffer.FlushAsync(ct); // explicit flush — delegate failures rethrow here await buffer.DisposeAsync(); // stops the timer, flushes the tail, never throws ``` The contract is **loss-tolerant samples**: * The buffer is bounded — past `Capacity` (default 4 × `MaxItems`) the *oldest* unflushed item is dropped, so a slow or down database bounds memory instead of growing it. `DroppedCount` meters the pressure; a climbing value means the flush target can't keep up. * A failed flush **drops its batch** rather than retrying it (a poisoned batch must never wedge the pipeline). Explicit `FlushAsync` rethrows to its caller; background and dispose flushes route to the `onFlushError` callback — without one they are swallowed, so supply it in anything beyond a prototype. * Flushes are single-flight: items added while a flush runs coalesce into the next drain pass, so a slow target gets fewer, larger calls — not a stack of concurrent ones. Samples that must not be lost don't belong here — record them transactionally in the handler and let [the outbox](/docs/capabilities/events/backends) do the deferring. ## `KeyedConflater` — latest-wins to the UI [#keyedconflatertkey-tvalue--latest-wins-to-the-ui] ```csharp var conflater = new KeyedConflater( async (symbol, quote, ct) => await clientEvents.PublishAsync(quote, ClientEventScope.Global, ct), new KeyedConflaterOptions { MinInterval = TimeSpan.FromMilliseconds(250) }); conflater.Post("ACME", update); // any thread, never blocks on the publish target await conflater.DisposeAsync(); // publishes every pending latest, then drops late posts ``` Each key emits at most once per `MinInterval`: * The first post of an idle key emits **immediately** (leading edge) — a dashboard shows the first value without waiting a window. * Posts inside the window **conflate**: only the newest value survives, and it emits when the window elapses (trailing edge). A quiet key therefore always publishes its final value — conflation never ends on a stale reading. * Emissions for one key never overlap: a publish slower than the window lowers the effective rate instead of stacking calls. Keys are independent, and idle keys retire automatically, so unbounded key spaces (device ids, symbols) don't leak. * Delivery is **at-most-once**, matching the client-event contract: a publish failure drops that emission to the optional `onPublishError` callback, and the next post heals. ## `BoundedMpscQueue` — commands into a single-writer loop [#boundedmpscqueuet--commands-into-a-single-writer-loop] When many producer threads (connection receive continuations, timers) feed one consumer thread (a simulation tick loop, a device writer), `ConcurrentQueue` allocates segments and is unbounded, and `Channel` allocates and is async-shaped. `BoundedMpscQueue` is the third shape: a fixed-capacity, array-backed, lock-free struct queue (Vyukov's bounded algorithm) whose `TryEnqueue` and `TryDequeue` never block and never allocate — all slots are preallocated at construction, and capacity rounds up to a power of two: ```csharp var commands = new BoundedMpscQueue(4096); // Producers — any thread, e.g. a connection receive continuation: if (!commands.TryEnqueue(new MoveCommand(entityId, x, y))) _dropped++; // full = backpressure; this message class is loss-tolerant // The single consumer — the tick loop: while (commands.TryDequeue(out var command)) Apply(command); ``` The contract: * **Bounded means backpressure, and the policy is yours.** A full queue returns `false` — there are no blocking or waiting APIs. Decide per message class: drop loss-tolerant traffic (movement, telemetry), retry or fail must-land control messages. The queue also owns no loop or thread; the application drains it from whatever tick it already has. * **FIFO per producer.** Cross-producer arrival order is slot-claim order (the order producers won the enqueue cursor), which under contention may differ from call order. * **Single consumer.** `TryDequeue` must never run concurrently with itself — one consumer at a time (migrating the consumer between threads is fine as long as calls don't overlap). A debug-only assertion catches violations. * **Reference hygiene.** `T` may carry object references (a command with a payload array); a dequeued slot is cleared so the queue never keeps them alive until the slot's next reuse. For pure value types the clear compiles away. ## Composition: the actor telemetry path [#composition-the-actor-telemetry-path] The recommended owner is the actor that already serializes the hot state (the [write-behind and live-telemetry use cases](/docs/concepts/actors#when-not-to-use-an-actor)): it constructs both helpers as activation state, `Add`s/`Post`s from its turns, and disposes them in `OnDeactivateAsync` — one sample stream, two shaped consumers: ```csharp public Task RecordAsync(Measurement m) { _buffer.Add(m); // → batched ExecuteInsertAsync every few seconds _conflater.Post(m.Sensor, m); // → at most 4 client events/s per sensor (MinInterval = 250 ms) return Task.CompletedTask; } ``` These four shapes are deliberately the whole surface — windows, joins, or replay are the trigger for a real reactive/streaming library, not for growing these helpers. For ordered, gap-visible streams where element identity matters, use [ordered streams](/docs/capabilities/events/streams) instead of conflation. ## Below the helpers: dirty-flag-and-sweep for simulation state [#below-the-helpers-dirty-flag-and-sweep-for-simulation-state] Both helpers assume an **append-shaped sample stream**: every reading is a new fact, produced at gateway rates — hundreds of keys, a few hertz each. A simulation loop is a different workload: thousands of entities mutating at tick rate, where only the *latest* state of each entity matters and the update path is allocation-sensitive. At that tier, even latest-wins helper machinery is overhead — `WriteBehindBuffer` queues every update, and `KeyedConflater` pays a dictionary hit and timer scheduling per key per window. Keep both off a per-update hot path. The standard shape there is **dirty-flag-and-sweep**, in application code: 1. An update mutates the entity the loop already owns and sets `Dirty = true` — field writes, zero allocation, no per-update queue entry. 2. A periodic sweep (tick-aligned or interval) walks a stable iteration structure — a preallocated list or bitset of dirty indices, not LINQ — copies dirty state into a reused batch buffer, clears the flags, and hands the batch off for **one batched write**. 3. Explicit save points (a session ending, an entity unloading) call the same sweep directly. The sweep itself allocates (rows, command, parameters) — at flush frequency, not update frequency, which is the point. A crash loses at most one interval: the same loss-tolerant contract as the rest of the family, so the same rule applies — state that must not be lost belongs in a handler transaction and [the outbox](/docs/capabilities/events/backends), not in this loop. ### `StagedBatchFlusher` — the generic half of the handoff [#stagedbatchflushertbatch--the-generic-half-of-the-handoff] The dirty bit, the iteration structure, and the batch's shape are application business. What *is* generic — and easy to get subtly wrong — is the ownership/signaling protocol between the sweep and the background write: who may touch the batch when, how the writer signals it's done, what happens when the write throws, and who drains on shutdown. `StagedBatchFlusher` owns exactly that half and never inspects the batch: * **Ownership protocol.** The producer stages into the batch only while `IsIdle` is `true`. `TrySubmit` transfers ownership to the background writer without blocking or allocating; when the write delegate returns *or throws*, ownership returns and `IsIdle` becomes `true` again — with full visibility of the writer's effects, so the producer can safely reuse the batch. An optional `reset` callback runs at each ownership return so the clear-the-sections logic lives in one place. * **Skip and retry.** `TrySubmit` returning `false` means a batch is still in flight — stage nothing and let the dirty flags carry the state to the next sweep. That is why there is exactly **one** batch and no internal queue: flags already bridge a busy interval, so a second buffer would buy latency nobody needs at the cost of ownership complexity. * **Error policy.** A throwing write drops that batch's staged content by contract (latest-wins makes this safe — the next sweep re-stages current values), surfaces through `onFlushError`, and never tears down the loop or leaks ownership. * **Shutdown drains.** `DisposeAsync` completes the in-flight write and writes a batch submitted before disposal, uncancelled — the last state of departed entities — bounded by an optional `DisposeTimeout`. `FlushAsync` awaits idleness at explicit save points without disposing. An [actor](/docs/concepts/actors) is the natural owner of the hot state: updates and the sweep are both turns on one mailbox, so the sweep sees a consistent view with no locking, the `IsIdle` gate is race-free (only the mailbox submits), and the sweep trigger is a facade call from whatever tick the application already has — the simulation loop, a [scheduled job](/docs/capabilities/scheduling), or a hosted service: ```csharp [SqlRecord("entity_positions")] public sealed partial record EntityPositionRow { public required Guid Id { get; init; } public required float X { get; init; } public required float Y { get; init; } } // The batch and its sections are application code; the flusher never looks inside. public sealed class PositionBatch { public List Rows { get; } = []; } [Actor] public sealed class ZoneActor : IActorLifecycle { // Mutable by design: hot per-entity state, owned and serialized by the mailbox. private sealed class EntitySlot { public Guid Id; public float X; public float Y; public bool Dirty; } private readonly Dictionary _entities = []; private readonly PositionBatch _batch = new(); // the one preallocated, producer-owned batch private readonly StagedBatchFlusher _flusher; public ZoneActor(ISqlDatabase db, ILogger logger) { _flusher = new StagedBatchFlusher( async (batch, ct) => { await using var session = await db.OpenSessionAsync(ct); await session.InsertManyAsync(batch.Rows, " ON CONFLICT (id) DO UPDATE SET x = EXCLUDED.x, y = EXCLUDED.y", ct); }, onFlushError: (ex, batch) => logger.LogWarning(ex, "Dropped {Count} rows", batch.Rows.Count), reset: static batch => batch.Rows.Clear()); } public Task Move(Guid id, float x, float y) { // hot path: field writes only var slot = _entities[id]; slot.X = x; slot.Y = y; slot.Dirty = true; return Task.CompletedTask; } public Task Sweep() { // tick-aligned, e.g. every 30 s if (!_flusher.IsIdle) return Task.CompletedTask; // writer busy — flags carry to the next sweep foreach (var slot in _entities.Values) { if (!slot.Dirty) continue; slot.Dirty = false; _batch.Rows.Add(new EntityPositionRow { Id = slot.Id, X = slot.X, Y = slot.Y }); } if (_batch.Rows.Count > 0) _flusher.TrySubmit(_batch); return Task.CompletedTask; } public async ValueTask OnDeactivateAsync(CancellationToken ct) { await Sweep(); // stage whatever is still dirty… await _flusher.DisposeAsync(); // …and drain it before the actor goes away } } ``` The framework's contribution beyond the handoff is the flush target, per host tier: | Tier | Batched upsert path | | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | EF | [`ExecuteInsertAsync`](/docs/capabilities/bulk-operations) with `OnConflict = BulkInsertConflictBehavior.Update` — binary COPY staged through a temp table, merged with native `ON CONFLICT` | | EF-free / AOT | [`InsertManyAsync`](/docs/capabilities/sql-mapping#reads-and-writes) with an `ON CONFLICT …` suffix — one auto-prepared statement per flush; source-generated binary COPY for this tier is proposed in [ADR-0068](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0068-aot-sql-binary-copy.md) | There is still deliberately no `DirtySweep` helper. The dirty bit and the iteration structure belong to the application's entity representation, and any framework intermediary between the update and the flag would reintroduce exactly the per-update bookkeeping this shape exists to avoid. New state families — even ones with maximally different persistence semantics, like replace-sets with deletions next to row updates — extend the *batch*, never the protocol: the framework's seams are the mailbox that serializes the hot state, the flusher that owns the handoff, and the batched write the sweep flushes into. # Device identity (/docs/capabilities/devices) Every device gateway ends up building the same identity chain: **pairing** (a short human-typeable code redeemed once by the device for its identity and key), **key storage** (a per-device symmetric key), and **connect-time authentication** (a challenge/response producing the device principal). Hand-rolling it is exactly where mistakes are security-relevant — nonce reuse, non-constant-time comparison, guessable codes, keys minted from the wrong randomness. `Elarion.Devices` owns that chain and nothing else (ADR-0054); it plugs into the [connections](/docs/capabilities/connections) handshake seam with three lines. Deliberate non-goals: device inventory/management UI, OTA/firmware, and certificate/mTLS enrollment stay app concerns. ## Wiring [#wiring] ```csharp // The DbContext maps the two tables (device keys + pending pairing codes): [GenerateDbSets] [GenerateElarionDeviceIdentity] public partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } // One call registers the whole chain — pairing service, HMAC verifier, durable stores: builder.Services.AddElarionDeviceIdentityEntityFrameworkCore(); ``` Tests and single-node demos can use the volatile stores instead — an explicit opt-in, never a silent default, because device keys are durable identity: ```csharp services.AddElarionDeviceIdentity(); services.AddElarionInMemoryDeviceIdentityStores(); ``` ## Pairing [#pairing] An operator asks for a code (an ordinary authorized handler); the device redeems it once. The device id is **pre-assigned at issue**, so the issuer can attach it to its own domain state (a pending device row, a site assignment) before the device ever calls in. ```csharp [Handler("devices.startPairing")] [RequirePermission("devices", "provision")] public sealed class StartDevicePairing(IDevicePairingService pairing) : IHandler> { public sealed record Command; public sealed record Response(string Code, string DeviceId, DateTimeOffset ExpiresAt); public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var issued = await pairing.IssueAsync(cancellationToken: ct); // Attach issued.DeviceId to your domain state here (pending device, site, tenant, …). return new Response(issued.Code, issued.DeviceId, issued.ExpiresAt); } } ``` Codes are CSPRNG-drawn from a Crockford-style alphabet (no `0/1/I/L/O/U`, so they survive being read aloud), default 8 characters and 10 minutes, and are stored **SHA-256-hashed** — the plain code exists only in the issue response. Redeem normalizes what a human typed (case, dashes, whitespace), claims the code atomically (one `DELETE … RETURNING`, so concurrent redeems have exactly one winner across nodes), mints the key, and returns the credentials. Unknown, expired, and already-used codes are deliberately indistinguishable. The redeem endpoint stays **app-owned** — it is anonymous by nature, so rate-limit it: ```csharp app.MapPost("/devices/redeem", async (RedeemBody body, IDevicePairingService pairing, CancellationToken ct) => { var credentials = await pairing.RedeemAsync(body.Code, ct); return credentials is null ? Results.NotFound() : Results.Ok(new { deviceId = credentials.DeviceId, key = Convert.ToBase64String(credentials.Key.Span), }); }).RequireRateLimiting("device-pairing"); ``` Redeeming a code issued for an **already-provisioned device id rotates its key** — issuing that code is the re-key authorization (device reset, lost key), so re-pairing is just "issue a new code for the same id". Reissuing for the same id atomically supersedes every earlier pending code, so a stale screen/photo cannot later rotate a newly established key. A pending device can also revoke its capability without deleting its identity: call `IDevicePairingService.RevokeAsync(deviceId)`. Revoked, expired, unknown, and used codes all redeem as the same `null` result. Expired codes are tiny rows swept by `IPairingCodeStore.DeleteExpiredAsync` — schedule it with a `[ScheduledJob]`. The EF Core provider adds an index on pending-code `device_id`; add/apply the corresponding migration when upgrading an existing database. Revoking established credentials is still `IDeviceKeyStore.RemoveAsync(deviceId)`: the device can no longer authenticate (to force the point immediately, look up its live connections with `registry.GetForPrincipal(deviceId)` and close each adapter connection). ## Connect-time authentication [#connect-time-authentication] `HmacChallengeVerifier` is shaped for a connection-handshake authenticator (a `WebSocketConnectionSession` / `TcpConnectionSession`, created per link by its handler): mint a nonce, send it, verify the device's `HMAC-SHA256(key, nonce)` in constant time, and return the ticket. ```csharp public sealed class GatewaySession(HmacChallengeVerifier verifier) : WebSocketConnectionSession { public override async ValueTask AuthenticateAsync( WebSocketHandshakeContext handshake, CancellationToken ct) { var nonce = HmacChallengeVerifier.CreateNonce(); await handshake.SendTextAsync($"challenge:{Convert.ToBase64String(nonce)}", ct); // Device answers "deviceId:base64(HMAC-SHA256(key, nonce))". var answer = await handshake.ReceiveTextAsync(ct); if (answer?.Split(':', 2) is not [var deviceId, var mac]) { return null; } var principal = await verifier.VerifyAsync(deviceId, nonce, Convert.FromBase64String(mac), ct); if (principal is null) { return null; // → policy-violation close, nothing registered } return new ClientConnectionTicket { Principal = principal, PrincipalId = deviceId }; } // CreateProtocol(...) — your codec, see the connections page. } ``` The nonce is per connection attempt and lives only for that handshake — a captured response can never be replayed. Unknown device ids pay the same MAC computation as known ones, so timing does not leak which ids exist. `HmacChallengeVerifier.ComputeResponse(key, nonce)` is the device-side half, handy for simulators (`Elarion.Connections.Simulation`) and tests. ## The device principal [#the-device-principal] `VerifyAsync` returns a `ClaimsPrincipal` with a stable shape — authentication type `ElarionDevice`, the device id as both the `elarion:device` claim and the name identifier — so device-initiated dispatches flow through `ICurrentUser`, `[RequirePermission]`, and auditing unchanged. `DevicePrincipal.Create(deviceId, extraClaims)` adds permission claims for devices that issue commands; `DevicePrincipal.IsDevice(...)` / `GetDeviceId(...)` recognize it later. One documented trade-off: keys are raw symmetric material (the server recomputes MACs), the self-hosted posture. An id is never the only gate — pair the device principal with the same authorization attributes any caller faces, fail-closed. # Entity Framework Core (/docs/capabilities/entity-framework) The EF Core package is **optional**. Use it when you want the same compile-time, explicit-convention style for persistence wiring that the rest of Elarion uses — generated `DbSet` properties and direct `IEntityTypeConfiguration` calls instead of reflection-based assembly scanning. It generates, onto your **concrete `DbContext`**, a `DbSet` for every entity you configure plus a `ConfigureEntities(ModelBuilder)` method that applies your configurations. Handlers use that `DbContext` **directly** — its `DbSet`s, LINQ, raw SQL, and provider functions. There is no repository layer, and no context interface in front of it: the database is application logic, not an abstraction. This is deliberate (see [Why Elarion → The database is application logic](/docs/why-elarion#the-database-is-application-logic-not-an-abstraction)). A per-entity `IClientRepository`, or an `IAppDbContext` interface, only hides the model you are actually programming against and forces a leaky escape hatch the moment you need raw SQL. With full LINQ, projections, change tracking, and provider features available on the `DbContext`, you query it directly. See [Handlers → Accessing data](/docs/concepts/handlers#accessing-data). ## Setup [#setup] Reference the `Elarion.EntityFrameworkCore` package — it bundles the EF Core source generator — in **every** project that declares `[EntityConfiguration]` configurations or a `[GenerateDbSets]` context. Configurations describe the one shared model every feature draws on, so they are part of the shared **data layer**, not feature-owned: they live in a shared `Persistence` layer alongside the concrete `DbContext` (the database is application logic — see [Solution structure](/docs/concepts/solution-structure)), while entities themselves stay plain classes. The generator discovers configurations wherever they live, so placement is a convention. If you *do* split the configurations and the `DbContext` into separate assemblies, each assembly that declares the configurations and the one that holds the `DbContext` need this reference: the former so its generator emits the per-assembly configuration manifest, the latter so the generator reads that manifest to fill the context with `DbSet`s: ```xml ``` ## Configuring entities [#configuring-entities] Entities themselves are **plain classes** — there is no entity marker attribute (previously `[DbEntity]`). Participation is driven entirely by an `[EntityConfiguration]` on the entity's `IEntityTypeConfiguration` implementation. That configuration class is the **single source of truth**: it drives both the generated `DbSet` and the `Configure(...)` application. A configured entity is a discovered entity. ```csharp // Domain/Invoice.cs — plain class, no attribute namespace MyApp.Domain; public sealed class Invoice { public Guid Id { get; set; } } ``` ```csharp // Persistence/InvoiceConfiguration.cs — the single source of truth using Elarion.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace MyApp.Persistence; [EntityConfiguration] public sealed class InvoiceConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { /* ... */ } } ``` Only a configuration carrying `[EntityConfiguration]` is discovered. A plain `IEntityTypeConfiguration` with no attribute is ignored — it produces neither a `DbSet` nor a `Configure(...)` call. A single `[EntityConfiguration]` class may implement `IEntityTypeConfiguration` more than once; each implemented entity gets its own `DbSet` and its own `Configure(...)` call. An `[EntityConfiguration]` class that implements no `IEntityTypeConfiguration` is reported as **ELEFC001** (Warning, category `Elarion.EntityFrameworkCore`) — nothing is generated for it. ## Entity identity [#entity-identity] **Elarion entities own their ids.** The application mints the id in code at the creation site, the database never generates domain keys, and the generated model declares exactly that. Use `Guid.CreateVersion7()` — a UUIDv7's time-ordered prefix keeps primary-key b-tree inserts append-mostly, where random v4 ids (`Guid.NewGuid()`) scatter across the whole index: ```csharp var invoice = new Invoice { Id = Guid.CreateVersion7(), CreatedAt = clock.GetUtcNow(), // … }; db.Invoices.Add(invoice); ``` Because the id exists *before* `SaveChanges`, handlers can wire foreign keys, soft references, and links inside one unit of work — and return the id from a create handler — without a round trip. Two conscious trade-offs come with v7: the id **embeds its creation instant** (readable wherever the id is visible, e.g. in URLs), and ids created within the same millisecond are **mutually unordered** — never sort business data by id; that is what `CreatedAt` is for. The one place to keep a random v4 `Guid.NewGuid()` is an id that must be *unpredictable* (a capability-style token) — precisely because a v7 id leaks its creation timestamp. **ELID001** (Warning, category `Elarion.Identifiers`) flags every `Guid.NewGuid()` reference — called or passed as a method group — and names `Guid.CreateVersion7()` as the replacement. Flagging every site is deliberate: whether a given id becomes a key is not decidable at the call site. At the unpredictable-id site, keep v4 and suppress `ELID001` with a justification — that turns the exception into an argued, visible choice instead of an accidental one. ### The model declares client-assigned keys [#the-model-declares-client-assigned-keys] EF Core's default convention claims the opposite of the idiom above: a `Guid` primary key is declared *generated* (`ValueGeneratedOnAdd`, client-side), and EF's **insert-vs-update heuristic rides that claim** — a set value on a "generated" key means "this row already exists". The mismatch detonates in one specific spot, the natural *replace the children* update on a tracked parent: ```csharp var tenant = await db.Tenants.Include(t => t.Contacts).SingleAsync(t => t.Id == id, ct); tenant.Contacts.Clear(); tenant.Contacts.Add(new Contact { Id = Guid.CreateVersion7(), … }); await db.SaveChangesAsync(ct); // Under the convention's claim: UPDATE … WHERE id = → 0 rows // → DbUpdateConcurrencyException (dotnet/efcore#35090) ``` The generated `ConfigureEntities` therefore ends with a client-assigned-keys pass that declares every domain entity's single-property `Guid` primary key `ValueGenerated.Never`. It is scoped to the **assemblies of the discovered `[EntityConfiguration]` entities**, so navigation-discovered children — exactly where the heuristic detonates — are covered, while Identity, DataProtection, and Elarion feature tables keep their packaged generation. Deliberate generation choices always win: explicit or data-annotation `ValueGenerated` configuration, a custom `HasValueGenerator`, and store defaults (`HasDefaultValueSql` and friends) are never overridden. One entity that *should* use EF-generated ids opts back in inside its configuration: ```csharp builder.Property(e => e.Id).ValueGeneratedOnAdd(); // explicit configuration wins over the pass ``` The change is **schema-neutral**: adopting it on an existing app produces an *empty* migration whose only purpose is re-syncing the model snapshot (EF refuses to `Migrate()` with pending model changes). An app that previously left `Id` unset and relied on EF's client-side generator must now set ids in code (recommended) or configure `ValueGeneratedOnAdd()` explicitly. The EF **InMemory provider skips the affected-rows check** (SQLite does not enforce it either), so a write misclassified by the generated-key heuristic stays green in unit tests and only fails on a real database. Cover replace-children behavior with a real-database integration test (e.g. Testcontainers PostgreSQL) — creates always work (`Add` forces the whole graph `Added`), so a create-path test proves nothing here. See [Testing persistence](/docs/concepts/persistence-and-transactions#testing-persistence) for the fixture pattern and why InMemory hides this class of bug. The full rationale — including why database-side `uuidv7()` and an EF `ValueGenerator` were rejected — lives in [ADR-0038](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0038-client-assigned-entity-identity.md). ## Generating DbSets [#generating-dbsets] Annotate your **concrete partial `DbContext`** with `[GenerateDbSets]`. The generator emits, onto that class, a `DbSet` for every configured entity and a `ConfigureEntities(ModelBuilder)` method — call it from `OnModelCreating`: ```csharp using Elarion.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace MyApp.Persistence; [GenerateDbSets] public sealed partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); ConfigureEntities(modelBuilder); // generated } } ``` The `DbContext`, its configurations, and the migrations all live together in the application's `Persistence` layer; provider registration (`UseNpgsql(...)` + the connection string) is the host's job. Handlers inject the concrete `AppDbContext` and query its `DbSet`s. ## Multiple contexts with scopes [#multiple-contexts-with-scopes] For multiple contexts, use string-constant scopes — on each `[EntityConfiguration]` and on each `[GenerateDbSets]` context — so each context only sees the entities it owns: ```csharp public static class PersistenceScopes { public const string Main = "main"; public const string AiAgent = "ai-agent"; } [EntityConfiguration(PersistenceScopes.Main)] public sealed class InvoiceConfiguration : IEntityTypeConfiguration { /* ... */ } [EntityConfiguration(PersistenceScopes.AiAgent)] public sealed class ChatSessionConfiguration : IEntityTypeConfiguration { /* ... */ } [EntityConfiguration(PersistenceScopes.Main, PersistenceScopes.AiAgent)] public sealed class UserConfiguration : IEntityTypeConfiguration { /* ... */ } [GenerateDbSets(PersistenceScopes.Main)] public sealed partial class MainDbContext(/* ... */) : DbContext { /* ... */ } [GenerateDbSets(PersistenceScopes.AiAgent)] public sealed partial class AiAgentDbContext(/* ... */) : DbContext { /* ... */ } ``` A scope is an **application-layer** partition (a separate `DbContext` over, by default, the same database and schema) — not physical data isolation; that is a [bounded context](/docs/concepts/solution-structure). Scope behavior: * `[GenerateDbSets]` without scopes includes every `[EntityConfiguration]`. * `[GenerateDbSets("scope")]` includes only configurations whose `[EntityConfiguration(...)]` scopes intersect. * `[EntityConfiguration]` without scopes participates only in unscoped/global contexts. * Shared configurations can list multiple scopes. ## Entity configuration [#entity-configuration] The generator discovers `[EntityConfiguration]` implementations in the current and referenced assemblies and emits a reflection-free, AOT-friendly `ConfigureEntities(ModelBuilder)` built from direct `ApplyConfiguration` calls, equivalent to: ```csharp modelBuilder.ApplyConfiguration(new InvoiceConfiguration()); ``` A single instance is reused across the entities a multi-entity configuration configures. Because the `[EntityConfiguration]` drives both the `DbSet` and the schema, every configured entity gets a `DbSet` — there is no separate "schema-only" path. An unscoped context applies every discovered configuration; a scoped context filters configurations to the selected scope, so unrelated scoped contexts do not configure each other's entities. This avoids `ApplyConfigurationsFromAssembly(...)` reflection scanning and keeps model wiring inspectable and AOT-friendly. The trade-off is explicit participation: each entity opts in through its `[EntityConfiguration]`, and scoped contexts require matching scopes. In-assembly configurations are discovered through the syntax provider, so `dotnet build` and the CLI always reflect the current source. If a **newly added** same-assembly `[EntityConfiguration]` does not produce its `DbSet` in Rider/ReSharper until you restart, that is the IDE's source-generator host refreshing lazily, not the generator — build the project or **Invalidate Caches / Restart** to refresh it. See [Troubleshooting](/docs/reference/troubleshooting). Blob entities are **not** part of `[EntityConfiguration]` / `[GenerateDbSets]`. A provider such as `Elarion.Blobs.PostgreSql` configures its tables directly in your `OnModelCreating` (via `UseElarionBlobStorage()`, or `[GenerateElarionBlobStorage]` on a `[GenerateDbSets]` context), so they join your context's model without opting into entity generation — see [Blob storage](/docs/capabilities/blob-storage). ## Value-shape conventions [#value-shape-conventions] Three conveniences every EF consumer ends up hand-rolling. All **opt-in**, all no-configuration: the call *is* the decision, and per-property deviation is already expressible in that property's own configuration. ### Enums as text [#enums-as-text] `modelBuilder.UseElarionEnumStringConversions(...)` stores enum properties as their **name** rather than their ordinal. A text column survives reordering or inserting enum members and reads as itself in a database you migrate and debug; an ordinal column silently re-points every existing row when the enum is edited. Call it as a post-pass, after the configurations have run, and **pass the assemblies that own your entities**: ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); ConfigureEntities(modelBuilder); // generated modelBuilder.UseElarionEnumStringConversions(typeof(Invoice).Assembly); } ``` Calling it with **no arguments** applies the pass to *every* entity type in the model — including types a third-party library or another Elarion package mapped into the same `DbContext`, whose enum columns then change from integer to text. That is a schema change on someone else's model, so scope the call unless the context's model is entirely application-owned. The generated client-assigned-keys pass scopes itself by entity assembly for the same reason. Nullable enums are covered. **Explicit configuration always wins** — a property that already declares a value converter or a provider CLR type is left alone, so one enum stored as an ordinal opts out by saying so: ```csharp builder.Property(e => e.Status).HasConversion(); // untouched by the pass ``` ### A `string[]` column, converter and comparer together [#a-string-column-converter-and-comparer-together] `HasElarionJsonStringArray()` stores a `string[]` as a JSON text column **and** attaches the matching comparer in the same call: ```csharp builder.Property(e => e.Tags).HasElarionJsonStringArray(); // A nullable string[]? property: PropertyBuilder is invariant, so the null-forgiving operator // selects the PropertyBuilder the method is declared on. builder.Property(e => e.OptionalTags!).HasElarionJsonStringArray(); ``` The pairing is the point. A converted collection with no comparer is compared by *reference*, so EF misses every in-place edit (`entity.Tags[0] = "…"` never saves). And a hand-rolled comparer is where the subtle bug lives: EF snapshots the property to detect changes, so its equality and hashing halves must **agree** — pairing an order-*independent* equality with an order-*dependent* hash (or the reverse) breaks the `GetHashCode` contract, and change detection then depends on how the elements happened to be ordered. `ElarionValueComparers.Sequence()` (arrays) and `ElarionValueComparers.SequenceList()` (`List`) expose that comparer for your own converters. Both are consistently **order-dependent**: equality is `SequenceEqual`, the hash aggregates the same elements in order, and the snapshot is a shallow copy that carries `null` through unchanged — reordering a stored list is a change, which is the right default when the persisted order is part of the value. ```csharp builder.Property(e => e.Tags) .HasConversion( tags => string.Join(',', tags), value => value.Split(',', StringSplitOptions.RemoveEmptyEntries), ElarionValueComparers.Sequence()); ``` Serialization goes through the package's own source-generated JSON context, so the column encoding is reflection-free (trim/AOT-safe) and never moves when a host retunes its wire JSON. Nulls are **not** converted: EF builds the converter with its default `convertsNulls: false` and short circuits them, so a `null` property writes SQL `NULL` and a `NULL` column reads back as a `null` array — not an empty one. What the converter does absorb is an **empty string**, the value an `AddColumn` migration with a `""` default leaves in existing rows, which reads back as an empty array instead of throwing on invalid JSON. ### Sortable `DateTimeOffset` on SQLite — a recipe, not an API [#sortable-datetimeoffset-on-sqlite--a-recipe-not-an-api] SQLite has no native `DateTimeOffset`: EF stores it as text, and `ORDER BY` on that text is not a chronological order across differing offsets. If a SQLite-backed query needs newest-first at the database (rather than sorting client-side), store a sortable surrogate — `UtcTicks` as `long`: ```csharp builder.Property(e => e.OccurredAt) .HasConversion( value => value.UtcTicks, ticks => new DateTimeOffset(ticks, TimeSpan.Zero)); ``` Two consequences to accept deliberately: the original **offset is discarded** — every value reads back as UTC, so keep the local offset in its own column if the application needs it — and the column is opaque in a SQL client. This stays a documented recipe rather than a shipped API because it is provider-specific and lossy; Elarion's centre of gravity is PostgreSQL, where `timestamptz` sorts correctly with no surrogate. ## Interceptors and their order [#interceptors-and-their-order] Elarion's EF Core features attach their interceptors through `IDbContextOptionsConfiguration`, so a host never calls `AddInterceptors` for them. EF Core runs `SaveChanges` interceptors in the order they were added, and the configurations apply in **registration order** — so the order of the `Add…` calls is the order of the interceptors: | Registration | Runs in | Must come | | ------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------------- | | `AddElarionTenantScopingEntityFrameworkCore()` | `SavingChanges` — stamps the tenant on added rows | before auditing, so the audit records the stamped tenant | | `AddElarionAuditingEntityFrameworkCore()` | `SavingChanges` — captures the field-level changes | after tenant scoping, so it records the final values | | The integration event bus / outbox | after the save or commit | anywhere — it reacts to the commit, not the change set | Interceptors added in `AddDbContext`'s own options callback run at that callback's registration position, which is usually first. That is the right place for an application soft-delete interceptor: it turns a deletion into an update before auditing records it. An interceptor your persistence assembly adds in `OnConfiguring` runs after all of these. ## Pagination [#pagination] List handlers page against the `DbContext` and return a transport-neutral envelope: `Page` with keyset cursors, or `OffsetPage` with a required total. The keyset definition generator (`[Keyset]`) ships in the EF Core generators package alongside the DbSet generation, but the runtime helpers, contracts, and the row-value seek note all live with the rest of pagination. Keyset (cursor) and offset paging, the `Page` and `OffsetPage` envelopes, sort maps, and the opaque cursor codec. # Event backends (/docs/capabilities/events/backends) The **domain** plane (`IDomainEventBus`) is always in-memory and inline — there is no backend choice to make there. The **integration** plane (`IIntegrationEventBus`) is the only broker-portable plane, and it is where you pick a backend. Two ship: a best-effort **in-memory** tier and the durable **EF Core transactional outbox**. (For the plane model itself, see the [events overview](/docs/capabilities/events).) ## Choosing a backend [#choosing-a-backend] **Recommended: the EF Core outbox** for anything that must not be lost. The in-memory tier is a best-effort convenience for events you can afford to drop on a crash. | | In-memory (`Elarion.Messaging.InMemory`) | EF Core outbox (`Elarion.Messaging.Outbox`) | | --------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | Durability | best-effort; flushed-but-undelivered events are **lost on crash** | **at-least-once**; survives restarts | | How it captures | a per-scope buffer flushed after commit | one immutable envelope per distinct target role in the **same transaction** as your data | | Delivery | a hosted channel pump (`EventDispatchPump`) | a hosted worker that polls, leases, dispatches, retries (`OutboxDeliveryService`) | | EF Core | needs interceptors on your `DbContext` (registered for you) | needs the outbox table on your `DbContext` | | Use when | events are advisory and loss is acceptable | events drive real side effects that must happen | Both deliver **at-least-once and unordered** to consumers. Handler-form consumers are deduped by the **built-in inbox** by default (a per-consumer claim on the message id, committed with the consumer's own writes); method-form and opted-out consumers must absorb duplicates themselves — see [Handling duplicates](/docs/capabilities/events/consuming-events#handling-duplicates). ## In-memory integration bus [#in-memory-integration-bus] Register the in-memory tier with `AddElarionInMemoryEventBus()` from `Elarion.Messaging.InMemory`. This wires the domain plane (`AddElarionDomainEventBus`) **plus** the in-memory integration plane, whose after-commit delivery is commit-gated by the database transaction without a hand-written decorator: the package's EF Core interceptors are attached to `TContext` automatically and flush buffered events after the `DbContext` commits and discard them on rollback. ```csharp title="Program.cs" builder.Services.AddElarionInMemoryEventBus(); // domain plane + in-memory integration plane (interceptors included) ``` `InMemoryIntegrationEventBus.PublishAsync` buffers each event into a per-scope `EventDispatchScope`; the `EventDispatchSaveChangesInterceptor`/`EventDispatchTransactionInterceptor` flush that buffer to the hosted `EventDispatchPump` after commit (and discard it on rollback). The pump drains a bounded channel and dispatches each event on an isolated scope. A configuration overload reads the `EventBus` section — `EventBus:Enabled` (default `true`) and `EventBus:DeliveryChannelCapacity` (default `1024`, the back-pressure bound on flushed-but-undelivered events) — and throws on a non-boolean/non-integer value: ```csharp builder.Services.AddElarionInMemoryEventBus(builder.Configuration); ``` If you only need the integration tier (the domain plane is already wired elsewhere), call `AddElarionInMemoryIntegrationEventBus()` directly; it registers `IIntegrationEventBus`, the scope buffer, the pump, and the two interceptors, sharing the same `EventSubscriptionRegistry`. The interceptors are resolved per scope by `AddDbContext`, so the in-memory integration tier needs an EF Core context registered the normal way. Events flushed but not yet delivered when the process exits are **lost** — reach for the outbox when that is unacceptable. ## EF Core transactional outbox [#ef-core-transactional-outbox] The outbox makes integration delivery durable by writing each event as a row in **your** `DbContext`, committed atomically with the business data. A background worker delivers it after commit. It **replaces** the in-memory integration tier; the domain plane and the generated consumer descriptors are registered separately. **Add the table** to the context that owns your business entities, in `OnModelCreating`: ```csharp title="BillingDbContext.cs" protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.UseElarionOutbox(); // adds the target-group envelope table } ``` `UseElarionOutbox` takes optional `tableName` and `schema` parameters plus a `snakeCase` toggle (default `true`; `false` switches the table/column/index names to PascalCase — the default becomes `ElarionOutboxMessages`), for example `modelBuilder.UseElarionOutbox("app_outbox", "app")`. On a `[GenerateDbSets]` context you can skip the hand-written call entirely: annotate the context with `[GenerateElarionOutbox]` (optionally with `SnakeCase`/`TableName`/`Schema`) and the bundled generator emits the DbSet and applies the same model configuration through the EF generator's model-config seam (`ELOBX001` if `[GenerateDbSets]` is missing): ```csharp title="BillingDbContext.cs" [GenerateDbSets] [GenerateElarionOutbox] public sealed partial class BillingDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } ``` **Register the tier** in the host, generic over that context: ```csharp title="Program.cs" builder.Services.AddElarionOutbox(o => { // Event payloads use the canonical IElarionJsonSerialization by default (contributed by AddElarion) — // register your event DTOs in a module JSON context. Set o.SerializerOptions only to override. // o.PollingInterval = TimeSpan.FromSeconds(1); // idle poll interval // o.BatchSize = 100; // target groups claimed per poll // o.LeaseDuration = TimeSpan.FromMinutes(2); // group lease before another worker may reclaim // o.MaxDeliveryAttempts = 10; // attempts before one group is left for inspection // o.BaseRetryDelay = TimeSpan.FromSeconds(5); // backoff base: a failed message is invisible for BaseRetryDelay × 2^(attempts-1) // o.MaxRetryDelay = TimeSpan.FromHours(1); // ceiling on the exponential retry backoff // o.RetentionPeriod = TimeSpan.FromDays(7); // null = keep delivered rows forever // o.RunDeliveryWorker = true; // false = publish-only node; another instance runs delivery }); ``` This registers the durable `IIntegrationEventBus` (`OutboxIntegrationEventBus`), the storage (`IOutboxStore` / `EfCoreOutboxStore`), the dispatcher (`OutboxEventDispatcher`), and the hosted `OutboxDeliveryService` (skipped when `RunDeliveryWorker` is `false` — see [Where the worker runs](#where-the-worker-runs)). The bus is registered last-wins, so the outbox is authoritative even if an in-memory integration bus was registered for the domain plane's sake. **Register the domain plane and the consumers.** The domain plane is always in-memory and inline — wire it on its own so only the outbox delivers Plane B: ```csharp title="Program.cs" builder.Services.AddElarionDomainEventBus(); // domain plane + registry builder.Services.AddElarionOutbox(); // integration plane (durable) ``` Consumer **descriptors** are registered separately — automatically and feature-gated when you use `[GenerateModuleBootstrapper]` (see [Module gating](/docs/capabilities/events#module-gating)), or explicitly via each module's generated `Add{Module}EventConsumers()`. If you only publish integration events you don't need the in-memory tier at all — the outbox and the consumer descriptors are enough. Publishing requires the descriptors because it resolves consumers into target groups before persistence. **Publish before you save.** `PublishAsync` only *tracks* the outbox row — it does not call `SaveChanges`. Your unit of work must persist it **within the same transaction** as the business data, so publish before the `SaveChanges` that commits the command: ```csharp db.Invoices.Add(invoice); await integrationEvents.PublishAsync(new InvoiceCreated(invoice.Id, client.Email), ct); await db.SaveChangesAsync(ct); // persists the invoice and the outbox row atomically ``` If the transaction rolls back, both the invoice and the event vanish together — no half-published notifications. The database transaction provides the commit-gating directly, so the outbox needs no per-scope flush/discard buffer. ### How delivery stays safe [#how-delivery-stays-safe] The `OutboxDeliveryService` claims pending **target-group envelopes** with a provider-neutral conditional `ExecuteUpdate` lease and a short `LeaseDuration`, dispatches each on an isolated scope, then finalizes and purges. A crashed worker's in-flight group is retried once its lease expires. A group that fails past `MaxDeliveryAttempts` is left for inspection and no longer retried. Defaults are tuned for low/single-instance deployments — in multi-instance deployments keep `LeaseDuration` comfortably above the time to deliver a full `BatchSize` batch. **Delivery is not atomic with your consumers.** Each handler-form consumer commits its **own** transaction; the worker then finalizes the target group — a separate lease-guarded write on the worker's connection. A crash between a consumer's commit and group finalize can redeliver consumers in that group. The **built-in inbox** absorbs the remaining at-least-once window for handler-form consumers by default — each consumer claims the message id inside its own transaction, so a redelivery is acknowledged instead of re-run (pair with `AddElarionIdempotencyEntityFrameworkCore` so claims survive restarts) — see [Handling duplicates](/docs/capabilities/events/consuming-events#handling-duplicates). **The common path stays one row.** When an event has no role-routed consumer, publish does not enumerate handlers or persist consumer ids: an immutable startup catalog answers that case in O(1). Delivery uses one lease, one payload deserialization, one scope, ordered sequential invocation, and one finalize regardless of consumer count. Multiple rows and duplicated payloads appear only when one publish genuinely resolves to multiple execution targets. **Finalizing is lease-guarded.** Every finalize — mark delivered, mark failed, or park — is conditioned on the finalizing worker still owning the lease it claimed under. If a worker stalls past its lease and another worker legitimately reclaims and delivers the message, the stalled worker's late finalize matches zero rows, is skipped, and is logged at `Warning` — it can never wipe the new owner's active lease and trigger overlapping redelivery. The claim and the guarded finalize are the [leased work rows](/docs/capabilities/coordination#leased-work-rows) primitive, which an application can reuse for its own queue tables. **Failures back off.** A failed delivery is made invisible for `BaseRetryDelay × 2^(attempts-1)` (capped at `MaxRetryDelay`) via a visibility timeout, so a poison consumer no longer re-enters the front of every claim batch at full poll frequency — head-of-line blocking is avoided and retries back off. Set `BaseRetryDelay` to `TimeSpan.Zero` to retry on the next poll instead. **Unresolvable groups are parked, not dropped.** A missing `ConsumerId`, incompatible event-type rename, or null payload parks only that target group. New publishes fail immediately when no consumer is registered, so malformed fan-out is caught before `SaveChanges`. ### Where the worker runs [#where-the-worker-runs] Every publishing instance must register the same generated consumer catalog because publish-time grouping stores target roles and, for role-routed events, stable consumer ids. `RunDeliveryWorker = false` is still available for a fixed publish-only process, but it disables claiming only; it does not remove the catalog requirement: ```csharp title="Program.cs (web node)" builder.Services.AddElarionOutbox(o => o.RunDeliveryWorker = builder.Configuration.GetValue("Outbox:RunDeliveryWorker", true)); ``` ```jsonc title="appsettings.json (web node)" { "Outbox": { "RunDeliveryWorker": false } } // the worker-role instance leaves the default (true) ``` Role-bound groups are different: every worker may run, but it claims a group only when its `TargetRole` is null or appears in the local `IRoleLeaseRegistry` as held. Generated `SingleHome` and `VirtualShards` actor consumers populate that role automatically; failover transfers eligibility without HTTP forwarding or a global delivery gate. The worker rechecks the live lease immediately before each dispatch; if ownership changed after the batch claim, it releases that group without incrementing its attempt count or applying backoff so the new holder can claim it immediately. The envelope table has a **partial (filtered) claim index** over `(target_role, occurred_on_utc, id)` where `processed_on_utc IS NULL` (PascalCase equivalents with `snakeCase: false`). The worker's "oldest eligible delivery first" scan therefore stays on one table; completed rows awaiting retention purge are absent from the index. Filtered indexes are supported on PostgreSQL, SQL Server, and SQLite; on MySQL, supply an unfiltered index in your own model. Retention purge starts from the processed-envelope index and deletes eligible groups in bounded batches. ### Tracing across the commit boundary [#tracing-across-the-commit-boundary] Each outbox row persists the publisher's W3C `traceparent` (the `trace_parent` column), and delivery parents its `consume {event}` span on it — so in your tracing backend the after-commit consumers appear inside the trace of the command that published the event, even when delivery happens on another worker instance or after a restart. Delivery outcomes are also counted and timed, and failure logs carry the message's correlation id. Register `EventTelemetry` to collect the signals — see [Telemetry](/docs/capabilities/telemetry). **Serializer options.** `OutboxOptions.SerializerOptions` is `null` by default, so event payloads use the canonical [`IElarionJsonSerialization`](/docs/capabilities/serialization) — register each event DTO in a module JSON context and it is trim/AOT-safe. Set `SerializerOptions` only to serialize the outbox differently from the rest of the app. The consumer model both backends deliver to, and how to keep consumers idempotent. The canonical `IElarionJsonSerialization` the outbox payload serializer uses by default. # Client events (near-realtime) (/docs/capabilities/events/client-events) A browser showing a list should update when the data changes — without polling on a timer, and without pretending the browser is a reliable message consumer. Elarion's model for this is deliberate: * **Push is a hint, not a source of truth.** A client event is *light* — an id or ref, never state. The client reacts by re-running the normal query handlers, which carry the real authorization gates. A missed event is therefore never corruption, just staleness until the next re-query. * **Delivery is at-most-once.** A closed laptop misses events, period. Anything that must not be missed belongs in an [integration event](/docs/capabilities/events) consumed server-side with at-least-once delivery — not on a socket to a browser. * **The internal event is not the wire contract.** What crosses the trust boundary is a separate, deliberate payload; the projection from the internal integration event is one hand-written line, which is exactly where you review what leaks. Three packages ship the machinery — `Elarion.ClientEvents` (topic catalog, publisher, in-process fan-out), `Elarion.ClientEvents.AspNetCore` (the SSE endpoint), and `Elarion.ClientEvents.PostgreSql` (cross-node fan-out, when you run more than one node) — so what you write is only the policy: the contract, the topic declaration, the projection, and the resource authorization. The command handler that causes the change is **not** on the list — it publishes its integration event exactly as before and never learns the client tier exists. ## When to reach for it [#when-to-reach-for-it] Client events are one tier in the event story; pick by *who must see the fact and how reliably*: | You need | Reach for | | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | Browsers to refresh within \~a second of a committed change | **Client events** (this page) | | A server-side reaction that must not be missed (email, billing, sync) | An [integration event](/docs/capabilities/events) — at-least-once, inboxed | | A change that must commit atomically with the command | A [domain event](/docs/capabilities/events) — same transaction | | Live progress of one long-running command | Client events, [the ephemeral tier](#progress-the-ephemeral-tier) | | One request returns a lazy export, token output, or tail query | [`IStreamHandler`](/docs/capabilities/transports/server-streaming) — a cold request response | | Every browser-visible item needs ordering, completion, and reconnect resume | An actor-owned [ordered stream](/docs/capabilities/events/streams) | | A dashboard where seconds of staleness are fine | Polling a [keyset query](/docs/capabilities/pagination) — less machinery | | Config/settings values that reload live | [`ISettingsManager.Watch`](/docs/concepts/settings) — not an event topic | The line to hold: a client event may be **dropped** (closed laptop, full buffer, reconnect gap) and the system must stay correct because the client re-queries. A deferred response to one request is instead a cold [`IStreamHandler`](/docs/capabilities/transports/server-streaming); a browser-visible sequence whose elements, completion, and resume behavior are data is an actor-owned [ordered stream](/docs/capabilities/events/streams). The moment a server-side fact must not be missed, it belongs on the integration plane — push the *consequence* to browsers as a hint afterwards. **The happy path**, end to end: declare an `IClientEvent` contract in the module (topic registration is generated), project the integration event onto it in a `[ConsumeEvent]` method, map `MapElarionClientEvents("/events")`, and let the generated TypeScript client drive cache invalidation. Running more than one node? Add the one `AddElarionPostgreSqlClientEvents(...)` line. Each step is below. ## 1. Declare the wire contract [#1-declare-the-wire-contract] ```csharp // Modules/Invoicing/Client/InvoiceChanged.cs — what the browser sees. An id, not state. public sealed record InvoiceChanged : IClientEvent { public required Guid InvoiceId { get; init; } } ``` `IClientEvent` marks a topic schema at the trust boundary — the client-side analogue of `[ModuleContract]`. An internal integration event must never implement it directly; publish a separate contract so internal renames cannot break deployed frontends. ## 2. Register the topic [#2-register-the-topic] Under `[assembly: UseElarion]` (or the standalone `[assembly: GenerateClientEventTopics]`), registration is **generated**: every `IClientEvent` contract under an `[AppModule]` becomes a topic named `{module}.{name}` — both parts camel-cased, a trailing `Event` suffix stripped, so `InvoiceChanged` in the Invoicing module is `"invoicing.invoiceChanged"`. Attributes on the contract become subscribe-time requirements, and `[ClientEvent("…")]` pins the full wire name across a type rename: ```csharp [RequirePermission("invoices", Verbs.Read)] // evaluated when a client subscribes public sealed record InvoiceChanged : IClientEvent { public required Guid InvoiceId { get; init; } } ``` The generated `Add{Module}ClientEvents` is wired into the module's `ConfigureDefaultServices`, so a disabled module's topics simply don't exist. A contract outside every module warns (`ELCEV001`), colliding topic names are a compile error (`ELCEV002`), and contracts without an `Elarion.ClientEvents` reference warn (`ELCEV003`). The manual path remains for hosts without the bootstrapper or for custom vocabularies: ```csharp builder.Services.AddElarionClientEvents(events => events .AddTopic("invoicing.invoiceChanged", t => t.RequirePermission("invoices", Verbs.Read))); ``` Either way, nothing reaches the wire without a declaration — opt-in by enumeration. Publishing an unregistered type fails loud; subscribing an unknown topic reads as 404, and a denied topic is indistinguishable from a nonexistent one. ## 3. Project the integration event [#3-project-the-integration-event] A [method-form consumer](/docs/capabilities/events/consuming-events) on a `[Service]` — integration consumers run **after commit** on a separate scope, so a rolled-back command can never push a ghost update. Note what the mapping drops: amounts, emails — internal fields never cross the boundary. ```csharp [Service] internal sealed class InvoicingClientProjections(IClientEventPublisher clientEvents) { [ConsumeEvent] public ValueTask On(InvoicePaid evt, CancellationToken ct) => clientEvents.PublishAsync( new InvoiceChanged { InvoiceId = evt.InvoiceId }, ClientEventScope.Resource($"customer:{evt.CustomerId}"), ct); } ``` The scope is the audience of this publish: `ClientEventScope.Global` (every subscriber of the topic), `ClientEventScope.User(id)` (one user), or `ClientEventScope.Resource(key)` (an application-defined group). Delivery fans out through bounded per-subscriber buffers that drop oldest on overflow — a slow client loses old hints, never stalls delivery to others. ## 4. Map the endpoint [#4-map-the-endpoint] ```csharp app.MapElarionClientEvents("/events"); ``` One SSE `GET` multiplexes a connection's subscriptions, with **fail-closed** subscribe-time authorization: unauthenticated → 401; an unknown topic, a failed topic requirement, or a resource scope without a passing authorizer → 404, so a topic's existence never leaks. User scope is always derived from the authenticated caller — a client cannot ask for someone else's. Control signals are named events: `elarion.connected` when the stream opens (every occurrence means "you may have missed events" — re-query) and `elarion.keepAlive` on idle so proxies keep the connection open. Resource scopes are fail-closed, and the framework distinguishes the two things a resource key can be: **A routing key.** When the resource merely selects *which* events to receive — a stock symbol, a public room id — declare it on the contract and no authorizer is involved: ```csharp [AllowAnyResource] // "the symbol is a routing key, not an entitlement" public sealed record QuoteChanged : IClientEvent { public required string Symbol { get; init; } // … } ``` Any caller who passes the topic's other requirements (authenticated, plus any `[RequirePermission]`/ `[RequireRole]` on the contract) may subscribe to any resource of *this* topic. The declaration is deliberately per-topic: a global "allow everything" authorizer would silently open every future resource-scoped topic too. (Imperative form: `AllowAnyResource()` on the topic options in `AddElarionClientEvents`.) **An entitlement.** When the resource gates *who* may observe it — "customer 42's invoices" — implement the authorizer; without it (and without `[AllowAnyResource]`), every resource subscription is denied: ```csharp // "May the current user observe customer:42?" — resolved from the request scope like any scoped service. internal sealed class CustomerScopeAuthorizer(AppDbContext db, ICurrentUser user) : IClientEventSubscriptionAuthorizer { public async ValueTask AuthorizeAsync(ClientEventSubscription subscription, CancellationToken ct) => TryParseCustomerKey(subscription.Scope.Value, out var customerId) && await db.CustomerMembers.AnyAsync(m => m.CustomerId == customerId && m.UserId == user.UserId, ct); } ``` Subscribe-time checks are a UX projection, never the security boundary — the data itself is only ever fetched through handlers carrying the real `[Require*]` gates. ## Producer-side lifecycle: initial values and interest [#producer-side-lifecycle-initial-values-and-interest] A topic can declare a **subscription observer** — the producer's view of its audience. The semantics are the proven Rx ones (`BehaviorSubject` + `RefCount`), minus backpressure, because client events stay a hot at-most-once stream: ```csharp [AllowAnyResource] [SubscriptionObserver] // or topic options: .ObserveSubscriptions() public sealed record QuoteChanged : IClientEvent { /* … */ } public sealed class QuoteSubscriptionObserver(IActorSystem actors) : IClientEventSubscriptionObserver { // "This is your subscriber" — the sink delivers to exactly that subscriber. Greet it with the // current value (a normal request/reply turn on the owning actor) and the stream is self-converging: // "last known value + everything since", on one connection, re-greeted on every reconnect. public async ValueTask OnSubscribedAsync( ClientEventSubscription sub, IClientEventSubscriberSink sink, CancellationToken ct) { if (sub.Scope is { Kind: ClientEventScopeKind.Resource, Value: { } symbol } && await actors.Get(symbol).GetQuote(ct) is { } quote) { await sink.PublishAsync(ToEvent(quote), ct); } } // RefCount with a disconnect delay: true on the first watcher of a (topic, scope), false only after // the last one leaves AND the linger elapses (default 5 s) — a browser reload never bounces the // upstream. Implement when the producer must start/stop real work (open a feed, run a poll loop). public ValueTask OnInterestChangedAsync(ClientEventSubscription sub, bool active, CancellationToken ct) => /* start/stop the per-resource upstream */ default; } ``` Callbacks run detached from the subscribe path (a slow observer never delays the stream) on a fresh DI scope, on the node holding the subscription — which for actor-fed topics is the producer's node, because the recommended topology routes the live prefixes (including the events endpoint) to the actor home. A greeting races live publishes by design; payload contracts carry a monotonic version and the client applies through one guard, so ordering resolves client-side. Client events guarantee **monotonicity you build in**, never gap-free ordered delivery — and no code placement changes that, because the pipe is lossy by construction: the per-subscriber buffer drops oldest on overflow, an SSE reconnect loses whatever was in flight, and the cross-node fan-out has no replay. Ordering without reliability would be false comfort — a consumer that breaks on reordering also breaks on the element it will eventually not get. So the doctrine splits by what you actually need: * **Latest-wins state** (quotes, presence, progress): carry a monotonic version in the payload and apply through one stale-drop guard. After the guard, delivery order is unobservable — this is the payload tier's contract, and it holds on every deployment shape. * **Every element matters, machine consumer**: integration events on the outbox (durable, at-least-once, inbox-deduped) — not client events. * **Every element matters, browser**: publish the *hint* and let the re-query be the ordered, complete read — or, when a single live producer (a homed actor) owns the sequence, use the [ordered-streams tier](/docs/capabilities/events/streams) (ADR-0052): a real stream contract with order, completion, and `Last-Event-ID` resume. It is a separate contract — never bolted onto hints. The cheap sibling is the **pull check** — no observer needed, injectable anywhere including actors: ```csharp // Inside the producing actor's tick: nobody watching → keep the value, skip the wire entirely. if (!interest.HasSubscribers(QuoteChanged.Topic, ClientEventScope.Resource(context.Key))) return; ``` Skipping is safe precisely *because* of the greeting: a watcher that arrives later gets the current value on subscribe, so a suppressed publish is never a missed one. Interest is deliberately node-local (no cross-node presence protocol at this tier); a publish never returns a subscriber count — interest is a separate read, never a delivery receipt. `samples/LiveQuotes` dogfoods the whole pattern. ## 5. The browser [#5-the-browser] The schema exporter emits the declared topics as the schema's `events` block, and the [TypeScript client generator](/docs/capabilities/transports/json-rpc) turns it into `events-client.ts`: a topic-typed subscription client (a typo'd topic is a compile error, payloads are Zod-validated on receipt) that multiplexes every subscription over one `EventSource`. With TanStack Query the whole client story is invalidation: ```ts import { createElarionEvents } from './generated/events-client.js' const events = createElarionEvents({ url: '/events' }) events.invoicing.invoiceChanged.subscribe( { resource: `customer:${customerId}` }, (evt) => queryClient.invalidateQueries({ queryKey: ['invoices', evt.invoiceId] }), ) // Fires on connect and every automatic reconnect — converge by re-querying. events.$client.onConnected(() => queryClient.invalidateQueries({ queryKey: ['invoices'] })) ``` The browser's `EventSource` reconnects a dropped connection by itself, but **gives up for good** when an answer is not a 200 event stream — a 401 or a login page after the session expired, a 502 while the server restarts. The generated client reopens such a connection after a backoff (1 s, doubling up to 30 s, reset by every `elarion.connected`; `reconnectDelay` changes it), and the reopened connection fires `onConnected` like any other. Behind an authenticating proxy, pass `eventSource: session.eventSource` from [session renewal](/docs/capabilities/pwa#renewing-an-expired-proxy-session), so an expired session is renewed instead of retried. Without the generator, a plain `EventSource` works too: pass the subscription set as the `subscriptions` query parameter (a URL-encoded JSON array of `{"topic":"…","resource":"…?"}`) and listen for the topic name as the event type. ## Progress: the ephemeral tier [#progress-the-ephemeral-tier] The projection consumer is the recommended path because it inherits commit-gating. Calling the publisher **directly from inside a handler** is the deliberate exception — progress of a long-running command, where there is no committed fact yet and hints about the ongoing attempt are exactly what you want: ```csharp await clientEvents.PublishAsync( new ImportProgress { Processed = processed, Total = total }, ClientEventScope.User(user.UserId), ct); ``` If the command later rolls back, the progress events were still sent — fine for status, wrong for facts. The guarantee is stated by where the call sits, mirroring how the two event planes state theirs. ## Going multi-node [#going-multi-node] The in-process broadcaster is single-node correct: an event published on node A does not reach a browser connected to node B. The moment you run a second node, add `Elarion.ClientEvents.PostgreSql` — cross-node fan-out over PostgreSQL `LISTEN/NOTIFY`, on the database the application already runs (no broker, no Redis): ```csharp builder.Services.AddElarionPostgreSqlClientEvents(connectionString); ``` Every publish becomes a `pg_notify` on one channel; every node holds a dedicated `LISTEN` connection and hands received envelopes to its own connected browsers. The publishing node receives its own events through the same loop-back, so there is exactly one delivery path to reason about. Everything else — topics, projections, the endpoint, the TypeScript client — is unchanged. The at-most-once contract does the heavy lifting on failures: PostgreSQL does not queue notifications for absent listeners, so after a dropped listen connection the node delivers `elarion.connected` to **every** subscriber it holds — the generated client's `$client.onConnected` fires and the UI re-queries, converging instead of trusting a stream with a hole in it. Payloads must fit NOTIFY's \~8 KB cap; light events (ids and refs) never get close, and an oversized publish fails loud on the publishing node rather than delivering on some nodes and not others. This default follows the [scale positioning](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0025-distributed-scheduler-coordination.md) of every Elarion default: correct for \~1–10 nodes on the one PostgreSQL. Past that tier, replace the `IClientEventBroadcaster` seam with a dedicated backend (Redis pub/sub, a broker) — the seam is one method. ## Limits [#limits] * **Scope-blind topic handlers.** The wire frame carries the topic, not the scope — handlers on the same topic see every event the connection's subscriptions match. Subscribe distinct concerns as distinct topics. * **At-most-once, always.** No transport tier changes this: buffers drop oldest under pressure, reconnects lose the gap. Design every consumer as "hint received → re-query", and it is impossible to be wrong. * **The humble alternative.** For dashboards where seconds of staleness are fine, polling a [keyset-paginated query](/docs/capabilities/pagination) on an interval is less machinery and often enough at this tier. # Consuming events (/docs/capabilities/events/consuming-events) `[ConsumeEvent]` is the **single, unified way to subscribe** — you never pick a bus or a plane on the consumer. The same attribute consumes either a domain or an integration event; the event type's marker (`IDomainEvent` / `IIntegrationEvent`) decides which plane delivers it. Every consumer is a **fan-out subscriber**: the event bus is **pub/sub-only** and never returns a value to the publisher. So a consumer reads identically whether the event runs inline or after commit. (For the two-plane model itself, see the [events overview](/docs/capabilities/events).) For request/reply — one typed response from a single target — don't use the event bus; call the handler directly (see [calling a handler from other code](/docs/concepts/handlers#calling-a-handler-from-other-code)). There are two ways to write the consumer. Prefer the **handler form** — it makes the consumer a first-class unit of business logic with the full decorator pipeline; the **method form** is a lightweight alternative for a small side effect on a service you already have. ## Handler form (preferred) [#handler-form-preferred] A consumer is a class implementing `IHandler` (the sugar over `IHandler>`) — its request type *is* the event — annotated with a class-level `[ConsumeEvent]`. The sugar returns the non-generic `Result`: ```csharp using Elarion.Abstractions; using Elarion.Abstractions.Messaging; [ConsumeEvent] public sealed class SendInvoiceEmail(IEmailSender email) : IHandler { public async ValueTask HandleAsync(InvoiceCreated e, CancellationToken ct) { await email.SendAsync(e.ClientEmail, ct); return Result.Success(); } } ``` Because it *is* a handler, it runs through the **full handler decorator pipeline** — tracing, resilience, validation, cache-invalidation — exactly like a command or query handler, and it is discovered, registered, and feature-gated by its module like every other handler. The event bus simply becomes one more trigger for the same unit of business logic. Use `[ConsumeEvent(Order = n)]` to order fan-out subscribers; `Order` ascends, and equal-order consumers run in a stable, generator-determined sequence. ### Every consumer is a fan-out subscriber [#every-consumer-is-a-fan-out-subscriber] The event bus is **pub/sub-only**, so a handler-form consumer always returns `Result` — use the `IHandler` sugar, or the explicit `IHandler>`. Every matching consumer runs — **any number of handler-form consumers may subscribe to one event** (each registers keyed by its own identity, so they never shadow one another), interleaved with method-form consumers by `Order`. A failed `Result` has no return channel to the publisher, so it surfaces as an `EventConsumerFailedException`, which each backend handles per its plane (the in-memory domain bus aggregates and rethrows, failing the command; the in-memory integration pump logs and isolates; the outbox dispatcher lets it propagate to trigger a retry). A consumer that returns a non-`Unit` `Result` is rejected (`ELEVT005`) on either plane — the bus has no response channel. When you need **one typed response** from a single target, that is request/reply, not pub/sub: call the target handler directly instead of publishing an event (see [calling a handler from other code](/docs/concepts/handlers#calling-a-handler-from-other-code)). **A domain-event handler runs nested in the command's pipeline.** The domain plane dispatches inline in the publisher's scope, so a handler consumer's decorator pipeline runs *inside* the command that published the event — same scope, same `DbContext`, same transaction. Give domain-event handlers a **read-only / minimal pipeline**: a nested **transaction** or **resilience** decorator is wrong, since opening a nested transaction or retrying writes against the already-dirty `DbContext` would corrupt the command's unit of work. Tracing, validation, and cache-invalidation nest safely. Integration-event handlers are the opposite — they run on a **fresh scope after commit**, so the full pipeline (including a transaction decorator) is exactly right. The clean way to get this right is a [transaction decorator with an `AppliesTo` predicate](/docs/concepts/decorator-pipelines#conditional-attachment-with-appliesto) that matches commands and integration-event handlers but **not** domain-event handlers — the generator then never attaches it to a domain-event handler, and the integration handler keeps it because its request is an `IIntegrationEvent`. One decorator, attached precisely at compile time, covers commands, queries, domain events, and integration events with no per-handler pipeline tags. Avoid a separate pipeline attribute per handler kind for this. It would work, because pipeline attributes are most-specific-wins, but it repeats what the request type already says and must be remembered on every new handler (see [decorator pipelines](/docs/concepts/decorator-pipelines#defining-named-pipelines)). ```csharp // Domain-event handler: shares the publisher's DbContext and transaction, so it must NOT // open a nested transaction. With an AppliesTo predicate it needs no pipeline annotation at all. [ConsumeEvent] public sealed class RecalculateTotals(AppDbContext db) : IHandler { public async ValueTask HandleAsync(InvoiceLineAdded e, CancellationToken ct) { // Shares the publisher's DbContext; this write commits atomically with the command. await db.Invoices .Where(i => i.Id == e.InvoiceId) .ExecuteUpdateAsync(s => s.SetProperty(i => i.Total, i => i.Total + e.Amount), ct); return Result.Success(); } } ``` ## Method form (alternative) [#method-form-alternative] When you just need a side effect on a service that already exists, annotate an **instance method on a `[Service]` class** instead — no dedicated handler class, but also no decorator pipeline. The consumed event type is the method's message parameter, and the plane comes from that type's marker: ```csharp [Service] public sealed class InvoiceNotifications(ILogger logger) { [ConsumeEvent] public async ValueTask OnInvoiceCreated(InvoiceCreated e, CancellationToken ct) { await NotifyAsync(e.ClientEmail, ct); } } ``` Here too the method is a **fan-out subscriber** — it returns `void` / `Task` / `ValueTask` (throw to fail) or the **non-generic `Result`** / `Task` / `ValueTask` (a failed `Result` → `EventConsumerFailedException`, the same failure channel as the handler form). Every matching consumer runs. The event bus is pub/sub-only, so a method that returns a `Result` *with a value* is rejected (`ELEVT002`); when you need one typed response, call the target handler directly instead of consuming an event (see [calling a handler from other code](/docs/concepts/handlers#calling-a-handler-from-other-code)). Beyond the message parameter, a method-form consumer may optionally declare — in any order — an `IEventContext` (or `IEventContext`) for the correlation id, the durable message id (`MessageId`, the dedup key on the integration plane), and the message, plus a `CancellationToken`. Both are supplied by the runtime; omit what you don't need, and use `[ConsumeEvent(Order = n)]` to order fan-out subscribers. (The handler form takes the event and an optional `CancellationToken`.) The durable consumer identity is `{service}.{method}({event type})`. Runtime-supplied context and `CancellationToken` parameters are intentionally excluded, so adding or removing either does not orphan pending outbox deliveries or inbox claims. Two overloads on the same service with the same method name and event type would share that identity and are rejected by `ELEVT006`; rename or split one consumer. A class-level `[ConsumeEvent]` on a non-handler class, or a method-form consumer not on a `[Service]`, is reported (`ELEVT005`/`ELEVT001`); an invalid signature is `ELEVT002`. What the `CancellationToken` *means* differs by plane. For **domain** consumers it is the originating command's token (cancelling the command cancels the consumer). For **integration** consumers it is the delivery host's shutdown token — delivery is decoupled from and after the command, so the token signals "wind down," not "the request was cancelled." ## Handling duplicates [#handling-duplicates] Integration delivery is **at-least-once**: a consumer can see the same message more than once — a worker crash after the consumer ran but before its delivery was finalized, or a lease that expired under multiple instances — or a fan-out sibling that failed: consumers sharing a target group (in the common unbound case, every consumer of the event) share one retry boundary, so a retry re-runs the siblings that already completed. There is no exactly-once *delivery*; exactly-once *effect* comes from deduplication on the consumer side. Every redelivery carries the **same** `IEventContext.MessageId` (the durable message identity — for the outbox, the published message's id, shared by every target group of one publish), so that id is the deduplication key. (`CorrelationId` is a *tracing* identifier — don't key dedup on it.) **Handler-form consumers get this for free: the inbox is on by default.** Every handler-form consumer whose event is an `IIntegrationEvent` is wrapped in an inbox decorator that claims the pair *(consumer, message id)* in **the consumer's own transaction** — replacing the plain transaction decorator — so the claim commits atomically with the consumer's business writes. A redelivery finds the committed claim and is acknowledged as already-done without re-running the consumer; a failed `Result` rolls the claim back with the writes, so the message retries. When two workers race the same message, the loser waits on the winner's uncommitted claim and then replays it — only a *committed* claim is ever acknowledged. Why this must live in *your* transaction rather than the outbox row: the outbox row has the wrong **grain**. It is one row per *event* (per target group), finalized by the delivery worker per **group**, on the worker's own connection, *after* your consumer's transaction has already committed — and only once **every** fan-out consumer in that group has run. Your effect is a fact per *(message, consumer)*, and only a write inside your consumer's own transaction can atomically couple "already processed" to the effect itself. The inbox is exactly that write, done for you. Two things to know about the default: * **Durability follows the idempotency store.** The delivery tiers register the in-memory store automatically (process-local dedup); pair the outbox with [`AddElarionIdempotencyEntityFrameworkCore`](/docs/concepts/idempotency) so inbox claims survive restarts — the outbox is durable, so its inbox should be too. * **Retention outlives retries.** Inbox rows expire like idempotency keys after 24 h — comfortably above the outbox's maximum retry window (≈43 minutes at the defaults). The margin matters: a still-retrying message must never re-run because its claim was purged. The inbox dedups the consumer's **transactional effect**. A foreign side effect inside the consumer — an email, a payment API call — re-runs only in the narrow window where the process dies between the foreign call and the commit. To close that last window, pass the **message id** as the downstream's idempotency key and let it collapse duplicates too. A method-form consumer reads it from its `IEventContext` parameter; a handler-form consumer (which takes only the event) injects `IIdempotencyKeyAccessor` — in a delivery scope its key *is* the seeded message id: ```csharp [ConsumeEvent] public sealed class ChargeInvoice(IPaymentGateway payments, IIdempotencyKeyAccessor messageId) : IHandler { public async ValueTask HandleAsync(InvoiceCreated e, CancellationToken ct) { // The same id the inbox claims — stable across redeliveries, unique per message. messageId.TryGetKey(out var key); await payments.ChargeAsync(e.InvoiceId, idempotencyKey: key!, ct); return Result.Success(); } } ``` **Opting out.** `[AllowDuplicates]` declares that redelivery is harmless to this consumer and removes the inbox (the plain transaction decorator returns) — the consumer-side mirror of `[AllowAnonymous]` switching off a default guard. Declare it when the effect is naturally idempotent, or when the only effect is a call to a downstream keyed on the message id: ```csharp [ConsumeEvent] [AllowDuplicates] // "mark paid only if not already paid" converges by itself public sealed class MarkInvoicePaid(AppDbContext db) : IHandler { public async ValueTask HandleAsync(InvoicePaid e, CancellationToken ct) { await db.Invoices .Where(i => i.Id == e.InvoiceId && i.Status != InvoiceStatus.Paid) .ExecuteUpdateAsync(s => s.SetProperty(i => i.Status, InvoiceStatus.Paid), ct); return Result.Success(); } } ``` ### Which one does my consumer need? [#which-one-does-my-consumer-need] The default is already correct — `[AllowDuplicates]` is an *optimization you may claim* when you can say out loud why re-running is harmless, never something correctness requires. By effect shape: | Consumer effect | Reach for | Why | | -------------------------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | Insert-per-event (audit row, projection append, notification record) | **default inbox** | Inserts don't converge — the "idempotent version" is a unique index on the message id, i.e. the inbox hand-rolled per table. | | Delta / increment ("stats.Total += amount") | **default inbox** | Deltas double-apply on redelivery. | | Recompute-from-source ("recalculate totals from the invoice table") | `[AllowDuplicates]` | Re-running recomputes the same result. | | Conditional transition / absolute set ("mark paid if not paid") | `[AllowDuplicates]` | Converges by itself. | | Foreign call only, provider takes a dedup key | `[AllowDuplicates]` + pass `MessageId` | The recipient collapses duplicates; the inbox would only save the wasted call. | | Foreign call only, keyless protocol (bare SMTP) | **default inbox** | Narrows duplicates to the crash window; accept the residual. | | Mixed DB writes + foreign call | **default inbox** + pass `MessageId` downstream | The inbox dedups the writes; the key dedups the send. | | Blob creation (`Elarion.Blobs`) | **default inbox** | The claim and the blob commit share the consumer's transaction; a crash-window orphan stays `Pending` and the blob GC reaps it. | ### A worked example: invoice creation, end to end [#a-worked-example-invoice-creation-end-to-end] The classic CRUD-with-side-effects shape — create a row, generate a PDF, send an email, keep another module's statistics current — maps onto the pieces like this: ```csharp // The command — natural key first: is there a unique constraint that makes a second insert impossible? // Here there isn't (nothing makes two invoices "the same"), so escalate to [Idempotent]: a client retry // must return the FIRST invoice, not create a second. The client sends an Idempotency-Key. // Bonus: a replayed command never re-runs, so InvoiceCreated is never published twice — the // entire downstream chain is protected at its source. [Idempotent] public sealed class CreateInvoiceHandler(AppDbContext db, IIntegrationEventBus events) : IHandler> { /* insert + PublishAsync + save */ } // Default inbox (do nothing): the PDF blob, its link on the invoice, and the inbox claim commit // atomically in the consumer's transaction. A redelivery replays instead of generating a second PDF. [ConsumeEvent] public sealed class GenerateInvoicePdf(AppDbContext db, IBlobStore blobs) : IHandler { … } // Default inbox (do nothing): SMTP takes no dedup key, so keep the inbox — duplicates narrow to the // crash window between the send and the commit, an accepted residual for email. With a keyed provider // (Resend, Brevo, …) instead: declare [AllowDuplicates] and pass the message id as the provider's // idempotency key — the recipient dedups better than the inbox can. [ConsumeEvent] public sealed class SendInvoiceEmail(IEmailSender email) : IHandler { … } // [AllowDuplicates]: recomputes from the source table, so re-running converges on the same numbers. // If this were incremental ("stats.Total += e.Amount") it would NOT converge — keep the default inbox. [ConsumeEvent] [AllowDuplicates] public sealed class RecalculateStatistics(StatsDbContext db) : IHandler { … } ``` The rule of thumb that falls out: **defaults need no justification; deviations must name their reason.** Write the consumer and ship it — the default inbox is safe; declare `[AllowDuplicates]` only when you can say why re-running is harmless. On the command side, model a **natural key + unique constraint** first, and escalate to `[Idempotent]` only for a named reason — no natural key, replay-beats-rejection, money, or increments (see [when does a command need it](/docs/concepts/idempotency#when-does-a-command-need-it)). **Method-form consumers have no pipeline, so no inbox.** Convert to the handler form when dedup matters, or dedup by hand keyed on `(consumer, context.MessageId)` — a unique-constrained insert in the same transaction as the side effect, which is precisely what the inbox automates: ```csharp [ConsumeEvent] public async ValueTask OnInvoiceCreated( InvoiceCreated e, IEventContext context, CancellationToken ct) { db.ProcessedEvents.Add(new ProcessedEvent { Consumer = nameof(InvoiceNotifications), MessageId = context.MessageId!.Value, // unique index on (Consumer, MessageId) }); DoTheSideEffect(e); try { await db.SaveChangesAsync(ct); } catch (DbUpdateException) { // The unique constraint rejected a duplicate — already processed, so let the message finalize. } } ``` The case where the inbox earns its keep is **routine, not exotic**: when a message has several fan-out consumers and one throws, the *whole* message is retried, so consumers that already succeeded run again — on every backoff attempt. The inbox absorbs that automatically; an opted-out consumer must absorb it itself (a naturally idempotent operation does so for free). ## Subscribing without the generator (advanced) [#subscribing-without-the-generator-advanced] `[ConsumeEvent]` is the normal path, but the runtime ultimately subscribes to whatever `EventSubscriptionDescriptor`s are **registered in DI** — the generator simply emits those registrations. The descriptor type is public (`Elarion.Abstractions.Messaging`), so you can register one by hand for tests or advanced host wiring. It is the **same unified shape for both planes**: `Plane` selects domain vs integration, and `InvokeAsync` is the fan-out subscriber callback (the bus is pub/sub-only, so every descriptor is a fan-out subscriber): ```csharp using Elarion.Abstractions.Messaging; using Microsoft.Extensions.DependencyInjection; builder.Services.AddScoped(); builder.Services.AddSingleton(new EventSubscriptionDescriptor { ConsumerId = "MyApp.InvoiceNotifications.OnInvoiceCreated(MyApp.InvoiceCreated)", // stable; the outbox requires it EventType = typeof(InvoiceCreated), Plane = EventPlane.Integration, // or EventPlane.Domain — same descriptor, either plane ServiceType = typeof(InvoiceNotifications), InvokeAsync = static (sp, evt, ctx, ct) => sp.GetRequiredService() .OnInvoiceCreated((InvoiceCreated)evt, ct), }); ``` This is **composition-time** registration. The `EventSubscriptionRegistry` is built **once** from the registered descriptors and then frozen, so the set of consumers is fixed when the container is built. A hand-registered descriptor is also **always active** — module feature-gating happens at the generated `Add{Module}EventConsumers` call site, not in the descriptor itself. **No dynamic, post-startup subscription today.** You cannot add or remove consumers at runtime after the host is built — the frozen registry is what keeps dispatch reflection-free and trimming/AOT-safe. Where integration consumers run from: the in-memory pump or the durable EF Core outbox. How `AppliesTo` attaches the transaction decorator to the right consumers and not the wrong ones. # Events & messaging (/docs/capabilities/events) Elarion's event bus is organized around one question: **when does the event run relative to the database transaction?** That split — not a verb like *publish* or *notify* — is the whole API. There are two planes, each its own interface in `Elarion.Abstractions.Messaging`, and an event binds to exactly one of them through a marker interface. | Plane | Interface | Marker | Runs | | --------------- | ---------------------- | ------------------- | ------------------------------------------------------ | | **Domain** | `IDomainEventBus` | `IDomainEvent` | **inline**, in the caller's scope and transaction | | **Integration** | `IIntegrationEventBus` | `IIntegrationEvent` | **after the transaction commits**, on a separate scope | Consumers are reflection-free: the `EventConsumerRegistrationGenerator` discovers them, validates the signatures, and emits the registration and invocation delegates. There is no runtime assembly scanning or reflective method dispatch. ## Binding an event to a plane [#binding-an-event-to-a-plane] An event is a plain type carrying exactly **one** marker interface. The marker decides which plane delivers it; the generator rejects a type that carries both. ```csharp using Elarion.Abstractions.Messaging; // Recorded in the unit of work, delivered after commit: public sealed record InvoiceCreated(Guid InvoiceId, string ClientEmail) : IIntegrationEvent; // Dispatched inline, inside the publisher's transaction: public sealed record InvoiceLineAdded(Guid InvoiceId, decimal Amount) : IDomainEvent; ``` `[ConsumeEvent]` is the **single, unified way to subscribe** — you never pick a bus or a plane on the consumer. The event type's marker decides the plane, and every consumer is a **fan-out subscriber**, so a consumer reads identically whether it runs inline or after commit. The event bus is **pub/sub-only**: it broadcasts notifications and never returns a value to the publisher. See [Consuming events](/docs/capabilities/events/consuming-events) for the consumer model. For request/reply (one typed response), call the target handler directly instead — see [calling a handler from other code](/docs/concepts/handlers#calling-a-handler-from-other-code). ## Plane A — domain events (inline) [#plane-a--domain-events-inline] `IDomainEventBus` dispatches **within the caller's DI scope**, and therefore within the caller's transaction. Consumers share the scoped `DbContext`, their writes commit atomically with the command, and **a consumer failure fails the command**. This is the right plane for in-aggregate invariants and synchronous side effects that must be part of the same unit of work. ```csharp // Inside a command handler, within the unit of work — RecalculateTotals runs now, // same scope, same transaction, and commits together with the line: await domainEvents.PublishAsync(new InvoiceLineAdded(c.InvoiceId, c.Amount), ct); ``` `PublishAsync where TEvent : IDomainEvent` fans out to every consumer in ascending `[ConsumeEvent(Order = …)]`, awaiting each in turn; if one or more consumers throw, the rest still run and the exceptions are aggregated and rethrown. The bus is **pub/sub-only** — `PublishAsync` returns no value, so when you need a single typed response from another handler, call that handler directly rather than going through the bus (see [calling a handler from other code](/docs/concepts/handlers#calling-a-handler-from-other-code)). Domain events are **never broker-portable** — they are an in-process, in-transaction mechanism by definition. **A domain-event handler runs nested in the command's pipeline.** Because the domain plane dispatches inline in the publisher's scope, a handler-form consumer's decorator pipeline runs *inside* the command that published the event — same scope, same `DbContext`, same transaction. So a domain-event handler must **not** open its own transaction or resilience scope; a nested transaction, or retrying writes against the already-dirty `DbContext`, would corrupt the command's unit of work. The clean way is a transaction decorator with an `AppliesTo` predicate that matches commands and integration events but not domain events — see [decorator pipelines](/docs/concepts/decorator-pipelines#conditional-attachment-with-appliesto). ## Plane B — integration events (after commit) [#plane-b--integration-events-after-commit] `IIntegrationEventBus` **records** the event in the caller's unit of work and delivers it **after the transaction commits**, on a fresh scope, retried independently. A consumer failure never fails the command, and **a rollback discards the event**. This is the plane for independent, after-the-fact reactions — notifications, read-model projections, outbound webhooks, cross-module fan-out. ```csharp await integrationEvents.PublishAsync(new InvoiceCreated(invoice.Id, client.Email), ct); ``` `PublishAsync where TEvent : IIntegrationEvent` only **records** the event; the configured backend delivers it after commit. Because delivery happens later on its own scope, integration consumers run **at-least-once** and **without an ordering guarantee**. Handler-form consumers are deduped by the **built-in inbox** by default; write them order-independent, and see [Consuming events](/docs/capabilities/events/consuming-events#handling-duplicates) for what the inbox covers and when to opt out. Unlike a domain-event handler, an integration-event handler runs on a **fresh post-commit scope** with its own `DbContext` and transaction, so the full pipeline is exactly right (the inbox decorator owns that transaction, claiming the message id atomically with the consumer's writes). This is the **only broker-portable plane**: an alternative backend implements *only* `IIntegrationEventBus`. Two backends ship — a best-effort in-memory tier and the durable EF Core outbox. See [Event backends](/docs/capabilities/events/backends) for the choice and the wiring. ## Choosing a plane [#choosing-a-plane] | Use the **domain** plane when… | Use the **integration** plane when… | | ---------------------------------------------------------- | ---------------------------------------------------------- | | the reaction must be **atomic** with the command | the reaction should happen **after** the command commits | | a failure should **fail** the command | a failure must **not** fail the command | | consumers must share the command's `DbContext`/transaction | consumers run on their own scope and unit of work | | in-aggregate invariants, synchronous side effects | notifications, projections, webhooks, cross-module fan-out | When in doubt: if the side effect should be undone when the command rolls back, it is a **domain** event; if it should be retried until it succeeds *after* the command is durably committed, it is an **integration** event. A third audience sits past both planes: the **browser**. When a committed fact should nudge connected UIs to refresh, project the integration event onto a [client event](/docs/capabilities/events/client-events) — an at-most-once hint carrying ids/refs, pushed over Server-Sent Events, with the client converging by re-query. It is deliberately not a plane: no delivery guarantee crosses the trust boundary to a browser. ## Module gating [#module-gating] When the host opts into `[GenerateModuleBootstrapper]`, event consumers are associated with their owning module and registered through that module's generated `ConfigureDefaultServices`, gated by `Modules:{Name}:Enabled`. So **disabling a module also stops its events from being consumed** — no separate wiring, consistent with how handlers, services, and scheduled jobs gate. A consumer whose namespace falls under no module is reported (`ELEVT003`, warning) so it is never silently dropped. ## Where to next [#where-to-next] Declare consumers in the handler form or the method form, on either plane, and keep them idempotent. Choose between the best-effort in-memory integration bus and the durable EF Core outbox, and wire it. Push after-commit facts to connected browsers as invalidation hints over Server-Sent Events. Use an actor-owned sequence with completion, bounded replay, and reconnect resume when every item matters. Publish an integration event on invoice creation and deliver it durably through the outbox. # Ordered streams (/docs/capabilities/events/streams) Client events are **at-most-once hints**: perfect for "re-query" and latest-wins state, structurally wrong when *element identity* matters. When a consumer needs **the current value and every change since — in order, with completion, resumable across reconnects** — that is a stream, and it needs a different contract ([ADR-0052](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0052-ordered-streams.md)). The litmus test is one question: **if a message is lost, is the consumer merely *stale*, or is it *wrong*?** Client events are at-most-once and self-healing — a lost hint means showing a value slightly longer (the next event or the reconnect greeting carries the complete current truth). Use a stream only when the **sequence itself is the data**, so a lost element makes the result silently wrong and no re-query can heal it: a client-side chart built from ticks, a recorder or analytics tailer, anything that asks "everything since sequence N", anything that must observe *completion* ("the auction closed" — client events just go quiet; silence and done are indistinguishable). And don't put a latest-wins UI on streams "because more guarantees can't hurt": full-fidelity sequences to a dashboard are pure wire waste, and per-key connections don't scale to a 100-symbol screen. **Client events are the default; a stream is the exception you justify.** The second axis is whether a **single live producer per key** exists — a sequencer. Ordering has to come from somewhere: | You need | Producer shape | Use | | -------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------------ | | One request returns a lazy export, token output, or tail query | One caller owns one response | [`IStreamHandler`](/docs/capabilities/transports/server-streaming) | | Invalidation hints ("re-query") | Any handler, any node, post-commit | [Client events](/docs/capabilities/events/client-events) | | Latest-wins live state | Live producer, versioned payload | Client events (payload tier + greeting) | | Every element, machine consumer | Any handler | [Integration events / outbox](/docs/capabilities/events/backends) | | Every element in order, completion, resume | One sequencer per key (a homed actor) | **Streams (this page)** | No sequencer → no ordering source → not a stream. If latest-wins is enough, stay on the payload tier. `StreamHub` is not merely an SSE implementation. It is a shared, producer-owned sequence/replay/resume contract; use a cold [`IStreamHandler`](/docs/capabilities/transports/server-streaming) when one request simply owns one lazy response and no shared sequence exists. ## The primitive: `StreamHub` [#the-primitive-streamhubt] A hot, ordered, completable in-memory broadcast, owned by the producer — typically a field on an [actor](/docs/concepts/actors), whose mailbox already serializes publishes: ```csharp using Elarion.Streams; private readonly StreamHub _stream = new(new StreamHubOptions { ReplayCapacity = 256, // the replay ring; 1 (default) = BehaviorSubject, more = resumable window }); // Inside a turn: assigns the next contiguous sequence and delivers to every subscriber in order. await _stream.PublishAsync(quote, ct); // Subscribing is atomic replay-then-live: the retained ring and every subsequent publish, no seam // between them — the greeting race client events resolve client-side does not exist here. IAsyncEnumerable> subscription = _stream.SubscribeSequenced(new StreamSubscribeOptions { ResumeAfterSequence = lastSeen, // replay everything newer; a gap that outran the ring }); // shows as a sequence jump, never a silent hole _stream.Complete(); // ends every subscription — the signal fire-and-forget events don't have _stream.Fail(exception); // ends them with the error ``` Each subscriber picks its own overflow strategy — one slow consumer must never stall the fan-out unless it asked to: `DropOldest` (conflation, the default), `Wait` (true backpressure — trusted in-process consumers only), or `Cancel` (the subscriber gets `StreamLaggedException` and re-subscribes with `ResumeAfterSequence`; the publisher is never delayed). `SubscriberCount` is the interest pull for lazy producers. Two contract points come with the single-sequencer design. **Serialize publishes with completion**: the ordering guarantees assume the producer serializes `PublishAsync` with `Complete`/`Fail` — automatic when the hub lives inside an actor's mailbox. Completing concurrently with an in-flight publish makes delivery of that final element per-subscriber nondeterministic (some live subscribers see it, others don't, and a late replay subscriber may see an element a live subscriber missed). **Cancellation is only clean before commit**: cancelling `PublishAsync` while it waits to enter the hub discards the element entirely; once the element is committed (sequence assigned, ring updated), cancelling — e.g. while a `Wait`-mode subscriber applies backpressure — abandons the remaining deliveries: the element exists in replay but pending `Wait`-mode subscribers never receive it. ## Actor stream methods [#actor-stream-methods] An `[Actor]` method returning `IAsyncEnumerable` becomes a **facade stream** — the Orleans 7+ grain-interface shape, so call sites stay migration-portable: ```csharp [Actor(Placement = ActorPlacementMode.SingleHome)] public sealed class StockQuoteActor(IActorContext context) : IActorLifecycle { private readonly StreamHub _stream = new(new() { ReplayCapacity = 256 }); public async Task Apply(QuoteTick tick, CancellationToken ct) { // ...update state... await _stream.PublishAsync(ToQuote(tick), ct); // inside the turn → ordered per symbol } // The attach runs as a mailbox turn (fast); enumeration never holds the mailbox. public IAsyncEnumerable> Watch(long? resumeAfter) => _stream.SubscribeSequenced(new StreamSubscribeOptions { ResumeAfterSequence = resumeAfter }); public ValueTask OnActivateAsync(CancellationToken ct) => ValueTask.CompletedTask; // The lifetime rule: a hub dies with its activation. Complete it here so consumers observe the // end and re-subscribe (which re-activates the actor) instead of starving silently. public ValueTask OnDeactivateAsync(CancellationToken ct) { _stream.Complete(); return ValueTask.CompletedTask; } } // Consumers use the generated facade like any IAsyncEnumerable — nothing happens until iteration, // and each enumeration is its own subscription: await foreach (var item in actors.Get("ELN").Watch(resumeAfter: null, ct)) { … } ``` Two generator rules keep this safe (**ELACT012**): a stream method must not take a `CancellationToken` — the turn token is pooled and its lifetime ends with the attach turn; the facade adds the trailing token, which cancels the queued attach and (linked with the enumerator's token) the stream — and it cannot be a `[ConsumeEvent]` consumer. **A live enumeration retains the activation** (refCount lifetime): idle passivation never ends a stream mid-flight, so a streaming-only actor — consumers attached, no turns arriving — stays alive, and the idle window restarts when the last consumer leaves. Correctness passivations are deliberately exempt (snapshot conflict, shutdown): those complete the hub via `OnDeactivateAsync`, consumers observe the end and re-subscribe, and the fresh hub starts a new sequence *epoch* — which is why resume is a within-one-hub-lifetime contract, and a consumer that sees ids restart treats it as a reset. ## The SSE endpoint: `MapElarionStream` [#the-sse-endpoint-mapelarionstream] `Elarion.AspNetCore` maps a stream as Server-Sent Events with **resume built in**: each element's canonical JSON is one event whose `id:` is the sequence, so the browser's automatic `Last-Event-ID` reconnect header (or an explicit `?after=`) resumes from the hub's ring — gap-free within the retained window, a visible sequence jump beyond it. ```csharp app.MapElarionStream("/quotes/{symbol}/stream", (context, after) => context.Request.RouteValues["symbol"] is string symbol && symbol.Length > 0 ? context.RequestServices.GetRequiredService() .Get(symbol.ToUpperInvariant()).Watch(after) : null); // null → 404 ``` The delegate is the host's control point: authorization happens inside it (or via `.RequireAuthorization()` on the returned builder), and returning `null` is a 404. The element type must be in a registered JSON source-gen context. The rest of the path is one TCP connection — ordered end-to-end with zero extra infrastructure. ## Multi-node reach: home-served by design [#multi-node-reach-home-served-by-design] A stream needs its sequencer, so consumers must connect to the producer's node — which the recommended topology already guarantees: put the streamed routes under the prefixes the [role-holder proxy](/docs/capabilities/hosting) (and later your identical ingress rule) sends to the actor home. `pg_notify` is deliberately not involved: it has no ordering across sessions and no replay — and no role, since one HTTP connection to the home is already reliable and ordered. Needing cross-node streams *without* home routing is the existing replace-the-seam/Orleans trigger, not a knob. `samples/LiveQuotes` ships both tiers side by side: the dashboard converges on conflated `market.quoteChanged` client events, while `curl -N /quotes/ELN/stream` tails every accepted tick in order with resumable ids. # Feature flag providers (/docs/capabilities/feature-flags) Every feature flag is **declared once** and has **exactly one owner**: a resolver class in its module (`[FeatureFlag]`, code-defined) or the host's backend (`[BackendFeatureFlag]`, evaluated by Microsoft.FeatureManagement or an OpenFeature provider). The attributes, the evaluation contracts and `IFeatureFlagService` ship in `Elarion.Abstractions`/`Elarion` core with **no** feature-management dependency; this page covers the host wiring for backend-evaluated flags. For declarations, gates, the evaluation context and the compile-time checks see [Feature flags & variants](/docs/concepts/feature-flags). ## Code-defined flags need no package [#code-defined-flags-need-no-package] A class that implements `IFeatureFlagResolver` and carries `[FeatureFlag]` is wired by the module generator — nothing to register in the host: ```csharp [FeatureFlag("beta-reports", ExposeToClient = true)] public sealed class BetaReportsFlag(IBetaRoster roster) : IFeatureFlagResolver { /* ... */ } ``` ## Choose a backend for backend-evaluated flags [#choose-a-backend-for-backend-evaluated-flags] A host that declares `[BackendFeatureFlag]`s must register exactly one `IBackendFeatureFlagEvaluator`, otherwise it fails at startup. Two opt-in packages provide one, built on [OpenFeature](https://openfeature.dev); the backend answers only for the flags declared as backend-evaluated, so switching one for the other never touches a `[FeatureGate]`. `Elarion.FeatureFlags.FeatureManagement` wires the OpenFeature Microsoft.FeatureManagement provider so declared flags read config-driven values out of the box. Best for getting started. `Elarion.FeatureFlags.OpenFeature` registers the evaluator over any OpenFeature provider you configure (LaunchDarkly, ConfigCat, flagd, Flagsmith, ...). Best when a flag platform is already in play. ### Config-driven flags (FeatureManagement) [#config-driven-flags-featuremanagement] ```csharp builder.Services.AddElarionFeatureManagement(builder.Configuration); ``` ```json title="appsettings.json" { "FeatureManagement": { "new-export": true, "new-dashboard": false } } ``` with the names declared in a module: ```csharp [AppModule("Billing")] [BackendFeatureFlag("new-export")] [BackendFeatureFlag("new-dashboard")] public static class BillingModule { } ``` ### Any OpenFeature provider [#any-openfeature-provider] ```csharp builder.Services.AddOpenFeature(b => b.AddProvider(/* LaunchDarkly, ConfigCat, flagd, ... */)); builder.Services.AddElarionOpenFeature(); ``` `AddElarionFeatureManagement` is sugar over `AddOpenFeature(...) + AddElarionOpenFeature()`. To replace the backend wholesale (a custom store, a test double), register your own `IBackendFeatureFlagEvaluator`. Targeting comes from the **explicit** `FeatureEvaluationContext`: the OpenFeature context is built from its user id (targeting key, plus `UserId`/`Groups`), tenant id (`TenantId`) and custom attributes. For the ambient request that context is derived from [`ICurrentUser`](/docs/capabilities/current-user) and the tenant scope, so rollouts work off-HTTP the same as on, with no `HttpContext`. ## Gate a handler [#gate-a-handler] Once a backend is wired, annotate the handler. The `FeatureGateDecorator` the generator inserts evaluates the flag **just inside the authorization gate**, before caching, validation, and the handler body: ```csharp [Handler("billing.export")] [FeatureGate("new-export")] public sealed class ExportInvoices(AppDbContext db) : IHandler> { /* ... */ } ``` A closed gate short-circuits to `AppError.NotFound` (404), identically under JSON-RPC, MCP, and HTTP — a gated-off operation is indistinguishable from one that doesn't exist. See the concept page for the `All`/`Any` requirement forms, `Negate`, and the `ELFEAT001`/`ELFEAT002` diagnostics. ## Swap an implementation per variant [#swap-an-implementation-per-variant] Beyond on/off gating, a flag can allocate a **variant** per user and resolve a different `[Service]` implementation for it. Mark each implementation of a contract with `[FeatureVariant]` (a modifier on `[Service]`); consumers inject the plain contract and stay unaware: ```csharp [Service] [FeatureVariant("ForecastAlgorithm")] // the default (no Variant) public sealed class LinearForecast : IForecastAlgorithm { /* ... */ } [Service] [FeatureVariant("ForecastAlgorithm", Variant = "neural")] public sealed class NeuralForecast : IForecastAlgorithm { /* ... */ } ``` The generator wires variant resolution automatically; outside a handler constructor, inject `IVariantServiceProvider`. See [Variant service injection](/docs/concepts/feature-flags#variant-service-injection) for how the async-resolving proxy keeps contracts synchronous, and the provider requirement for surfacing variant names. For a **process-global, admin- or ops-made** choice (which e-mail backend?), use the configuration-selected sibling `[ConfigurationVariant("Email:Backend", Value = "office365")]` instead: a plain `IConfiguration` value picks the implementation synchronously — no flag provider, no proxy — and pairing it with the [settings bridge](/docs/concepts/settings) makes the switch admin-writable at run time, cluster-wide. The generated **`ElarionVariants` registry** catalogs every switch (keys, value consts for `[AllowedValues]`, descriptors) so admin surfaces enumerate and validate with zero hand-kept lists — seed it with `AddElarionVariantCatalog(ElarionVariants.All)` + `AddElarionVariantValidation()`. Choose the axis by *who decides*: per-caller experiments are `[FeatureVariant]`; a process-global admin/ops choice is `[ConfigurationVariant]` — and when in doubt, start configuration-selected (the smaller machine). For switchable adapters the recommended shape is a **port-owned vocabulary** (consts beside the port). See [Feature-selected or configuration-selected?](/docs/concepts/feature-flags#feature-selected-or-configuration-selected) and [Who owns the switch](/docs/concepts/feature-flags#who-owns-the-switch). Gate forms, the runtime `IFeatureFlagService`, variant injection, and the design rationale. # Hosting (/docs/capabilities/hosting) The host turns generated registration code into a running JSON-RPC endpoint. It owns composition and transport; modules own application logic. ## Host project references [#host-project-references] ```xml ``` ## Generated host partial [#generated-host-partial] A single assembly attribute tells the generator to emit the cross-module wiring in the host assembly: ```csharp using Elarion.AspNetCore; [assembly: GenerateModuleBootstrapper] ``` `ElarionBootstrapper` gains **extension methods on their natural receivers** so the host wires modules fluently: `services.AddElarion(configuration)`, `endpoints.MapElarionEndpoints(configuration)`, `registry.RegisterHandlers(configuration)`, `configuration.GetMcpMetadata()`, `configuration.GetAllJsonTypeInfoResolvers()`, and `configuration.IsModuleEnabled(name)` — plus the parameterless `ElarionBootstrapper.GetAllModuleNames()` and per-module transport extension methods (`Map{Module}Http`, `Add{Module}Handlers`) and the parameterless `Get{Module}McpMetadata` for every module that owns `[HttpEndpoint]` / `[Handler]` handlers. All transports are **module-scoped and feature-flag-gated** through the bootstrapper: a module disabled with `Modules:{Name}:Enabled = false` has its services, validation metadata, `MapEndpoints`, `[HttpEndpoint]` routes, `[Handler]` JSON-RPC methods, **and** MCP tools all left unmapped, so a disabled module disappears across every surface. Core modules are always mapped. ## Composing the host [#composing-the-host] ```csharp var builder = WebApplication.CreateSlimBuilder(args); builder.Services.AddDbContext(/* provider setup */); builder.Services.AddScoped(sp => sp.GetRequiredService()); // Scheduled-job descriptors are registered per module by AddElarion below; the host picks the runtime. builder.Services.AddElarionScheduler(builder.Configuration); builder.Services.AddMyApp_ApplicationResiliencePolicies(); builder.AddMyAppPlatformCapabilities(); // Also contributes every enabled module's source-generated JSON context to the canonical serializer. builder.Services.AddElarion(builder.Configuration); // Registers JSON-RPC options and the frozen JsonRpcDispatcher singleton, gated per module. Serialization // comes from the canonical IElarionJsonSerialization — no hand-built JsonSerializerOptions is threaded in. builder.Services.AddElarionJsonRpc(ElarionBootstrapper.RegisterHandlers); var app = builder.Build(); app.MapElarionEndpoints(app.Configuration); app.MapElarionJsonRpc(); app.Run(); ``` See [Serialization](/docs/capabilities/serialization) for the canonical `IElarionJsonSerialization` and `ConfigureElarionJson`. `AddElarionJsonRpc(ElarionBootstrapper.RegisterHandlers)` is the **config-aware** overload: it resolves `IConfiguration` when the dispatcher singleton is built and registers only the enabled modules' handlers. The JSON-RPC adapter then serves only the operations flagged `HandlerTransports.JsonRpc`. `MapElarionEndpoints` does the same gating for module `MapEndpoints` and generated `[HttpEndpoint]` routes — including hooks the host declares on behalf of a web-free module assembly with [`[ModuleEndpoints]`](/docs/concepts/modules#declaring-the-hooks-outside-the-module-moduleendpoints). It maps them all into one prefix-less route group and returns it, so `app.MapElarionEndpoints(cfg).RequireAuthorization()` guards those endpoints at once while `[AllowAnonymous]` handlers stay open — the JSON-RPC and MCP endpoints are mapped separately and take their own conventions (see [HTTP endpoints › Public handlers stay public](/docs/capabilities/transports/http-endpoints#public-handlers-stay-public)). To expose the same handlers over MCP (a thin adapter over the same handler bus, equally gated), pair `builder.Configuration.GetMcpMetadata()` with the same `ElarionBootstrapper.RegisterHandlers` registry via `AddElarionMcp` — see [MCP server](/docs/capabilities/transports/mcp). The dispatcher is **frozen** after registration. Freezing produces an immutable, thread-safe map and lets the [build-time schema exporter](/docs/capabilities/transports/schema-generation) read a complete, deterministic method set. A missing, unfrozen, or empty dispatcher is treated as an error rather than producing a stale schema. The exporter reads the dispatcher as configured at build time. Because feature modules are **enabled by default**, the schema stays the complete contract unless a module is explicitly disabled in the configuration the schema build sees — make sure every module is enabled for the schema build if you need the full contract regardless of runtime gating. ## Modules are the only hosting path [#modules-are-the-only-hosting-path] Every transport — services, HTTP, JSON-RPC, and MCP — is wired through `[GenerateModuleBootstrapper]`, so it all stays feature-flag-gated together. There is no flat, ungated map: a host that conceptually has "no modules" simply declares a single **core** `[AppModule]` (core modules map unconditionally), which gives the same always-on behavior while keeping one consistent path. Handlers whose namespace falls under no module are reported (`ELHTTP003`/`ELRPC001`) so they are never silently dropped. The bootstrapper discovers modules and handlers both from **referenced module assemblies** (through their per-assembly Elarion manifests) and from the **host compilation itself**, so the project layout is your choice: the multi-project layout shown above, or a single project where `Program`, the `[AppModule]` declarations, and every handler live in one csproj with `[assembly: GenerateModuleBootstrapper]`. Both wire identically. ## What the host still owns [#what-the-host-still-owns] Mapping the endpoint does not move platform concerns into the framework. The host remains responsible for: * authentication and authorization policy setup, * cross-origin request protection when browsers authenticate with a cookie (see below), * database provider configuration and migrations, * concrete platform capability providers, * middleware order, * health checks, telemetry exporters, and deployment integration, * JSON-RPC endpoint publication and transport-specific error mapping, * the wording of the answer to unexpected exceptions, through [`ConfigureElarionUnexpectedErrors`](/docs/concepts/results-and-errors#unexpected-errors) (every transport already catches them and answers with a support reference). ## CSRF and cookie authentication [#csrf-and-cookie-authentication] A browser attaches some credentials on its own: an ASP.NET Core Identity cookie, the session cookie of an authenticating reverse proxy (Cloudflare Access, Google IAP, oauth2-proxy, …), cached HTTP Basic/Negotiate credentials, or a client certificate. A page on another site can then make the browser send a state-changing request that carries them (cross-site request forgery). A bearer token the client adds in code is not exposed this way, so a host whose browsers only send `Authorization: Bearer …` needs none of this section. The browser sends a cross-origin request without asking first (no CORS preflight) only when it is a "simple" request: `GET`, `HEAD`, or `POST` with a `text/plain`, `application/x-www-form-urlencoded`, or `multipart/form-data` body (or none). Anything else, including a JSON body, is preflighted, and the browser sends it only when the host's CORS policy allows that origin. What that means for each surface: | Surface | Without further setup | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `MapElarionJsonRpc()` (`/rpc`) | Protected: a request whose `Content-Type` is not JSON (or missing) is refused with `415` before the body is read. | | `MapElarionMcp()` (`/mcp`) | Protected: the MCP transport refuses a non-JSON body with `415`. | | `[HttpEndpoint]` with a JSON body (the `POST`/`PUT`/`PATCH` default) | Protected: a non-JSON body is a `415`. | | `[HttpEndpoint]` form and file routes, `MapElarionBlobUploads()`, a `POST` that binds only from the route or query, hand-written routes | **Not protected**: these accept simple requests, and generated form routes are `.DisableAntiforgery()`. | | WebSocket endpoints: `MapElarionConnectionSocket()` ([WebSocket endpoint](/docs/capabilities/connections/websocket)), a hand-written `UseWebSockets` route, a SignalR hub | **Not protected**: the handshake is a `GET` that the browser sends cross-site with its cookies and without CORS, and the open socket can then send and read anything (Cross-Site WebSocket Hijacking). The cross-origin protection covers it. | | `MapElarionClientEvents()`, `MapElarionStream()` (server-sent events) | Read-only `GET`s: a page on another origin can make the browser open one, but can read the events only when the host's CORS policy allows that origin. | | Any `GET` that changes state | **Not protected**: don't write one. | ### The JSON content-type requirement on `/rpc` [#the-json-content-type-requirement-on-rpc] `JsonRpcOptions.RequireJsonContentType` (default `true`) accepts `application/json` and `application/*+json`, with or without a charset. The generated TypeScript client always sends `Content-Type: application/json`; a hand-written caller such as `curl -d` must send it too (`-H 'content-type: application/json'`). The refusal is HTTP `415` with a JSON-RPC `invalid_request` envelope. Turn the requirement off only for a host whose callers cannot send the header **and** whose browsers never carry an ambient credential: ```csharp builder.Services.AddElarionJsonRpc(ElarionBootstrapper.RegisterHandlers, o => o.RequireJsonContentType = false); // only without cookie authentication ``` ### Cross-origin protection middleware [#cross-origin-protection-middleware] For the remaining surfaces, and as defense in depth for all of them, install the cross-origin protection. It needs no token in the client and no identity, so it goes before authentication and routing: ```csharp var app = builder.Build(); app.UseForwardedHeaders(); // behind a proxy: so the request sees its public origin app.UseElarionCrossOriginProtection(o => { o.AllowedOrigins.Add("https://app.example.com"); // a separate front-end origin, if any o.ExemptPathPrefixes.Add("/signin-oidc"); // the identity provider's form_post callback }); app.UseAuthentication(); app.UseAuthorization(); app.MapElarionEndpoints(app.Configuration); app.MapElarionJsonRpc(); ``` For every method except `GET`, `HEAD`, `OPTIONS`, and `TRACE`, and for every WebSocket handshake, it reads the [Fetch Metadata](https://developer.mozilla.org/docs/Glossary/Fetch_metadata_request_header) header `Sec-Fetch-Site` that every current browser sends, and falls back to `Origin` for older ones: * `Sec-Fetch-Site: same-origin` or `none` (the user typed the address) passes. * `Sec-Fetch-Site: same-site` or `cross-site` passes only when `Origin` is one of `AllowedOrigins`. `same-site` is refused on purpose: a sibling subdomain receives the same `SameSite=Lax` cookies but is not the application. * Without `Sec-Fetch-Site`, an `Origin` passes when it is the request's own origin (scheme and `Host` as the host sees them) or one of `AllowedOrigins`; `Origin: null` and more than one `Origin` header are refused. * A request with neither header passes: it does not come from a browser page, so it carries no browser credential. Server-side rendering, scripts, and server-to-server calls are unaffected. A WebSocket handshake is a `GET` whose `Upgrade` header names `websocket`; the middleware reads the header itself, so it works before `UseWebSockets` and before routing. Browsers send `Origin` on every handshake, so a cross-site one is refused with `403` before the socket is accepted, while a device or server client that sends no `Origin` connects as before. An HTTP/2 handshake is a `CONNECT`, which is never a safe method. Every other `GET` (including server-sent events) is unaffected. An endpoint that authenticates every request with a credential a browser never attaches by itself can opt out with `.DisableElarionCrossOriginProtection(pathPrefix)` (`CrossOriginProtectionExemptMetadata`); with a path prefix the exemption also holds when the middleware runs before routing. `MapElarionDav()` does this for the DAV routes. A refusal is HTTP `403` with a ProblemDetails body whose `code` is `cross_origin.refused` (`CrossOriginProtectionErrorCodes.Refused`); a registered `IProblemDetailsService` writes it, so host customization applies. `AllowedOrigins` entries are validated at startup (`scheme://host[:port]`, no path). Two things to get right: * **Behind a reverse proxy**, the request's own origin is what the host sees. Apply forwarded headers before the middleware, or list the public origin in `AllowedOrigins`; otherwise an older browser's same-origin write is compared against the internal address and refused. The failure is closed, never open. * **Exempt only what must receive a cross-site post** (an OpenID Connect `form_post` callback, a payment provider's return) or what authenticates every request with its own non-ambient credential. Exempt prefixes match whole path segments. The middleware does not replace CORS. A separate front-end origin still needs a CORS policy for the browser to send JSON, and an origin that CORS allows to send credentials should also be in `AllowedOrigins`. ASP.NET Core's own antiforgery is token-based and remains an option for form posts; this protection covers every route without one. # ASP.NET Core Identity (/docs/capabilities/identity) Elarion's ASP.NET Core Identity support is split across two **optional** packages: * **`Elarion.EntityFrameworkCore.Identity`** — the web-free Identity *model*: the `[GenerateElarionIdentity]` marker and the `ApplyElarionIdentity` helper. It depends only on EF Core + the Identity stores package, so the project that owns your `DbContext` can model Identity **without** referencing the ASP.NET shared framework. * **`Elarion.AspNetCore.Identity`** — the host *wiring*: `AddElarionIdentity`, the Identity [`ICurrentUser`](/docs/capabilities/current-user) claim mapping, and the transport-neutral authorizer. This one pulls in ASP.NET Core. Identity is one authentication provider among many — [authorization](/docs/concepts/authorization) itself does not depend on either package. The distinguishing trait is **composition over inheritance**: your application `DbContext` stays a plain `DbContext` and *composes* the Identity model, rather than deriving from `IdentityDbContext`. In a layered solution, reference `Elarion.EntityFrameworkCore.Identity` from the **persistence/application** project (where the `DbContext` and `[GenerateElarionIdentity]` live) and `Elarion.AspNetCore.Identity` from the **web host** (where `AddElarionIdentity` runs). The data layer composes the Identity model with no web-framework dependency. In a single-project host, reference both. ## Wiring [#wiring] ```csharp // Program.cs builder.Services.AddElarionIdentity(); builder.Services.AddDbContext(o => o.UseNpgsql(connectionString)); ``` `AddElarionIdentity`: * registers `AddIdentity()` + `AddEntityFrameworkStores()` (+ default token providers), * maps [`ICurrentUser`](/docs/capabilities/current-user) to the Identity claim types (`NameIdentifier`/`Email`/`Role`, overridable), and * registers the transport-neutral authorizer via `AddElarionAuthorization`, so handler `[Require*]` attributes are enforced. Cookie/authentication policy (`ConfigureApplicationCookie`, login endpoints, `UseAuthentication`, `UseElarionCurrentUser`) stays the host's job — the package wires Identity and authorization, not your sign-in UX. ## The context composes Identity [#the-context-composes-identity] `AddEntityFrameworkStores` only needs the Identity entities mapped — it does **not** require `IdentityDbContext`. Annotate a plain `[GenerateDbSets]` context (the `[GenerateElarionIdentity]` marker and its generator come from `Elarion.EntityFrameworkCore.Identity`, so this assembly needs no web dependency): ```csharp [GenerateDbSets] [GenerateElarionIdentity(SnakeCase = true)] public sealed partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } public sealed class ApplicationUser : IdentityUser; public sealed class ApplicationRole : IdentityRole; ``` The bundled generator emits the seven Identity `DbSet`s (`db.Users`, `db.Roles`, `db.UserClaims`, …) and applies the full Identity model configuration — keys, composite keys, unique normalized indexes, relationships, max-lengths — through the EF generator's **per-feature** model-configuration seam (one seam per `[GenerateElarion…]` feature, so Identity composes with resource grants, idempotency keys, and any other feature on the same context). The neutral `OnEntitiesConfigured` seam stays reserved for **your** hand-written model configuration — implement it for a global query filter or extra mapping without colliding with Identity. So the single `ConfigureEntities(modelBuilder)` call configures **both** your domain entities (from `[EntityConfiguration]`) and Identity, with no `` repeated at the call site and no `IdentityDbContext` in the hierarchy. (Requires `[GenerateDbSets]` on the same context, else `ELIDN001`.) ## snake\_case [#snake_case] `SnakeCase = true` (the default) makes the generated Identity model use snake\_case **table, column, and index** names directly — `users`, `roles`, `user_claims`, `normalized_user_name`, `ix_users_normalized_user_name`, … — instead of the ASP.NET `AspNet*` PascalCase defaults. It is self-contained: no `EFCore.NamingConventions` dependency, and the names match what that convention would produce, so an app already using it for domain tables sees a consistent schema. Set `SnakeCase = false` to keep the Identity defaults. Two more knobs place and name the tables: `Schema` puts all seven Identity tables in a non-default schema, and `TablePrefix` prepends a verbatim prefix to every Identity table name (e.g. `TablePrefix = "auth_"` → `auth_users`, `auth_roles`, …). Because Identity spans seven tables, the prefix *is* the table-name override — there are no per-table name parameters — and the snake\_case index names incorporate the prefixed table name. The underlying primitive, `modelBuilder.ApplyElarionIdentity(schema, tablePrefix, snakeCase)` (also in `Elarion.EntityFrameworkCore.Identity`), is public for advanced hosts that prefer to call it directly. ## What stays in your app [#what-stays-in-your-app] The package is deliberately minimal. Role→permission policy, seeding, sign-in/registration endpoints, and the user-management surface stay app-owned — they are domain decisions, not framework mechanics. Permissions are typically issued as a `permission` claim (the default [`AuthorizationOptions.PermissionClaimType`](/docs/concepts/authorization)) on roles, and enforced on handlers with `[RequirePermission]`. You no longer hand-maintain the *list* of permissions, though: inject [`IPermissionCatalog`](/docs/concepts/authorization#permission-catalog) to enumerate every `[RequirePermission]`/`[RequireRole]` across your modules when seeding: ```csharp // Seeding: every [RequirePermission] across enabled modules, no hand-kept Permissions.All list. public sealed class RoleSeeder(IPermissionCatalog catalog, RoleManager roles) { public async Task SeedAdminAsync(ApplicationRole adminRole) { foreach (var permission in catalog.Permissions) { // "{resource}.{verb}", e.g. "clients.read" await roles.AddClaimAsync(adminRole, new Claim("permission", permission)); } } } ``` ## See also [#see-also] * [Authorization](/docs/concepts/authorization) — the attributes and the provider-neutral decision path. * [Current user](/docs/capabilities/current-user) — the `ICurrentUser` abstraction Identity populates. * [Why Elarion → Composition over inheritance](/docs/why-elarion#composition-over-inheritance). # Capabilities (/docs/capabilities) [Concepts](/docs/concepts) covers the application model you cannot avoid: every Elarion app has handlers, results, modules, and the source generation that wires them. **Capabilities are different — they are the platform pieces you opt into and explicitly wire.** You can ship a working application without any of them, and add each one only when a real requirement calls for it. That line is the framework's guiding principle in practice: > Auto-detect application patterns, explicitly wire platform capabilities. Each capability below is independent. Add its package, declare any compile-time opt-in it needs, and wire the runtime in your host. ## Hosting & transports [#hosting--transports] Compose modules into an ASP.NET Core host with the generated bootstrapper, feature gating, and endpoint mapping. Compose per-module JSON contexts into one AOT-friendly serializer shared across transports. Map the same handler over HTTP, JSON-RPC, MCP, or gRPC — and decide which one fits. ## Application policy [#application-policy] Transport-neutral access to the authenticated caller, without depending on `HttpContext`. Optional ASP.NET Core Identity host wiring over the application's existing `DbContext`. Validate the token an authenticating reverse proxy forwards, fail closed at startup, and develop with a stand-in user. One generated handler gate for permissions, roles, claims, policies, and every transport. Data-annotation request validation with generated metadata and transport-safe failures. Declarative handler result caching with `[Cacheable]` and tag-based invalidation. Named retry and timeout policies applied to handlers and jobs. Gate handlers with `[FeatureGate]` and swap per-variant services over any OpenFeature provider. ## Work, messaging & realtime [#work-messaging--realtime] Source-generated recurring and one-off jobs, with optional cross-node occurrence claims. In-process domain events and after-commit integration events, with a durable EF Core outbox. At-most-once, latest-wins hints that tell browsers when to re-query authoritative state. Hot sequenced broadcasts with replay, visible gaps, and resumable SSE delivery. Elect one instance for a coarse application role and route holder-owned HTTP work to it. Long-lived bidirectional links (device gateways, interactive clients) over a transport-neutral kernel. Pairing codes, per-device keys, and the connect-time HMAC handshake for device gateways. Batch samples to the database, conflate hot values to the UI, and feed or flush producer-owned hot state. ## Data & persistence [#data--persistence] Generated `DbSet`s and entity configuration on your concrete `DbContext`. Ambient per-tenant isolation — a read filter and a write-time stamp from one marker interface. Non-tracking `ExecuteInsertAsync` at PostgreSQL binary COPY speed. Transport-neutral keyset and offset paging that produces a `Page` or an `OffsetPage`. Deliberate soft delete — an `ArchivedAt` timestamp, explicit predicates, and restore as a command. One startup-applied plan for SQL scripts, C# code steps and EF Core migrations — one version order, one history, one lock; PostgreSQL or SQLite. Generated `ISqlRowMapper` contracts + injection-safe SQL interpolation for EF-free (NativeAOT) hosts. Extensions are composition, not scale-out — one image for TimescaleDB, pgvector & co. Telemetry on the PostgreSQL you already run — the TimescaleDB recipe. Provider-neutral, streaming-first blob contracts with a PostgreSQL implementation. Direct and resumable uploads over one staged-upload lifecycle, with tus as the recommended transport. Render invoices, protocols, and reports with Typst: a pinned binary bundled by the build, templates as a package. Export records and fill-in templates as `.xlsx`, and import uploaded workbooks with every row and every located problem. ## Operations & governance [#operations--governance] OpenTelemetry-compatible traces and metrics through `System.Diagnostics` — no SDK lock-in. Durable, explicit action records with outcomes, resource context, correlation ids, and optional diffs. Global and per-user settings with optimistic concurrency and cross-node change notification. # Migrations (/docs/capabilities/migrations) Elarion applies schema **and data** changes through one **migration plan** ([ADR-0081](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0081-one-migration-plan.md), building on [ADR-0057](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0057-postgresql-sql-migration-runner.md) and [ADR-0060](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0060-database-neutral-migration-core.md)). A plan is made of typed **steps** contributed by step **sources**: | Step kind | Source | Declared as | | --------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------- | | `sql` | Embedded scripts | `V{version}__{description}.sql` (once, ordered) and `R__{description}.sql` (repeatable) | | `code` | `ICodeMigration` implementations | A C# class with a `Version`, discovered at compile time | | `ef` | EF Core migrations (`Elarion.Migrations.EntityFrameworkCore`) | The `20260713093000_AddDevices` migrations of a `DbContext` | The runner merges **every** step of **every** source into **one version-ordered sequence**, runs it under **one lock** and records it in **one history table**. That is what makes an *expand → backfill → contract* release a single ordered plan instead of three tools and a deployment-ordering convention: the expand migration, the C# backfill and the contract migration run in that order, once per database, no matter how many instances start together. The engine is **database-neutral**; a provider package supplies the SQL and locking: | Provider package | Registration | Use it for | Driver | | ------------------------ | ----------------------------------------------- | ------------------------------------------------------------------------- | ----------------------- | | `Elarion.Sql.PostgreSql` | `AddElarionPostgreSql` + `AddElarionMigrations` | Multi-node PostgreSQL hosts (session advisory lock serializes 1–10 nodes) | `Npgsql` | | `Elarion.Sql.Sqlite` | `AddElarionSqlite` + `AddElarionMigrations` | Single-node / edge hosts on a local file (one file per node) | `Microsoft.Data.Sqlite` | Each provider package ships the migration engine **alongside the EF-free tier's access half** — generated row mappers over hand-written SQL, [SQL mapping](/docs/capabilities/sql-mapping) (ADR-0058) — so the single provider call picks the database for both and they share one data source. `AddElarionMigrations` itself is provider-neutral. PostgreSQL runs both together in the [`samples/EdgeTelemetry`](https://github.com/swimmesberger/Elarion/tree/main/samples/EdgeTelemetry) NativeAOT host. Pick the packages that match your app: | Your app | Packages | Steps | | --------------------------------------- | ----------------------------------------------------------------------------------- | ---------------------------------------- | | EF-free / NativeAOT | `Elarion.Migrations` + a provider (`Elarion.Sql.PostgreSql` / `Elarion.Sql.Sqlite`) | SQL scripts + code steps | | Uses EF Core | The same, plus `Elarion.Migrations.EntityFrameworkCore` | EF migrations + SQL scripts + code steps | | Either, with real deploy infrastructure | Bundles / `migrations script --idempotent` / Flyway in CI | Replace the tool, don't grow the default | The EF tier does **not** call `Database.MigrateAsync()` any more — it runs the one runner, with its migrations as steps (see [EF Core migrations as steps](#ef-core-migrations-as-steps)). The package ships no Elarion framework-table scripts: the EF-based packages remain EF-delivered. ## Quick start [#quick-start] Embed your scripts and register the runner for your database. The API is identical across providers apart from the registration method: ```xml ``` Registration is two steps and identical across providers: pick the database with the provider call, then register migrations with the neutral `AddElarionMigrations` — the only line that differs is the provider. ```csharp // PostgreSQL — the same call also wires the SQL access tier, on one shared NpgsqlDataSource: builder.Services.AddElarionPostgreSql(builder.Configuration.GetConnectionString("Default")!); // ...or SQLite (single-node / edge): builder.Services.AddElarionSqlite(builder.Configuration.GetConnectionString("Default")!); // "Data Source=app.db" // Neutral — names no provider: builder.Services.AddElarionMigrations( o => o.AddScripts(typeof(Program).Assembly, "MyApp.Migrations.")); ``` `AddElarionMigrations` registers `IMigrationRunner` plus a hosted service that applies pending migrations **before the host reports ready** and fails startup on error — serving traffic against a half-migrated schema is worse than not starting. Register it before other hosted services that expect the schema (hosted services start in registration order); set `ApplyOnStartup = false` to invoke the runner yourself. The PostgreSQL provider call also has an `NpgsqlDataSource` overload for hosts that already manage one. Scripts are plain SQL in your database's own dialect — the runner never rewrites them, so write PostgreSQL for the PostgreSQL provider and SQLite for the SQLite provider. ## Code steps [#code-steps] Work a SQL script cannot express — parsing, hashing, calling a domain service, filling a column with computed data — is a C# step. Implement `ICodeMigration` and give it a **version in the same space as the scripts**: ```csharp public sealed class BackfillOrderTotals : ICodeMigration { public string Version => "20260901120000"; // between the expand and contract scripts below public string Description => "backfill order totals"; public async Task ExecuteAsync(MigrationStepContext context, CancellationToken ct) { // Runs in the plan's transaction on the plan's connection — rolled back together with the history row. await context.ExecuteSqlAsync( "UPDATE orders SET total = (SELECT sum(price * qty) FROM order_lines WHERE order_id = orders.id) WHERE total IS NULL", ct); } } ``` ```text Migrations/V20260901110000__orders_add_total.sql -- expand: ADD COLUMN total numeric NULL (BackfillOrderTotals, 20260901120000) -- backfill: C# Migrations/V20260901130000__orders_require_total.sql -- contract: SET NOT NULL ``` The three run in version order, in one run, exactly once per database. Register them at compile time — no reflection scan: ```csharp public static partial class MigrationRegistrations { [GenerateContractSetRegistration(typeof(ICodeMigration))] // ADR-0070 public static partial IServiceCollection AddCodeMigrations(this IServiceCollection services); } // builder.Services.AddCodeMigrations(); or one at a time: services.AddCodeMigration(); ``` A code step is stateless metadata held as a singleton: it must not inject scoped services. Everything it needs is resolved from `context.Services` — a **fresh scope per step** — such as a `DbContext`, an `ISqlSession` or a handler. Without DI (the `PostgreSqlMigrationRunner` façade) pass `options.AddCodeMigrations(instance)`. The semantics mirror a transactional SQL script: * **Transaction by default.** The step runs in a transaction on `context.Connection` (the connection that holds the migration lock), and its history row commits in that same transaction. Anything written through `context.Connection` / `context.ExecuteSqlAsync` is atomic with the record. * **Failure stops the plan.** An exception rolls the transaction back, records **nothing** for the step, throws `MigrationExecutionException` naming it and fails startup. The next start retries it — and no later step runs before it succeeded, because later steps may build on it. * **Services bring their own connections.** A `DbContext` or `ISqlSession` resolved from `context.Services` uses a different connection, *outside* the step's transaction: its writes are **not** rolled back on failure. Keep such conversions idempotent (`WHERE` matches only unconverted rows, `ON CONFLICT DO NOTHING`) — or let an EF context adopt `context.Connection`/`context.Transaction` (`Database.SetDbConnection`, `Database.UseTransaction`) to make its writes atomic with the record. * **Opt out for long batches.** `UseTransaction => false` runs the step without a transaction so a very large conversion can commit as it goes. The consequence: a failure can leave partial writes behind, still records nothing, and the next start reruns the step — so it **must** be idempotent and resumable. (A SQL `no-transaction` script differs deliberately: a half-applied *schema* fails closed until you resolve it, see below.) * **Satisfied.** `IsAlreadySatisfiedAsync` lets a step declare "nothing to do" — a fresh install where the legacy source never existed — and is recorded with outcome `satisfied` without running. Baselining an adopted database covers the rest. Neither is automatic: a guess about "fresh" is a bug waiting to happen. * **Exactly once across instances.** The same migration lock as the scripts: a waiting instance re-reads the history *after* it holds the lock, finds the step recorded and does nothing. A recorded step whose class was later deleted is simply ignored — removing a conversion once it rolled out everywhere is the intended cleanup. ## EF Core migrations as steps [#ef-core-migrations-as-steps] The EF tier keeps its **EF migrations** — `dotnet ef migrations add` and the model snapshot are unchanged — but runs them through the plan instead of `Database.MigrateAsync()`: ```csharp builder.Services.AddDbContext(o => o.UseNpgsql(cs)); builder.Services.AddElarionPostgreSql(cs); // the plan's connection and advisory lock builder.Services.AddCodeMigration(); builder.Services.AddElarionMigrations(o => o.AddEntityFrameworkMigrations()); ``` Each EF migration becomes one step versioned by the timestamp in its id (`20260901110000_OrdersAddTotal` → `20260901110000`), so it interleaves with scripts and code steps in the same sequence — an EF expand migration, a C# backfill, an EF contract migration. An EF step executes the migration's own generated SQL (what `dotnet ef migrations script` prints for that one migration) in the plan's transaction, so the migration and the plan's history row commit atomically. EF's `__EFMigrationsHistory` row is written by that script as well — EF tooling stays truthful — while the plan's history is the authority for ordering and exactly-once. Notes for EF hosts: * **Adoption needs no baseline.** On a database EF already migrated, each EF step whose id is listed in `__EFMigrationsHistory` is recorded as `satisfied` the first time the plan runs; only newer steps apply. * **EF migrations are transactional steps.** An operation EF marks `suppressTransaction` (for example `CREATE INDEX CONCURRENTLY`) cannot run in the plan's transaction; put it in a `-- elarion: no-transaction` SQL script with a version between the surrounding steps. * The step source needs `Elarion.Migrations.EntityFrameworkCore` (which brings `Microsoft.EntityFrameworkCore.Relational`) and supports providers whose migration script is a plain statement batch — PostgreSQL and SQLite. The EF-free NativeAOT tier never references it. * Do not also call `Database.Migrate()`/`MigrateAsync()` at startup — two runners over one set of migrations is exactly what the plan removes. ## SQL script conventions [#sql-script-conventions] Scripts are embedded resources (discovery reads the assembly manifest — AOT-safe, no filesystem): | Name | Meaning | | ------------------------------- | ------------------------------------------------------------------------------------------------ | | `V{version}__{description}.sql` | Versioned: applied exactly once, in version order | | `R__{description}.sql` | Repeatable: re-applied whenever its checksum changes, after all versioned scripts, in name order | * **Use timestamp versions** (`V20260713093000__add_devices.sql`): they make branch-merge collisions structurally rare instead of policing them at deploy time — and they are the same timestamps code steps and EF migrations carry, which is what lets the three interleave. * A version belongs to **one step across all kinds**: a script and a code step claiming the same version fail validation naming both. * Multi-segment versions separate segments with single underscores (`V1_2__…` is version 1.2) — file names cannot contain dots, because folder paths become dot-separated resource-name segments. * Validation is **fail-closed and total**: within the configured scope (assembly + optional resource prefix), every `.sql` resource must be a valid script — duplicate versions, malformed names, and undecodable content each fail naming the offending resource. Nothing is silently skipped. * Repeatables are for idempotent `CREATE OR REPLACE` surfaces (views, functions) — never destructive DDL. **Checksums are SHA-256 over normalized content** (BOM stripped, CRLF→LF), so line-ending churn — git `autocrlf`, an editor touching whitespace — can never invalidate an applied script. A genuine mismatch fails validation with the script name, both hashes, and the two legal resolutions: revert the edit, or add a new script. ## Execution model [#execution-model] One runner, one dedicated connection, guarded by an **exclusive migration lock** so concurrent startups serialize, waiters re-read history and no-op. The lock's scope is the provider's: * **PostgreSQL** takes a **session-level** `pg_advisory_lock` — it serializes the 1–10-node tier across processes, and a crashed runner releases it with its connection (no lock row to clean up). * **SQLite** takes a per-file **in-process** lock — SQLite is single-node by design (one file per node, never shared across nodes), so *this process* is the correct scope; `LockTimeout` bounds the wait and `busy_timeout` backstops the unsupported cross-process case. Each versioned step runs in its own transaction on that connection, and **its history row commits in that same transaction**. A failed transactional step therefore leaves *no* history row: fix it and rerun. There is no repair command because there is nothing to repair — and no undo either (a dropped column's data cannot be un-dropped; roll forward). This invariant is identical on both providers (SQLite has full transactional DDL) and for every step kind. ### The history table [#the-history-table] One table, `elarion_schema_history`, one row per step: | Column | Meaning | | --------------------------- | -------------------------------------------------------------------- | | `installed_rank` | True execution order | | `kind` | `sql`, `code`, `ef`, or `baseline` | | `version` | Canonical dotted version (null for repeatable scripts), unique | | `step_name` | Script file name, code-migration type name, EF migration id | | `description` | Human-readable description | | `checksum` | SHA-256 of a script's normalized content; null for code and EF steps | | `outcome` | `applied`, `satisfied`, `baseline`, or `failed` | | `applied_at`, `duration_ms` | Server timestamp and measured duration | A history table written by the earlier script-only runner (`script_name`, `state`, no `kind`) is **upgraded in place** by the first run that holds the lock — columns renamed, rows tagged `sql` (baseline markers `baseline`), nothing re-applied; read-only calls (`ValidateAsync`, `GetPendingAsync`) understand the old layout meanwhile. Applications that queried `script_name`/`state` directly must switch to `step_name`/`outcome`. ### Non-transactional SQL scripts [#non-transactional-sql-scripts] DDL a database forbids inside a transaction opts out via a directive on the leading comment block: ```sql -- elarion: no-transaction CREATE INDEX CONCURRENTLY orders_customer_idx ON orders (customer_id); ``` On **PostgreSQL** this is for statements like `CREATE INDEX CONCURRENTLY`; the runner executes the script statement by statement (each as its own implicit transaction — batching them would reintroduce the transaction the directive opts out of). On **SQLite** it is rarely needed — SQLite has full transactional DDL and no `CREATE INDEX CONCURRENTLY` — and such a script runs in autocommit mode (each statement commits on its own). Only a non-transactional script can leave a mid-applied state on failure: the runner records an explicit **failed** history row and subsequent runs fail closed, naming the script and the recovery API: ```csharp // AddElarionMigrations registers IMigrationRunner — inject/resolve it where you handle recovery: IMigrationRunner runner = app.Services.GetRequiredService(); await runner.ResolveFailedAsync("20260713093000", ResolveAction.Retry); // rerun the fixed script await runner.ResolveFailedAsync("20260713093000", ResolveAction.MarkApplied); // schema was completed by hand ``` A deliberate in-code decision at the call site — not a CLI habit. An unknown directive (a typo like `no-transactoin`) fails validation instead of silently changing transaction semantics. Failed rows are recorded for **versioned** scripts only: a repeatable script that fails under `no-transaction` records nothing — repeatables are idempotent by doctrine and their changed checksum was never recorded, so the next run simply retries them. A non-transactional **code** step likewise records nothing and is retried (see [Code steps](#code-steps)). ## Migrating into a schema [#migrating-into-a-schema] By default everything lands in the connection's own default schema (`public` on a stock PostgreSQL). To keep the application's objects in a schema of their own — **without putting a prefix in a single script** — name it on the provider registration: ```csharp builder.Services.AddElarionPostgreSql( builder.Configuration.GetConnectionString("Default")!, schema: "app"); ``` There is no migration option for this, deliberately. The schema is the connection's `Search Path`, so **one setting steers both** the SQL access tier and migrations: prefix-free scripts and unqualified application queries resolve through the same path and cannot drift into different schemas. `schema:` is pure convenience — `Search Path=app` in the connection string is the same thing, and wins if you set both. The `NpgsqlDataSource` overload takes no `schema` argument for the same reason: your data source already carries it. What migrations add on top is the one thing a connection setting cannot do: the runner **creates the schema if it does not exist**, under the migration lock so concurrent starters cannot race, and writes the history table schema-qualified — so two schemas in one database keep independent histories and a script that leaves `search_path` pointing elsewhere cannot misplace history rows. Multi-schema deployments follow from this: one connection string per schema, each with its own history. Give them distinct `advisoryLockKey` values to let them migrate concurrently. SQLite has no schema concept — its "schema names" are ATTACHed database files — so use a separate database file per tenant there instead. ## Out-of-order scripts [#out-of-order-scripts] When a merge lands a step versioned below one already applied, the default policy is **`Warn`**: the step is applied, logged as a warning, and recorded in true execution order (`installed_rank`). The history table records what actually happened either way; a strict default only teaches teams a global escape flag. Teams that want strict ordering opt into `OutOfOrder = OutOfOrderPolicy.Deny`, which fails the run naming the offenders. ## Adopting an existing database [#adopting-an-existing-database] `BaselineAsync(version)` marks an existing schema as already at a version — steps of every kind at or below it are treated as applied and never run. It is explicit only (allowed solely while the history is empty); there is no `baselineOnMigrate` auto-magic. `ValidateAsync` (checksum + pending report, no writes) and `GetPendingAsync` back health checks and deploy gates; everything ships in the box, no feature tiers: ```csharp IMigrationRunner runner = app.Services.GetRequiredService(); // One-time adoption of an existing database (history must be empty): await runner.BaselineAsync("20260713093000", "adopt existing schema", ct); // Health check / deploy gate — read-only: MigrationValidationResult validation = await runner.ValidateAsync(ct); if (!validation.IsValid) Report(validation.Errors); // checksum drift, malformed scripts IReadOnlyList pending = await runner.GetPendingAsync(ct); ``` ## Options [#options] At least one step source is required. The neutral options apply to every provider: | Option | Default | Meaning | | -------------------------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `AddScripts(assembly, prefix?)` | — | Assemblies + optional resource-name prefix to scan for SQL scripts | | `AddCodeMigrations(...)` / `AddCodeMigration()` | — | Code steps (the options form is for non-DI use) | | `AddStepSource(source)` | — | A further step source, e.g. `AddEntityFrameworkMigrations()` | | `HistoryTableName` | `elarion_schema_history` | The runner-created history table | | `OutOfOrder` | `Warn` | `Warn` (apply + log) or `Deny` (fail the run) | | `ApplyOnStartup` | `true` | Register the migrate-before-ready hosted service | | `CommandTimeout` | none | Per-command timeout; long DDL is normal, so unlimited by default. **PostgreSQL only** — SQLite has no server-side statement timeout, so it is ignored there | | `LockTimeout` | none | How long to wait for the migration lock (unlimited: serialize behind a long migration) | The PostgreSQL provider adds two *registration* arguments rather than options: `advisoryLockKey` (a fixed constant by default) — distinct keys let two apps sharing one database migrate independent schemas concurrently — and `schema` (see [Migrating into a schema](#migrating-into-a-schema)). Both belong to the connection, not to the migration set. SQLite adds neither. ## What it deliberately is not [#what-it-deliberately-is-not] No undo, no repair, no placeholders/variable substitution, no dialect *setting*, no feature tiers, no repeatable code steps, no step dependency graph — order is the version, and that is the whole model. A new database engine is a new **provider package** implementing the `IMigrationDatabase` seam — never a `Dialect` flag on one runner; a new kind of step is a new **step source** implementing `IMigrationStepSource`. If you need any of the rejected features, replace the tool (Flyway or Evolve in CI) rather than growing this default — the same doctrine as every Elarion seam ([ADR-0025](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0025-distributed-scheduler-coordination.md)). App-side *data access* under AOT is a separate concern, owned by ADR-0058. A conversion too large for a startup step — hours of work, progress checkpoints, per-batch leases — belongs in a background job, not the plan. # Multi-tenancy (/docs/capabilities/multi-tenancy) Every row belongs to exactly one tenant — workspace, org, realm, account — and cross-tenant visibility is never legitimate. That is a different problem from [sharing](/docs/concepts/resource-authorization), where a row *some* users may see is a per-feature decision written at the query. Tenancy is unconditional, so Elarion makes it **ambient**: a property of the scope rather than something each query and each `Add` has to remember. Tenancy and [resource authorization](/docs/concepts/resource-authorization) compose. Tenant scoping decides *which tenant's rows exist at all*; `[ResourceFilter]` decides *which of them this user may see* within that tenant. ## 1. Mark the entity [#1-mark-the-entity] One interface, on the entity. There is no attribute and nothing to declare per query. ```csharp public sealed class Contact : ITenantScoped { public Guid Id { get; init; } = Guid.CreateVersion7(); public Guid TenantId { get; set; } // stamped on insert, filtered on read public required string Name { get; set; } } ``` The key may be `Guid`, `string`, `int`, or `long` — the same key types `[ResourceFilter]`'s tenant rule accepts. The property must be settable: the framework stamps it, and a hand-set value is *verified* rather than trusted. ## 2. Wire it up [#2-wire-it-up] Two registrations and one attribute. The split is deliberate — how a tenant is *resolved* is transport-neutral and lives in `Elarion`; how it reaches the database lives in the EF package. ```csharp [GenerateDbSets] [GenerateElarionTenantScoping] public partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } ``` ```csharp builder.Services.AddDbContext(o => o.UseNpgsql(connectionString)); builder.Services.AddElarionTenantScoping(); // ITenantContext + claim resolver builder.Services.AddElarionTenantScopingEntityFrameworkCore(); // filter value + write stamp ``` Use `AddDbContext`, **not** `AddDbContextPool`. A pooled context builds its options once, so every scope would serve the *first* scope's tenant — a silent cross-tenant leak. The registration fails fast rather than degrading quietly. A host that writes its own `OnModelCreating` can skip the attribute and call `modelBuilder.ApplyElarionTenantScoping(this)` as the last statement instead. ## 3. Write handlers that say nothing about tenancy [#3-write-handlers-that-say-nothing-about-tenancy] That is the point. Neither of these mentions the tenant, and both are correct: ```csharp [Handler("crm.contacts.list")] public sealed class ListContacts(AppDbContext db) : IHandler>> { public async ValueTask>> HandleAsync(Query request, CancellationToken ct) => await db.Contacts // already scoped to the caller's tenant .Where(c => c.Name.Contains(request.Search)) .ToKeysetPageAsync(request, RecentContacts.Definition, c => new ContactDto(c.Id, c.Name), cancellationToken: ct); } [Handler("crm.contacts.create")] public sealed class CreateContact(AppDbContext db) : IHandler> { public async ValueTask> HandleAsync(Command request, CancellationToken ct) { var contact = new Contact { Name = request.Name }; // TenantId stamped on save db.Contacts.Add(contact); await db.SaveChangesAsync(ct); return contact.Id; } } ``` ## How it holds [#how-it-holds] ### Reads — a named model-level filter [#reads--a-named-model-level-filter] `ApplyElarionTenantScoping` attaches a named EF Core query filter to every tenant-scoped root entity: ``` e => IsSystemScope(ctx) || e.TenantId == AsGuid(CurrentTenantId(ctx)) ``` It is the one place this repository uses a global query filter, and the [archive/restore recipe](/docs/capabilities/archive-restore#why-not-a-global-hasqueryfilter) — which argues at length against them — names this exact exception: *a global filter earns its keep when the predicate is a security boundary that must hold even when a developer forgets.* Two properties matter: * **It fails closed.** The comparison is against a *nullable* key, so an unresolved tenant compares against SQL `NULL` and matches nothing. Comparing against `Guid.Empty` instead would expose every row that happens to carry it. * **It is named**, so your own filters on the same entity survive, and a query can drop only this one: `db.Contacts.IgnoreQueryFilters([ElarionTenantScoping.QueryFilterKey])`. Prefer a [system scope](#work-that-spans-every-tenant) — it says so once for a whole unit of work and covers writes too. ### Writes — a stamp and a guard [#writes--a-stamp-and-a-guard] A `SaveChanges` interceptor closes the other half: | Change | Behavior | | ---------------------------------------- | ----------------------------------------------------------------- | | Insert, tenant unset | Stamped with the tenant in scope | | Insert, tenant set by hand | Verified; a different tenant throws | | Insert with no tenant resolved | Throws — a row stamped with nothing fails the read filter forever | | Update or delete of another tenant's row | Throws, even for an entity attached without being loaded | | Changing an existing row's tenant | Throws — a row belongs to one tenant for its whole life | Violations raise `TenantScopeViolationException`. It is a fault, not an `AppError`: it means the isolation was bypassed, which no caller should handle and no client should see explained. ### Cached reads — keyed by tenant [#cached-reads--keyed-by-tenant] A [`[Cacheable]`](/docs/capabilities/caching) hit returns a stored result without running the handler, so the read filter never sees it. `Elarion.Caching` closes that gap itself: when `ITenantContext` is registered, the tenant in scope is part of every cache key and tag, for `Global` and `CurrentUser` scope alike. * A tenant's entries are served only to that tenant, including for a user who switches tenants with `Scope(tenantId)`. * A [system scope](#work-that-spans-every-tenant) caches in a namespace of its own. * A scope with **no tenant resolved is not cached**: the handler runs every time, so its filter decides, as it does for every uncached read. * `[CacheInvalidate]` inside a tenant evicts that tenant's entries for every user and leaves other tenants' entries cached. From a system scope, or with no tenant, it evicts every tenant. [Caching → Tenant isolation](/docs/capabilities/caching#tenant-isolation) explains why there is no cache without a tenant, and what this means for cached data that is not tenant-scoped. ## Work that spans every tenant [#work-that-spans-every-tenant] Declare it. A background job crossing tenants is legitimate; *silently omitting a filter* is not, and the two must not look alike. ```csharp public sealed class PurgeExpiredSessions(AppDbContext db, ITenantContext tenant) { [ScheduledJob("sessions.purgeExpired", Cron = "0 3 * * *")] public async Task RunAsync(CancellationToken ct) { using var _ = tenant.SystemScope(); // deliberately every tenant — greppable await db.Sessions.Where(s => s.ExpiresAt < DateTimeOffset.UtcNow).ExecuteDeleteAsync(ct); } } ``` To act as one tenant at a time instead — the usual shape for a per-tenant worker — enter each one: ```csharp foreach (var tenantId in await LoadActiveTenantsAsync(ct)) { using var _ = tenant.Scope(tenantId); await RebuildDigestAsync(ct); } ``` ## Resolving the tenant [#resolving-the-tenant] `ITenantResolver` produces the id. The shipped `ClaimsTenantResolver` reads a claim (`"tenant"` by default) from `ICurrentUser`, so it works identically under HTTP, JSON-RPC, MCP, and a connection adapter: ```csharp builder.Services.AddElarionTenantScoping(o => o.ClaimType = "workspace"); ``` Two tenant claims resolve to *nothing* rather than the first — an isolation boundary must not depend on claim ordering. ### When the tenant is not a claim [#when-the-tenant-is-not-a-claim] Resolution is **synchronous**, because a query filter is evaluated during query translation and cannot await. If your tenant comes from a membership table, resolve it where awaiting is legal and enter the scope with the result — do not synthesize a claim: ```csharp app.Use(async (context, next) => { var tenant = context.RequestServices.GetRequiredService(); var workspace = await memberships.ResolveAsync(context.User, context.RequestAborted); using var _ = workspace is null ? null : tenant.Scope(workspace); await next(); }); ``` Register your own `ITenantResolver` before `AddElarionTenantScoping()` and its `TryAdd` leaves the claim-based default out. ## What this does not cover [#what-this-does-not-cover] Both legs sit on the Entity Framework Core path. These bypass them, exactly as they bypass [`[ResourceFilter]`](/docs/concepts/resource-authorization): * **Raw SQL** (`FromSql`, `SqlQuery`) and the [AOT SQL tier](/docs/capabilities/sql-mapping) — scope your own statements. * **Bulk COPY** ([bulk operations](/docs/capabilities/bulk-operations)) — set the tenant yourself. * **`ExecuteUpdate`/`ExecuteDelete`** run against the *filtered* query, so they cannot reach another tenant's rows, but they are not stamped or guarded because they never reach `SaveChanges`. Tenant scoping is application-level isolation, not a database-level one. It is not a substitute for PostgreSQL row-level security in a threat model where the application itself is untrusted — which is the same posture [ADR-0013](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0013-resource-and-data-level-authorization.md) takes for resource authorization. ## Related [#related] * [Resource authorization](/docs/concepts/resource-authorization) — sharing *within* a tenant * [Archive & restore](/docs/capabilities/archive-restore) — why global query filters are otherwise rejected * [Entity Framework Core](/docs/capabilities/entity-framework) — the generated context and model seams * [ADR-0075: Ambient tenant scoping](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0075-ambient-tenant-scoping.md) — the design, the trade-offs, and the alternatives rejected # Pagination (/docs/capabilities/pagination) A list handler returns one of two transport-neutral envelopes (from `Elarion.Abstractions.Paging`), each the same across JSON-RPC, MCP, HTTP, and the generated TypeScript client — `Page` for a keyset list, `OffsetPage` for a numbered one: ```csharp title="Elarion.Abstractions.Paging" public sealed record Page { // keyset: ToKeysetPageAsync public required IReadOnlyList Items { get; init; } public string? StartCursor { get; init; } public string? EndCursor { get; init; } public bool HasNext { get; init; } public bool HasPrevious { get; init; } public int? Total { get; init; } // only when a handler counts } public sealed record OffsetPage { // offset: ToOffsetPageAsync public required IReadOnlyList Items { get; init; } public required int Total { get; init; } public bool HasNext { get; init; } public bool HasPrevious { get; init; } } ``` The cursors follow the Relay convention: `StartCursor`/`EndCursor` are opaque tokens for the first and last items. Offset paging always counts and never has cursors, so its envelope says exactly that: `Total` is required and the generated TypeScript type is `{ items, total: number, hasNext, hasPrevious }`. `Page.Empty` and `OffsetPage.Empty` (with `Total = 0`) are ready-made empty pages, and `offsetPage.ToPage()` converts an offset page for an endpoint whose contract stays `Page`. Keyset (seek) pagination is the default for feeds and large lists; offset pagination is available where a UI needs page numbers and a total count. Pagination ships in a **separate package** (`Elarion.Paging`) so the EF Core marker package stays dependency-free. The execution helpers depend on EF Core (`Microsoft.EntityFrameworkCore.Relational`), while the provider-neutral `Page` and `OffsetPage` envelopes and the `IKeysetPageRequest`/`IOffsetPageRequest` contracts live in `Elarion.Abstractions.Paging`. Reference `Elarion.Paging` (the runtime helpers) and `Elarion.EntityFrameworkCore` (which bundles the generator that emits keyset definitions) in the project that owns your entities and handlers: ```xml ``` ## Keyset pagination [#keyset-pagination] Declare the ordered key columns on a dedicated partial class with `[Keyset]` — the entity stays free of pagination concerns, and an entity can have any number of orderings. Columns are ascending by default; prefix a name with `-` for descending. The generator ([`KeysetGenerator`](/docs/concepts/source-generation)) fills the class with a reflection-free `IKeysetDefinition` (ordering and seek predicate are plain typed expressions the provider translates to SQL like hand-written `OrderBy`/`Where`) plus a static `Definition` singleton and an opaque cursor codec that carries the key values (no extra round-trip to reload a reference row): ```csharp using Elarion.Paging; // [Keyset] public sealed class Client { public Guid Id { get; init; } public DateTime CreatedAt { get; init; } public string Name { get; init; } = ""; } // one partial class per ordering, declared near the feature that pages it [Keyset(nameof(Client.CreatedAt), nameof(Client.Id))] // CreatedAt, then Id to break ties public sealed partial class ClientsByCreated; ``` For a "newest first" feed, prefix each column with `-` to sort descending. Keeping every column the same direction also lets the Npgsql provider use a row-value seek (see below): ```csharp [Keyset("-CreatedAt", "-Id")] // CreatedAt desc, then Id desc to break ties public sealed partial class RecentPosts; ``` Handlers call `ToKeysetPageAsync` with the keyset definition and a server-side projection. Passing the definition explicitly (`ClientsByCreated.Definition`) keeps keyset symmetric with offset paging — which passes a `SortMap` — and lets one handler choose among an entity's orderings. The request implements `IKeysetPageRequest`, so its `After`/`Before`/`Size` fields stay flat for HTTP GET query binding (`KeysetPageRequest` is a ready-made implementation for handlers that need no extra filters): ```csharp [Handler("clients.list")] [HttpEndpoint("clients")] public sealed class ListClients(AppDbContext db, ICurrentUser user) : IHandler>> { public sealed record Query : IKeysetPageRequest { public string? After { get; init; } public string? Before { get; init; } public int Size { get; init; } = 20; public string? Search { get; init; } } public sealed record Item(Guid Id, string Name, DateTime CreatedAt); public async ValueTask>> HandleAsync(Query query, CancellationToken ct) { var rows = db.Clients.Where(c => c.OwnerId == user.UserId); if (!string.IsNullOrEmpty(query.Search)) { rows = rows.Where(c => c.Name.Contains(query.Search)); } return await rows.ToKeysetPageAsync( query, ClientsByCreated.Definition, c => new Item(c.Id, c.Name, c.CreatedAt), maxSize: 100, ct); } } ``` The `selector` is the only projection — it runs server-side, composed with the key columns so the query reads just your columns plus the keys (untracked, no extra round-trip) and encodes the boundary cursors from those keys. That is why it is passed in rather than applied as a separate `.Select` before paging: the cursor needs the key values your DTO does not carry. Pass `After` (an `EndCursor` from a prior page) to page forward, `Before` (a `StartCursor`) to page backward, or neither for the first page. `Size` is clamped to `maxSize` (defaulting to `QueryablePagingExtensions.DefaultMaxSize`, which is `100`). Cursors are opaque but **not** a security boundary — they encode the boundary row's key values and are neither signed nor encrypted. Keep applying your own authorization filter (e.g. `Where(c => c.OwnerId == user.UserId)`); never trust a cursor for access control. Each cursor embeds a build-stable **keyset-identity tag** (a hash of the definition's fully-qualified name and its ordered column types), so a cursor minted by one keyset endpoint is rejected — not silently reinterpreted — when fed to another. A cursor that is malformed, truncated, of the wrong format version, or carries a mismatched identity tag makes `BuildSeek` (and therefore `ToKeysetPageAsync`) throw a `MalformedCursorException` rather than resetting to the first page. Map it to a validation / `400 Bad Request` response so the client learns its cursor is invalid; its message names no key values and is safe to surface. ### Keyset column rules [#keyset-column-rules] The generator enforces the hard column rules at compile time, so a typo or a column that cannot be translated is a **build error**, not a runtime bug: * Column names must match a property (`ELKEY001`, error), so a typo — or a rename you forget to propagate — fails the build. That is why the `"-Column"` string form needs no `nameof`. * Columns must be **non-nullable** (`ELKEY003`, error) for deterministic SQL ordering. * If the entity has a primary-key property that is not part of the keyset, the generator **warns** (`ELKEY004`) that paging may skip or repeat rows; append it (or another unique column). The key is detected as a `[Key]`-annotated property, or the EF conventional name `Id` or `{EntityType}Id`. It stays a warning rather than an error because a keyset whose own columns are already unique is legitimately deterministic without the key. * Supported column types are the integral types (`int`, `long`, `short`, `byte`), `decimal`/`double`/`float`, `string`, `Guid`, `DateTime`, `DateTimeOffset`, `DateOnly`, `TimeOnly`, and enums; others report `ELKEY002`. * The keyset class must be a **top-level, non-nested partial class** (`ELKEY005`) so the generator can emit the definition into it. ### Provider-optimized seek (Npgsql row values) [#provider-optimized-seek-npgsql-row-values] By default the seek predicate is a portable lexicographic comparison (`a > x || (a == x && b > y)`) that every provider can translate. PostgreSQL can do better: a [row-value expression](https://www.npgsql.org/efcore/release-notes/7.0.html#row-value-expressions) `(a, b) > (x, y)` is a single comparison that a composite index on `(a, b)` satisfies directly. EF Core has no provider-neutral row-value API yet ([dotnet/efcore#26822](https://github.com/dotnet/efcore/issues/26822)), so this is an explicit opt-in that keeps the default output provider-neutral. Add the assembly-level attribute (typically in the project that owns your entities) to switch the generated seek to row values: ```csharp using Elarion.EntityFrameworkCore; [assembly: UseElarionEntityFrameworkCore(Provider = EfCoreProvider.Npgsql)] ``` With `Npgsql` selected, a keyset of two or more columns (up to seven) that share one direction emits `EF.Functions.GreaterThan`/`LessThan` over `ValueTuple`s, which Npgsql renders as a row value: ```csharp // [Keyset(nameof(Client.CreatedAt), nameof(Client.Id))] with the Npgsql provider: __e => EF.Functions.GreaterThan( ValueTuple.Create(__e.CreatedAt, __e.Id), ValueTuple.Create(__key0, __key1)); ``` The generator falls back to the portable predicate automatically when row values do not apply: a single-column keyset, mixed sort directions (e.g. `-CreatedAt, Id`), a keyset of more than seven columns, or the default `Portable` provider. The opt-in requires the `Npgsql.EntityFrameworkCore.PostgreSQL` package, which supplies the `EF.Functions.GreaterThan(ValueTuple, ValueTuple)` overloads the generated code calls. ## Offset pagination [#offset-pagination] When a UI needs random page access and a total count, use `ToOffsetPageAsync`, which returns an `OffsetPage`, with a `SortMap` — an AOT-safe whitelist that binds sort keys to typed selectors (no dynamic LINQ, and clients can only sort by columns you allow). Each entry may chain `ThenBy` tiebreakers (each with a `SortDirection`) for a stable composite order. The map is a fixed whitelist that doesn't depend on the request, so build it once with `CreateBuilder(...).Add(...).Build()` and keep the immutable result in a `static readonly` field rather than rebuilding per call: ```csharp private static readonly SortMap Sort = SortMap .CreateBuilder("createdAt", c => c.CreatedAt, SortDirection.Descending) // default sort .ThenBy(c => c.Id, SortDirection.Descending) // stable tiebreaker .Add("name", c => c.Name) .ThenBy(c => c.Id) .Build(); public async ValueTask>> HandleAsync(Query query, CancellationToken ct) { return await db.Clients .Where(c => c.OwnerId == user.UserId) .ToOffsetPageAsync(query, c => new Item(c.Id, c.Name, c.CreatedAt), Sort, maxSize: 100, ct); } ``` The request implements `IOffsetPageRequest` — flat `Page` (1-based), `Size`, and `Sort` fields, again to keep HTTP GET query binding simple (`OffsetPageRequest` is the ready-made implementation). `Build()` produces an immutable map backed by a `FrozenDictionary`, so a shared static instance is safe for concurrent requests; the mutable `SortMapBuilder` is single-threaded and used only at startup. A request `Sort` names a key in one of three forms: | `Sort` | Primary column | Tiebreakers | | ------------ | ---------------------------------- | ----------- | | `key` (bare) | the entry's **declared** direction | declared | | `+key` | ascending | declared | | `-key` | descending | declared | A bare key is **not** "ascending": `"createdAt"` above sorts descending, because that is how the key was declared, and a client that wants it ascending sends `"+createdAt"`. `"-name"` sorts `Name` descending, `Id` ascending. Keys match case-insensitively. A blank `Sort` means the default entry. In a query string, send `+` as `%2B`: a bare `+` decodes to a space, which leaves the key bare. ### Sorting by several keys [#sorting-by-several-keys] `Sort` may list several keys, comma-separated, each in one of the three forms: `"+city,-name"` orders by `City` ascending, then `Name` descending. The keys apply from left to right (`OrderBy`, then `ThenBy`), and the declared tiebreakers of the **last** key follow, so the order stays stable; the tiebreakers of the other keys are not applied. A single key keeps its own tiebreakers, as before. Spaces around a key are ignored. **Every `SortMap` accepts up to three keys by default**, without any change to the handler: a list that was written for one key now also sorts by two or three. The cap is `SortMap.DefaultMaxLevels` (3); `.MaxLevels(n)` on the builder changes it, and `.MaxLevels(1)` keeps a list to a single key, as it was before multi-key sorts. A handler's description of its sort parameter ("sort: one of `createdAt`, `number`") should say that keys combine, or set `.MaxLevels(1)`. `SortMap.MaxLevels` reads the cap of a map, for a description built from the map. A key named twice, an empty key (`"city,"`) and a sort above the cap are refused like an unknown key. The cap is checked before any key is looked up, so a sort parameter of thousands of keys costs one pass over the text. The schema exports the cap next to the keys (`maxSortLevels`, see below); a client that combines more keys than the handler allows gets the validation error below. ### Refusing a bad sort [#refusing-a-bad-sort] An **unknown** key also falls back to the default entry — right for a list that must always render, wrong when a client sends a key it should not. `Sort.Validate(query.Sort)` checks the sort first and answers a refused one (an unknown or repeated key, or more keys than the cap) with a field-keyed validation error (code `paging.sort_key_unknown`, keyed by the request field, naming the allowed keys), so the client bug surfaces instead of a silently re-sorted list: ```csharp [ProducesError(PagingErrorCodes.SortKeyUnknown, ErrorKind.Validation)] public async ValueTask>> HandleAsync(Query query, CancellationToken ct) { if (Sort.Validate(query.Sort) is { } unknownSort) return unknownSort; return await db.Clients .Where(c => c.OwnerId == user.UserId) .ToOffsetPageAsync(query, c => new Item(c.Id, c.Name, c.CreatedAt), Sort, maxSize: 100, ct); } ``` The default message is English. Pass a `message` function to word it yourself, for example in the application's language; it receives a `SortRefusal` with the `Reason` (`UnknownKey`, `RepeatedKey`, `TooManyKeys`), the offending `Key`, the `AllowedKeys` and `MaxLevels`, and its text becomes both the error message and the field message: ```csharp if (Sort.Validate(query.Sort, message: refusal => refusal.Reason switch { SortRefusalReason.TooManyKeys => $"Höchstens {refusal.MaxLevels} Sortierschlüssel.", _ => $"Unbekannter Sortierschlüssel „{refusal.Key}“." }) is { } badSort) return badSort; ``` `Sort.Keys` lists every allowed key in declaration order with its declared direction and which one is the default — what a client needs to build sort parameters (a column header toggling between `+key` and `-key`) without mirroring the declarations by hand. The [JSON-RPC schema](/docs/capabilities/transports/schema-generation) exports them under the method's `sortKeys` when the handler declares one static `SortMap` field (with several it exports none and the build warns, `ELRPC012`), together with the map's cap as `maxSortLevels`. The generated TypeScript client gives them as `rpcSortKeys['{method}']` and `rpcMaxSortLevels['{method}']`, so a frontend reads the allowed keys and how many it may combine instead of copying them. ### Mapping a page [#mapping-a-page] `Map(selector)` on a `Page` or an `OffsetPage` projects every item and keeps the cursors, flags and total, so enriching or renaming the rows of a page never rebuilds the envelope by hand. `MapAsync` hands the whole item list to the selector at once — one batched lookup for the page instead of one per row — and requires one result per item, in order: ```csharp var page = await db.Notes.ToOffsetPageAsync(query, n => new { n.Id, n.Text, n.AuthorId }, Sort, maxSize: 50, ct); return await page.MapAsync(async (rows, token) => { var authors = await directory.GetNamesAsync(rows.Select(r => r.AuthorId).Distinct(), token); return rows.Select(r => new NoteRow(r.Id, r.Text, authors[r.AuthorId])).ToArray(); }, ct); ``` ### Consuming an offset page [#consuming-an-offset-page] An offset endpoint returns `OffsetPage`, so the client gets exactly what it can use: * `total` is **always present** (`ToOffsetPageAsync` counts the filtered query every call), and the generated type says so (`total: number`), so page numbers are computable: `totalPages = Math.ceil(total / size)` — where `size` is the **effective** page size, not necessarily the one you sent. * There are no cursors to ignore. * `hasNext` / `hasPrevious` are filled on both strategies, so a plain prev/next control needs nothing else. The effective size matters because the server clamps `Size` to the handler's `maxSize` (default `100`, as described under [keyset pagination](#keyset-pagination) — the same clamp applies to both strategies), and substitutes `20` for anything below `1`, itself capped at `maxSize` (so a handler with `maxSize: 10` substitutes `10`). `OffsetPage` does not echo the size back, so divide by the size the server would actually have used, or the last page number is wrong whenever a client over-asks: ```ts // Mirror the handler's maxSize; the server clamps and the envelope never reports what it used. const MAX_SIZE = 100 const requested = 20 const size = Math.min(requested < 1 ? 20 : requested, MAX_SIZE) const page = await rpc.clients.list({ page: 1, size, sort: '-createdAt' }) // Offset endpoint: `total` is always a number. const totalPages = Math.ceil(page.total / size) renderRows(page.items) renderPager({ totalPages, canPrev: page.hasPrevious, canNext: page.hasNext }) ``` The simplest way to stay honest is to never send a size above the handler's `maxSize` in the first place — then requested and effective size are the same number. The two envelopes share `items`, `hasNext` and `hasPrevious`, so one list component can render either; each adds only what its strategy fills. A component that takes both reads `total` where it is a number and the cursors where they are strings. If you find yourself wanting a cursor on an offset endpoint, you are on the wrong strategy — switch the handler to `ToKeysetPageAsync`. ### Naming the request fields [#naming-the-request-fields] `IOffsetPageRequest` fixes three member names — `Page`, `Size`, `Sort` — and the execution helpers read the request through that interface. Those names reach the wire through your DTO, so a request that implements the interface publishes `page` / `size` / `sort`. If a contract needs different wire names (`pageSize`, say, or a `sortBy`/`sortDirection` pair), do not rename the interface members — a request DTO owns its wire contract, and the paging contract is not the place to negotiate it. Carry your own fields and build an `OffsetPageRequest` inside the handler: ```csharp public sealed record Query { public int Page { get; init; } = 1; public int PageSize { get; init; } = 20; // this endpoint's own wire name public string? SortBy { get; init; } public bool Descending { get; init; } // this endpoint's own wire shape } public async ValueTask>> HandleAsync(Query query, CancellationToken ct) { var paging = new OffsetPageRequest { Page = query.Page, Size = query.PageSize, Sort = query.Descending ? $"-{query.SortBy}" : query.SortBy, }; return await db.Clients .Where(c => c.OwnerId == user.UserId) .ToOffsetPageAsync(paging, c => new Item(c.Id, c.Name, c.CreatedAt), Sort, maxSize: 100, ct); } ``` The translation is three lines in one place, and the endpoint keeps the vocabulary its clients expect. Generated `DbSet`s on the concrete `DbContext` that handlers page against. How list handlers accept a paging request and return `Result>` or `Result>`. # PDF documents (Typst) (/docs/capabilities/pdf-documents) [Typst](https://typst.app) is a markup-based typesetting system with a single, self-contained CLI. It compiles a business document in milliseconds, gives the same output for the same input, and keeps the layout in a readable text file next to your code. That makes it a good fit for documents an application generates from its own data: invoices, quotes, delivery notes, inspection protocols, reports. Wiring Typst into a .NET service involves the same chores every time. You have to install and pin the binary, find it at runtime, keep concurrent compilations apart, respect Typst's file sandbox, drain the process pipes without deadlocking, kill a hung compilation, clean up temporary files, keep fonts deterministic, and say at startup when any of that is broken. `Elarion.Typst` handles these chores. **What a document looks like and what data it receives stay in the application.** | Piece | Role | | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ITypstCompiler` | Compiles one document to a `TypstPdf`: a self-deleting, streamable file. | | `TypstSource`, `TypstData`, `TypstAsset` | What to render, the template's JSON model, and its files (logos, photos). | | `TypstImage` | Accepts a user-uploaded picture only when Typst can decode it, so one broken upload cannot fail the document. | | Build targets | Download the pinned Typst release, verify its SHA-256 checksum, cache it, and copy it into every executable that references the package, matching the executable's runtime identifier. They also copy your template and font tree. | | Startup check | Refuses to start (or warns) when the toolchain is incomplete. | Use it for documents the server produces from data. It is not an HTML-to-PDF converter, and it is not a user-editable document editor. ## Getting started [#getting-started] ### Reference the package and point it at your templates [#reference-the-package-and-point-it-at-your-templates] Reference `Elarion.Typst` from the assembly that renders documents: usually an infrastructure library, or the host itself. Set `ElarionTypstAssetsDirectory` to the directory that holds your Typst package and fonts: ```xml Typst ``` Building any executable that references this assembly, directly or through other projects (the host, a worker, a test project), now produces: ``` bin/…/typst/ bin/typst the pinned CLI for this executable's RID packages/local/acme-documents/1.0.0/ your templates fonts/ your fonts ``` The binary is downloaded once per version and platform into `/elarion/typst`, checked against the SHA-256 checksums that ship with the package, and reused offline afterwards. The application never downloads anything at runtime. Check that your templates are committed. Typst's package folder is named `packages/`, and most .NET `.gitignore` files (including the standard Visual Studio template) ignore every `packages/` folder as a NuGet restore folder. The build and tests then pass on your machine, and CI or a colleague's checkout fails with `package not found`. Add an exception: ```text # Typst templates are source, not a NuGet packages folder !**/Typst/packages/ !**/Typst/packages/** ``` Both lines are needed: the first re-includes the folder for rules that ignore the folder itself (`packages/`), the second its contents for rules that ignore what is inside (`**/[Pp]ackages/*`). ### Write the template as a Typst package [#write-the-template-as-a-typst-package] ``` Typst/ packages/local/acme-documents/1.0.0/ typst.toml lib.typ entry points: one function per document kind invoice.typ the invoice layout theme.typ shared page frame, colors, typography samples/ sample data and main files for local preview fonts/ Inter-Regular.ttf … ``` ```toml # typst.toml [package] name = "acme-documents" version = "1.0.0" entrypoint = "lib.typ" compiler = "0.15.1" ``` ```typst // lib.typ: an entry point takes the parsed data and a dictionary of asset bytes #import "invoice.typ": invoice-layout #let invoice(data, assets: (:)) = invoice-layout( data, logo: assets.at("logo.png", default: none), ) ``` ```typst // invoice.typ #let invoice-layout(data, logo: none) = { set document(title: "Invoice " + data.number) set page(paper: "a4", margin: 2cm) set text(font: "Inter", lang: sys.inputs.at("lang", default: "en")) if logo != none { image(logo, width: 3cm) } [= Invoice #data.number] table( columns: (1fr, auto), ..data.items.map(item => (item.description, item.amount)).flatten(), ) [*Total:* #data.total] } ``` ### Register the compiler [#register-the-compiler] ```csharp builder.Services.AddElarionTypst(options => { options.PdfStandards.Add(TypstPdfStandard.PdfA2b); // archival PDF/A for business records options.RequiredPackages.Add("@local/acme-documents:1.0.0"); // checked at startup }); ``` Every option has a working default, so `AddElarionTypst()` with no arguments is enough when the build bundles the binary. You can call it from several modules: later calls apply to the same options instance. To take deployment settings from configuration (appsettings, `Typst__ExecutablePath` environment variables), pass the section. Binding is source-generated, so it stays NativeAOT-safe, and the delegate runs after it: ```csharp builder.Services.AddElarionTypst(builder.Configuration.GetSection(TypstOptions.SectionName), options => options.PdfStandards.Add(TypstPdfStandard.PdfA2b)); ``` ### Render through your own document service [#render-through-your-own-document-service] Keep the template model and the request in one application service, so handlers and tests depend on *your* contract, not on Typst: ```csharp public interface IInvoiceDocuments { Task RenderAsync(Invoice invoice, CancellationToken cancellationToken); } internal sealed class TypstInvoiceDocuments(ITypstCompiler typst, IBlobStore blobs) : IInvoiceDocuments { public async Task RenderAsync(Invoice invoice, CancellationToken cancellationToken) { await using var pdf = await typst.CompilePdfAsync(new TypstCompileRequest { Source = TypstSource.Package("@local/acme-documents:1.0.0", "invoice"), Data = TypstData.FromValue(InvoiceDocument.From(invoice), DocumentJsonContext.Default.InvoiceDocument), Assets = [new TypstAsset("logo.png", invoice.Company.Logo)], Inputs = new Dictionary { ["lang"] = invoice.Language }, }, cancellationToken); return await blobs.SaveAsync(new BlobUploadRequest { Container = "invoices", Name = $"{invoice.Number}.pdf", ContentType = TypstPdf.ContentType, ContentLength = pdf.Length, }, pdf.Content, cancellationToken); } } ``` ## What a compilation sees [#what-a-compilation-sees] Every compilation runs in a fresh workspace below `TypstOptions.WorkingDirectory`. That workspace is Typst's project root (`--root`): ``` /main.typ generated (TypstSource.Package) or yours (TypstSource.Main) /data.json TypstCompileRequest.Data /assets/ TypstCompileRequest.Assets ``` Typst only reads files below the project root and the package directory. That is why templates live in a **package**: the package is read-only, it is shared by all workspaces, and it is never written to. Concurrent compilations cannot see each other's data, and the template tree can sit on a read-only file system. When the compilation ends, the workspace is deleted. The PDF is written next to the workspace, and the returned `TypstPdf` owns that file until you dispose it. A package cannot read files from the project root. For that reason, `TypstSource.Package(spec, function)` generates a main file that reads the request's files and hands them to your function: ```typst #import "@local/acme-documents:1.0.0": invoice #invoice(json("/data.json"), assets: ("logo.png": read("/assets/logo.png", encoding: none), )) ``` That gives every entry point the same signature: `#let name(data, assets: (:))`. `data` is `none` when the request has no data. `assets` is always passed, so declare the parameter even if a template uses no files. When one function renders several variants, pass named arguments. They go between the data and the assets, as Typst literals: strings are escaped, and a `decimal` arrives as an exact Typst `decimal`, not a float: ```csharp TypstSource.Package("@local/acme-reports:1.0.0", "render-report") .WithArgument("kind", "test-report") // string .WithArgument("chrome", false) // bool .WithArgument("copies", 2) // integer .WithArgument("total", 1280.50m); // decimal("1280.50") ``` ```typst #let render-report(data, kind: "test-report", chrome: true, copies: 1, total: none, assets: (:)) = … ``` For anything beyond that, use `TypstSource.Main("…")` and read `/data.json` and `/assets/…` yourself. ## The template model [#the-template-model] `TypstData` writes `data.json`. The data is the **template's** contract, not your handler's wire DTO: it carries what the layout prints. Declare it as a record and serialize it with a source-generated `JsonSerializerContext`, as you would any AOT-safe JSON: ```csharp public sealed record InvoiceDocument { public required string Number { get; init; } public required string Date { get; init; } // "18.11.2026" public required string Total { get; init; } // "1.280,00 €" public required IReadOnlyList Items { get; init; } public string? Notes { get; init; } } [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] [JsonSerializable(typeof(InvoiceDocument))] internal sealed partial class DocumentJsonContext : JsonSerializerContext; ``` * **Format amounts and dates in C#.** Typst's `json()` turns every JSON number into a float. Pass money as a string that is already formatted, or as an invariant decimal string that the template converts with `decimal("…")`, so a cent never rounds. Formatting in C# also keeps one formatting authority for PDFs, e-mails, and the UI. * **Leave out empty values.** With `WhenWritingNull`, a missing optional field lets the template's default apply: `data.at("notes", default: none)`. * **Keep the model flat and printable.** Compute totals, VAT groups, and position numbers in C#, where they are tested. Typst should lay data out, not derive it. **Inputs** (`TypstCompileRequest.Inputs`) are short strings visible as `sys.inputs`, such as a language code or a brand switch. They are passed on the command line, so the document's data belongs in `Data`. ## Images and other files [#images-and-other-files] Assets are written to `/assets/`. A name is a plain file name made of ASCII letters, digits, `.`, `-`, and `_`. It cannot contain a directory or `..`, so it cannot escape the workspace or break the generated main file. The `TypstAsset` constructor throws an `ArgumentException` for any other name. When the name comes from a user, check it first with `TypstAsset.IsValidName(name)`, or use `TypstAsset.TryCreate(name, content, out var asset)`, and reject it with your own error: ```csharp if (!TypstAsset.TryCreate(upload.FileName, upload.Content, out var attachment)) return AppError.Validation("The file name cannot be used in a document.", code: "document.attachment-name"); ``` Typst stops the whole compilation on an image it cannot decode. For pictures from users (inspection photos, scanned receipts), let `TypstImage` decide what is printable. It detects PNG, JPEG, GIF, and WebP from the bytes and rejects truncated files, so the template can print a placeholder instead of the document failing: ```csharp var assets = new List { new("logo.png", company.Logo) }; var photos = new List(); foreach (var (photo, index) in inspection.Photos.Select((photo, index) => (photo, index))) { var printable = TypstImage.TryCreateAsset($"photo-{index:D4}", photo.Content, out var asset); if (printable) assets.Add(asset!); photos.Add(new PhotoDocument { Caption = photo.Caption, Asset = printable ? asset!.Name : null }); } ``` ```typst #for photo in data.photos { if photo.at("asset", default: none) != none { image(assets.at(photo.asset), width: 100%) } else [_Picture not printable._] } ``` SVG and PDF files can be passed as plain `TypstAsset`s; `TypstImage` covers raster formats only. ### Several models [#several-models] A request has one `Data` model. A second model that is independent of the document's own, such as a letterhead every document of the application receives, goes in as a JSON asset. `TypstAsset.FromJson` serializes it with a source-generated context, like `TypstData.FromValue`: ```csharp var request = new TypstCompileRequest { Source = TypstSource.Package("@local/acme-documents:1.0.0", "invoice"), Data = TypstData.FromValue(invoice, DocumentJsonContext.Default.InvoiceDocument), Assets = [TypstAsset.FromJson("letterhead.json", letterhead, DocumentJsonContext.Default.Letterhead)] }; ``` The template parses it from the asset's bytes (`json` accepts bytes since Typst 0.13): ```typst #let invoice(data, assets: (:)) = { let letterhead = json(assets.at("letterhead.json")) … } ``` This keeps each document's model type to itself: the application adds the letterhead to every request in its document service, and no document model has to carry it. ## Using the PDF [#using-the-pdf] `TypstPdf.Content` is a read-only stream backed by a temporary file, which is deleted when the `TypstPdf` is disposed. Use the PDF in one of three ways: * **Store it.** Stream it into `IBlobStore.SaveAsync` as shown above. This works for any size and never puts the whole document in memory. * **Return it from a handler.** `await pdf.ToElarionFileAsync("invoice-2026-0042.pdf")` buffers it into an [`ElarionFile`](/docs/capabilities/transports/http-endpoints#files-downloads-and-uploads), which the generated HTTP mapping serves as a file download. This is the small-file tier: fine for typical business documents of a few hundred kilobytes. * **Offer a large download.** Store it as a pending blob with an expiry and return the blob reference, as [blob storage](/docs/capabilities/blob-storage) describes for large exports. ## Errors [#errors] `ITypstCompiler` throws. It does not return a `Result`: a failed compilation is an infrastructure fault, like a failed blob write. Every exception derives from `TypstException`: | Exception | Meaning | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TypstCompilationException` | Typst rejected the document because of a template or data defect. `Diagnostics` holds Typst's error output, with file, line, and message. | | `TypstPackageNotFoundException` | A package the document imports is not installed, for example because the build did not bundle your package. `Package` names it (`@local/acme-documents:1.0.0`). This is a deployment problem, not a template defect; `RequiredPackages` reports it at startup instead. | | `TypstTimeoutException` | The compilation exceeded its timeout, and the process tree was killed. | | `TypstUnavailableException` | The executable cannot be started. This is a deployment problem, which the startup check normally catches first. | | `OperationCanceledException` | The caller cancelled, for example because the browser navigated away. The process was killed. | On .NET 11 the process is also tied to the host: it is started with `KillOnParentExit` (on Windows and Linux, a crashed host leaves no Typst process behind) and inherits no handles except its standard ones. When the operating system kills Typst, for example for running out of memory, `Diagnostics` names the signal (`SIGKILL`). The compiler logs the diagnostics. They quote server paths and template internals, so translate the exception into a generic `AppError` where your document service meets the handler, and do not return Typst's text to the caller: ```csharp try { var blob = await documents.RenderAsync(invoice, cancellationToken); return new InvoicePdfCreated { Blob = blob.Value }; } catch (TypstTimeoutException) { return AppError.BusinessRule("The document took too long to generate. Please try again.", code: "document.timeout"); } catch (TypstPackageNotFoundException) { return AppError.BusinessRule("The document templates are not installed.", code: "document.templates-missing"); } catch (TypstException) { return AppError.Internal("The document could not be generated.", code: "document.failed"); } ``` ## Configuration [#configuration] `TypstOptions`, set through `AddElarionTypst(options => …)`: | Option | Default | Purpose | | -------------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `ExecutablePath` | the bundled `typst/bin/typst`, else `typst` on `PATH` | The executable. A bare name is looked up on `PATH`. | | `ToolchainDirectory` | `/typst` | The directory that holds `bin/`, `packages/`, and `fonts/`. | | `PackagePath` | `packages/` in the toolchain directory, if present | `--package-path`: your package and any vendored `@preview` packages. | | `PackageCachePath` | Typst's per-user cache | `--package-cache-path`. | | `FontPaths` | `fonts/` in the toolchain directory, if present | Additional `--font-path` directories. | | `RequiredPackages` | none | Packages the startup check requires in `PackagePath`, such as `@local/acme-documents:1.0.0`. | | `IgnoreSystemFonts` | `true` | Hides the host's fonts, so output is the same on every machine. | | `PdfStandards` | none (PDF 1.7) | `--pdf-standard`, for example `PdfA2b`, `PdfA3b`, or `PdfUa1`. A request can override it. | | `PdfTags` | `true` | Tagged, accessible PDF. Set it to `false` for smaller files when no standard requires tags. | | `Timeout` | 60 s | The upper bound for one compilation. A request can override it. | | `MaxConcurrency` | `Environment.ProcessorCount` | How many Typst processes may run at once. Further requests wait. | | `Jobs` | Typst's default (all CPUs) | `--jobs`: threads per compilation. | | `WorkingDirectory` | `/elarion-typst` | Where workspaces are created. It must be writable. | | `StartupCheck` | `Fail` | `Fail`, `Warn`, or `None`. See below. | The options are the only configuration a compilation sees. The compiler removes inherited `TYPST_*` and `SOURCE_DATE_EPOCH` environment variables from the child process, so a stray `TYPST_FONT_PATHS` on a build agent cannot change a document. Bind them from configuration with `AddElarionTypst(configuration.GetSection("Typst"))`: every option above is a key (`Typst:Timeout` = `00:00:30`, `Typst:PdfStandards:0` = `PdfA2b`, `Typst__ExecutablePath` as an environment variable). The options are read once at registration; changing configuration later has no effect on a running host. **Code defaults, then configuration.** `AddElarionTypst(section, configure)` binds the section first and runs `configure` after it, so the delegate always wins over configuration. For defaults of your own that deployment configuration can still override, such as a shorter timeout or a `Warn` startup check, use two calls. Both apply to the same options instance, in order: ```csharp builder.Services.AddElarionTypst(options => { // 1. the application's defaults options.Timeout = TimeSpan.FromSeconds(30); options.StartupCheck = TypstStartupCheck.Warn; }); builder.Services.AddElarionTypst(builder.Configuration.GetSection(TypstOptions.SectionName)); // 2. deployment wins ``` A key that configuration does not set keeps the code default. **Reproducible output.** Typst writes the creation date into the PDF and uses it for `datetime.today()`. Set `TypstCompileRequest.CreationTimestamp`, for example to the invoice date, and the same data produces a byte-identical file. ### Startup check [#startup-check] With the default `TypstStartupCheck.Fail`, the host refuses to start when the executable, a configured package directory, a font directory, or a package listed in `RequiredPackages` is missing. List your own template package there: without it, a deployment that lacks the package starts, and every document fails with `TypstPackageNotFoundException`. A required package is installed when `////typst.toml` exists. `TypstToolchain.HasPackage("@local/acme-documents:1.0.0")` runs the same test at render time, for example to answer with a "templates not installed" error before compiling. `typst --version` runs next to the startup rather than in its path, so a virus scanner that holds up a large executable does not delay the web server. If the version check fails, the host stops, and the exception is logged. `Warn` logs a warning and keeps running; documents then fail with `TypstUnavailableException`. `Warn` suits a host where PDFs are one optional feature among many. ## Build integration [#build-integration] The package's `build`/`buildTransitive` targets read these MSBuild properties: | Property | Default | Purpose | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ElarionTypstBundle` | `true` for executables (`OutputType` `Exe`/`WinExe`, including Microsoft.Testing.Platform test projects), `false` for libraries | Copy the pinned binary to `typst/bin/` of the output and publish directory. | | `ElarionTypstAssetsDirectory` | empty | A project directory copied as is to `typst/` in the output. Set it in the project that owns the templates: the files flow to every executable that references it. | | `ElarionTypstVersion` | the version the package was tested with (`0.15.1`) | The Typst release to bundle. | | `ElarionTypstSha256` | built-in table | Required only with a non-default `ElarionTypstVersion`: the SHA-256 of the release archive for the target platform. | | `ElarionTypstExecutable` | empty | A pre-fetched binary to bundle instead of downloading, for air-gapped build agents. | | `ElarionTypstCacheDirectory` | `/elarion/typst` | The download cache. | The binary follows `$(RuntimeIdentifier)` when one is set, so `dotnet publish -r linux-x64` on a Mac bundles the Linux binary. Without a RID, it follows the SDK's platform. Linux builds use Typst's statically linked musl binaries, which run on glibc and musl distributions alike, including distroless and chiseled images. Windows, macOS, and Linux on x64 and arm64 are covered. The Linux and macOS archives are `.tar.xz` files, unpacked with `tar -xJf`. bsdtar (macOS, Windows) decompresses xz itself. GNU tar (Debian, Ubuntu, and the `mcr.microsoft.com/dotnet/sdk` images built on them) needs the `xz` program, which those images do not install. Without it, the build stops before the download with an error that names the package to install. Install `xz-utils` (Alpine: `xz`), or bundle a pre-fetched binary through `ElarionTypstExecutable`. ### Containers [#containers] The runtime image needs no Typst installation step. The binary, your package, and your fonts are part of the publish output. The SDK image needs `xz-utils` to unpack the Typst archive: ```dockerfile FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build RUN apt-get update && apt-get install -y --no-install-recommends xz-utils && rm -rf /var/lib/apt/lists/* WORKDIR /src COPY . . RUN dotnet publish src/Acme.Api -c Release -r linux-x64 -o /app FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app COPY --from=build /app . ENTRYPOINT ["dotnet", "Acme.Api.dll"] ``` To avoid downloading again on every image build, mount the cache (`RUN --mount=type=cache,target=/root/.local/share/elarion/typst dotnet publish …`). Alternatively, point `ElarionTypstExecutable` at a binary from your own artifact store. Workspaces go to the system temporary directory. With a read-only root file system, mount a writable volume and set `WorkingDirectory` to it. The template tree itself is only read. ## Fonts [#fonts] With `IgnoreSystemFonts` (the default), the only fonts visible are Typst's embedded fonts (Libertinus Serif, New Computer Modern, DejaVu Sans Mono) and the files in `fonts/`. Ship the fonts your templates name in `fonts/`, and check that their licenses allow embedding in PDFs. An unknown font family does not fail the compilation. Typst falls back and reports a warning, which the compiler logs and exposes as `TypstPdf.Warnings`. Treat such a warning as a defect in tests. ## Third-party Typst packages [#third-party-typst-packages] `@preview/…` imports are downloaded from the Typst package registry on first use. A server should not do that at runtime. **Vendor them**: copy the package into `packages/preview///` next to your own package. Typst looks in the package directory first for every namespace. To get the files, compile locally once, then copy them from Typst's cache (`~/Library/Caches/typst/packages/preview` on macOS, `~/.cache/typst/packages/preview` on Linux, `%LOCALAPPDATA%\typst\packages\preview` on Windows). ## Previewing templates locally [#previewing-templates-locally] Put a sample main file and sample data in the package, and let Typst re-render on every save: ```typst // packages/local/acme-documents/1.0.0/samples/invoice.typ #import "../lib.typ": invoice #invoice(json("invoice.json"), assets: ("logo.png": read("logo.png", encoding: none))) ``` ```bash typst watch --root Typst/packages/local/acme-documents/1.0.0 --font-path Typst/fonts --ignore-system-fonts Typst/packages/local/acme-documents/1.0.0/samples/invoice.typ ``` `--root` is the package directory: without it, Typst treats `samples/` as the project root and refuses the `../lib.typ` import. The sample data also makes a regression fixture: produce it from your C# model in a test (see below), so the template and the model cannot drift apart unnoticed. ## Testing [#testing] A test project is an executable, so the build bundles Typst and your package into its output, just as for the host. CI needs no Typst installation. * **Document tests** compile real documents through `ITypstCompiler` and check that the result starts with `%PDF-`. Add `assert(...)` calls to a test-only template, or to the real one where they guard the contract, to prove that the data arrived. A compilation that violates them fails with `TypstCompilationException`, which carries the message. * **Handler tests** that don't care about the layout replace *your* document service (`IInvoiceDocuments`) with a fake. They should not depend on `ITypstCompiler`. * **Skipping.** On a machine where the toolchain is missing, skip instead of failing: ```csharp var toolchain = new TypstToolchain(new TypstOptions()); Assert.SkipUnless(toolchain.ExecutableExists, $"Typst is not available at '{toolchain.ExecutablePath}'."); ``` * **A compiler without a host.** `TypstCompiler.Create(options, loggerFactory)` builds the compiler that `AddElarionTypst` registers, without a service collection. Use it when a test needs its own executable (a stand-in script), package directory, or working directory. The logger factory is optional. The compiler is not disposable: it holds no process, file, or handle between compilations, so a test kit can create one per test and drop it. Dispose each `TypstPdf` it returns, which deletes the output file. ```csharp var options = new TypstOptions { WorkingDirectory = workspace, PackagePath = emptyPackages }; var compiler = TypstCompiler.Create(options); var act = () => compiler.CompilePdfAsync(request, cancellationToken); await act.Should().ThrowAsync(); // the "templates not installed" path ``` * **A missing package without the binary.** `Create` runs no startup check, so `RequiredPackages` is not checked and a missing package shows only as `TypstPackageNotFoundException` from a compilation, which needs the Typst executable. To test the "templates not installed" path on a machine without Typst, ask the toolchain: `HasPackage` only looks for the package's `typst.toml` and runs nothing. ```csharp new TypstToolchain(options).HasPackage("@local/acme-documents:1.0.0").Should().BeFalse(); ``` ## Telemetry [#telemetry] Register the `Elarion.Typst` activity source and meter (`TypstTelemetry.ActivitySourceName`, `TypstTelemetry.MeterName`). Each compilation creates a `typst compile` span, tagged with the document (`elarion.typst.document`: the package function) and the outcome. Two metrics are recorded: * `elarion.typst.compile.duration` (seconds), by outcome: `success`, `compilation_error`, `package_not_found`, `timeout`, `unavailable`, or `cancelled`. * `elarion.typst.compile.queue.duration` (seconds): the time spent waiting for a free `MaxConcurrency` slot. A rising queue time means documents are requested faster than the configured concurrency can render them. ## Moving an existing integration [#moving-an-existing-integration] If your application already runs `typst compile` through `Process.Start`, the move is mostly deletion: 1. Remove the Typst install step from the Dockerfile and CI, the process wrapper, the availability probe, and any temporary-directory handling. Add the package reference and `ElarionTypstAssetsDirectory`. A probe for your own template package becomes an entry in `RequiredPackages` (startup) or a `TypstToolchain.HasPackage` call (render time). 2. Move the templates into `packages/local/-documents/1.0.0/`, add `typst.toml`, and turn each top-level template file into a function `#let invoice(data, assets: (:))` that takes the data as a parameter instead of reading `json(sys.inputs.data-file)`. Extra parameters such as a document kind become `WithArgument` calls. 3. Replace data files written next to the templates, often under a `tmp/` directory inside the template root to satisfy the sandbox, with `TypstCompileRequest.Data`. Replace images read from that directory with `Assets`. 4. Keep your application's document interface, and implement it over `ITypstCompiler`. Translate `TypstException` to your error shape in that implementation. 5. Replace your own options class and its configuration section with `AddElarionTypst(configuration.GetSection(…))`, renaming keys where they differ (`BinaryPath` → `ExecutablePath`, `TimeoutSeconds` → `Timeout`). The design rationale (CLI rather than a native binding, a package rather than a template directory, build-time rather than runtime acquisition) is recorded in [ADR-0093](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0093-typst-pdf-rendering.md). An in-process engine behind the same `ITypstCompiler` has been prototyped and measured in [ADR-0094](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0094-in-process-typst-engine.md). # PostgreSQL extensions (/docs/capabilities/postgres-extensions) Specialized workloads — time-series telemetry, vector search, geospatial queries, graphs — trigger the reflex to add a second database, and with it a second connection string, a second backup story, a second thing that can be down. Elarion's positioning says otherwise: **a PostgreSQL extension changes what the one Postgres can do, not how many infrastructure pieces you run.** Adding [TimescaleDB](https://www.timescale.com/) or [pgvector](https://github.com/pgvector/pgvector) to your existing database is composition, exactly like the `UNLOGGED` L2 cache or `LISTEN/NOTIFY` fan-out — not scale-out ([ADR-0056](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0056-postgres-extensions-posture.md)). That posture has a corollary in both directions: * **Recipes may assume extensions.** The [time-series recipe](/docs/capabilities/time-series) freely assumes TimescaleDB; a vector-search recipe would assume pgvector the same way. * **Packages may not.** There is deliberately no `Elarion.TimeSeries` package, and no Elarion package silently requires an extension. Every Elarion package keeps working on a stock `postgres` image; an extension is always a *recipe's* documented prerequisite. The one real friction is the server image, so that is what this page covers. ## One extension: use the official image [#one-extension-use-the-official-image] An extension must be present in the server image before `CREATE EXTENSION` can activate it — the stock `postgres` image carries neither TimescaleDB nor pgvector. A single extension usually has an official image (`timescale/timescaledb`, `pgvector/pgvector`, `apache/age`); use it everywhere you run Postgres, dev, CI, and production alike: ```yaml # docker-compose.yml — a drop-in replacement for the postgres image services: db: image: timescale/timescaledb:latest-pg17 ``` Integration tests point Testcontainers at the same image: ```csharp var container = new PostgreSqlBuilder() .WithImage("timescale/timescaledb:latest-pg17") .Build(); ``` (Under .NET Aspire: `builder.AddPostgres("db").WithImage("timescale/timescaledb", "latest-pg17")`.) Activation is schema, so it belongs in the same EF migration history as everything else: ```csharp migrationBuilder.Sql("CREATE EXTENSION IF NOT EXISTS timescaledb;"); ``` ## Combining extensions [#combining-extensions] Needing **several extensions at once** is where hand-assembly starts — resolve it in this order: 1. **Check for an official image that already carries your combination.** [`timescale/timescaledb-ha`](https://github.com/timescale/timescaledb-docker-ha) bundles TimescaleDB + PostGIS + pgvector (and pgvectorscale), which covers the common "time-series + vectors + geo" stack with no custom image at all. 2. **Otherwise, the canonical image is a \~10-line Dockerfile, not a build-from-source project.** The official `postgres` Debian image ships with the PGDG apt repository already configured, and PGDG packages a large share of the ecosystem (`postgresql-17-pgvector`, `postgresql-17-age`, PostGIS, …); a vendor repo covers the rest (TimescaleDB): ```dockerfile # One image for compose, Testcontainers, and production — pin the PG major everywhere. FROM postgres:17-bookworm # TimescaleDB ships from its own apt repo; pgvector and Apache AGE come from PGDG, # which the base image already has configured. RUN apt-get update && apt-get install -y --no-install-recommends wget gnupg lsb-release \ && echo "deb https://packagecloud.io/timescale/timescaledb/debian/ $(lsb_release -c -s) main" \ > /etc/apt/sources.list.d/timescaledb.list \ && wget -qO- https://packagecloud.io/timescale/timescaledb/gpgkey \ | gpg --dearmor -o /etc/apt/trusted.gpg.d/timescaledb.gpg \ && apt-get update && apt-get install -y --no-install-recommends \ timescaledb-2-postgresql-17 \ postgresql-17-pgvector \ postgresql-17-age \ && rm -rf /var/lib/apt/lists/* # Extensions that hook the planner/executor must be preloaded — each extension's docs # say whether it needs this (TimescaleDB and AGE do; pgvector does not). CMD ["postgres", "-c", "shared_preload_libraries=timescaledb,age"] ``` CI builds this once and every environment — compose, `PostgreSqlBuilder().WithImage(...)` in tests, production — runs the same image, so an extension version bump is one line reviewed in one place. Migrations stay per-extension and unchanged (`CREATE EXTENSION IF NOT EXISTS vector;` / `… age;`), as does any session setup an extension wants (AGE's `ag_catalog` search path, for example — per its own docs). Two rules of thumb for combinations: * **The combination pins your Postgres major to the *slowest* extension.** Each extension supports a range of majors and lags new releases by months (Apache AGE only reached PostgreSQL 17 with its 1.6 line); the majors available to you are the intersection. Decide the major from that intersection *before* writing the Dockerfile, and prefer explicit `-pgN` tags over `latest` everywhere. * **An extension must stay a recipe's prerequisite, never a package's silent dependency** (ADR-0056). If a module needs AGE, that is the module's documented requirement — every Elarion package keeps working on a stock `postgres` image. ADR-0056 defers a framework-level easing of this (e.g. a Testcontainers helper that assembles the image from a declared extension list) until a consuming project forces the design. The Dockerfile above is the documented canonical shape until then. ## The same shape for every extension [#the-same-shape-for-every-extension] Whatever the workload, the recipe structure repeats: the entity and migration own the extension-specific column or conversion, queries use the extension's operators through raw SQL or a provider plugin, and the surrounding Elarion machinery (handlers, paging, jobs, events) neither knows nor cares. The worked example is the [time-series recipe](/docs/capabilities/time-series) — TimescaleDB composed with bulk insert, keyset paging, scheduled retention, and client events; pgvector for similarity search or PostGIS for geospatial follow the same shape. # Proxy identity (/docs/capabilities/proxy-identity) Many small apps never run a sign-in flow of their own. An **authenticating reverse proxy** in front of them — Cloudflare Access, Google Cloud IAP, oauth2-proxy, an OpenID Connect gateway — signs the person in and forwards a short-lived **signed token** with every request, in a vendor header or a cookie. The app's job is to validate that token, never to trust an unsigned "user" header, and every app ends up rebuilding the same adapter around JwtBearer. The optional **`Elarion.AspNetCore.ProxyIdentity`** package is that adapter: * reads the token **only** from the configured header and/or cookie (a `Bearer ` prefix is stripped); * validates issuer, audience, lifetime and signature, with **audience required** unless you opt out explicitly; * gets the signing keys from a **JWKS URL** or **OpenID Connect discovery** through IdentityModel's `ConfigurationManager` — no hand-rolled key cache; * keeps the token's claim names (`MapInboundClaims = false`) and maps [`ICurrentUser`](/docs/capabilities/current-user) to them; * **refuses to start** outside Development when it is disabled or half-configured, unless you explicitly sign everyone in as one [fixed identity](#fixed-identity-without-a-proxy); * gives Development a **stand-in identity** with user, roles and groups switches, so the app runs locally without the proxy; * exposes an `ExternalIdentity` record (issuer, subject, e-mail with a trust decision, name, groups, roles) and an optional session-snapshot section. Authentication stays a host concern: handlers still declare `[RequirePermission]`/`[RequireRole]` and read `ICurrentUser`; only the host wiring changes ([authorization](/docs/concepts/authorization)). ## Wiring [#wiring] ```csharp using Elarion.AspNetCore.Identity; // UseElarionCurrentUser using Elarion.AspNetCore.ProxyIdentity; // AddElarionProxyIdentity builder.Services.AddElarionProxyIdentity(builder.Configuration, builder.Environment); // section "ProxyIdentity" builder.Services.AddElarionAuthorization(); var app = builder.Build(); app.UseElarionCrossOriginProtection(); // the proxy's session cookie is an ambient credential (see below) app.UseAuthentication(); app.UseElarionCurrentUser(); // after authentication, before endpoints app.UseAuthorization(); ``` `AddElarionProxyIdentity` binds the `ProxyIdentity` section, applies the optional `configure` callback, validates the result and throws an `InvalidOperationException` naming the offending setting when it cannot run. It registers the proxy scheme (`ProxyIdentityDefaults.AuthenticationScheme`) as the default and returns the `AuthenticationBuilder`, so further named schemes can be added. It also registers `ICurrentUser` mapped to the configured subject, e-mail and role claims — registration is first-wins, so call it before any other `AddElarionCurrentUser`; an application that signs in a principal of its own builds it under these names ([replacing the principal](#replacing-the-principal)). At startup it logs once what the instance accepts (issuer, key source, header, cookie, e-mail trust) and warns when audience validation is off or the Development stand-in is active. ## Configuration [#configuration] ```json { "ProxyIdentity": { "Enabled": true, "Issuer": "https://myteam.cloudflareaccess.com", "JwksUrl": "https://myteam.cloudflareaccess.com/cdn-cgi/access/certs", "Audiences": [ "4714c1358e65fe4b408ad6d432a5f878f08194bdb4752441fd56faefa9b2b6f2" ], "TokenHeader": "Cf-Access-Jwt-Assertion", "TokenCookie": "CF_Authorization", "EmailTrust": "Trusted", "LogoutUrl": "/cdn-cgi/access/logout" } } ``` | Setting | Default | Meaning | | -------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Enabled` | `false` | Validate proxy tokens. `false` selects the Development stand-in and is refused outside Development, unless `Fixed:Enabled` is set. | | `Issuer` | — | The exact `iss` of the proxy's tokens. Required when enabled. | | `JwksUrl` | — | A bare JSON Web Key Set. Mutually exclusive with `MetadataAddress`. | | `MetadataAddress` | — | An OpenID Connect discovery document. With neither set, `{Issuer}/.well-known/openid-configuration` is used. | | `RequireHttpsMetadata` | `true` | Key and discovery URLs must be https; turn off only for a local test issuer. | | `Audiences` | — | Accepted `aud` values; each entry may be a comma-separated list. Required unless `AllowAnyAudience`. | | `AllowAnyAudience` | `false` | Accept any audience of the issuer. Logged as a warning; cannot be combined with `Audiences`. | | `TokenHeader` | — | The header carrying the token. At least one of `TokenHeader`/`TokenCookie` is required. | | `TokenCookie` | — | The cookie read when the header is absent. | | `Claims:Subject` | `sub` | The stable subject; becomes `ICurrentUser.UserId`. | | `Claims:Email` | `email` | Becomes `ICurrentUser.Email`. | | `Claims:EmailVerified` | `email_verified` | Read under `EmailTrust = Claim`. | | `Claims:Name` | `name` | The display name (also the principal's name claim). | | `Claims:Groups` | `groups` | Identity-provider groups, exposed on `ExternalIdentity.Groups` only. | | `Claims:Roles` | `roles` | Application roles ([RFC 9068 §2.2.3.1](https://www.rfc-editor.org/rfc/rfc9068#section-2.2.3.1)); the role claim of the principal, so `ICurrentUser.Roles` and `[RequireRole]` use it. | | `EmailTrust` | `Claim` | `Claim` (verified when `email_verified` is true), `Trusted` (the proxy vouches for every address), `None`. | | `LogoutUrl` | — | Where the browser signs out of the proxy; surfaced in the session section. | | `ClockSkew` | `00:01:00` | Tolerance for `exp`/`nbf`. Proxy tokens are short-lived, so it is tighter than JwtBearer's five minutes. | | `AutomaticRefreshInterval` | `01:00:00` | How long fetched keys are used before a background refresh (library minimum: 5 minutes). | | `RefreshInterval` | `00:01:00` | Minimum time between refreshes triggered by an unknown key id (library minimum: 1 second). | | `LastKnownGoodLifetime` | `00:00:00` (off) | IdentityModel's last-known-good grace for a configuration a refresh replaced (see below). | | `AwaitRefreshOnUnknownKey` | `false` | A token naming an unknown key id waits for one fetch of the keys instead of being refused (see below). | | `UnknownKeyRefreshTimeout` | `00:00:05` | How long such a request waits for that fetch before it is refused. | | `Development:*` | see below | The stand-in identity. | | `Fixed:*` | off | One identity every request is signed in as, in any environment ([below](#fixed-identity-without-a-proxy)). | Set any value from code with the `configure` callback, which runs after binding and before validation: ```csharp builder.Services.AddElarionProxyIdentity(builder.Configuration, builder.Environment, options => options.Audiences.Add(builder.Configuration["PUBLIC_HOSTNAME"]!)); ``` ## Proxy recipes [#proxy-recipes] Each recipe is the `ProxyIdentity` section; everything not shown keeps its default. ### Cloudflare Access [#cloudflare-access] ```json { "Enabled": true, "Issuer": "https://.cloudflareaccess.com", "JwksUrl": "https://.cloudflareaccess.com/cdn-cgi/access/certs", "Audiences": [ "" ], "TokenHeader": "Cf-Access-Jwt-Assertion", "TokenCookie": "CF_Authorization", "EmailTrust": "Trusted", "LogoutUrl": "/cdn-cgi/access/logout" } ``` Access forwards the header on proxied requests; the cookie covers requests where the header is absent. The application token carries `sub` and `email` but no `email_verified`, so decide `EmailTrust` from your login methods (`Trusted` for one-time PIN or a directory you trust). ### Google Cloud IAP [#google-cloud-iap] ```json { "Enabled": true, "Issuer": "https://cloud.google.com/iap", "JwksUrl": "https://www.gstatic.com/iap/verify/public_key-jwk", "Audiences": [ "/projects//global/backendServices/" ], "TokenHeader": "x-goog-iap-jwt-assertion", "EmailTrust": "Trusted", "Claims": { "Name": null } } ``` IAP signs with ES256 keys, which the JWKS handles like any other. For App Engine the audience is `/projects//apps/`. The token has no display name. ### oauth2-proxy [#oauth2-proxy] With `--pass-authorization-header` (or `--set-authorization-header` behind an `auth_request` proxy) oauth2-proxy forwards the identity provider's ID token as `Authorization: Bearer …`: ```json { "Enabled": true, "Issuer": "", "Audiences": [ "" ], "TokenHeader": "Authorization" } ``` The keys come from the issuer's discovery document. Note the `TokenHeader`: the standard `Authorization` header is read **only** when it is configured, because the package never falls back to a location the proxy does not control. ### Any OpenID Connect gateway [#any-openid-connect-gateway] A gateway that forwards tokens of a standard OIDC provider needs the issuer, the audience and the header; the keys come from discovery. When the discovery document lives somewhere other than `{Issuer}/.well-known/openid-configuration`, set `MetadataAddress`: ```json { "Enabled": true, "Issuer": "https://login.example.com/tenant/v2.0", "MetadataAddress": "https://login.example.com/tenant/v2.0/.well-known/openid-configuration", "Audiences": [ "api://my-app" ], "TokenHeader": "X-Forwarded-Id-Token", "Claims": { "Subject": "oid" } } ``` A discovery document must name exactly the configured issuer (OpenID Connect Discovery §4.3); one that names another issuer is refused, so it can never widen the accepted issuers. Proxies that publish keys in another format than a JWKS (for example per-key PEM endpoints) are not covered. ## Expired sessions in the browser [#expired-sessions-in-the-browser] The proxy's session expires on its own schedule, and the app only learns of it from the next request. A page load is fine: the proxy renews the session on the way, through redirects to its own and the identity provider's origins, usually without the person seeing a sign-in. An API call is not, and a single-page app or an installed one makes little else: | Proxy | API call after expiry | Without a marker header | | ----------------- | ------------------------------------------------------------------------- | ------------------------------------------- | | Cloudflare Access | `401` with `X-Requested-With: XMLHttpRequest` | Redirect to the team domain: a CORS failure | | Google Cloud IAP | `401`; send `X-Requested-With: XMLHttpRequest` where it redirects instead | Redirect: a CORS failure | | oauth2-proxy | `401` with `Accept: application/json` | Redirect to the provider: a CORS failure | A browser's `EventSource` sends neither header, so a live-update stream fails without a reason. Elarion's browser side handles both: `createSessionRenewal()` from `@swimmesberger/elarion-pwa` marks the JSON-RPC calls, probes a failing event stream, and answers an expired session with one reload that lets the proxy renew it — see [Renewing an expired proxy session](/docs/capabilities/pwa#renewing-an-expired-proxy-session). How often that reload ends at a sign-in page is the proxy's and the identity provider's configuration, not the app's. On Cloudflare Access the application token expires after the application's session duration (24 hours unless set), and Access renews it silently while the **global session** is still valid; raise both for an app people keep open for weeks, and keep the identity provider's own session persistent (an IdP that forces a password on every re-authentication, or a session cookie that dies with the browser process, defeats the silent renewal). ## Signing keys [#signing-keys] The package builds one IdentityModel `ConfigurationManager` per scheme; a JWKS URL is read through a small retriever into the same configuration shape, so both modes behave identically. The configuration is accepted only when it names the configured issuer and holds at least one signing key. What follows is the library's behaviour, pinned by the package's tests: | Situation | Behaviour | | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | First requests after startup | One fetch; every concurrent request waits for it, none is validated against an empty key list. | | Key endpoint down at startup | Requests are refused (401, fail-closed); the next request after the endpoint recovers fetches again and succeeds. | | Routine refresh | In the background every `AutomaticRefreshInterval`; requests keep using the current keys. | | Token with an unknown key id | That request is refused and a background refresh is requested (at most once per `RefreshInterval`); the new key is accepted as soon as it lands. With `AwaitRefreshOnUnknownKey`, the request waits for the fetch instead (below). | | Refresh fails, or returns no keys / a foreign issuer | The current keys keep serving. | | A key the issuer withdrew | Stops validating once the refresh lands, unless `LastKnownGoodLifetime` grants a grace. | Most proxies publish a new key well before they sign with it, so the routine refresh normally picks it up before the first token arrives; lower `AutomaticRefreshInterval` if yours rotates faster. `LastKnownGoodLifetime` is off by default although IdentityModel's own default is one hour: that grace keeps accepting tokens signed with a key the issuer withdrew, which is the wrong default when a key is withdrawn because it leaked. An outage never needs it. An issuer that rotates by replacing its key, without publishing the next one ahead, signs with a key nobody fetched yet, so the requests until the background refresh lands are refused. `AwaitRefreshOnUnknownKey: true` lets them wait: a token whose key id the current keys do not hold waits for one fetch of the key endpoint, then validates against what it found. * **Single-flight.** Concurrent requests naming the unknown key share one fetch. * **Rate-limited.** At most one such fetch per `RefreshInterval`; a request in that window whose key is still unknown is refused at once, so forged key ids cannot make the instance call the endpoint more often than the background refresh already may. * **Bounded.** A request waits at most `UnknownKeyRefreshTimeout` (five seconds); the fetch goes on for later ones. * **Short-lived.** The keys that fetch found validate tokens for `RefreshInterval`, while the regular refresh, which it requests, catches up; a key the issuer withdraws stops validating at the latest then. A failed or refused fetch (another issuer, no keys) changes nothing. Pre-publishing the next key remains the better fix where the issuer allows it; the option is for issuers that do not. The keys are fetched with the named `HttpClient` `ProxyIdentityDefaults.HttpClientName` (10-second timeout); configure it with `services.AddHttpClient(ProxyIdentityDefaults.HttpClientName)` to add an outbound proxy or a handler. ## Startup refusal [#startup-refusal] Outside the Development environment, `Enabled: false` throws at startup — a deployment that lost its proxy configuration must not come up as "everybody is the development user". The only way past it is the explicit [fixed identity](#fixed-identity-without-a-proxy). An enabled configuration is refused when the issuer, the audience (without `AllowAnyAudience`), the token location or the subject claim is missing, when both `JwksUrl` and `MetadataAddress` are set, when a key URL is not https (unless `RequireHttpsMetadata` is off), or when a refresh interval is below the library minimum. The token only says who the proxy signed in. Make sure the app is reachable **only** through the proxy, and keep the audience scoped to this app: without it any other application behind the same issuer could present its tokens here. The proxy signs the browser in with its own session cookie and forwards the token on every request it lets through, including one that a page on another site makes the browser send. The token is therefore an ambient credential whether the app reads it from a header or a cookie: install `UseElarionCrossOriginProtection` (see [CSRF and cookie authentication](/docs/capabilities/hosting#csrf-and-cookie-authentication)). ## Development stand-in [#development-stand-in] With `Enabled: false` in Development, every request is signed in as the configured developer, with the same claim shape a proxy token carries (under your `Claims` names) and the issuer `ProxyIdentityDefaults.DevelopmentIssuer`. The `X-Elarion-Dev-User` header or the `elarion-dev-user` cookie (URL-encoded) switches the user: to one of `Development:Users` when its e-mail address or subject matches, otherwise to an ad-hoc user with that address, a subject of `dev:{address}` and no groups or roles (the [roles and groups switches](#switching-roles-and-groups) give it some). ```json { "ProxyIdentity": { "Enabled": false, "Development": { "Subject": "developer", "Email": "developer@example.com", "Roles": [ "admin" ], "Users": [ { "Subject": "reader-1", "Email": "reader@example.com", "Name": "A Reader", "Roles": [ "reader" ] } ] } } } ``` Set `Development:UserHeader`/`UserCookie` to empty to turn the switch off. With `Enabled: true` the real proxy scheme runs in Development too, for testing against a staging proxy. | User switch value | Signs in | | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | | absent or empty | the configured developer (`Development:Subject`/`Email`) | | the e-mail address or subject of a `Development:Users` entry | that user | | any other value | an ad-hoc user with that address, subject `dev:{address}`, no groups or roles | | `-` (`ProxyIdentityDefaults.DevelopmentSignedOutUser`) | nobody: the request is anonymous ([signed-out state](#seeing-the-signed-out-state-in-development)) | ### Seeing the signed-out state in development [#seeing-the-signed-out-state-in-development] The stand-in signs someone in on every request, but the application also has a signed-out face — a landing page, a sign-in prompt, the `401` an `[Authorize]` endpoint returns. Set the user switch to the reserved value **`-`** to see it: ```http GET /api/settings X-Elarion-Dev-User: - ``` or set the `elarion-dev-user` cookie to `-`. For that request the stand-in signs nobody in — the same outcome as a proxy that forwarded no token: `HttpContext.User` and `ICurrentUser` are anonymous, an endpoint that requires authorization is challenged with `401`, no `IExternalIdentityFeature` is captured, and the roles and groups switches are ignored, since there is nobody to give them to. The [session section](#session-section) carries no identity but still names the switch cookies, so a development switcher can sign back in; removing the switch returns to the configured developer. A client-side development menu does not need to hard-code the value: the section's `developmentSignedOutUser` member carries it whenever the user switch cookie is named, so the menu sets `developmentUserCookie` to that value instead of a literal `-`. Like every switch value it is trimmed, and it is reserved: `AddElarionProxyIdentity` refuses a stand-in user — the configured developer or a `Development:Users` entry — whose subject or e-mail address is `-`. It belongs to the stand-in alone; validated proxy tokens never read the switch. ### Switching roles and groups [#switching-roles-and-groups] An identity provider grants roles and groups that configuration cannot predict for an ad-hoc user — an owner or admin role, a team group. The **roles switch** sets them per request, for any user the stand-in signs in: ```http GET /api/settings X-Elarion-Dev-User: new.person@example.com X-Elarion-Dev-Roles: owner,admin ``` The `X-Elarion-Dev-Roles` header, or the `elarion-dev-roles` cookie (URL-encoded) when the header is absent, carries a comma-separated list. When present it **replaces** the resolved user's roles — the configured developer, a `Development:Users` entry or an ad-hoc user alike; absent, the configured roles stay. Values are trimmed and de-duplicated, and are emitted under the configured `Claims:Roles` name, so `ICurrentUser.Roles`, `[RequireRole]` and `ExternalIdentity.Roles` see them exactly as they would see a proxy token's roles. An empty header means no roles; ASP.NET Core ignores a cookie with an empty value, so a cookie clears the roles with `,` (a list of no entries), and removing the cookie restores the configured ones. A value longer than 256 characters is ignored. The **groups switch** — `X-Elarion-Dev-Groups` header, `elarion-dev-groups` cookie — works the same way for `ExternalIdentity.Groups`, so an application that maps identity-provider groups to its own permissions can be tested too. Set `Development:RolesHeader`/`RolesCookie` or `GroupsHeader`/`GroupsCookie` to empty to turn a switch off. Like the user switch, these exist only where the stand-in does: with `Enabled: false` and no fixed identity, which is refused outside Development. When proxy tokens are validated or the fixed identity is on, no switch is read, in any environment. ## Fixed identity without a proxy [#fixed-identity-without-a-proxy] Some deployments have no authenticating proxy on purpose: an instance reachable only on a home or office network, or behind a VPN, where everyone who can reach it is trusted. `Fixed` signs **every request in as one configured user**, in any environment: ```json { "ProxyIdentity": { "Fixed": { "Enabled": true, "Subject": "household", "Name": "Household", "Roles": ["admin"] } } } ``` Requests carry the same claim shape as a proxy token, under the issuer `urn:elarion:proxy-identity:fixed` (`ProxyIdentityDefaults.FixedIssuer`, `ExternalIdentity.IsFixedIdentity`), so the application reads `ICurrentUser` and `ExternalIdentity` exactly as it does behind a proxy, and enabling a proxy later is a configuration change. `Subject` is required; it is the key the application stores that user's data under, so keep it stable. `Email`, `Name`, `Groups` and `Roles` are optional. Unlike the Development stand-in, the fixed identity has **no switches**: no header or cookie changes the user, its roles or its groups, so a visitor cannot give themselves `admin`. Nobody can sign out either. A proxy token on the request is ignored. `Fixed:Enabled` together with `Enabled: true` is refused at startup, and the app logs a warning on every start that it runs unauthenticated. Anybody who can reach the instance acts as the fixed user, with its roles. Use it only where the network itself is the access control, and give the user only the roles everyone may have. Keep `UseElarionCrossOriginProtection` installed: an always-signed-in user is an ambient credential too. ## Reading the identity [#reading-the-identity] Handlers read `ICurrentUser` as always. When the application needs more — linking the person to a local account, mapping identity-provider groups to permissions, trusting the address for an invitation — read the `ExternalIdentity` record: ```csharp // In a handler: transport-neutral, from ICurrentUser. var identity = ExternalIdentity.TryRead(currentUser, proxyOptions.Value); // IOptions if (identity is { EmailVerified: true }) { /* link by e-mail */ } // In host code: from the request. Keeps working after the application replaced the principal. var fromRequest = ExternalIdentity.TryRead(httpContext, proxyOptions.Value); ``` The request reader returns the identity captured when the token (or the stand-in) was accepted, kept in `HttpContext.Features` as `IExternalIdentityFeature`, and falls back to `httpContext.User`. The `ICurrentUser` and `ClaimsPrincipal` readers see only the principal in place ([replacing the principal](#replacing-the-principal)). | Member | Meaning | | ------------------------ | -------------------------------------------------------------------------------------------- | | `Issuer`, `Subject` | Together the stable key of the person. | | `Email`, `EmailVerified` | The address and the `EmailTrust` decision (always false without an address or under `None`). | | `Name` | The display name, or null. | | `Groups`, `Roles` | Trimmed, de-duplicated values; a JSON array and a single string read the same. | | `IsDevelopmentIdentity` | True for the stand-in. | It grants nothing by itself; account linking and group-to-permission mapping stay application policy. ## Replacing the principal [#replacing-the-principal] Some applications replace the proxy's principal after authentication, in a middleware between `UseAuthentication` and `UseElarionCurrentUser`: they link the person to a local account and sign in that account's principal (built with ASP.NET Core Identity's `IUserClaimsPrincipalFactory`), or build a principal by hand, for example one carrying permissions mapped from identity-provider groups. `ICurrentUser` reads whatever principal is in place through **one** claim mapping, `ClaimsCurrentUserOptions`, so the replacement must carry its claims under that mapping's names. The mapping in effect is the **first one registered**. `AddElarionCurrentUser` adds it with `TryAdd`, and so do the packages that call it — `AddElarionProxyIdentity` (the proxy's names: `sub`, `email`, `roles` by default) and `AddElarionIdentity` (Identity's `ClaimTypes.NameIdentifier`/`Email`/`Role`). A later registration is ignored without an error. So with the proxy identity registered first, a principal built under Identity's default claim types has no user id `ICurrentUser` can find. Don't fix that with a second mapping: which one wins would depend on registration order, and the proxy's own principal (the stand-in included) would no longer be read. Keep the one mapping and build the replacement under its names, read from DI. With ASP.NET Core Identity, point `IdentityOptions.ClaimsIdentity` at the mapping, so the claims-principal factory emits those names: ```csharp using Elarion.Identity; // ClaimsCurrentUserOptions using Microsoft.AspNetCore.Identity; builder.Services.AddElarionProxyIdentity(builder.Configuration, builder.Environment); // registers the mapping builder.Services.AddElarionIdentity(); // its mapping is ignored // The factory names claims after IdentityOptions.ClaimsIdentity: use the mapping in effect, whichever call supplied it. builder.Services.AddOptions() .Configure((identity, currentUser) => { identity.ClaimsIdentity.UserIdClaimType = currentUser.UserIdClaimType; identity.ClaimsIdentity.EmailClaimType = currentUser.EmailClaimType; identity.ClaimsIdentity.RoleClaimType = currentUser.RoleClaimType; }); ``` Identity's own readers, such as `UserManager.GetUserId(principal)`, use the same `IdentityOptions` and follow along. A hand-built principal takes the claim types from an injected `ClaimsCurrentUserOptions` and passes `RoleClaimType` as the `ClaimsIdentity` role type, so `ClaimsPrincipal.IsInRole` agrees with `ICurrentUser.Roles`. Code that hard-codes `ClaimTypes.*` to read the user should read `ICurrentUser` instead. The replacement does not carry the proxy's issuer, so `ExternalIdentity.TryRead(ICurrentUser, …)` and `TryRead(ClaimsPrincipal, …)` return null after the swap — ASP.NET Core also drops its own authentication result once `HttpContext.User` is assigned. The proxy scheme and the stand-in therefore capture the identity when they accept the token, as `IExternalIdentityFeature` in `HttpContext.Features`. Read it with `ExternalIdentity.TryRead(httpContext, options)`: it returns who the proxy signed in whether the application put a local account's principal in place or, for a person it has no account for, an anonymous one. The [session section](#session-section) reads it the same way. The capture runs in the scheme's `JwtBearerEvents` (`OnTokenValidated`); a host that customizes those events for this scheme wraps the existing handlers rather than replacing the events instance. ## Session section [#session-section] To render an account menu without a second round trip, add the `proxyIdentity` section to the [client-capability snapshot](/docs/concepts/client-capabilities): ```csharp builder.Services.AddElarionSession(builder.Configuration.GetClientCapabilityManifest()); builder.Services.AddElarionProxyIdentitySessionSection(); ``` It carries `email`, `name`, `logoutUrl`, `isDevelopmentIdentity` and `isFixedIdentity` for whoever the proxy signed in, read from the request, so they survive an application [replacing the principal](#replacing-the-principal). `logoutUrl` is omitted for the Development stand-in and the [fixed identity](#fixed-identity-without-a-proxy), which have no proxy session to end. While the stand-in is configured (`Enabled: false`, no fixed identity) it also names the cookies a development switcher sets — `developmentUserCookie`, `developmentRolesCookie` and `developmentGroupsCookie`, each omitted when that switch is turned off. Alongside the user switch cookie it carries `developmentSignedOutUser`, the reserved value (`-`) that signs nobody in, so a switcher reads it instead of hard-coding it; it is omitted exactly where `developmentUserCookie` is. Those names are static configuration, so they are present whoever is signed in, including a person the application treats as anonymous because no local account matches, and also while nobody is, with the user switch [signed out](#seeing-the-signed-out-state-in-development) (`-`). The section is omitted when the proxy signed nobody in and the stand-in is not configured; like every section, it is a read-only UX projection. The snapshot endpoint is anonymous-friendly (`MapElarionSession()` adds no authorization), which is what lets a switcher reach a person without an account. A host that puts `.RequireAuthorization()` on it hides the section from exactly that person; the names are also available outside the snapshot from `IOptions` (`Development.UserCookie`, `RolesCookie` and `GroupsCookie`, meaningful while `Enabled` is false). # Installable apps (PWA) (/docs/capabilities/pwa) An Elarion frontend added to a phone's Home Screen should behave like an app: open without a browser frame, start offline, load its hashed assets from a cache, and — because an installed app is **resumed**, not reopened, and can stay in memory for days — move to a new deploy before it talks to an API whose contract changed under it. The pieces are the same in every app, and so are their traps: a service worker that caches an API answer or a server-rendered page with personal data, an auth proxy's login page stored as a script, a stylesheet pinned to the first visit, a reload that wipes a form when the user comes back from the camera. `@swimmesberger/elarion-pwa` (ADR-0083) owns that plumbing with the safety rules built in. **What** is cached, the manifest, the icons, the offline page, and every UI string stay in the application. | Entry | Role | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `@swimmesberger/elarion-pwa` | `createInstallPrompt()`, `createUpdateWatcher()`, `createSessionRenewal()`, `registerServiceWorker()`, standalone/iOS detection. Framework-neutral. | | `@swimmesberger/elarion-pwa/sw` | `registerShellRouter(self, …)` — the service worker's install, activate and fetch handlers. | | `@swimmesberger/elarion-pwa/vite` | `appVersionFile()` — publishes `/app-version.json` and bakes the same version into the bundle. | | `@swimmesberger/elarion-webpush` | Optional: [Web Push](/docs/capabilities/web-push) for the same worker — `registerWebPushHandlers(self)`. | ## Checklist [#checklist] 1. A **manifest** and **icons** in the web build's static directory. 2. The **head tags**: the manifest link, the iOS tags, `viewport-fit=cover`. 3. A **service worker** composed from `registerShellRouter` (and `registerWebPushHandlers` if the app sends pushes), bundled into one script at `/sw.js`. 4. **Registration** and the **update watcher** in the client entry, the watcher wired to the router. 5. **Caching headers** on the host: hashed assets immutable, everything else revalidated. 6. The **iOS details**: 16 px inputs, safe-area insets, no rubber-band in standalone mode. 7. Behind an **authenticating proxy** (Cloudflare Access, IAP, oauth2-proxy): **session renewal** on the JSON-RPC and client-events clients. ## Manifest and icons [#manifest-and-icons] ```json title="public/manifest.webmanifest" { "id": "/", "name": "Acme Operations", "short_name": "Acme", "start_url": "/", "scope": "/", "display": "standalone", "lang": "en", "theme_color": "#0e1733", "background_color": "#0e1733", "icons": [ { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" }, { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" }, { "src": "/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" } ] } ``` * `192` and `512` PNGs with purpose `any`, and a **maskable** 512 whose mark sits inside the central 80 % circle — launchers crop it to a circle, squircle or teardrop. * A **180 px `apple-touch-icon.png`**, full-bleed (no transparent corners — iOS rounds the corners itself and shows transparency as black). iOS ignores the manifest's icons. * Generate the PNGs from the app's SVG mark with a script rather than exporting them by hand, so they never drift. ```html title="index.html (or the root route's head)" ``` ## The service worker [#the-service-worker] ```ts title="src/sw/service-worker.ts" import { ELARION_SERVER_PREFIXES, registerShellRouter } from '@swimmesberger/elarion-pwa/sw' import { registerWebPushHandlers } from '@swimmesberger/elarion-webpush/sw' declare const self: ServiceWorkerGlobalScope registerShellRouter(self, { // Change it when the precache list changes; activate deletes the previous cache. cacheName: 'acme-v1', // Every server endpoint, matched by path segment. Mirror the reverse proxy's API routes and the dev proxy. serverPrefixes: [...ELARION_SERVER_PREFIXES, '/auth', '/attachments', '/.well-known', '/health'], // Server-rendered pages carry personal data: never cached, an offline page instead. navigation: { mode: 'network-only', offlineUrl: '/offline.html' }, // Precached and served stale-while-revalidate. staticFiles: ['/manifest.webmanifest', '/favicon.svg', '/icon-192.png', '/icon-512.png', '/apple-touch-icon.png'], // The app pins its stylesheet to a hash-free name, so it must not be served cache-first. assets: { mutable: (url) => url.pathname.endsWith('.css') }, }) registerWebPushHandlers(self, { icon: '/icon-192.png', badge: '/icon-192.png' }) ``` The two modules split the worker's events: the shell router handles `install`, `activate` and `fetch`; Web Push handles `push`, `notificationclick` and `pushsubscriptionchange`. ### What it does with each request [#what-it-does-with-each-request] | Request | Answer | | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | Navigation, `network-only` | Always the network; **nothing is stored**. Offline: the precached `offlineUrl`. | | Navigation, `network-first` | The network; a plain HTML answer is kept under `shellUrl` (`/`). Offline: that shell, else `offlineUrl`. | | `assets.prefix` (`/assets/`) | Cache first — content-hashed files are immutable. The newest `maxEntries` (400) are kept. | | `assets.mutable(url)` | Network first, the cache when offline — for hash-free files under the prefix. | | `staticFiles` | Stale-while-revalidate: the cached copy at once, refreshed in the background. | | `serverPrefixes`, `bypass(url, request)` | Not touched. | | Non-GET, cross-origin, `cache: 'no-store'`, `Range` | Not touched. | | Anything else | Not touched — the router only answers what it was told about. | Only a **plain** answer is ever stored: status 200 (not a partial 206), not reached through a redirect, same-origin `basic` (not opaque), and without `Cache-Control: no-store`. HTML is stored only as the `network-first` shell — never under an asset URL. Each rule closes a failure the source apps hit: * An auth proxy (Cloudflare Access, oauth2-proxy) answers an expired session with a **redirect to its login page**. Followed, that is a 200 — stored under an asset URL, cache-first would serve the login page as the script for good. * A server whose SPA fallback answers a **missing chunk with `index.html`** would store HTML as a script the same way. * A `serverPrefixes` entry is a **path segment**: `/rpc` covers `/rpc` and `/rpc/batch` but not `/rpcx`. A plain string prefix both misses (`/api/` does not cover `/api`) and over-matches. * The update check fetches its version file with `cache: 'no-store'`, which the router never answers, so it always sees what is deployed now. **Choosing the navigation mode is the privacy decision**, which is why it has no default. Use `network-only` when the server renders pages (TanStack Start, Next, Razor): their HTML carries the signed-in user's names and records, and must not outlive the session on a shared device. Use `network-first` for a static SPA shell (`index.html` that loads the app and fetches data over `/rpc`) — then every navigation outside `serverPrefixes` is cached as that shell, so any server-rendered page (a login form, an OAuth consent page) **must** be on the list. **Size `maxEntries` to a whole build.** A larger app emits hundreds of route chunks; a cap below one build evicts the running build's own chunks while it is in use, and its next lazy route fails offline. Count the files your build writes to `assets/` and keep a margin. The router precaches the offline page, the shell and the static files on `install`, past the HTTP cache. A precache answer that is not plain (a login redirect, a 404, an HTML page for an icon) **fails the install** — the previous worker stays in charge and the browser tries again on the next visit, rather than storing a login page as the offline page. To route something yourself, create the router without registering it and fall through to it: ```ts import { createShellRouter } from '@swimmesberger/elarion-pwa/sw' const shell = createShellRouter(self, options) self.addEventListener('install', (event) => event.waitUntil(shell.install())) self.addEventListener('activate', (event) => event.waitUntil(shell.activate())) self.addEventListener('fetch', (event) => { if (new URL(event.request.url).pathname.startsWith('/fonts/')) { event.respondWith(shell.strategies.staleWhileRevalidate(event)) // same safety rules, same cache return } shell.handleFetch(event) }) ``` ### Bundling the worker [#bundling-the-worker] A service worker must be served from the origin root to control the whole app, and it cannot share the app's code-split output. Build it as a second, single-file bundle next to the app: ```ts title="vite.sw.config.ts" import { defineConfig } from 'vite' export default defineConfig({ publicDir: false, build: { outDir: 'dist', // the app's output directory (dist/client for TanStack Start) emptyOutDir: false, // runs after the app build — keep its output target: 'es2022', lib: { entry: 'src/sw/service-worker.ts', formats: ['iife'], // one classic script: every browser runs it name: 'AppServiceWorker', fileName: () => 'sw.js', }, }, }) ``` ```json title="package.json" "build": "tsc --noEmit && vite build && vite build --config vite.sw.config.ts" ``` Type-check the worker under the `WebWorker` library — it conflicts with `DOM`, so give `src/sw/` its own `tsconfig.json` with `"lib": ["ES2022", "WebWorker"]` and exclude it from the app's. Both modules are typed structurally, so the real `self` fits without a cast. ## Registering it [#registering-it] ```ts title="src/main.tsx" import { registerServiceWorker } from '@swimmesberger/elarion-pwa' // Production only: under the dev server a worker would sit between the browser and modules hot reload replaces. if (import.meta.env.PROD) void registerServiceWorker('/sw.js') ``` `registerServiceWorker` registers with `updateViaCache: 'none'`, so the browser's update check for `/sw.js` skips the HTTP cache, and resolves to `null` instead of throwing where there is no service worker (an old browser, an insecure origin, a private mode): an installable shell is an enhancement, the app works without it. With Web Push, pass the registration it returns to `enablePush`/`refreshOnStart` as `registration`. ## The install entry [#the-install-entry] Chromium offers its install prompt once, through `beforeinstallprompt`, as soon as the page qualifies — possibly before the UI framework has mounted. Create the controller **at module load** of the client bundle: ```ts title="src/lib/install.ts" import { createInstallPrompt } from '@swimmesberger/elarion-pwa' export const install = createInstallPrompt() ``` ```tsx title="src/components/install-app.tsx" import { useSyncExternalStore } from 'react' import { install } from '../lib/install' export function InstallApp() { // 'none' while server rendering: the browser is unknown there, so the entry appears after hydration. const option = useSyncExternalStore(install.subscribe, install.availability, () => 'none' as const) if (option === 'prompt') return if (option === 'ios') return

Tap Share, then “Add to Home Screen”.

return null } ``` | `availability()` | Meaning | Offer | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- | | `prompt` | The browser handed over its prompt (Chrome, Edge, Android). | An "Install app" action; `prompt()` resolves to `accepted`, `dismissed` or `unavailable`. | | `ios` | iPhone or iPad — no prompt API. iPadOS reports a Mac user agent; the touch screen gives it away. | The share-sheet instructions. Every iOS browser offers "Add to Home Screen" since iOS 16.4. | | `none` | Already installed (standalone), or a browser that cannot install (Firefox desktop, an in-app browser, Chromium before the page qualifies). | Nothing — no dead end. | The controller suppresses Chromium's own install mini-infobar (`preventDefault: false` keeps it) and drops the prompt after `appinstalled` or once it was shown — a prompt can be used once. `isStandalone()` and `isAppleTouchDevice()` are exported for other UI, such as a "notifications need the Home Screen app on iOS" hint (`pushAvailability()` in `@swimmesberger/elarion-webpush` reports that case as `install-first`). ## Reloading into a new deploy [#reloading-into-a-new-deploy] An installed app is resumed, not reopened: after a deploy that adds an enum value, the old client in memory fails validation on the new answer and shows an empty list — for days. So the app compares its own build with the one the server ships when it returns to the foreground, and reloads into the new one. **Never on the foreground return itself.** Coming back from the camera (a `capture` file input), a share sheet or a password manager is a foreground return too, and the page may hold a whole form in local state — with nothing on screen that looks busy, and iOS never asks on `beforeunload`. A first version that reloaded there wiped a half-filled form whose photo had just been taken. The watcher therefore only marks the update **pending** and applies it on the **next navigation that changed the path**: * not a search-only navigation (a list filter writing `?q=` on every keystroke) or a router re-resolving the same location; * not while a dialog is open (`[role="dialog"]`, `[role="alertdialog"]`, `dialog[open]`) or a text field has focus — pass `isBusy` to add the app's own rule; * not within 60 s of the last update reload of the tab (kept in `sessionStorage`), so a proxy serving a stale version file cannot turn every page change into a reload. At most one check runs per minute (`checkIntervalMs`); no answer (offline, mid-deploy) never reloads, and an answer equal to the running build clears a pending update (a rolled-back deploy). ### Publishing the version [#publishing-the-version] ```ts title="vite.config.ts" import { appVersionFile } from '@swimmesberger/elarion-pwa/vite' // CI passes the build stamp; a local build is 'dev'. const version = process.env.APP_VERSION?.trim() || 'dev' export default defineConfig({ plugins: [appVersionFile({ version, define: '__APP_VERSION__' }), react()], }) ``` ```ts title="src/env.d.ts" declare const __APP_VERSION__: string ``` The plugin emits `/app-version.json` (`{"version":"…"}`) in the **client** build only — not the SSR environment, which has no static directory — and `define` bakes the same string into the bundle, so the two ends cannot drift. Serve the file with `Cache-Control: no-cache` from the web build, never routed to the API. ### Wiring the watcher [#wiring-the-watcher] ```ts title="src/lib/updates.ts" import { createUpdateWatcher } from '@swimmesberger/elarion-pwa' export const updates = createUpdateWatcher({ currentVersion: __APP_VERSION__, enabled: import.meta.env.PROD, // a dev server publishes no version }) ``` With **TanStack Router**, whose `onResolved` event carries `pathChanged`: ```ts router.subscribe('onResolved', (event) => updates.navigationResolved({ pathChanged: event.pathChanged })) ``` With **React Router** (or any router that only reports the location), let the watcher compare paths: ```tsx function ApplyUpdates() { const { pathname } = useLocation() useEffect(() => { updates.navigatedTo(pathname) }, [pathname]) return null } ``` A response that fails the running build's validation is the surest sign a newer contract is live. Force a check there (it still reloads only on the next safe page change): ```ts const queryClient = new QueryClient({ queryCache: new QueryCache({ onError: (error) => error instanceof ZodError && void updates.check({ force: true }) }), }) ``` `isPending()`/`subscribe()` back an "Update available" hint, and `reloadNow()` applies the update at once from an explicit "Reload" button. Without a build step to publish a version file, compare the hashed entry script instead — `createUpdateWatcher({ currentVersion: currentEntryScript(), servedVersion: entryScriptVersionSource('/') })` — at the cost of one shell render per check. ## Renewing an expired proxy session [#renewing-an-expired-proxy-session] An app behind an [authenticating proxy](/docs/capabilities/proxy-identity) has no session of its own: the proxy's expires after a fixed time (24 hours by default on Cloudflare Access), and the proxy renews it — usually silently, from its own longer session and the identity provider's — **only on a full page load**, because the renewal runs through redirects to other origins. An installed app is resumed rather than reloaded, so it meets the expiry on an API call instead, and there neither transport can tell: * **`fetch`** follows the proxy's redirect to its login page on another origin and fails CORS — a `TypeError` indistinguishable from being offline. Cloudflare Access and Google IAP answer `401` instead when the request carries `X-Requested-With: XMLHttpRequest` (ASP.NET Core's cookie handler does too), oauth2-proxy when it carries `Accept: application/json`. * **`EventSource`** cannot send headers. Redirected off-origin it retries forever; answered with a `401` or a login page it gives up. Either way the live updates stop without a sign. `createSessionRenewal()` turns both into one signal and answers it with **one reload**, which lets the proxy renew the session and lands the user on the page they were on: ```ts title="src/lib/rpc.ts" import { createSessionRenewal } from '@swimmesberger/elarion-pwa' import { createElarionEvents } from '@/generated/events-client' import { createRpcApi } from '@/generated/rpc-client' const session = createSessionRenewal({ onSignedOut: () => signedOut.set(true) }) export const rpc = createRpcApi({ url: '/rpc', fetch: session.fetch }) export const events = createElarionEvents({ url: '/events', eventSource: session.eventSource }) ``` * **`session.fetch`** adds `X-Requested-With: XMLHttpRequest` and `Accept: application/json` (unless the call sets them) and fetches with `redirect: 'manual'`, so a proxy that redirects anyway yields a readable opaque redirect instead of a CORS failure. A `401` or a redirect reloads the page, and the call never settles — the page goes away instead of flashing an error first. * **`session.eventSource`** opens the platform `EventSource` and, when the stream reports an error, probes the same URL once with those headers (at most every 10 s, `probeIntervalMs`). Only a `401` or a redirect renews; a network error is left to the stream's own retries, and the generated events client reopens a stream that gave up. * **One reload per minute at most.** The time of the last renewal is kept in `sessionStorage`; an expiry within 60 s of it (`reloadGuardMs`) is not one a reload can renew — the proxy denies the person, or the app itself answers `401` — so the answer passes through and `onSignedOut` runs: show a signed-out state with a button that reloads. Without `sessionStorage` it never reloads on its own. The reload is an ordinary navigation, which the [service worker](#what-it-does-with-each-request) never answers from a cache when it is redirected, so the browser follows it to the proxy's login page whenever the proxy cannot renew silently. Use it only behind a proxy, or with a server whose `401` means "sign in again on a full page load": an app with its own sign-in form handles `401` in the app instead. The [proxy recipes](/docs/capabilities/proxy-identity#expired-sessions-in-the-browser) list the session settings that decide how often renewal needs a real sign-in. ## Caching headers on the host [#caching-headers-on-the-host] The worker decides what the **service worker's** cache holds; the HTTP cache needs the same split: | Path | `Cache-Control` | Why | | ---------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------- | | `/assets/*` (content-hashed) | `public, max-age=31536000, immutable` | A new build has new names. | | `/sw.js` | `no-cache` | A stale worker keeps an old caching strategy alive. | | `/app-version.json` | `no-cache` | A cached answer hides a deploy. | | `/`, `index.html`, `/offline.html` | `no-cache` | The shell must revalidate so a deploy reaches installed apps. | | `/manifest.webmanifest`, icons | `no-cache` | A changed name or icon reaches installed apps; serve the manifest as `application/manifest+json`. | An ASP.NET Core host serving the built app from `wwwroot`: ```csharp var staticFiles = new StaticFileOptions { OnPrepareResponse = context => { context.Context.Response.Headers.CacheControl = context.Context.Request.Path.StartsWithSegments("/assets") ? "public, max-age=31536000, immutable" : "no-cache"; }, }; app.UseDefaultFiles(); app.UseStaticFiles(staticFiles); app.MapElarionJsonRpc(); // The SPA fallback is an endpoint, so the static-file middleware is skipped for it: pass the same options so // index.html gets its no-cache header from there too. app.MapFallbackToFile("index.html", staticFiles); ``` ASP.NET Core's default content-type map already serves `.webmanifest` as `application/manifest+json`. Behind Caddy, in front of a Node server that sends neither the manifest type nor any `Cache-Control`: ```text title="Caddyfile" @manifest path /manifest.webmanifest header @manifest { Content-Type "application/manifest+json" Cache-Control "no-cache" defer # apply after the upstream's own headers } @pwaNoCache path /sw.js /app-version.json /offline.html header @pwaNoCache { Cache-Control "no-cache" defer } ``` ## iOS details [#ios-details] * **Inputs at 16 px or larger.** iOS Safari zooms into any focused field whose text is smaller and does not zoom back out: `@media (pointer: coarse) { input, select, textarea { font-size: max(16px, 1em); } }`. * **Safe-area insets.** With `viewport-fit=cover` and the `black-translucent` status bar the page runs under the notch and the home indicator: pad the top bar by `env(safe-area-inset-top)` and the bottom tab bar by `env(safe-area-inset-bottom)` — including fixed elements such as a bottom sheet's close button. * **The dynamic viewport.** Size the shell with `100dvh` (`h-dvh`), not `100vh`, which hides the bottom of the page behind the browser bars. * **No rubber-band in standalone mode.** Overscrolling drags the whole shell, header and tab bar included: `@media (display-mode: standalone) { html, body { overscroll-behavior-y: none; } }`. * **Web Push needs the Home Screen app.** iOS exposes the Push API only to an installed app (16.4+); see [Web Push](/docs/capabilities/web-push). * **The offline page is self-contained.** No stylesheet, script or font request that would fail offline as well — inline its styles, and keep the app's language and colors. ## Limits [#limits] * One cache, one origin, one scope. A worker for a sub-path app, background sync, or periodic background fetch is the application's own code — `createShellRouter` and its `strategies` compose with it. * The router precaches a fixed list; it does not read a build manifest. Assets are cached on first use, which covers the routes a user actually visited. An app that must work fully offline from the first visit needs a generated precache list (for example Workbox's `injectManifest`) — and then likely Workbox altogether. * The update watcher reloads the page; it does not swap modules in place. A page holding unsaved state is protected by the navigation rule, not by the reload. # Resilience (/docs/capabilities/resilience) Resilience is a framework-level capability expressed as **neutral policy metadata** plus an `IResiliencePipelineRunner` contract. Application code uses Elarion attributes and generated registrations; the default runtime is backed by `Microsoft.Extensions.Resilience` / Polly, but that is an explicit host choice — the attributes and generated metadata do not require it. ## Defining a policy [#defining-a-policy] Enable policy generation with `[assembly: UseElarion]` or `[assembly: GenerateResiliencePolicies]`, then declare named policies as partial static classes: ```csharp using Elarion.Abstractions.Resilience; [ResiliencePolicy( "invoice-email", MaxRetryAttempts = 4, Delay = "10s", Backoff = ResilienceBackoffType.Exponential, MaxDelay = "5m", UseJitter = true, Timeout = "30s")] public static partial class InvoiceEmailPolicy; ``` The generator emits the policy name, a typed `Reference`, a per-policy registration method, and an assembly aggregation method. ### Policy properties [#policy-properties] These are behavioral, not just metadata: | Property | Runtime meaning | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------- | | `MaxRetryAttempts` | Retries after the original attempt. `4` means up to 5 total attempts. Supplying any retry property enables retry generation. | | `Delay` | Base delay before the next retry. Inline: awaited in the current call/run. Deferred: becomes the next attempt's due time. | | `Backoff` | Delay growth: `Constant` reuses `Delay`, `Linear` multiplies by attempt number, `Exponential` doubles from the base. | | `MaxDelay` | Optional cap for calculated retry delays. | | `UseJitter` | Randomizes retry delays so many jobs do not retry at the same instant. | | `Timeout` | **Per-attempt** timeout. It limits one try, not the whole policy execution across all retries. | `Timeout = "30s"` means each attempt may run for at most 30 seconds. With `MaxRetryAttempts = 4`, the operation can run longer than 30 seconds in total, because each retry gets its own window plus retry delays. Use a caller/host cancellation token or an outer deadline when you need a total end-to-end limit. Timeouts are cooperative: when one fires, the framework cancels the attempt token and records the attempt as timed out. Handler and job code must pass that token into database calls, HTTP calls, delays, and other async work so the underlying operation stops promptly. ## Registering a runtime [#registering-a-runtime] Generated registration stores neutral `ResiliencePolicyMetadataRegistration` instances only — it does not build pipelines. The host picks a runtime: ```csharp builder.Services.AddMyApp_ApplicationResiliencePolicies(); builder.Services.AddElarionResilience(); ``` `AddElarionResilience()` consumes the generated metadata and lazily builds executable Microsoft/Polly pipelines. A custom runtime can register its own `IResiliencePipelineRunner` and `IResiliencePolicyCatalog` while reusing the same attributes and metadata. ## Handler resilience [#handler-resilience] Handlers opt into request-path resilience with `[Resilient]`: ```csharp [Resilient(InvoiceEmailPolicy.Name)] public sealed class SendInvoiceEmail : IHandler> { // ... } ``` The generated `ResilienceDecorator` wraps the existing [pipeline](/docs/concepts/decorator-pipelines) so each retry attempt runs through the normal decorators. Use handler resilience only for **idempotent** work where the caller should wait for all attempts. The flow with the policy above: 1. Attempt 1 starts. 2. If it throws an ordinary exception, the retry policy waits per `Delay`/`Backoff`. 3. Attempt 2 starts with a fresh timeout window. 4. The caller waits until an attempt succeeds, retries are exhausted, cancellation is requested, or a non-retryable failure is thrown. `OperationCanceledException` and `NonRetryableException` are terminal and are not retried. `Result` failures are also terminal — they are normal return values, not exceptions. **Retry × transaction = double execution.** On a command, the resilience decorator wraps the transaction decorator, whose finalizing commit deliberately runs uncancellable so a committed transaction is never abandoned half-acknowledged. A per-attempt `Timeout` abandons the attempt *without waiting for it*: the in-flight commit completes in the background, the timeout exception is not a cancellation, so the retry fires — and the command executes and commits **twice**. Always pair a retrying `[Resilient]` policy on a command with [`[Idempotent]`](/docs/concepts/idempotency), which turns the retry into a replay of the first committed outcome. The generator warns (`ELPIPE004`) on a `[Resilient]` command without `[Idempotent]` unless the policy is declared timeout-only in the same assembly. ## Scheduler resilience [#scheduler-resilience] Scheduled jobs can opt into resilience two ways. ### Inline resilience [#inline-resilience] `[Resilient]` on a scheduled method retries inside the current scheduler run — Spring-style composition. `RunId` and scheduler status still represent one occurrence. This is right for short idempotent work where one occurrence owns all attempts; it is not ideal for long operations that should show `WaitingRetry` between attempts. ```csharp [Resilient(InvoiceEmailPolicy.Name)] [ScheduledJob("invoice-email.retryOutbox", FixedDelay = "1m")] public async ValueTask RetryOutboxAsync(CancellationToken ct) { await outbox.SendPendingAsync(ct); } ``` ### Deferred retry [#deferred-retry] For runtime one-off jobs where another handler needs to observe status, use scheduler-deferred retry with the same generated policy reference: ```csharp var handle = await scheduler.EnqueueAsync( payload, new ScheduledJobOptions { ResiliencePolicy = InvoiceEmailPolicy.Reference, ResilienceMode = ScheduledJobResilienceMode.DeferredRetry, CorrelationId = payload.InvoiceId.ToString() }, ct); return new QueueEmailResponse(handle.JobId); ``` Deferred retry releases scheduler concurrency between attempts. A failed attempt records `WaitingRetry`, calculates the next due time from the generated retry metadata, and enqueues a fresh attempt with a new `RunId` and the same `JobId`. `Timeout` remains per attempt: 1. Attempt 1 starts with its own `RunId`. 2. If it throws or times out, the scheduler records that attempt outcome. 3. If retries remain, the logical state becomes `WaitingRetry` and `NextAttemptDueTimeUtc` is set from the policy delay/backoff. 4. At the retry due time, attempt 2 starts with a new `RunId`, the same `JobId`, and a fresh timeout. Deferred retry requires generated policy metadata, because the scheduler needs framework-owned retry settings to calculate future due times without sleeping inside an executing pipeline. It stays in-memory — missing state can mean the id was never known, the process restarted, or a terminal state aged out. Use durable infrastructure if retry history must survive restarts. Resilience execution is also [trace-visible](/docs/capabilities/telemetry): named policy spans expose the final outcome and duration, and retry/timeout callbacks add span events under the default runtime. # Scheduling (/docs/capabilities/scheduling) Scheduled jobs are in-memory background work owned by one host-local scheduler. They are intended for recurring application tasks and delayed one-off jobs where persistence, dashboards, distributed locks, and cross-process catch-up are **not** required. The scheduler uses source-generated descriptors and invocation delegates — there is no runtime assembly scanning, `Type` activation, or reflection-based method invocation. Every run executes through an async DI scope, receives a cancellation token, is tracked during shutdown, and emits [scheduler telemetry](/docs/capabilities/telemetry). ## Implementation-neutral by design [#implementation-neutral-by-design] The source-generation surface is implementation-neutral. `[ScheduledJob]`, `IScheduledJob`, and the scheduler contracts live in `Elarion.Abstractions`; application assemblies reference `Elarion` (which bundles the generator), and the generated descriptors never choose the default in-memory scheduler. A host then chooses a runtime by registering `AddElarionScheduler(...)` or a custom `IJobScheduler` / `IJobSchedulerInspector` that consumes the generated descriptors. ## Enabling and registering [#enabling-and-registering] Enable scheduled job generation in the assembly that contains jobs: ```csharp using Elarion.Abstractions; [assembly: UseElarion] ``` Jobs are registered per [module](/docs/concepts/modules): the generator emits an `Add{Module}ScheduledJobs` method for each `[AppModule]` and calls it from that module's generated `ConfigureDefaultServices`, so the bootstrapper's `AddElarion` registers the descriptors of every enabled module. A job whose namespace falls under no module is reported (`ELSG010`, warning) because it would never be registered. The host adds only the chosen scheduler runtime: ```csharp builder.Services.AddElarion(builder.Configuration); // module descriptors, gated per module builder.Services.AddElarionScheduler(builder.Configuration); // the in-memory runtime ``` The generated `Add{Module}ScheduledJobs` methods are descriptor registration only — they do not start a scheduler, register a hosted service, or choose `InMemoryScheduler`. That separation is intentional so a different scheduler runtime can reuse the same generated descriptors. `AddElarionScheduler(IConfiguration)` reads the `Scheduler` section: ```json { "Scheduler": { "Enabled": true, "MaxConcurrentExecutions": 8, "MaxRetainedCompletedJobs": 1024, "MaxMisfireCatchUpRuns": 32 } } ``` ## A recurring job [#a-recurring-job] A compile-time recurring job is an ordinary accessible method annotated with `[ScheduledJob]`. It must be non-generic, return `Task` or `ValueTask`, and accept only optional `IScheduledJobContext` and `CancellationToken` parameters. ```csharp using Elarion.Abstractions.Scheduling; namespace MyApp.Application.Modules.Invoicing.Services; public sealed class RecurringBillingJob( IRecurringBillingProcessor processor, TimeProvider timeProvider) { [ScheduledJob( "invoicing.recurringBilling", FixedRate = "1d", Enabled = "${Modules:Invoicing:Enabled}")] public async ValueTask RunAsync(IScheduledJobContext context, CancellationToken ct) { var today = DateOnly.FromDateTime(timeProvider.GetUtcNow().UtcDateTime); await processor.ProcessAllAsync(today, ct); } } ``` A job that writes row by row gives each row its own transaction with [`RunEachInTransactionAsync`](/docs/concepts/persistence-and-transactions#one-transaction-per-item): a row that fails is logged and counted, and the others still commit. ## Operational characteristics [#operational-characteristics] * The scheduler runtime is **in-memory**. Queued runtime jobs and due recurring state are lost when the process stops; recurring jobs re-derive their schedules at the next start. Cross-instance coordination of recurring jobs is an opt-in database backend (below). * Fixed-rate and cron schedules **skip missed in-process slots** instead of replaying a burst (tunable with [misfire policy](/docs/capabilities/scheduling/overlap-and-misfire)). * There is **no global polling loop**. The runtime waits until the nearest due item and wakes early when an earlier item is enqueued. * `TimeProvider` is used throughout, so tests can drive millisecond schedules deterministically with a fake clock. Production precision is bounded by OS timer resolution and host load. * Scheduling, enqueue, cancel, and execution all emit [telemetry](/docs/capabilities/telemetry). * A routine run is not news. Under the `Elarion.Scheduling` log category, a run's start and its successful completion (with its duration in milliseconds) log at `Debug`, the scheduler's own lifecycle (started with N descriptors, shutting down, stopped) at `Information`, a cancelled run or an occurrence skipped because an earlier run still holds its slot (the job overran its schedule) at `Warning`, and a failed run at `Error`. The claims purge of the database backend logs its deleted rows at `Debug`. To see every run, raise the category's level (`Logging:LogLevel:Elarion.Scheduling` = `Debug`). If you need durable queues or retry history that survives restarts, use dedicated job infrastructure. Elarion's scheduler runtime is deliberately in-process and lightweight; what it does offer for clusters is the recurring-job coordination below. ## Running on more than one node [#running-on-more-than-one-node] Every node runs the same source-generated job set, so without coordination each recurring job fires once **per node**. `Elarion.Scheduling.EntityFrameworkCore` closes that with per-occurrence claim rows over PostgreSQL (ADR-0025): right before executing a recurring occurrence, a node claims it in the `elarion_scheduler_claims` table, and exactly one node wins — the others record the occurrence as skipped (`claimed-elsewhere`) and continue. See [Multi-node coordination](/docs/capabilities/scheduling/multi-node) for the architecture, diagrams, and practical trade-offs. ```csharp // In Program.cs, next to AddElarionScheduler (either order): builder.Services.AddElarionScheduler(builder.Configuration); builder.Services.AddElarionSchedulerEntityFrameworkCore(); // In OnModelCreating (or [GenerateElarionSchedulerClaims] on a [GenerateDbSets] context): modelBuilder.UseElarionSchedulerClaims(); ``` How the claim dedupes depends on the schedule kind: **cron** occurrences are wall-clock deterministic on every node, so they claim their exact `(job, occurrence)` slot; **fixed-rate/fixed-delay** due times are anchored per node, so they dedupe by a one-interval window (at most one run per interval cluster-wide); **one-time** startup schedules are never coordinated (startup work is per node by design). If a claim cannot be made — say the database is briefly unreachable — the node fails **closed** and skips the occurrence rather than risking a duplicate; the next occurrence retries. A claim-retention purge worker keeps the table small (`SchedulerClaimsOptions`, default 7 days). Runtime one-shot jobs (`IJobScheduler`) remain in-memory; durable one-shot scheduling is a planned follow-up phase of ADR-0025. ## In this section [#in-this-section] FixedRate, FixedDelay, Cron, initial delay, and config placeholders. What happens when runs collide or fall behind. Typed one-off jobs scheduled at runtime with a payload. Snapshots, next-due times, and cancellation. Where each kind of work runs, what survives restarts, and when to pick a dedicated job system. How recurring jobs execute exactly once across a cluster, and why it matters. # Inspection (/docs/capabilities/scheduling/inspection) The scheduler exposes lightweight, read-only state through `IJobSchedulerInspector`. This is enough to build an admin dashboard or a job-status endpoint without a separate trigger API. ## Snapshots [#snapshots] ```csharp var snapshot = schedulerInspector.GetSnapshot(); var activeRuns = snapshot.ActiveRuns; var nextDue = snapshot.Jobs .Single(job => job.Name == "reports.daily") .NextDueTimeUtc; var job = schedulerInspector.GetJob(handle.JobId); ``` `NextDueTimeUtc` is the next queued due time known to the running in-memory scheduler — enough to show the next fire time for enabled recurring jobs. Runtime jobs with deferred retry expose their next retry due time through `ScheduledJobState.NextAttemptDueTimeUtc`. ## Per-job status [#per-job-status] A status handler can inspect the logical job and surface it to a caller: ```csharp var state = schedulerInspector.GetJob(jobId); if (state is null) { return AppError.NotFound("Job state is no longer available."); } return new JobStatusResponse( state.Status, state.Attempt, state.MaxAttempts, state.NextAttemptDueTimeUtc, state.LastError); ``` Job state is in-memory. A missing state can mean the id was never known, the process restarted, or a terminal state aged out beyond `Scheduler:MaxRetainedCompletedJobs`. Use durable infrastructure if status history must survive restarts. Terminal states are `Succeeded`, `Failed`, `Cancelled`, or `Skipped`, retained in memory up to `Scheduler:MaxRetainedCompletedJobs`. # Multi-node coordination (/docs/capabilities/scheduling/multi-node) Every node of your application runs the **same source-generated job set** — the scheduler registry is compiled into the binary, and all nodes run the same binary. Without coordination, that means every recurring job fires once **per node**: three replicas send the daily report three times. `Elarion.Scheduling.EntityFrameworkCore` fixes this with one idea: > **Before a node executes a recurring occurrence, it claims that occurrence in a shared database > table. Exactly one node wins the claim and runs the job; every other node skips it and moves on.** There is no leader, no election, no extra broker — the claim row *is* the coordination, using the PostgreSQL you already run (the same posture as the [outbox](/docs/capabilities/events/backends) and the [idempotency store](/docs/concepts/idempotency)). See [ADR-0025](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0025-distributed-scheduler-coordination.md) for the full decision record. ## The architecture [#the-architecture] Each node keeps its complete local scheduler — timers, queues, overlap rules, telemetry. The only new piece is a single question asked at the very last moment before a run starts: *"may I?"* ```text Node A Node B ┌──────────────────────┐ ┌──────────────────────┐ │ InMemoryScheduler │ │ InMemoryScheduler │ │ │ │ │ │ timer loop │ │ timer loop │ │ occurrence queue │ │ occurrence queue │ │ overlap / misfire │ │ overlap / misfire │ │ telemetry, inspector│ │ telemetry, inspector│ │ │ │ │ │ │ │ "may I run this │ │ "may I run this │ │ occurrence?" │ │ occurrence?" │ └──────────┼───────────┘ └──────────┼───────────┘ │ TryClaimAsync(job, due) │ TryClaimAsync(job, due) ▼ ▼ ┌──────────────────────────────────────────┐ │ PostgreSQL (your database) │ │ │ │ elarion_scheduler_claims │ │ ┌────────────┬────────────────┐ │ │ │ job_name │ occurrence_utc │ ← PK │ │ ├────────────┼────────────────┤ │ │ │ report │ 03:00:00 │ │ │ │ cleanup │ 03:05:00 │ │ │ └────────────┴────────────────┘ │ │ one row per fired occurrence │ └──────────────────────────────────────────┘ ``` The seam is `IScheduledOccurrenceCoordinator` (in `Elarion.Abstractions.Scheduling`). On a single node the default implementation answers "yes" instantly with no I/O, so nothing changes until you opt in. ## One occurrence, two nodes [#one-occurrence-two-nodes] Both nodes' clocks reach 03:00 and both dequeue the same cron occurrence of `report`. Both try to insert the same claim row; the table's primary key `(job_name, occurrence_utc)` guarantees only one insert succeeds: ```text Node A PostgreSQL Node B │ │ │ │ INSERT claim │ │ │ (report, 03:00) │ INSERT claim │ ├──────────────────────────►│◄───────────────────────────┤ │ │ │ │ 1 row — you win │ 0 rows — already taken │ │◄──────────────────────────┼───────────────────────────►│ │ │ │ ▼ │ ▼ runs the job │ records the occurrence as (full local pipeline: │ Skipped("claimed-elsewhere") scope, overlap, telemetry) │ and continues its chain ``` The losing node is not idle-forever — it simply skips *this* occurrence and keeps its own schedule chain running. If node A is later drained during a deploy, node B naturally wins the next claims. Work migrates between nodes automatically, one occurrence at a time, with no failover event. ## Why the claim looks different per schedule kind [#why-the-claim-looks-different-per-schedule-kind] A claim can only deduplicate what both nodes *agree on naming*. The schedule kinds differ in exactly that respect: ```text Cron "0 0 3 * * *" — wall-clock deterministic: every node computes the SAME instants ────────────────────────────────────────────────────────────────────────────── Node A: 03:00:00 04:00:00 05:00:00 Node B: 03:00:00 04:00:00 05:00:00 │ │ └── identical keys ⇒ claim the EXACT SLOT (job, 03:00:00) FixedRate "10m" — the grid is anchored at each node's own start time ────────────────────────────────────────────────────────────────────────────── Node A (started 09:02): 09:12 09:22 09:32 Node B (started 09:05): 09:15 09:25 09:35 │◄─ 10m window ─►│ └── keys never match ⇒ claim a WINDOW: succeeds only if no claim for this job exists within one interval before the due time ``` * **Cron** → *exact-slot claim*. A plain `INSERT … ON CONFLICT DO NOTHING`; the primary key serializes any number of racers. Result: **exactly one run per cron occurrence, cluster-wide.** * **Fixed-rate / fixed-delay** → *window claim*. The due times are node-anchored and never align, so the claim asks "has anyone run this job in the last interval?" A per-job PostgreSQL advisory lock (`pg_advisory_xact_lock`) serializes concurrent claimants — two nodes checking simultaneously would otherwise both see "no recent claim" and both run. Result: **at most one run per interval, cluster-wide** — a 10-minute poller polls every \~10 minutes for the whole cluster instead of every 10 minutes *per node*. * **One-time startup schedules** are deliberately **not coordinated**: startup work (cache warm-up, local initialization) is usually meant to run on every node. Cluster-wide "exactly once ever" work belongs behind an [`[Idempotent]` handler](/docs/concepts/idempotency). A recurring job can also opt out of coordination entirely with `[ScheduledJob(..., Placement = JobPlacement.EveryNode)]` — for jobs that maintain **process-local state** (an in-memory lookup table, a per-node cache), where suppressing the run on the losing nodes would leave them silently stale. The rule of thumb and the full decision matrix live in [Execution semantics & positioning](/docs/capabilities/scheduling/semantics). ## What you gain in practice [#what-you-gain-in-practice] **Scale out without auditing your jobs.** Going from one replica to three no longer means every nightly report, digest email, retention purge, and reconciliation sweep runs three times. You scale the web workload; the scheduled workload stays single. **No new infrastructure and no leader.** The alternative designs both cost more: dedicated job infrastructure (Quartz clustering, Hangfire) brings its own schema, dashboard, and operational surface; leader election needs lease renewal, failover detection, and has a "the leader just died" window where either nothing runs or two nodes think they lead. A claim row per occurrence has neither problem — coordination degrades *per occurrence*, never per cluster, and the "election" is one `INSERT` on the database your job was about to use anyway. **Deploys and crashes are non-events.** Because any node may win any occurrence, there is no scheduler node to drain, promote, or babysit. Kill a pod mid-deploy and the next occurrence simply fires on a surviving node. **It fails safe, not loud.** If the claims database is briefly unreachable, a node **skips** the occurrence instead of running unconfirmed (fail-closed) — duplicate suppression is the whole point, and a job that needs the database wouldn't have succeeded anyway. The next occurrence retries naturally. **You can see what happened.** A lost claim is recorded like any other skip — reason `claimed-elsewhere` — in the [inspector snapshot](/docs/capabilities/scheduling/inspection) and telemetry, so "why didn't this node run the job?" has a queryable answer instead of a mystery. **Zero cost until you need it.** The seam's local default claims everything synchronously with no I/O; single-node behavior is unchanged down to the byte, and no database table exists until you register the EF backend. ## Honest limitations [#honest-limitations] * **At-most-once per occurrence.** If the winning node crashes *mid-run*, that occurrence is not re-executed elsewhere (the other nodes have already moved on). The next occurrence fires normally. Jobs whose single occurrence must never be lost should be idempotent and/or re-derive their work from state (as the framework's own sweepers do). * **Interval kinds dedupe by window, not slot** — across a pathological pause, two runs can land closer than one interval (one late, one on time). Use cron for hard "once per calendar slot" semantics. * **Runtime one-off jobs (`IJobScheduler`) are not durable yet** — they remain in-memory per node; durable one-shot scheduling is the planned phase 2 of ADR-0025. * **PostgreSQL-specific** (`ON CONFLICT`, advisory locks), like the idempotency store. ## Wiring [#wiring] ```csharp // Program.cs — next to AddElarionScheduler (either order): builder.Services.AddElarionScheduler(builder.Configuration); builder.Services.AddElarionSchedulerEntityFrameworkCore(); // The claims table, on the context (or hand-written in OnModelCreating): [GenerateDbSets] [GenerateElarionSchedulerClaims] // or: modelBuilder.UseElarionSchedulerClaims(); public sealed partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } ``` `UseElarionSchedulerClaims` takes the usual `tableName`/`schema`/`snakeCase` overrides. A hosted purge worker deletes claim rows past `SchedulerClaimsOptions.ClaimRetention` (default 7 days — keep it comfortably above your largest fixed-rate/fixed-delay interval, since a purged claim can no longer suppress a duplicate inside its window): ```csharp builder.Services.AddElarionSchedulerEntityFrameworkCore(options => { options.ClaimRetention = TimeSpan.FromDays(3); options.PurgeInterval = TimeSpan.FromMinutes(30); }); ``` # Overlap & misfire (/docs/capabilities/scheduling/overlap-and-misfire) Two independent policies govern what happens under load: **overlap** (a new occurrence is due while one is still running) and **misfire** (a grid occurrence is observed so late that later ones are also due). They are separate because they answer different questions. ## Overlap [#overlap] Overlap decides what to do when the same job already has an active occurrence. The default is `Skip`. | Policy | Behavior | | ----------------- | --------------------------------------------------------------------------------------------------------------------------- | | `Skip` | Drop a recurring occurrence when the job is already running. | | `Queue` | Serialize occurrences of the same job; recurring queued occurrences coalesce so slow jobs do not pile up unlimited waiters. | | `AllowConcurrent` | Allow multiple occurrences to run at once, still subject to the global `MaxConcurrentExecutions`. | ### Groups [#groups] Use `Group` when *different* jobs must not overlap each other — for example because they share a mailbox, an export directory, or a third-party API quota: ```csharp [ScheduledJob("imports.customerSync", FixedRate = "30s", Group = "imports")] public async ValueTask SyncCustomersAsync(CancellationToken ct) { /* ... */ } ``` ### Bounding concurrency per job [#bounding-concurrency-per-job] Use `MaxConcurrentRuns` with `AllowConcurrent` when a single job may overlap but should still be bounded: ```csharp [ScheduledJob( "imports.customerSync", FixedRate = "30s", Overlap = ScheduledJobOverlap.AllowConcurrent, MaxConcurrentRuns = 2)] public async ValueTask SyncCustomersAsync(CancellationToken ct) { await importer.SyncAsync(ct); } ``` ## Misfire [#misfire] Misfire applies only to recurring **grid** schedules (`FixedRate` and `Cron`) when the scheduler observes a due occurrence *after* one or more later occurrences would also already be due — for example after an in-process pause or a large clock jump. Small timer jitter is **not** a misfire. `FixedDelay` schedules have no missed grid slots because the next due time is computed after completion. | Policy | Behavior | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `FireOnce` (default) | Run one overdue occurrence, then schedule the next future occurrence and skip the intermediate slots. | | `Skip` | Do not run the stale overdue occurrence. Record a skipped outcome with reason `misfire`, then schedule the next future occurrence. | | `CatchUp` | Run missed occurrences in due-time order, respecting normal overlap/concurrency rules. Bounded by `Scheduler:MaxMisfireCatchUpRuns`; after the cap, the scheduler coalesces to the next future occurrence. | Runtime one-off jobs scheduled through `IJobScheduler` do not use recurring misfire policy. A one-off job with a due time in the past runs as soon as scheduler capacity is available. # Runtime jobs (/docs/capabilities/scheduling/runtime-jobs) Beyond compile-time recurring jobs, you can enqueue **one-off** work at runtime with a typed payload. The job type still carries `[ScheduledJob]` so the generator emits its descriptor and a direct invocation delegate — but it usually omits a recurring schedule. ## Defining a runtime job [#defining-a-runtime-job] A runtime job implements `IScheduledJob`: ```csharp using Elarion.Abstractions.Scheduling; [ScheduledJob("emails.send")] public sealed class SendEmailJob(IEmailSender sender) : IScheduledJob { public async ValueTask ExecuteAsync( SendEmailPayload payload, IScheduledJobContext context, CancellationToken ct) { await sender.SendAsync(payload.To, payload.Subject, payload.Body, ct); } } public sealed record SendEmailPayload { public required string To { get; init; } public required string Subject { get; init; } public required string Body { get; init; } } ``` ## Scheduling and cancelling [#scheduling-and-cancelling] Use the typed `IJobScheduler` API: ```csharp var handle = await scheduler.ScheduleAsync( new SendEmailPayload { To = "customer@example.com", Subject = "Invoice", Body = "Your invoice is ready." }, timeProvider.GetUtcNow().AddMinutes(5), ct); await scheduler.CancelJobAsync(handle.JobId, ct); ``` When a handler enqueues background work and needs to return an operation id, return `handle.JobId`. That is the id callers pass back to `CancelJobAsync`. ## Which node runs it — and what a restart costs [#which-node-runs-it--and-what-a-restart-costs] A runtime job lives entirely on **the node that accepted the `EnqueueAsync`/`ScheduleAsync` call**: it is enqueued into that process's in-memory queue, no other node ever learns it exists, and it is therefore trivially duplicate-free — but also **lost if that node restarts, deploys, or crashes before (or while) it runs**. Two practical consequences: * `ScheduleAsync(payload, dueTime)` far in the future is fragile in deploy-heavy environments: a pod recycled before the due time silently discards the job. * `CancelJobAsync`/`CancelRunAsync` and the [inspector](/docs/capabilities/scheduling/inspection) only know about jobs held by the node answering the call — behind a load balancer, a cancel request landing on a different node returns `false`. Use runtime jobs for **short-lived, loss-tolerable work anchored to the current process** ("resize this image", "send this email now-ish"). For work that must reliably happen later, publish an [outbox integration event](/docs/capabilities/events/backends) — durable, cluster-executed, at-least-once — or wait for the durable one-shot store planned as ADR-0025 phase 2, which inverts the placement model (the receiving node records the job; whichever node claims it at due time executes it). See [Execution semantics & positioning](/docs/capabilities/scheduling/semantics) for the full decision matrix. ## JobId vs. RunId [#jobid-vs-runid] These two identifiers serve different purposes: * **`JobId`** identifies the *logical* runtime job. `CancelJobAsync(jobId, ct)` is the user-facing cancellation API: it cancels a queued job, a waiting retry attempt, or the active attempt without the caller needing to know the current state. * **`RunId`** identifies *one* scheduler attempt, for diagnostics and snapshots. With [deferred retry](/docs/capabilities/resilience), each attempt gets a new `RunId` but keeps the same `JobId`. `CancelRunAsync(runId, ct)` targets one concrete attempt — use it for operator/diagnostic workflows acting on a specific run shown in a snapshot. Job code can also request cancellation through `IScheduledJobContext.RequestCancellation()`. ## Resilience for runtime jobs [#resilience-for-runtime-jobs] Runtime jobs can opt into scheduler-deferred retry, which releases scheduler concurrency between attempts and exposes `WaitingRetry` status — the right model when another handler needs to observe progress. See [Resilience](/docs/capabilities/resilience#scheduler-resilience) for `EnqueueAsync` with a policy reference and `ScheduledJobResilienceMode.DeferredRetry`. # Schedules (/docs/capabilities/scheduling/schedules) Every schedule-bearing method sets exactly one of `FixedRate`, `FixedDelay`, `Cron`, or an `InitialDelay`-only one-time startup schedule. The authoring API is intentionally **string-based**. ## Duration literals [#duration-literals] Use compact duration literals or invariant `TimeSpan` text: ```text "1000ms" "1s" "15m" "6h" "1d" "00:00:01" ``` There are no numeric `TimeUnit`-style variants — string values are the single API, because the same property must support literals *and* configuration placeholders. ## Schedule properties [#schedule-properties] | Property | Meaning | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `FixedRate` | Grid-aligned interval between due times. Long runs or host pauses skip missed slots instead of producing a catch-up burst. | | `FixedDelay` | Delay measured from completion of one occurrence to the due time of the next. Matches polling loops that should wait after each pass. | | `Cron` | Five-field or six-field cron expression. Six fields include seconds; five-field Unix syntax defaults seconds to `0`. | | `InitialDelay` | Optional startup delay for `FixedRate` / `FixedDelay`. Not valid with `Cron`. | | `RunOnStart` | Whether an interval job is due immediately at host start. Defaults to `true`; not valid with `Cron`. | | `TimeZone` | Optional time zone id for cron evaluation. Defaults to UTC. | | `Enabled` | Boolean literal or placeholder evaluated before every occurrence. | | `Group` | Optional serialization key for jobs that share an external resource. | | `Overlap` | What to do when the same job already has an active occurrence. Defaults to `Skip`. | | `MisfirePolicy` | What to do when a grid occurrence is so late that later ones are also due. Defaults to `FireOnce`. | | `MaxConcurrentRuns` | Job-local cap when `Overlap = AllowConcurrent`. `0` means no job-local cap. | | `Placement` | `JobPlacement.Cluster` (default — one node per occurrence when a coordinator is registered) or `EveryNode`. See [Multi-node coordination](/docs/capabilities/scheduling/multi-node). | See [Overlap & misfire](/docs/capabilities/scheduling/overlap-and-misfire) for `Group`, `Overlap`, `MisfirePolicy`, and `MaxConcurrentRuns` in detail. ## Examples [#examples] ```csharp [ScheduledJob( "mailbox.poll", FixedDelay = "${Mailbox:PollingInterval:-15m}", Group = "mailbox", Enabled = "${Mailbox:Enabled:-false}", Overlap = ScheduledJobOverlap.Skip)] public async ValueTask PollAsync(CancellationToken ct) { await mailboxProcessor.PollAsync(ct); } [ScheduledJob( "reports.daily", Cron = "0 0 3 * * *", TimeZone = "Europe/Vienna")] public async ValueTask RunDailyReportsAsync(CancellationToken ct) { await reports.RunDailyAsync(ct); } [ScheduledJob("warmup.searchIndex", InitialDelay = "10s")] public async ValueTask WarmSearchIndexAsync(CancellationToken ct) { await searchIndex.WarmAsync(ct); } ``` ## Disabling a cron trigger [#disabling-a-cron-trigger] Use `Cron = "-"` to disable a cron trigger (matching Spring's disabled-cron sentinel). This is most useful with a placeholder default: ```csharp [ScheduledJob("reports.daily", Cron = "${Reports:DailyCron:--}")] public async ValueTask RunDailyReportsAsync(CancellationToken ct) { await reports.RunDailyAsync(ct); } ``` ## Configuration placeholders [#configuration-placeholders] Placeholders use Spring-style syntax and are re-resolved for every recurring occurrence: | Placeholder | Behavior | | ----------------------- | ---------------------------------------------------------------------------- | | `${Jobs:Interval}` | Resolve `Jobs:Interval`; throw during schedule resolution if not configured. | | `${Jobs:Interval:-15m}` | Resolve `Jobs:Interval`; use `15m` when not configured or blank. | If a previously valid schedule later becomes invalid, the scheduler logs the error and keeps the last valid schedule — the recurring chain does not die while configuration is being fixed. ## Job references [#job-references] Generated registries also emit job references so admin/manual-run code does not repeat string literals: ```csharp var jobName = MyAppApplicationScheduledJobRegistrationJobReferences.ReportsDaily.Name; ``` # Execution semantics & positioning (/docs/capabilities/scheduling/semantics) This page is the decision guide: what the Elarion scheduler guarantees today, what it deliberately does not, and how it compares to dedicated job systems — so you can pick the right tool per workload instead of discovering the semantics in production. **Positioning.** Elarion's defaults target small-to-mid deployments — roughly **1–10 nodes, vertical-first, on the one PostgreSQL the application already runs**. Within that tier the shipped defaults are designed to just work. Beyond it, the scheduler's seams (`IScheduledOccurrenceCoordinator` today, the durable job store planned in ADR-0025 phase 2) are the supported path to a different strategy — including a dedicated job engine — without changing your job code. The defaults will not grow configuration surface to chase larger tiers. ## Where runs what — and what survives [#where-runs-what--and-what-survives] | Work type | Declared via | Executes on | Survives node restart | Survives full-cluster restart | Duplicate protection | | ------------------------------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------ | ----------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | Recurring **cron** | `[ScheduledJob(Cron = "…")]` | Whichever node wins the occurrence claim | Yes — the chain is re-derived at start | Future occurrences yes; occurrences due **during** the downtime are not fired on restart | Exactly one node per occurrence ([exact-slot claim](/docs/capabilities/scheduling/multi-node)); at-most-once if the winner crashes mid-run | | Recurring **fixed-rate / fixed-delay** | `[ScheduledJob(FixedRate = "…")]` / `[ScheduledJob(FixedDelay = "…")]` | Whichever node wins the window claim | Yes — chain restarts with the process | Same as cron | At most one run per interval cluster-wide (window claim) | | Recurring, **`Placement = EveryNode`** | `[ScheduledJob(..., Placement = JobPlacement.EveryNode)]` | **Every node**, uncoordinated | Yes — chain restarts with the process | Same as cron | None, by design (process-local state must update everywhere) | | **One-time startup** | `[ScheduledJob(InitialDelay = "…")]` (no recurrence property) | **Every node**, at process start | Runs again on each start — that is its contract | n/a | None, by design (per-node startup work) | | **Runtime one-off** | `IJobScheduler.EnqueueAsync` / `ScheduleAsync` | **The node that accepted the call** — no other node knows the job exists | **No — lost** | No — lost | Trivially at-most-once (only one node holds it) | | Durable "run this later" today | Outbox [integration event](/docs/capabilities/events/backends) | Whichever node's delivery worker claims the lease | **Yes** | **Yes** | At-least-once — consumer must be idempotent | Four consequences worth internalizing: * **Recurring jobs are a *suppression* model, not a *guarantee* model.** Coordination ensures an occurrence never runs twice; it does not ensure it runs at all. A winner that crashes mid-run is not re-executed elsewhere (the other nodes have already moved past that occurrence), and a full cluster outage over 03:00 means the 03:00 job simply did not happen. Jobs whose work must not be lost should re-derive it from state (as the framework's own sweepers do — a purge that missed a pass simply purges more next pass) or be `[Idempotent]`-guarded and re-triggerable. * **Runtime one-offs are node-affine and volatile.** `ScheduleAsync(payload, tomorrow)` enqueues into the accepting process's memory: a deploy tonight silently discards it, and `CancelJobAsync` / inspection only answer on the node that holds the job. Use runtime one-offs for short-lived, loss-tolerable background work anchored to the current process ("resize this image", "send this email now-ish"). For anything that must survive until later, publish an **outbox event** — it is the durable, cluster-executed primitive that exists today. * **Jobs that maintain process-local state must opt out of coordination.** A "refresh the in-memory lookup table every 5 minutes" job under cluster coordination means one node refreshes and the rest serve stale data — silently. Declare it `Placement = JobPlacement.EveryNode` and every node runs every occurrence, coordinator or not. Rule of thumb: *if the job's output lives in process memory, it is `EveryNode`; if it lives in shared state, it is `Cluster` (the default).* And when the in-memory thing mirrors shared changing state that has a change feed, prefer push over polling — watch it (the settings `IChangeToken` pattern) instead of scheduling a per-node refresh. * **One-time startup jobs multiplying per node is a feature**, not a missing coordination case: cache warm-up and local initialization are meant to run everywhere. Cluster-wide "once ever" work belongs behind an [`[Idempotent]` handler](/docs/concepts/idempotency). ## Scenario walkthroughs [#scenario-walkthroughs] **A deploy replaces node A while the 03:00 cron is due.** Node B (still up) computes 03:00 itself, wins the claim, runs the job. Nothing to fail over; work migrates per occurrence. **The winner crashes halfway through the job.** The occurrence is spent (at-most-once). The 04:00 occurrence fires normally on any node. If half-done work is unacceptable, make the job idempotent and derive its work from state so the next occurrence completes it. **The claims database is unreachable at fire time.** The node **fails closed**: it skips the occurrence (recorded as a `claimed-elsewhere` skip with an error log) rather than running unconfirmed — running anyway would reintroduce the duplication coordination exists to prevent, and a job that needs the database would fail anyway. The next occurrence retries. **The whole cluster is down 02:50–03:10.** The 03:00 occurrence is not fired on restart — each node re-derives its schedule from *now*. This is the most significant gap versus Quartz's persistent triggers; closing it (a durable last-completed-occurrence per job, enabling catch-up on restart) is part of ADR-0025 phase 2. **A handler schedules `ScheduleAsync(payload, +2h)` and its pod is recycled at +1h.** The job is gone, silently. This is documented behavior today and the core motivation for phase 2's durable one-shots (below). Until then: outbox event. ## What phase 2 adds (and changes) [#what-phase-2-adds-and-changes] [ADR-0025](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0025-distributed-scheduler-coordination.md) phase 2 — designed, not yet implemented — turns runtime one-offs into rows: `ScheduleAsync` records the serialized payload + due time, and every node's scheduler claims due rows with an outbox-style lease. That **inverts the placement model**: the receiving node merely records the job, and *whichever node claims it at due time executes it*. Jobs survive restarts and deploys, retries persist across processes, cancellation and inspection become cluster-wide — and semantics shift from at-most-once to **at-least-once** (an expired lease is reclaimed), so durable one-offs should be idempotent. Immediate `EnqueueAsync` work is expected to stay in-memory by default (the caller's node is demonstrably alive; a database round-trip per fire-and-forget is real overhead), with durability as an opt-in. ## Versus dedicated job systems [#versus-dedicated-job-systems] | | Elarion scheduler | Quartz.NET (clustered) | Hangfire | TickerQ | | ------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------- | | Coordination | Per-occurrence claim rows (PK fence + advisory lock) | Cluster-wide DB locks (`QRTZ_LOCKS`, `SELECT … FOR UPDATE`) | Competing workers over shared storage; distributed locks for recurring | Per-job owner row (EF Core row locks), optional Redis heartbeats | | Recurring semantics | Exactly one node per occurrence; at-most-once on crash | Near exactly-once; **recovers occurrences missed during full downtime** | At-least-once (invisibility timeout re-runs) | Lease per job, retry on failure | | Durable one-offs | Not yet (phase 2); use the outbox | Yes (persistent triggers) | Yes (its core competency) | Yes | | Retry history / dashboard | Inspector snapshot + telemetry | Minimal built-in | Rich dashboard | Dashboard (commercial hub emerging) | | Reflection / AOT | Source-generated invocation, AOT-clean | Reflection + serialized type names | Expression-tree serialization | Source-generated, reflection-free | | Extra moving parts | None — your Postgres | `QRTZ_*` schema to operate | Storage + server/worker topology | EF Core schema (+ optional Redis) | When a **dedicated system is the right call** — reach for it without guilt, beside or beneath Elarion: * You need **queue-style background processing at volume** (thousands of enqueued jobs, competing consumers, per-job retry dashboards): that is Hangfire's home turf; run it *beside* Elarion rather than through it. * You need **missed-occurrence recovery after full downtime today** (regulatory "must run once per calendar day, even if we were down at the scheduled time"): Quartz's persistent triggers do this now; Elarion plans it for phase 2. * You are **beyond the 1–10 node tier** or need cross-region scheduling: replace the coordination through the seams instead of stretching the default. When the **Elarion default is the right call**: your jobs are the application's own recurring housekeeping and business rhythms (reports, digests, purges, reconciliations, pollers) on a small-to-mid cluster, you want them AOT-safe and typed with zero extra infrastructure, and duplicate suppression plus fail-closed behavior matches how you already write idempotent, state-derived jobs. # Serialization (/docs/capabilities/serialization) Elarion uses `System.Text.Json` source-generated metadata so serialization is AOT-friendly and follows module boundaries. Each module contributes its own `JsonSerializerContext`, and the framework composes them into **one canonical `JsonSerializerOptions`** that every subsystem — JSON-RPC, MCP, idempotency, caching, the outbox, and settings — reads through the `IElarionJsonSerialization` accessor. You configure the JSON type context **once**; you no longer build or thread `JsonSerializerOptions` into each subsystem. See [ADR-0023](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0023-canonical-json-serialization.md) for the design. ## Per-module JSON contexts [#per-module-json-contexts] Each module declares a source-generated context for its request/response and nested DTO types: ```csharp using System.Text.Json.Serialization; namespace MyApp.Application.Modules.Clients; [JsonSerializable(typeof(GetClient.Query))] [JsonSerializable(typeof(GetClient.Response))] [JsonSerializable(typeof(CreateClient.Command))] [JsonSerializable(typeof(CreateClient.Response))] public sealed partial class ClientsJsonContext : JsonSerializerContext; ``` List each handler's request and response type. A type they reach through a property, a type argument, an array element or `[JsonDerivedType]` gets its metadata with them and needs no line of its own. Handlers usually nest their `Query`/`Command` and `Response`, so two of them share a simple name; give those a `TypeInfoPropertyName` (`[JsonSerializable(typeof(GetClient.Response), TypeInfoPropertyName = "GetClientResponse")]`). The file is written by hand: a source generator cannot write it, because System.Text.Json's generator does not see attributes another generator emits. The build checks it instead. `ELRPC016` names a `[Handler]` whose request or response type no context of the assembly lists or reaches, at the handler, before the first call or the schema export fails on it. It is a suggestion by default, because a host that serves a handler over HTTP only, binding its request from the route and the query string, rightly lists neither. An application whose handlers are called over JSON-RPC makes it a warning (or an error) in `.editorconfig`: ```ini [*.cs] dotnet_diagnostic.ELRPC016.severity = warning ``` The module exposes it through `GetJsonTypeInfoResolver()`: ```csharp public static IJsonTypeInfoResolver GetJsonTypeInfoResolver() => ClientsJsonContext.Default; ``` ## The canonical serializer [#the-canonical-serializer] `IElarionJsonSerialization` (in `Elarion.Abstractions.Serialization`) is the accessor for the one framework-wide `JsonSerializerOptions`. It materializes the options **once** from a composed `ElarionJsonOptions` and freezes them (`MakeReadOnly()`) on first use, then exposes `Options`, `GetTypeInfo()`, and `GetTypeInfo(Type)`. Subsystems depend on this accessor — Elarion deliberately registers **no bare `JsonSerializerOptions`** in DI, so it never collides with a host's own (ASP.NET Core / MVC) registration. The options are **composed** from contributions, in order (first-match-wins): 1. **Transport envelope contexts** — `AddElarionJsonRpc` / `AddElarionMcp` insert their envelope context first. 2. **Module DTO contexts** — a module's generated `ConfigureDefaultServices` contributes its own `GetJsonTypeInfoResolver()`, and the generated `AddElarion(configuration)` contributes every enabled module's again (gated by `Modules:{Name}:Enabled`). The same resolver instance composes into the chain **once**. 3. **Host extras** — anything you add via `ConfigureElarionJson`. 4. **The framework context** — `ElarionFrameworkJsonContext`, seeded automatically (see below). It is appended last *unless* a host contributed that same instance earlier, in which case it stays where the host put it — the chain composes each resolver instance once. Because the module's context rides along with its own registration, **composing a module is self-contained**: a test host (or any assembly that cannot reference the host's generated `ElarionBootstrapper` without inverting the dependency) gets the module's JSON metadata by calling that module's registration — no hand-written `ConfigureElarionJson(o => o.TypeInfoResolvers.Add(MyModule.GetJsonTypeInfoResolver()))`. Contribute a **stable resolver instance** (a generated context's `.Default` singleton is one) so the duplicate collapses; a freshly constructed resolver per contribution is a distinct instance and lands in the chain repeatedly. The transport serializes with these composed options — **not** with any `JsonSerializerOptions` a host hands to ASP.NET Core / MVC. So a JSON-RPC error is written under the resolver chain above (`JsonRpcJsonContext` envelope + the module contexts + the framework error context), independent of the host's own JSON setup. Register your DTO/error-data types through `ConfigureElarionJson` (or a module context), not on a host-built `JsonSerializerOptions`. ### Enum members hold declared values [#enum-members-hold-declared-values] The exported schema lists an enum's member names. System.Text.Json's enum converters also read any number of the underlying type, a numeric string and a comma list, so `"kind": 99` would arrive as a value no member has. The canonical options refuse it: once an object is read, every member whose type is an enum, a nullable enum, or an array, list or dictionary of them must hold a declared member (for a `[Flags]` enum, a combination of declared members), or the read fails. Over a transport that is a [refused request body](/docs/reference/result-and-errors#a-refused-request-body) naming the member, so a handler needs no `Enum.IsDefined` check. A declared value is accepted however it is written (`2`, `"cash"`). The check applies to everything read through the canonical options, stored JSON included. ### Shared-kernel types [#shared-kernel-types] Value types every module uses (a record reference, a money amount) live in the shared kernel, outside every module. They need no entry in each module's context: a source-generated context generates the metadata of every type its listed types reach, and a type it never reaches is served by the next resolver in the chain. When a shared type is also serialized on its own (an error payload, a polymorphic base), give it **one** context in the shared kernel and contribute that context once, with a stable instance: ```csharp [JsonSerializable(typeof(RecordRef))] [JsonSerializable(typeof(Money))] public sealed partial class SharedKernelJsonContext : JsonSerializerContext; builder.Services.ConfigureElarionJson(o => o.TypeInfoResolvers.Add(SharedKernelJsonContext.Default)); ``` The chain composes each resolver instance once, however many times it is contributed, so a module's `ConfigureServices` may contribute it too (for a test host that composes only that module). A shared type listed in several contexts needs a `TypeInfoPropertyName` only when two types *in the same context* share a simple name. ### Framework types (`ElarionFrameworkJsonContext`) [#framework-types-elarionframeworkjsoncontext] Some framework-owned types must be serializable but are **not statically reachable** from your `[JsonSerializable]` roots, so no module/host context would ever register them. The canonical case is a payload behind a polymorphic `object` slot: `AppError.Data` is typed `object`, so when a failed `Result` is serialized (for example the JSON-RPC error object) `System.Text.Json` dispatches on the runtime type and needs a `JsonTypeInfo` for each concrete payload — which the source generator never pulls into a module context because the `object` breaks static reachability. `ElarionFrameworkJsonContext` holds these types (currently `ValidationErrorData`, produced by `AppError.Validation(message, errors)`, plus the idempotency `StoredResult` replay envelope, the `AppError` it carries, and `ElarionFile`) and is **seeded into the canonical resolver chain automatically** — so a validation failure serializes under source generation with **no per-app registration** and no reflection, even on an AOT-strict host. Payloads you attach yourself (via `AppError.Validation(message, data)` / `AppError.BusinessRule(...)`) are your own types, so they still belong in your module/host context. So a typical host composes nothing by hand: ```csharp builder.Services.AddElarion(builder.Configuration); // contributes module contexts + registers the accessor builder.Services.AddElarionJsonRpc(ElarionBootstrapper.RegisterHandlers); builder.Services.AddElarionMcp( builder.Configuration.GetMcpMetadata(), ElarionBootstrapper.RegisterHandlers, o => o.ServerName = "MyApp"); ``` ### Customizing the options [#customizing-the-options] Use `ConfigureElarionJson` to change naming/knobs or add an extra resolver — contributions accumulate across calls and layers: ```csharp builder.Services.ConfigureElarionJson(o => { o.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower; // default is CamelCase o.TypeInfoResolvers.Add(SomeExtraContext.Default); }); ``` `ElarionJsonOptions` also exposes `PropertyNameCaseInsensitive`, `DefaultIgnoreCondition`, a `PostConfigure` escape hatch (converters, a custom encoder), and `EnableReflectionFallback` (below). Resolution is first-match-wins, and transport envelope contexts insert themselves at the front of `TypeInfoResolvers` when they register — so an entry the host adds there can never beat them for a type they also cover. To override how such a type serializes, use `OverrideTypeInfoResolvers`, which is composed ahead of every contributed resolver: ```csharp builder.Services.ConfigureElarionJson(o => o.OverrideTypeInfoResolvers.Add(MyOverridesJsonContext.Default)); ``` Schema export reads the same accessor, so the exported JSON-RPC schema matches exactly what the server serializes. ## AOT considerations [#aot-considerations] The canonical options are **AOT-strict by default**: no reflection-based `DefaultJsonTypeInfoResolver` is added, matching the project-wide `JsonSerializerIsReflectionEnabledByDefault=false`. A type missing from every source-generated context therefore **throws** at runtime, surfacing a forgotten `[JsonSerializable(...)]` instead of silently reflecting (and being trimmed away under AOT). Register **every** command, query, response, and nested DTO type explicitly with `[JsonSerializable(...)]`. If you knowingly want a reflection fallback for development, opt in with `ConfigureElarionJson(o => o.EnableReflectionFallback = true)` — but leave it off for AOT/trimmed builds. # Spreadsheets (/docs/capabilities/spreadsheets) Applications export lists to Excel and import master data from it. `Elarion.Spreadsheets` puts one type between the file and the handler: a **spreadsheet record**, a `partial` class marked `[SpreadsheetRecord]`. Its properties are the columns of a worksheet, and a bundled source generator emits the code that writes a record as a row and reads a row into a record. There is no reflection, so an application that writes and reads spreadsheets still publishes with NativeAOT. | Piece | Role | | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `[SpreadsheetRecord]`, `[SpreadsheetColumn]`, `[SpreadsheetIgnore]`, `[SpreadsheetChoice]` | Declare the worksheet: its name, the columns, their headers, aliases, order, formats, widths, boolean labels and the extra spellings of enum members. | | `SpreadsheetWorkbook` | Writes records, or rows of a worksheet declared at run time (`SpreadsheetSheetDefinition`), as an `.xlsx` workbook, forward-only to a stream, an `ElarionFile` or an `ElarionStreamedFile`. | | `SpreadsheetReader` | Reads `.xlsx`, `.xlsb` and `.xls` workbooks into records, or into plain rows of typed cells. | | `SpreadsheetReadResult` | Every row with its cell texts, its errors and its record; the columns the file contains; the conversion to an `AppError`. | | `SpreadsheetOptions` | The read limits and the extra date formats and yes/no words, bound from configuration. | Why it is shaped this way, and what was rejected, is in [ADR-0108](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0108-spreadsheet-records.md). ## Getting started [#getting-started] ### Reference the package [#reference-the-package] ```bash dotnet add package Elarion.Spreadsheets ``` The package bundles its generator, so the reference is all a project needs. It depends on `Elarion.Abstractions`, the `Microsoft.Extensions` abstractions and, behind an internal interface, [Sylvan.Data.Excel](https://github.com/MarkPflug/Sylvan.Data.Excel) for reading. No type of that library appears in the public API. ### Declare a record [#declare-a-record] ```csharp using System.ComponentModel.DataAnnotations; using Elarion.Spreadsheets; namespace Shop.Crm; // inside the module that validates it [SpreadsheetRecord("Contacts")] public sealed partial class ContactRow { public required string Name { get; init; } [SpreadsheetColumn("E-mail", Aliases = ["Mail"])] [EmailAddress(ErrorMessage = "Keine gültige E-Mail-Adresse.")] public string? Email { get; init; } [Display(Name = "Customer since")] public DateOnly? CustomerSince { get; init; } [SpreadsheetColumn(Format = "#,##0.00")] public decimal? Balance { get; init; } [SpreadsheetColumn("Newsletter", TrueLabel = "Ja", FalseLabel = "Nein")] public bool Newsletter { get; init; } public ContactKind Kind { get; init; } [SpreadsheetIgnore] public Guid InternalId { get; init; } } public enum ContactKind { [Display(Name = "Customer")] Customer, [Display(Name = "Supplier")] Supplier, } ``` ### Register the reader [#register-the-reader] Writing needs no registration. Reading does, because the reader validates each row through the scoped request validator: ```csharp builder.Services.AddElarionValidation(); // when a record carries validation attributes builder.Services.AddElarionSpreadsheets(builder.Configuration.GetSection(SpreadsheetOptions.SectionName)); ``` `AddElarionSpreadsheets` registers `SpreadsheetReader` as a scoped service and binds `SpreadsheetOptions` with the configuration-binding source generator, so it stays trimming- and NativeAOT-safe. ## Records and columns [#records-and-columns] Every public instance property with a getter is a column, in declaration order. A property's header is the name given in `[SpreadsheetColumn]`, else its `[Display(Name)]`, else the property's name. The worksheet's name is the one given in `[SpreadsheetRecord]`, else the type's name. | Property type | Written as | Read from | | -------------------------------------------- | ----------------------------------------------------- | -------------------------------------------------------------------- | | `string` | a text cell, never a formula, whatever it starts with | any cell, as its text | | integral types, `float`, `double`, `decimal` | a number cell | a number cell, or text by the [lenient rules](#values-typed-by-hand) | | `bool` | a boolean cell, or its labels as text | a boolean cell, a number, a yes/no word, its labels | | `DateTime`, `DateOnly`, `TimeOnly` | a date cell, as its date and time whatever its `Kind` | a date cell, or text by the lenient rules | | `DateTimeOffset` | ISO 8601 text with its offset | ISO 8601 text that states an offset, only | | `Guid` | text | text | | an enum | its member's `[Display(Name)]`, else its name | the label, the name or an alias, ignoring case | Nullable forms of all of these are supported. Requiredness comes from nullability, as everywhere in Elarion: an empty cell reads as `null` for a nullable property and is an error for a non-nullable one. A get-only (computed) property is written and never read, which covers a derived export column. Any other property type fails the build (`ELSHEET001`); mark it `[SpreadsheetIgnore]` or map a text property and convert it in the handler. An enum member can also read from extra spellings, such as an older label, a word typed without umlauts or a short form. `[SpreadsheetChoice(Aliases = …)]` on the member lists them; they match like the label and the name, ignoring case and surrounding white space, but they are never written and never offered in the dropdown list: ```csharp public enum EnergySource { [Display(Name = "Erdgas")] [SpreadsheetChoice(Aliases = ["gas", "naturalgas"])] NaturalGas, [Display(Name = "Wärme")] [SpreadsheetChoice(Aliases = ["waerme"])] Heating, } ``` A file holding `gas`, `GAS ` or `Erdgas` reads as `NaturalGas`, and `waerme` as `Heating`; written cells and the dropdown show only `Erdgas` and `Wärme`. When two members of one enum share a label, name or alias ignoring case, the build fails (`ELSHEET008`). An alias equal to its own member's label or name, or an empty one, is ignored. The generator also emits a nested `Columns` class with one `SpreadsheetColumn` per column, for example `ContactRow.Columns.Email`. Handlers use these constants to ask about a column or to add an error to it, never a header string. `[SpreadsheetColumn]` sets: | Parameter | Meaning | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `header` (constructor) | The header text. | | `Order` | The column's position; columns without one keep their declaration order. | | `Format` | The number format of a number or date column, such as `#,##0.00` or `yyyy-mm-dd hh:mm`. | | `Width` | The width in characters; without it, the column is as wide as its header and the values of the first 200 records, at most 80. | | `Aliases` | Older headers that still read as this column. When a file carries both, the column's own header wins and the alias column is ignored. | | `TrueLabel`, `FalseLabel` | Both together, on a boolean only: the texts written for it, offered as a dropdown and read besides the usual yes/no words. | | `Choices` | On a `string` only: `nameof` a static field or property of the record that holds the labels offered as a dropdown, such as labels loaded from data or a subset of an enum. | | `StrictChoices` | With `Choices`: reading accepts only those labels, ignoring case, and reports any other text as `invalid_value` with the labels as `AllowedValues`. | ### Dropdown labels that are data [#dropdown-labels-that-are-data] An enum column offers its members. When the labels are data rather than an enum (a catalog's labels, a subset of a domain enum, a yes/no column that older files fill with free text), point a `string` column at a static `IReadOnlyList` of the record with `Choices`: ```csharp [SpreadsheetRecord("Contacts")] public sealed partial class ContactRow { public static IReadOnlyList ChannelLabels => ChannelCatalog.Labels; [SpreadsheetColumn("E-mail 1 label", Choices = nameof(ChannelLabels))] public string? EmailLabel { get; init; } [SpreadsheetColumn("Platform", Choices = nameof(ChannelLabels), StrictChoices = true)] public string? Platform { get; init; } } ``` The column is a choice column: it writes its value as text and offers the list as a dropdown, as an enum column does. The list is read once, when the record is first written or read. Reading a column without `StrictChoices` takes any text, so an older file with free text still imports; with `StrictChoices` a value must be one of the labels and reads as the label is spelled. The member must be static, public or internal, and of a type that is or implements `IReadOnlyList`, such as `string[]`; anything else fails the build (`ELSHEET009`). ## Export [#export] ### A small file for any transport [#a-small-file-for-any-transport] `SpreadsheetWorkbook.ToFileAsync` writes the workbook into memory and returns an [`ElarionFile`](/docs/capabilities/transports/http-endpoints#files-downloads-and-uploads) with the `.xlsx` content type. HTTP serves it as a download, and the JSON surfaces carry it as their base64 envelope: ```csharp [Handler("contacts.export")] [HttpEndpoint("contacts/export")] public sealed class ExportContacts(CrmDbContext db) : IHandler> { public sealed record Query : IQuery; public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var contacts = await db.Contacts.AsNoTracking() .Select(c => new ContactRow { Name = c.Name, Email = c.Email, Kind = c.Kind }) .ToListAsync(ct); return await SpreadsheetWorkbook.ToFileAsync(contacts, "contacts.xlsx", cancellationToken: ct); } } ``` The same one line takes [worksheet options](#columns-a-caller-may-not-see) after the file name, such as footer rows or a column filter: `ToFileAsync(contacts, "contacts.xlsx", new SpreadsheetWorksheetOptions { … }, cancellationToken: ct)`. `SpreadsheetWorkbook.ToBytes(records)` writes the same workbook synchronously and returns its bytes, for code without an asynchronous context such as a test. It writes into memory from an `IEnumerable`, so it never waits and never blocks on a task; it also takes worksheet options, and a [run-time worksheet](#columns-known-only-at-run-time) as `ToBytes(sheet, rows)`. ### A large file, streamed [#a-large-file-streamed] An `ElarionFile` is held in memory. For an export that can be large, an HTTP-only handler returns a [streamed file](/docs/capabilities/transports/http-endpoints#streamed-files-http-only-endpoints): the workbook is written to the response body while the records come. The writer holds only the first 200 records, which it measures for the column widths, so the server's memory does not grow with the number of rows. ```csharp [HttpEndpoint("devices/{deviceId}/readings.xlsx")] public sealed class ExportReadings(ISqlSession db) : IHandler> { public sealed record Query(string DeviceId) : IQuery; public ValueTask> HandleAsync(Query query, CancellationToken ct) { IAsyncEnumerable rows = db.QueryUnbufferedAsync( $"{ReadingRow.Select} WHERE device_id = {query.DeviceId} ORDER BY recorded_at", ct); // ToSheetRows maps each ReadingRow to a [SpreadsheetRecord] ReadingSheetRow as it comes (an async iterator). return ValueTask.FromResult(Result.Success( SpreadsheetWorkbook.ToStreamedFile(ToSheetRows(rows), $"{query.DeviceId}.xlsx"))); } } ``` The records are enumerated when the response is written, after the handler's pipeline and transaction, inside the request's scope. They must not depend on anything that ends with the handler. The [EdgeTelemetry sample](https://github.com/swimmesberger/Elarion/tree/main/samples/EdgeTelemetry) has the complete handler, published with NativeAOT. ### Several worksheets, or any stream [#several-worksheets-or-any-stream] `SpreadsheetWorkbook.Create(stream)` starts a workbook on any writable stream (it need not be seekable). Each `AddWorksheetAsync` adds one worksheet, in the order written. The workbook is finished when it is disposed: ```csharp await using (var workbook = SpreadsheetWorkbook.Create(stream)) { await workbook.AddWorksheetAsync(contacts, cancellationToken: ct); await workbook.AddWorksheetAsync(bankAccounts, new SpreadsheetWorksheetOptions { Name = "Accounts" }, ct); } ``` `ToStreamedFile("customers.xlsx", async (workbook, ct) => …)` does the same into a response body, and `ToFileAsync("customers.xlsx", async (workbook, ct) => …)` into an `ElarionFile`. `SpreadsheetWorkbook.WriteAsync(stream, records)` is the one-worksheet shortcut. ### Columns a caller may not see [#columns-a-caller-may-not-see] `SpreadsheetWorksheetOptions` chooses the record's columns per call, by property name. `ExcludedColumns` leaves columns out and `IncludedColumns` writes only the ones it names; the others keep the record's order and close up. So a column that depends on a permission needs no second record: ```csharp var options = new SpreadsheetWorksheetOptions { ExcludedColumns = permissions.Holds(ElarionPermissions.Payments.Read) ? null : [nameof(InvoiceRow.PaidAmount)] }; await workbook.AddWorksheetAsync(invoices, options, ct); ``` A name that matches no property throws an `ArgumentException` before anything is written. The writer does not read `[VisibleWith]`: a spreadsheet record is written outside the handler pipeline that answers that attribute, so the handler decides with its `IPermissionChecker` and says so in the options. ### Totals and a second block below the records [#totals-and-a-second-block-below-the-records] `FooterRows` writes rows below the records. Each value takes the cell its own type needs, so the label of a total row can stand in a date column, and a second block of other columns can follow: ```csharp await workbook.AddWorksheetAsync(expenses, new SpreadsheetWorksheetOptions { FooterRows = [ ["Total", null, expenses.Sum(expense => expense.Amount)], [], ["Booked hours"], [new DateOnly(2026, 11, 3), 7.5, "Holiday"], ] }, ct); ``` A value of the column's kind takes the column's format: the total above shows as `#,##0.00` if the amount column declares that. Any other value takes its own default, so `Total` is a text cell even in a date column. Values follow the written columns from the first, after any filter, and a shorter row ends with empty cells. The dropdown lists stop above the footer rows. A reader reads footer rows as data rows, so give a worksheet meant for importing again none. ### A title above the header, and hidden worksheets [#a-title-above-the-header-and-hidden-worksheets] `TitleRows` writes rows above the header row, typed as footer rows are, for a title, the period an export covers or the account it is for. The header row moves down by their number and still stays in place while scrolling, together with the title; the dropdown lists start below it: ```csharp await workbook.AddWorksheetAsync(bookings, new SpreadsheetWorksheetOptions { TitleRows = [["Booked hours, November 2026"], ["Employee", employee.Name], []] }, ct); ``` The reader takes the first non-empty row as the header row, so read such a worksheet back with `new SpreadsheetWorksheetSelection { HeaderRow = 4 }`, the row number the spreadsheet shows for the header. `Hidden = true` writes a worksheet that the spreadsheet application lists under "Unhide" instead of as a tab, such as lookup values another worksheet refers to. The workbook opens on its first visible worksheet, and a reader skips hidden worksheets. A workbook needs one visible worksheet: disposing one whose worksheets are all hidden throws an `InvalidOperationException`. ### Columns known only at run time [#columns-known-only-at-run-time] When a worksheet's columns come from data, such as numbered slots (`E-mail 1` to `E-mail 4`) or columns that depend on a setting, a `[SpreadsheetRecord]` class would repeat that schema. A `SpreadsheetSheetDefinition` declares the worksheet at run time instead, with the same header, formats, widths and dropdown lists: ```csharp var sheet = new SpreadsheetSheetDefinition("Contacts", [ SpreadsheetColumnDefinition.Text("ID"), .. Enumerable.Range(1, 4).Select(slot => SpreadsheetColumnDefinition.Choice($"E-mail {slot} label", channelLabels)), SpreadsheetColumnDefinition.Number("Area", format: "#,##0.00"), SpreadsheetColumnDefinition.Date("Born", format: "dd.mm.yyyy") with { Width = 12 }, ]); await workbook.AddWorksheetAsync(sheet, contacts.Select(contact => (IReadOnlyList)contact.ToRow()), ct); ``` The factories are `Text`, `Number`, `Boolean`, `Date`, `DateTime`, `Time`, `Choice` and `General`. A `General` column holds text, numbers or both, such as a reference that is a number in one row and a code in the next: each value is written as its own type, and the column has no format of its own, so neither text nor numbers are forced into the other's format and a cell typed below the data stays the spreadsheet's "General". Each row is a list of values in column order, typed as footer values are: text, a boolean, a number, a date or time (`DateTime`, `DateOnly`, `TimeOnly`), a `DateTimeOffset`, a `Guid`, an enum (written as its name), or `null` for an empty cell. A value of another type, or a row with more values than columns, fails with a `SpreadsheetWriteException` naming the row. Rows may be an `IEnumerable` or an `IAsyncEnumerable` and stream like records. Because each value carries its own type, a definition also serves a worksheet of several blocks. A definition only writes; read such a worksheet back as [plain rows](#plain-rows) and match the headers with the same column list. `AddWorksheetAsync(sheet, rows, options, ct)` takes the same `SpreadsheetWorksheetOptions` as a record's worksheet: another `Name`, `TitleRows`, `FooterRows`, so a total row gets no dropdown, and `Hidden`. A column filter is refused with an `ArgumentException`, because the definition already decides its columns per call. ### What a written file looks like [#what-a-written-file-looks-like] * The header row is bold on a light fill with a thin bottom border, and stays in place while scrolling. * Numbers are number cells, dates are date cells, and booleans without labels are boolean cells. A date column without a `Format` uses the built-in format that the spreadsheet application shows in its user's own notation: `24.11.2026` in Austria, `11/24/2026` in the US. * Text is always a text cell. A value that starts with `=` shows as text and is never evaluated. Control characters that XML cannot carry are escaped and read back unchanged. * The same records give byte-identical files with the same package version on the same runtime and platform. * A value a spreadsheet cannot hold fails the write with a `SpreadsheetWriteException` that names the worksheet, the row and the column. Such values are text longer than 32,767 characters, a row beyond 1,048,576, a date before 1900-01-01, `NaN` and infinities. Two worksheets whose names are equal ignoring case fail the same way. `SpreadsheetWriteOptions` holds `DropdownRows` (2,000), `WidthSampleRows` (200) and `MaxColumnWidth` (80). ## Templates and dropdown lists [#templates-and-dropdown-lists] Writing no records produces a **template**: the header row, the column formats and widths, and the dropdown lists. An enum column offers its labels, and a boolean column with `TrueLabel`/`FalseLabel` offers both labels, on every written row and on at least the first 2,000 data rows, so rows a person adds keep their pickers. A list longer than the 255 characters a list formula holds moves to a hidden worksheet, so a sixty-member enum still offers every label. Text columns carry the text number format on the same rows. When a person types `01010` or a 16-digit reference into one, the spreadsheet application keeps it as text instead of turning it into a number. ```csharp return await SpreadsheetWorkbook.ToFileAsync(Array.Empty(), "contacts-template.xlsx", cancellationToken: ct); ``` ## Import [#import] ### Read an upload [#read-an-upload] A handler takes the uploaded file and injects `SpreadsheetReader`. A small upload arrives as an `ElarionFile`. A large one arrives as an [`UploadedFile`](/docs/capabilities/blob-uploads#passing-an-upload-to-a-handler), which the handler opens through `IUploadedFiles`. ```csharp [Handler("contacts.import")] [HttpEndpoint("contacts/import")] public sealed class ImportContacts(SpreadsheetReader reader, CrmDbContext db) : IHandler> { public sealed record Command : ICommand { public required ElarionFile Workbook { get; init; } } public sealed record Response(int Imported); public async ValueTask> HandleAsync(Command command, CancellationToken ct) { using var content = new MemoryStream(command.Workbook.Bytes.ToArray(), writable: false); var result = await reader.ReadAsync(content, cancellationToken: ct); if (result.HasErrors) return result.ToAppError("workbook"); foreach (var contact in result.Records) db.Contacts.Add(new Contact { Name = contact.Name, Email = contact.Email }); await db.SaveChangesAsync(ct); return new Response(result.Rows.Count); } } ``` The reader recognizes the format from the content, not the file name, and reads the first visible worksheet with its first non-empty row as the headers. `SpreadsheetWorksheetSelection` names another worksheet (ignoring case) or the header row, as the row number the spreadsheet shows. Columns match by header, ignoring case, surrounding whitespace and order. Columns no property maps are ignored. Empty rows produce nothing, and every other row keeps the row number the spreadsheet shows. A formula cell reads as its last calculated value and is never evaluated. Dates follow the date system (1900 or 1904) the workbook declares. One upload can hold several worksheets of different record types. `OpenAsync` reads the file once: ```csharp using var document = await reader.OpenAsync(content, cancellationToken: ct); var contacts = await document.ReadAsync(new() { Name = "Contacts" }, ct); var accounts = await document.ReadAsync(new() { Name = "Bank accounts" }, ct); ``` ### A preview: every row, then decide [#a-preview-every-row-then-decide] A read never throws because of what a file contains: it throws only on cancellation and on misconfiguration. Everything else is in the result, so a handler can show a preview before it saves anything. | Member | Meaning | | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `Rows` | Every data row read, each a `SpreadsheetRow`. | | `row.RowNumber`, `row.Worksheet` | Where the row is, as the spreadsheet shows it. | | `row.CellText(column)` | The text of the row's cell in that column, for a preview of a row that failed. | | `row.IsValid`, `row.Record` | Whether the row has no error, and then its record. `IsValid` tells the compiler that `Record` is set. | | `row.Errors`, `row.AddError(column, code, message)` | The row's problems; the handler adds its own. | | `FileErrors` | Problems with the file or its columns. Such a result holds no rows. | | `Errors`, `HasErrors` | All of them, the handler's included. | | `Records` | The records of the valid rows. | | `Contains(column)` | Whether the file has that column. | | `ToAppError(fieldPath, format, maxMessages)` | The errors as one `AppError.Validation`. | Every error of every row is reported, so a file with 500 broken rows returns 500 errors. The row limit bounds the result. Rules that need the database belong in the handler. It adds them to the row, and they are located and converted exactly like the package's own: ```csharp foreach (var row in result.Rows.Where(static row => row.IsValid)) { if (!knownKeys.Contains(row.Record.Key)) row.AddError(ContactUpdateRow.Columns.Key, "contacts.unknown_key", "No contact has this key."); } if (result.HasErrors) return result.ToAppError("workbook"); ``` `ToAppError("workbook")` returns a validation error keyed by the uploaded-file member, which the HTTP transport renders as a `400` problem with `errors.workbook`. Each message names the row, the column and the cell, such as `Row 13, E-mail (C13): Keine gültige E-Mail-Adresse.`. At most 100 messages are listed, plus one that counts the rest, so a broken large file does not become a multi-megabyte response. ### Validation [#validation] A record's DataAnnotations run on every row read, through the registered `IRequestValidator`, with the messages a handler request would get. A violation is an error with the code `validation` and the validator's message, located at its cell. `[SpreadsheetRecord]` makes the record a [validation root](/docs/concepts/validation#validating-outside-a-handler-request), so the record must lie in the namespace of a module (`ELVAL004` otherwise). Its metadata is registered while that module is enabled. An import is never silently unchecked. Reading a record that carries validation attributes throws an `InvalidOperationException` that names the cause when no validator holds its metadata, either because `AddElarionValidation()` is missing or because the record's module is disabled. ### Update only what the file states [#update-only-what-the-file-states] A column the file lacks is an error only when its property is not nullable. Otherwise its value reads as `null`, and `Contains` tells the handler that the file did not state it. An empty cell in a column the file has is a stated empty value. So one record serves both creating rows and updating them from a trimmed sheet: ```csharp var result = await reader.ReadAsync(content, cancellationToken: ct); var statesPhone = result.Contains(ContactUpdateRow.Columns.Phone); foreach (var row in result.Records) { var contact = contacts[row.Key]; contact.Name = row.Name; if (statesPhone) contact.Phone = row.Phone; // an empty cell clears it; a missing column leaves it alone } ``` ## Error codes and wording [#error-codes-and-wording] Every error is a `SpreadsheetError` with a stable `Code`, an English default `Message`, and the data needed to word it: `Worksheet`, `RowNumber`, `Header`, `CellReference`, `ExpectedKind`, `AllowedValues` and `Limit`. The codes are constants on `SpreadsheetErrorCodes`: | Code | When | Data | | ---------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------- | | `spreadsheet.unreadable` | The file is no workbook, or it is truncated, damaged or password-protected. | — | | `spreadsheet.too_large` | The workbook unpacks to more than `MaxUnpackedBytes`. | `Limit` | | `spreadsheet.too_many_rows` | The worksheet has more data rows than `MaxRows`. The rows before are kept. | `Limit` | | `spreadsheet.too_many_columns` | A plain-rows read meets more columns than `MaxColumns`. | `Limit` | | `spreadsheet.no_visible_worksheet` | Every worksheet is hidden. | — | | `spreadsheet.worksheet_not_found` | The named worksheet does not exist. | `Worksheet` | | `spreadsheet.column_missing` | The file lacks the column of a non-nullable property. | `Header` | | `spreadsheet.column_duplicated` | The file carries a mapped header twice. | `Header` | | `spreadsheet.required` | A non-nullable property's cell is empty. | the cell | | `spreadsheet.invalid_value` | A value does not convert. | the cell, `ExpectedKind`, and `AllowedValues` for a choice | | `validation` | A DataAnnotations rule failed. The message is the validator's. | the cell | A file-level error (the first seven) is the only error of its result. `too_many_rows` and `too_many_columns` keep the rows read before the limit; the other five leave the result without rows. To word errors in the application's language, pass a formatter that switches on the code and never parses a message: ```csharp return result.ToAppError("workbook", error => error.Code switch { SpreadsheetErrorCodes.ColumnMissing => $"Die Spalte „{error.Header}“ fehlt.", SpreadsheetErrorCodes.Required => $"Zeile {error.RowNumber}: „{error.Header}“ ist leer ({error.CellReference}).", SpreadsheetErrorCodes.InvalidValue when error.AllowedValues is { } allowed => $"Zeile {error.RowNumber}: erlaubt sind {string.Join(", ", allowed)} ({error.CellReference}).", SpreadsheetErrorCodes.TooManyRows => $"Höchstens {error.Limit} Zeilen.", _ => error.ToString(), // validation messages are already the application's own }); ``` An application's own codes follow the same `area.snake_case` form, such as `contacts.unknown_key`. ## Values typed by hand [#values-typed-by-hand] Cells that hold their own type read as that type. Text in a typed column is read by one rule that does not depend on the server's culture: * **Decimal and floating-point columns.** Spaces are ignored. When both `,` and `.` occur, the rightmost is the decimal mark. A separator that occurs more than once alone groups thousands in threes. A single `,` or `.` is the decimal mark. So `1.234,56`, `1,234.56`, `1234,56`, `1234.56` and `1 234,56` all read as 1234.56, `1.234.567` reads as 1234567, and `1.23.4` is an error. * **Integral columns.** Digits and an optional sign only. A number cell with a fraction or out of range is an error. * **Date and date-and-time columns.** ISO 8601, `d.M.yyyy` and `d.M.yy` (a two-digit year is in the 2000s), each with an optional `H:mm` or `H:mm:ss` time. `DateFormats` in the read options adds formats. * **Boolean columns.** Boolean cells, a number (`true` when not zero), `true`/`yes`/`x`/`1` and `false`/`no`/`0` ignoring case, the column's labels, and the `TrueWords`/`FalseWords` of the read options, such as `ja`, `j`, `nein`. * **`DateTimeOffset` columns.** Only ISO 8601 text that states an offset. A date cell or a text without an offset is `spreadsheet.invalid_value`, so an import never depends on the server's time zone. * **Number cells.** They read as the at most 15 significant digits a spreadsheet shows. A stored 1234.56 reads into a `decimal` as exactly 1234.56, and into a text column without an exponent, so a postal code stored as the number 1010 reads as `1010`. ## Plain rows [#plain-rows] A worksheet in a foreign layout, such as a bank's statement export with account details above its header, reads without a record. The result holds every non-empty row with its row number and its cells, and the application finds the header row itself: ```csharp var result = await reader.ReadRowsAsync(content, cancellationToken: ct); var header = result.Rows.First(row => row[0].Text == "Booking date"); foreach (var row in result.Rows.Where(row => row.RowNumber > header.RowNumber)) { if (row[0].TryGetDate(out var booked) && row[3].TryGetNumber(out var amount)) { /* … */ } } ``` Each `SpreadsheetCell` has a `Kind` (`Blank`, `Text`, `Number`, `Boolean`, `Date` or `Error`), its `Text`, and `TryGetNumber`, `TryGetDouble`, `TryGetBoolean` and `TryGetDate`. A number or date cell also carries the `NumberFormat` of the file, such as `#,##0.00 "€"` or `dd.mm.yyyy`, for a preview that shows a value the way the file does; `Text` stays invariant (`2026-11-24`, `1234.5`). Plain rows use the same format detection, worksheet choice, cell rules and limits as records, and they also stop at `MaxColumns`. A plain-rows read knows no header row, so `MaxRows` counts every non-empty row, the header row and any lines above it included: allow for them when the limit is meant for data rows. A workbook already in memory, such as an `ElarionFile`'s `Bytes`, reads synchronously with `reader.ReadRows(file.Bytes)`, or opens with `reader.Open(file.Bytes)` for several worksheets, without copying the bytes. ## Limits and options [#limits-and-options] A read buffers the upload, then refuses a zip-based workbook whose declared unpacked size exceeds the limit before it unpacks anything. It never processes a document type definition or resolves an external entity. | `SpreadsheetReadOptions` | Default | Meaning | | ------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `MaxUnpackedBytes` | 256 MiB | The largest unpacked workbook (`spreadsheet.too_large`). | | `MaxRows` | 100,000 | The most rows read; empty rows do not count. A record read counts the data rows below its header; a plain-rows read every non-empty row, header included (`spreadsheet.too_many_rows`). | | `MaxColumns` | 256 | The most columns of a plain-rows read (`spreadsheet.too_many_columns`). | | `DateFormats` | none | Extra .NET date formats for text in date columns, such as `M/d/yyyy HH:mm`. | | `TrueWords`, `FalseWords` | none | Extra yes and no words for boolean columns. | The application's defaults are `SpreadsheetOptions.ReadDefaults`, bound from the `Spreadsheets` section. A read can pass its own `SpreadsheetReadOptions` instead: ```json { "Spreadsheets": { "ReadDefaults": { "MaxRows": 20000, "TrueWords": [ "ja", "j" ], "FalseWords": [ "nein" ] } } } ``` The defaults fit the 1–10 node tier Elarion targets. A read holds the whole upload and its rows in memory, so keep `MaxRows` and the upload limit at what a person actually imports. ## Formats [#formats] | Format | Write | Read | | ------------------------------- | ----- | ----------------------------- | | `.xlsx` (Office Open XML) | yes | yes, Strict Open XML included | | `.xlsb` (Excel binary workbook) | — | yes | | `.xls` (Excel 97–2003) | — | yes | `.xlsx` is the format to hand out. `.xlsb` and `.xls` are read so that whatever a person saves can be uploaded. ## Out of scope [#out-of-scope] * Styling beyond the fixed header style, formulas, merged cells, images, charts, comments, hyperlinks, and data validation other than the dropdown lists of choice columns. * A record property whose type changes from row to row. Footer rows and run-time worksheets carry values of any type. * Writing `.xls` or `.xlsb`, and reading or writing CSV. * Password-protected workbooks, beyond reporting `spreadsheet.unreadable`. * Custom value converters. A computed get-only property covers an export, and a text property converted in the handler covers an import. * Numbered column groups ("Phone 1", "Phone 2") mapped to one collection property. * Deciding what an import does with a row (create, update, skip), references between worksheets, and committing all or nothing. Those are the application's. * Enumerating an import's rows one at a time without collecting them, and a spreadsheet error contract in the schema and the generated TypeScript client. ## Build-time checks [#build-time-checks] If a record builds, it maps. The generator reports `ELSHEET001`–`ELSHEET009` for an unsupported property type, a type that is not `partial`, duplicate headers or aliases, an invalid worksheet name, misused boolean labels, a struct or nested or generic type, a member that collides with the generated `Columns` or `SpreadsheetMapper`, two enum members that share a label, name or alias, and `Choices` that names no static `IReadOnlyList` of the record. See [Diagnostics](/docs/reference/diagnostics#elsheet--spreadsheet-records). # SQL mapping (/docs/capabilities/sql-mapping) Elarion's persistence story is EF-model-first, and an EF application keeps EF Core — that default is not in question. The gap is the **EF-free host**: an app published NativeAOT on raw Npgsql still needs to turn `DbDataReader` rows into records and records into parameters, per row type, by hand. `Elarion.Sql` is that tier's access half ([ADR-0058](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0058-aot-sql-row-mapping.md)), completing the pair with [migrations](/docs/capabilities/migrations) (ADR-0057, the schema half). It is chosen **by tier, not preference**: | Your app | Data access | | ------------------- | -------------------------------------------------------------------------- | | Uses EF Core | EF Core — see [Entity Framework Core](/docs/capabilities/entity-framework) | | EF-free / NativeAOT | **`Elarion.Sql`** — generated mappers over hand-written SQL | A runnable end-to-end host — NativeAOT publish, embedded migrations (TimescaleDB hypertable included), generated mappers, \~120–160 ms start to first response — is [`samples/EdgeTelemetry`](https://github.com/swimmesberger/Elarion/tree/main/samples/EdgeTelemetry). The core property: **if it builds, it maps**. A `[SqlRecord]` type gets an explicit generated mapper; a type without one has no mapper to call. There is no reflection twin to fall back to — an unmapped type, an unsupported property, a duplicate column are compile errors (`ELSQL001`–`ELSQL011`), never a runtime surprise. ## Quick start [#quick-start] A `[SqlRecord]` type is `partial` (the generator adds its self-mapping half; else `ELSQL010`): ```csharp using Elarion.Sql; [SqlRecord("orders")] public sealed partial record Order { public required Guid Id { get; init; } public required string CustomerName { get; init; } public string? Note { get; init; } public required OrderStatus Status { get; init; } // enums map via their underlying type public DateTimeOffset CreatedAt { get; init; } } ``` The generator emits `OrderSqlMapper : ISqlRowMapper` **and** makes `Order` self-mapping, so the query extensions resolve its mapper from the type — **no mapper argument**. In a handler, inject the scoped **`ISqlSession`** — the transaction-aware entry point (see [Transactions](#transactions-unit-of-work)); interpolated values become parameters, and `Order.Select` splices the generated `SELECT`-list with no `:raw`: ```csharp [Handler] public sealed class ListOrders(ISqlSession db) { public async ValueTask>> HandleAsync(ListOrdersQuery query, CancellationToken ct) { List orders = await db.QueryAsync( $"{Order.Select} WHERE status = {query.Status} AND customer_name IN {query.Names}", ct); return orders; } } ``` The other read shapes take the same interpolated SQL on the same session: ```csharp Order? one = await db.QueryFirstOrDefaultAsync($"{Order.Select} WHERE id = {id}", ct); ``` Write with the same self-mapping on the same injected session — no command/transaction/`BindParameters` ceremony: ```csharp await db.InsertAsync(order, ct); // one row await db.InsertManyAsync(orders, " ON CONFLICT DO NOTHING", ct); // batch, one transaction long open = await db.ExecuteScalarAsync($"SELECT count(*) FROM {Order.Table} WHERE status = {OrderStatus.Open}", ct); ``` ## What the generator emits [#what-the-generator-emits] Per `[SqlRecord]` type, a sealed `partial` `{Type}SqlMapper` **and** a self-mapping partial on the row: | Member | On | Purpose | | -------------------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Read` / `Read(reader, in Ordinals)` | mapper | One row → `T`. Ordinals resolve **by name once per result set**, then typed `GetFieldValue` per row — no name lookups, no boxing, no per-column `await`. | | `ReadAll` / `ReadAllAsync` / `ReadAllStreamAsync` | mapper | All rows → `List` (ordinals once), or an unbuffered `IAsyncEnumerable` stream. | | `BindParameters(command, row)` | mapper | One typed `DbParameter` per column, named like the column. `null` → `DBNull`. | | `TableName`, `Columns.*`, `Columns.All`, `Columns.AllParameters`, `Columns.AllAssignments`, `Insert`, `Select` | mapper | `const string`s for composing hand-written SQL (`AllAssignments` = the `UPDATE … SET` list; `Insert`/`Select` are clause-free — pure column enumeration, compose as consts, never a predicate). | | `Instance` | mapper | The cached singleton. | | `Order.SqlMapper`, `Order.InsertCommandText` | **row** | The self-mapping contract (`ISqlRecord`) the query extensions resolve `T.SqlMapper` through. | | `Order.Table`, `Order.Select` | **row** | Typed trusted `SqlStatement` fragments (`Verbatim`) — splice them into interpolations with no `:raw`; forgetting the marker is impossible. | One generated `AddElarionSqlMappers()` per assembly registers every mapper as an `ISqlRowMapper` singleton — a mapper is still a *value you pass around* (the explicit-mapper overloads remain for hand-written mappers of non-`[SqlRecord]` shapes). For JSON-column assemblies it also installs the canonical JSON accessor at startup (a hosted service), so a `[SqlJson]` host wires nothing extra. Conventions and knobs: * Names default to **snake\_case** (property `CreatedAt` → `created_at`; type `OrderLine` → table `order_line`, no pluralization guessed). Override with `[SqlRecord("orders")]` / `[SqlColumn("…")]`. * `[SqlIgnore]` excludes a property; get-only (derived) members are skipped automatically. * **Positional records** construct through their primary constructor; nominal records with `required`/`init` members through an object initializer — no parameterless-constructor requirement. * `[SqlJson]` maps a property as a JSON column through the canonical accessor's `JsonTypeInfo` ([serialization](/docs/capabilities/serialization), ADR-0023) — AOT-strict, one JSON config everywhere. Under `[assembly: UseElarionSql(Provider = SqlProvider.Npgsql)]` JSON parameters bind as `jsonb`. * Supported column types: the numeric/text/boolean primitives, `Guid`, `DateTime`, `DateTimeOffset`, `DateOnly`, `TimeOnly`, `TimeSpan`, `char`, `byte[]`, enums (underlying type), `Nullable` of all of these, and nullable reference types. Anything else: `[SqlJson]` or `[SqlIgnore]` — or `ELSQL001`. ## Safe SQL interpolation [#safe-sql-interpolation] `new SqlStatement($"…")` (and every query extension's `$"…"` overload) is the C#-native equivalent of jOOQ's plain-SQL templating tier: full SQL stays full SQL — window functions, CTEs, `ON CONFLICT`, any PostgreSQL feature — with injection safety enforced by the compiler, not by review: ```csharp SqlStatement where = new($"WHERE status = {status} AND id IN {ids}"); var page = await db.QueryAsync($"{Order.Select} {where} LIMIT {limit}", ct); ``` * A **scalar** hole binds as a `@pN` parameter — there is no string concatenation to get wrong. * A **collection** hole expands to a parenthesized parameter list for `IN`. An **empty** collection throws at build time: no SQL spelling keeps both `IN` (match nothing) and `NOT IN` (match everything) correct for the empty set, so guard the query instead of shipping silently wrong rows. * A **`SqlArray`** hole binds a whole collection as **one** array parameter — see [Array parameters](#array-parameters). * A **`SqlStatement`** hole splices as a fragment with its parameters renumbered — a reusable `WHERE` piece is just a value. A pure-literal fragment (`Verbatim`, `Order.Select`) inlines with no cost. * Trusted identifiers (a validated sort column) splice via **`SqlStatement.Verbatim(col)`** — never a raw `string`. There is no `:raw` format and no `SqlStatement(string)` constructor: a plain string interpolated into a query always binds as a parameter, so injection is structurally impossible. ### Array parameters [#array-parameters] Where SQL expects a single **array value** rather than a list — PostgreSQL's `= ANY(…)`, `<> ALL(…)`, and the array operators `@>`, `<@`, `&&` — wrap the collection in `SqlArray.Of(…)`: ```csharp long[] ids = [1, 2, 3]; var orders = await db.QueryAsync($"{Order.Select} WHERE id = ANY({SqlArray.Of(ids)})", ct); // renders … WHERE id = ANY(@p0) with @p0 = bigint[] {1, 2, 3} ``` The statement carries one parameter whatever the length (one cached plan), and an empty array is valid: `= ANY` matches nothing and `<> ALL` matches everything, both correct for the empty set. An existing `T[]` is bound by reference — leave it unmodified until the statement has executed; any other sequence is copied once when wrapped. `byte` elements are rejected, since a `byte[]` always binds as a scalar binary value. A bare collection in an array position — `WHERE id = ANY({ids})` — expands to an `IN` list and renders `= ANY((@p0, @p1, @p2))`, which PostgreSQL rejects at run time (*op ANY/ALL (array) requires array on right side*). The `ELSQL012` analyzer reports it at build time; write `IN {ids}` or `ANY({SqlArray.Of(ids)})`. Array parameters need a provider with array types. PostgreSQL binds the matching array type (`long[]` → `bigint[]`, `Guid[]` → `uuid[]`, …); `AddElarionPostgreSql(connectionString)` enables the array mappings its slim data-source builder leaves out, and a host that passes its own `NpgsqlSlimDataSourceBuilder`-built source calls `EnableArrays()` itself. Every other provider (SQLite included) fails with `NotSupportedException` when the statement is bound, before anything executes — use `IN {collection}` there. ### Optional filters without a query DSL [#optional-filters-without-a-query-dsl] `SqlWhere` is the answer to the dominant call-site shape — a list with optional filters — without a query builder. Accumulate parenthesized predicate fragments; it renders `WHERE (a) AND (b)` or nothing, so `WHERE 1=1` disappears and the *same* accumulator drives a page query and its `count(*)`: ```csharp var where = new SqlWhere(); where.And($"org_id = {orgId}"); if (status is not null) where.And($"status = {status}"); if (since is not null) where.And($"created_at >= {since}"); var page = await db.QueryAsync($"{Order.Select} {where} ORDER BY created_at DESC LIMIT {take}", ct); var total = await db.ExecuteScalarAsync($"SELECT count(*) FROM {Order.Table} {where}", ct); ``` Each predicate's interpolated values become parameters — the obvious thing to type is the safe thing. `SqlWhere` knows only the `WHERE`/`AND` joiners; `OR`, grouping, and joins are hand-written SQL inside a predicate fragment. Its build-path cost is a small per-call constant (\~2.4 KB for three predicates, zero per row); there is no cheaper *safe* way to build a dynamic `WHERE`. ## Reads and writes [#reads-and-writes] The query/write surface lives on **one receiver: `ISqlSession`** — a connection paired with its transaction intent. There is deliberately no raw-`DbConnection` or `DbDataSource` twin of these methods: a look-alike surface that skips transaction enlistment is exactly the silent-footgun class this tier removes. How you obtain the session states the semantics: * **In a handler**, inject the scoped `ISqlSession` — writes join the framework unit of work ([Transactions](#transactions-unit-of-work)). * **In a singleton-eligible handler** (no scoped dependencies, deliberately no unit of work), inject the singleton `ISqlDatabase` handle: `OpenSessionAsync` for per-call auto-commit, `BeginTransactionAsync` when several statements must commit together. * **Owning your own connection** — DI-free / NativeAOT hosts, tooling, tests — bridge with `AsSqlSession`, deciding the transaction **once at wrap time**: ```csharp // The default: a scoped handler injects ISqlSession — every read and write below runs on the // request's connection and joins its unit of work; the decorator commits or rolls back by Result. [Handler] public sealed class CloseOrder(ISqlSession db) { public async ValueTask HandleAsync(CloseOrderCommand command, CancellationToken ct) { await db.ExecuteAsync( $"UPDATE {Order.Table} SET status = {OrderStatus.Closed} WHERE id = {command.Id}", ct); return Result.Success(); } } // Singleton-eligible handler: one call through the seam, autonomous per-call semantics. // The receiver is ISqlDatabase — OpenSessionAsync lives on the handle, NOT on a data source. public sealed class ListOpenOrders(ISqlDatabase db) { public async ValueTask>> HandleAsync(Query query, CancellationToken ct) { await using var session = await db.OpenSessionAsync(ct); return await session.QueryAsync($"{Order.Select} WHERE status = {query.Status}", ct); } } // Atomic multi-write outside the unit of work: an owning transactional session — commit on it, // dispose without commit rolls back. No hand-assembled connection/transaction/wrap. await using var tx = await db.BeginTransactionAsync(ct); await tx.ExecuteAsync($"UPDATE {Account.Table} SET session_key = {key} WHERE id = {id}", ct); await tx.ExecuteAsync($"UPDATE {Ticket.Table} SET ticket = NULL WHERE account_id = {id}", ct); await tx.CommitAsync(ct); // Read first, then transact — on the SAME connection: OpenSessionAsync returns an ISqlOwnedSession, // and only that owning session can begin a deferred transaction (the scoped session's belong to the // unit of work). After commit/rollback the session continues autonomously. await using var session = await db.OpenSessionAsync(ct); var account = await session.QueryFirstOrDefaultAsync($"{Account.Select} WHERE id = {id}", ct); await using (var deferred = await session.BeginTransactionAsync(cancellationToken: ct)) { await deferred.ExecuteAsync($"UPDATE {Account.Table} SET session_key = {key} WHERE id = {id}", ct); await deferred.CommitAsync(ct); } // Only when you already own the connection (and maybe its transaction): wrap once — every write enlists. var owned = connection.AsSqlSession(transaction); ``` **Migrating a handler that injected `NpgsqlDataSource`/`DbDataSource` directly:** the whole change is the injected type — replace it with `ISqlDatabase` and open sessions instead of connections (`dataSource.OpenConnectionAsync` → `db.OpenSessionAsync`). `OpenSessionAsync` deliberately does not exist on `DbDataSource`: going through the handle is what lets tenant/replica routing apply. The wrap is a cheap non-owning view (disposing it disposes nothing); because the transaction is bound when the session is created — wrap, `BeginTransactionAsync`, or the framework unit of work — there is no per-call `transaction:` parameter anywhere: a write can never accidentally run outside the transaction its scope declared. Commit lives only on `ISqlTransaction` (and the unit-of-work scope), never on `ISqlSession` itself, so a scoped handler cannot commit the framework's transaction out from under the decorator. | Call | Shape | | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `QueryAsync($"…")` | many rows → `List` | | `QueryFirstOrDefaultAsync($"…")` | first row or `default` | | `QuerySingleOrDefaultAsync($"…")` | single row or `default`; **throws** on more than one | | `QueryUnbufferedAsync($"…")` | `IAsyncEnumerable` — unbuffered streaming for large exports | | `ExecuteAsync($"…")` / `ExecuteScalarAsync($"…")` | affected rows / first scalar | | `InsertAsync(row)` | one full-row insert | | `InsertManyAsync(rows, sqlSuffix?)` | batch insert in one transaction (one command per row on the auto-prepared statement; `sqlSuffix` appends `ON CONFLICT …`) | `InsertManyAsync` is a *convenience* batch (Npgsql auto-prepare), not bulk COPY — for high-throughput bulk load on the **EF tier**, use the binary-COPY path ([bulk operations](/docs/capabilities/bulk-operations), ADR-0051). That path is EF-only (its entry is `DbSet`, its metadata comes from the EF model) and is **not** AOT-compatible (it compiles per-column writers at runtime via `System.Linq.Expressions`), so the EF-free/AOT tier has no binary-COPY path today. A **source-generated** COPY for this tier — the `[SqlRecord]` generator emitting per-column `NpgsqlBinaryImporter` writes the same way it emits `BindParameters`, AOT-clean and reflection-free, with the EF tier's upsert vocabulary — is proposed in [ADR-0068](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0068-aot-sql-binary-copy.md). `QueryUnbufferedAsync` streams **client-side**: Npgsql reads rows off the socket incrementally, so client memory stays bounded (roughly one row at a time) regardless of result size — there is no JDBC/Hibernate-style `fetchSize` because Npgsql does not buffer the whole result set the way JDBC does. Bounding work on the *server* (incremental production) is a `DECLARE CURSOR … FETCH n` concern, which this thin API deliberately does not wrap — hand-write the cursor SQL and map each fetch through the generated mapper if you ever need it. The explicit-mapper overloads (`db.QueryAsync(mapper, $"…")`, `db.QueryFirstOrDefaultAsync(mapper, $"…")`) remain the escape hatch for hand-written mappers of non-`[SqlRecord]` shapes. Under the hood a closed connection is opened for the call and closed afterwards (Dapper semantics); an already-open connection — the scoped session's, or one you wrapped — is left open. ## Transactions (unit of work) [#transactions-unit-of-work] Because a handler injects `ISqlSession` — one connection pinned for the request scope — several statements can run in one transaction. That is what makes a command that writes more than once atomic. This tier supplies the same `IUnitOfWork` seam the EF tier does, so the framework [`TransactionDecorator`](/docs/capabilities/entity-framework) wraps a command handler in one commit/rollback with no per-handler transaction code. On PostgreSQL, `Elarion.Sql.PostgreSql` registers one **central data source** — the shared core, EF Core's `DbContext` analogue — that the access tier and [migrations](/docs/capabilities/migrations) both draw from, so the database is configured once: ```csharp // Pick the provider once — one NpgsqlDataSource shared by every subsystem (command logging auto-wired): builder.Services.AddElarionPostgreSql(connectionString); // ...then the neutral registrations name no provider: builder.Services.AddElarionSqlUnitOfWork(); builder.Services.AddElarionMigrations(o => o.AddScripts(typeof(Program).Assembly, "MyApp.Migrations.")); ``` `AddElarionSqlUnitOfWork()` registers the scoped `ISqlSession` and replaces the default no-op `IUnitOfWork` with `SqlUnitOfWork`, which opens the transaction on the session's shared connection. The handler calls the convenience surface on the session; every read and write runs on that connection and enlists the open transaction automatically. (A read-only host that never writes can register just `AddElarionSqlSession()` — the session with per-call auto-commit, no transaction machinery.) **`ISqlDatabase` is the application's database handle — the tier's `DbContext`/`IDbContextFactory` counterpart, and the only thing the session resolves, so there is no ambient `DbDataSource` the tier assumes.** `Elarion.Sql` itself stays Npgsql-free; the Npgsql binding lives in `Elarion.Sql.PostgreSql`. Register it with one of: | Registration | Package | Use it when | | ---------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------ | | `AddElarionPostgreSql(connectionString)` | `Elarion.Sql.PostgreSql` | the common PostgreSQL host — one central `NpgsqlDataSource` shared by the access tier and migrations | | `AddElarionSqlite(connectionString)` | `Elarion.Sql.Sqlite` | a single-node / edge SQLite host — a `DbDataSource` over `Microsoft.Data.Sqlite` plus migrations, the same shape as PostgreSQL | | `AddElarionSqlDatabase(sp => …)` | `Elarion.Sql` | build and own a `DbDataSource` yourself (any provider) | | `AddElarionSqlDatabase()` | `Elarion.Sql` | a `DbDataSource` is already in the container (`AddNpgsqlDataSource`) | | `AddElarionSqlDatabase()` | `Elarion.Sql` | route per scope — a tenant's database, a read replica: `T.GetDataSource()` reads the current tenant from `ICurrentUser` | Beyond feeding the scoped session, the handle is directly usable: `db.OpenSessionAsync(ct)` opens an **owning** one-shot session over a fresh pooled connection (autonomous per-call semantics, disposed with the session), and `db.BeginTransactionAsync(ct)` opens the transactional variant — an `ISqlTransaction` whose statements commit or roll back together (commit explicitly; dispose without commit rolls back) — which upgrades the singleton-eligible pattern from three steps to one: ```csharp public sealed class WorldTick(ISqlDatabase db) { // singleton-eligible: no scoped dependencies public async ValueTask HandleAsync(Tick tick, CancellationToken ct) { await using var session = await db.OpenSessionAsync(ct); // through the seam — routing still applies var rows = await session.QueryAsync($"{Reading.Select} WHERE cell = {tick.Cell}", ct); // … } } ``` ```csharp [Handler] public sealed class PlaceOrder(ISqlSession db) { public async ValueTask HandleAsync(PlaceOrderCommand command, CancellationToken ct) { await db.InsertAsync(command.Order, ct); await db.ExecuteAsync($"UPDATE {Customer.Table} SET order_count = order_count + 1 WHERE id = {command.Order.CustomerId}", ct); return Result.Success(); // both writes commit together; a failure/error result rolls both back } } ``` * **Atomicity by result.** The decorator commits on a successful `Result` and rolls back otherwise — the two writes above are one transaction. Reads on the session inside the scope observe its own uncommitted writes (they share the connection); an outside connection sees nothing until commit. * **Nested handlers join, never nest physically.** A transactional command that invokes another through `IHandlerSender` on the same scope joins the ambient transaction via a **savepoint** (commit releases it, rollback discards only the inner writes) — PostgreSQL forbids a second physical transaction on one connection. * **Lock timeout.** `UnitOfWorkOptions.LockTimeout` applies `SET LOCAL lock_timeout` on PostgreSQL (how `[Idempotent]` fast-fails a concurrent duplicate to a 409 instead of blocking); other ADO.NET providers ignore it, the closest semantics they can offer. * **No change tracker.** Unlike EF there is no pending-change buffer to flush — the handler's statements have already executed on the connection inside the transaction, so commit only commits. * **Without it.** With neither `AddElarionSqlUnitOfWork()` nor `AddElarionSqlSession()` registered, a command handler that injects `ISqlSession` fails to resolve at activation; and if only the session is registered, the framework's `IUnitOfWork` stays the core no-op (commit/rollback do nothing, logged once) so a failed multi-write command is **not** rolled back. Register `AddElarionSqlUnitOfWork()` on any EF-free host whose handlers write. **A write cannot silently escape its transaction.** Every write on this surface enlists the session's transaction automatically (`InsertManyAsync` without one opens its own — a batch is atomic on its own), and there is no raw-connection twin of these methods to reach for by accident: the only way to run against your own connection is `AsSqlSession(transaction?)`, which makes the transaction decision explicit at wrap time. What used to be a documented footgun — a record-level write on a raw connection running outside the handler's unit of work — is now unrepresentable. ## Why not Dapper.AOT [#why-not-dapperaot] Dapper.AOT is actively maintained and its *emitted code* is excellent. The difference is architectural, not maturity: Dapper.AOT works by **call-site interception** of the reflection-based Dapper API. Only direct, inline Dapper calls are intercepted — a call the interceptor cannot statically see (your own helper wrapping `Query`, a generic utility) compiles cleanly and silently executes classic reflection Dapper, which under NativeAOT is a *runtime* failure. The one guarantee an AOT-first framework must give — "if it builds, it maps" — is exactly the one interception cannot make. `Elarion.Sql` inverts the consumption model: the mapper is an **explicit generated contract**, not a recognized call pattern. Indirection is free (the mapper is a value), private/internal types work, and the failure mode for an unmapped type is a compile error. What Dapper.AOT does better remains true and documented: it accepts arbitrary result shapes per query (Elarion maps declared `[SqlRecord]` types), and it drops into an existing Dapper codebase unchanged. The benchmark suite keeps an honest comparison column for both classic Dapper and Dapper.AOT. ## Performance [#performance] The benchmark gate (`tests/Elarion.Benchmarks`, `--filter "*SqlMapping*"`, real PostgreSQL via Testcontainers — the ADR-0051 discipline): the generated read path must sit at parity with a hand-written ADO.NET reader in **time and allocations**, with classic Dapper, Dapper.AOT, and EF Core (no-tracking) as comparison columns, on both the many-rows path (1k/100k rows → `List`) and the single-row path (per-call overhead: statement build, parameter binding, command setup). The generated mapper emits the same code you would write by hand — an ordinal struct and typed `GetFieldValue` calls — so parity is by construction, and the benchmark exists to keep it that way. Representative numbers (Apple M4 Pro, .NET 10, PostgreSQL 17 in a container; 2026-07): | Method | 1k rows | 100k rows | Single row | Allocated (1k / single) | | ----------------------------------------------- | -------------- | --------------- | ---------------- | ----------------------------------------------------- | | Hand-written ADO.NET (baseline) | 702 μs | 52.0 ms | 196.7 μs | 217.2 KB / 2.66 KB | | **Elarion generated mapper** | 703 μs (1.00×) | 52.4 ms (1.01×) | 196.0 μs (1.00×) | **217.4 KB (1.00×) / 2.66 KB (1.00×)** | | Elarion `QueryAsync` (interpolation end-to-end) | 703 μs (1.00×) | 52.4 ms (1.01×) | 195.6 μs (0.99×) | 218.1 KB / 3.36 KB (+0.7 KB per-call statement build) | | Dapper | 716 μs (1.02×) | 52.3 ms (1.01×) | 200.9 μs (1.02×) | 373.3 KB (1.72×) / 2.52 KB | | Dapper.AOT | 719 μs (1.02×) | 51.9 ms (1.00×) | 200.0 μs (1.02×) | 217.4 KB (1.00×) / 2.60 KB | | EF Core (no-tracking) | 820 μs (1.17×) | 58.9 ms (1.13×) | 250.6 μs (1.27×) | 409.7 KB (1.89×) / 10.05 KB (3.78×) | ## Observability [#observability] `Elarion.Sql` deliberately ships **no telemetry of its own**: a mapper at hand-written parity has nothing worth measuring, and a per-query wrapper span would only duplicate the provider's. The story is the two layers around it — and every EF Core observability feature has a direct equivalent: | EF Core | This tier | | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Command logging (`LogTo`, `Microsoft.EntityFrameworkCore.Database.Command`) | Npgsql command logging: `NpgsqlDataSourceBuilder.UseLoggerFactory(loggerFactory)` → `Npgsql.Command` logs every command's SQL + duration at Information. | | `EnableSensitiveDataLogging` (parameter values) | `NpgsqlDataSourceBuilder.EnableParameterLogging()` — same rule: development only. | | Command tracing (provider spans) | The same provider spans, no EF in between: `ActivitySource "Npgsql"` command spans with the SQL text. | | `Microsoft.EntityFrameworkCore` meter | The `"Npgsql"` meter: connection pool, command, and byte counters. | | `DbCommandInterceptor` | No interception seam — deliberately. The SQL is hand-written, so there is nothing hidden to observe or rewrite; cross-cutting behavior belongs in the handler pipeline (decorators), and the [Elarion handler span](/docs/capabilities/telemetry) already wraps every query with its use case. | That last row is the part EF does not give you by default: because data access runs inside handlers, every command span nests under an `Elarion.Handlers` span — the dashboard reads HTTP → `handle IngestReadings` → `INSERT INTO readings …`, so a slow query is attributed to its use case without any extra wiring. The [`samples/EdgeTelemetry`](https://github.com/swimmesberger/Elarion/tree/main/samples/EdgeTelemetry) host wires all of it (OTLP-gated) and its e2e test asserts the span nesting. ## Non-goals [#non-goals] No change tracking, no LINQ or query translation, no relationship/graph mapping, no query generation — SQL stays hand-written; the generated constants (columns and the clause-free `Insert`/`Select` statements) remove the boilerplate, not the SQL: nothing generated ever contains a predicate. No query-builder DSL (rejected as LINQ-to-SQL-by-another-name, ADR-0058). The planned follow-up is the **schema-derived metamodel and drift verification**: a design-time tool introspects a real PostgreSQL brought to schema by any means and writes a committed `elarion-sql-schema.json`; the generator then validates every `[SqlRecord]` against the actual schema at build time. # Telemetry & observability (/docs/capabilities/telemetry) Elarion emits OpenTelemetry-compatible signals through `System.Diagnostics.ActivitySource` and `System.Diagnostics.Metrics`. The runtime packages **do not depend on the OpenTelemetry SDK** — the host chooses exporters and registers the sources and meters it wants to collect. This keeps the framework lightweight while making every framework-owned boundary observable. ## Registering sources and meters [#registering-sources-and-meters] ```csharp using Elarion.JsonRpc; using Elarion.Diagnostics; using Elarion.Abstractions.Messaging; using Elarion.Abstractions.Scheduling; using Elarion.Caching; using Elarion.Connections.Diagnostics; using Elarion.Connections.Tcp.Diagnostics; using Elarion.Resilience; using Elarion.Typst; builder.Services .AddOpenTelemetry() .WithTracing(tracing => tracing .AddSource( JsonRpcTelemetry.ActivitySourceName, SchedulerTelemetry.ActivitySourceName, HandlerCacheTelemetry.ActivitySourceName, ResilienceTelemetry.ActivitySourceName, HandlerTelemetry.ActivitySourceName, EventTelemetry.ActivitySourceName, TypstTelemetry.ActivitySourceName) // hosts using Elarion.Typst /* add exporters */) .WithMetrics(metrics => metrics .AddMeter( JsonRpcTelemetry.MeterName, SchedulerTelemetry.MeterName, HandlerCacheTelemetry.MeterName, ResilienceTelemetry.MeterName, HandlerTelemetry.MeterName, EventTelemetry.MeterName, ConnectionTelemetry.MeterName, // hosts using Elarion.Connections TcpConnectionTelemetry.MeterName, // hosts using Elarion.Connections.Tcp TypstTelemetry.MeterName) // hosts using Elarion.Typst /* add exporters */); ``` ## First-party surfaces [#first-party-surfaces] Elarion telemetry follows the [OTel semantic conventions](https://opentelemetry.io/docs/specs/semconv/) wherever one exists, and applies their spirit where none does: * **Durations** are histograms recording *"seconds as a floating point number with the highest precision available"* (unit `s`), per the OTel instrument guidance — never milliseconds — with the semconv-recommended bucket boundaries supplied as instrument advice so exporters don't fall back to millisecond-scaled defaults. (Span attributes with an explicit unit suffix like `scheduler.job.duration_ms` are self-describing and exempt.) * **Semconv names are adopted, not paralleled**: the JSON-RPC/MCP duration metric is `rpc.server.call.duration` per the current RPC conventions (the retired experimental `rpc.server.duration`, which was defined in milliseconds, is not emitted). Where no convention exists, names and attributes use a namespaced prefix (`elarion.*`, `handler.*`, `actor.*`, …). * **Cardinality discipline**: metric tags stay bounded (type/operation/outcome names — never keys, payloads, or user identity); high-cardinality identity (an actor key, the current user) appears on **spans and log scopes only**. | Surface | Source / meter | Coverage | | ------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | JSON-RPC | `JsonRpcTelemetry` (`JsonRpc`) | Every request dispatch creates a span: single calls, notifications, batch items, invalid versions, unknown methods, invalid params, application errors, unhandled exceptions, invalid envelopes, parse errors, and batch-level failures. Registered methods use their canonical name; invalid/unregistered ones use bounded sentinels to avoid unbounded metric cardinality. Tags are bounded: method, response/error code, version, and batch index/size. | | MCP | `JsonRpcTelemetry` (`JsonRpc`) | MCP tool calls share the JSON-RPC source/meter — one registration covers both adapters over the shared handler bus. Every tool invocation creates a span (`mcp {method}`) and request count/duration metrics distinguished by `rpc.system.name: "mcp"`, covering success, unknown tools (bounded `_unregistered` sentinel), invalid params, application errors, and unhandled exceptions. | | Messaging | `EventTelemetry` (`Elarion.Messaging`) | Both event planes and every delivery tier. Domain publishes create a span that parents the inline consumers; integration events capture the publisher's trace context at publish time — in the in-memory envelope or as a persisted `traceparent` on the outbox row — so the after-commit consume span stays in the publishing operation's trace, across restarts and worker instances for the outbox. Metrics: publish counts by event type/plane, consumer invocation count/duration by consumer and outcome, and outbox delivery count/duration by outcome. Failure logs carry the correlation id. | | Scheduler | `SchedulerTelemetry` (`Elarion.Scheduling`) | Schedule/enqueue/cancel operations and job executions create spans. Runtime-scheduled jobs preserve scheduling trace context into the later execution span when possible. Fixed-rate, fixed-delay, cron, skipped, misfired/coalesced, retry, cancellation, and failure outcomes are trace-visible. | | Handler cache | `HandlerCacheTelemetry` (`Elarion.Caching`) | Cache get/create spans expose the precise outcome — `miss-factory-executed`, `miss-non-cacheable`, `cached-or-coalesced`, or `bypass-no-tenant`. Factory execution events, payload policy errors, and invalidation spans are trace-visible. Tags avoid full keys, raw user ids, and request values. | | Resilience | `ResilienceTelemetry` (`Elarion.Resilience`) | Named policy execution spans expose final outcome and duration. Retry and timeout callbacks add span events under the default Microsoft/Polly-backed runtime. | | Connections | `ConnectionTelemetry` (`Elarion.Connections`), `TcpConnectionTelemetry` (`Elarion.Connections.Tcp`) | The kernel meter tracks registered connections (`connection.active`, `connection.opened`/`connection.closed`), identity promotion attempts by bounded outcome (`connection.identity_promotions`), and live client-event subscriptions. The TCP meter adds TLS handshake duration in seconds by outcome, connection failures by bounded establishment stage, closes by `graceful`/`forced` mode, admitted-outbound-send pressure and saturation rejections, and idle-window events. All tags are fixed vocabularies plus the endpoint's transport tag — never connection/principal ids, payloads, endpoint addresses, operation names, certificate data, or raw exception text. | | PDF documents | `TypstTelemetry` (`Elarion.Typst`) | Every compilation creates a `typst compile` span tagged with the document (`elarion.typst.document`, the package function) and `elarion.typst.outcome` (`success`/`compilation_error`/`timeout`/`unavailable`/`cancelled`). Metrics: `elarion.typst.compile.duration` in seconds by outcome, and `elarion.typst.compile.queue.duration`, the wait for a free concurrency slot. Typst's diagnostics go to the log, never to tags. | | Handler | `HandlerTelemetry` (`Elarion.Handlers`) | Every generated handler is wrapped in an `ObservabilityDecorator` as the outermost decorator, emitting one `Internal` span per invocation that parents any cache/resilience/pipeline child spans, plus execution count/duration metrics. The pipeline gates surface their decisions on the same handler span and meter: authorization denials tag `elarion.authorization.outcome` (`unauthorized`/`forbidden`) and count denials per handler, a closed feature gate tags `elarion.feature_gate.outcome` and counts per handler (the wire response stays an opaque 404), and idempotent handlers tag `elarion.idempotency.outcome` (`completed`/`replayed`/`conflict`/`fingerprint_mismatch`/`abandoned`) and count outcomes per request type, and [previewable commands](/docs/concepts/previewable-commands) tag `elarion.preview.outcome` (`previewed`/`committed`/`changed`/`failed`/`unsupported`) on calls that are not ordinary. **Metric** tags stay bounded: handler name, request type name, and outcome — never request/response payloads or user identity. The same decorator additionally runs [context enrichment](#user--request-context) — stamping caller identity (`user.id`, `user.roles`, `user.permissions`) onto the **span** and opening a matching log scope — on the span and in logs only, never on metrics. | ## Handler tracing [#handler-tracing] Handler tracing follows the same "instrument always, collect on demand" model as the other surfaces: the generator wraps every handler in an `ObservabilityDecorator` by default, but the span is a no-op until a host registers the `Elarion.Handlers` source. To suppress handler telemetry, omit `HandlerTelemetry.ActivitySourceName`/`MeterName` from the OpenTelemetry registration. This mirrors how `HttpClient` and EF Core ship always-present `ActivitySource`s and leave collection to the host — no opt-in attribute required. The handler span adds the application-operation boundary as the stable parent of the decorator chain, so JSON-RPC, scheduler, cache, and resilience child spans all appear inside it. One part of the decorator is deliberately **not** free-when-unobserved: [context enrichment](#user--request-context) runs whenever enrichers are registered (current-user support registers one by default), because its consumers are the log scope and the ambient transport span — handler log lines should carry user context whenever logging is on, listener or not. That costs a small per-call allocation (\~300 B with the default user-context enricher). For per-message hot paths where that matters, the leveled `[HandlerTelemetry(HandlerTelemetryMode.None)]` attribute — on a handler, a module class, or the assembly, nearest wins — makes the generator skip the decorator entirely for the affected handlers: no span, execution metric, enrichment, or log scope, and no wrapper object per call (ADR-0066). Failures are unaffected. This is a compile-time composition decision, distinct from the host-side "registered but unobserved" default above — see [the low-allocation dispatch profile](/docs/capabilities/connections/low-allocation) for the full recipe. The span carries `elarion.handler`, `elarion.handler.request_type`, `elarion.handler.outcome` (`ok`/`error`/`exception`), and **`elarion.handler.pipeline`** — the decorators actually wrapping this handler in this process, in execution order (e.g. `Observability,Authorization,Validation,Transaction,Audit?`). A trailing `?` marks a decorator that attached through a runtime gate — a soft-attached one whose presence depends on a registered service (the audit trail, the idempotency inbox) or a `[DecoratorList]` decorator with an `AppliesTo` predicate — so it answers "why didn't caching/auditing apply here?" straight from a trace. The same list is available programmatically as [`HandlerMetadata.Pipeline`](/docs/concepts/decorator-pipelines) (`IHandlerPipeline` — its `Steps` and `Contains(typeof(SomeDecorator<,>))`), populated once the handler is first resolved. All tags are bounded (one constant value per handler type), so they are span-safe and never carry payloads or identity. ## User & request context [#user--request-context] Every handler span is enriched with **who made the call**, and a matching logging scope carries that context onto every log line the handler produces — so a trace or a log search can be filtered by user. This is a first-class part of handler tracing: the same `ObservabilityDecorator` that opens the span also runs the enrichers, so it tags the handler span (`Activity.Current`) and its log scope wraps the authorization, validation, and handler chain — a denied or invalid request is still attributed to its caller. (Tracing and context enrichment were two adjacent always-on decorators before ADR-0059 merged them into one.) Because it runs in the handler pipeline (not an ASP.NET middleware), it works the same across **every** transport — JSON-RPC, `[HttpEndpoint]`, MCP, scheduler jobs, and event consumers — reading the [current user](/docs/capabilities/current-user) the dispatch scope already seeded. The decorator itself knows nothing about "user": it drains whatever the registered `IHandlerContextEnricher` instances contribute. The framework ships one — `UserContextEnricher` — that is registered **by default when current-user support is added** (`AddElarionClaimsCurrentUser` / `AddElarionCurrentUser`), so user context is on out of the box; anonymous executions (scheduler, after-commit delivery) contribute nothing. By default it emits, from `ICurrentUser`: | Span tag | Log-scope key | Source | | ------------------ | ----------------- | -------------------------------------------------------------------- | | `user.id` | `UserId` | the caller's id | | `user.roles` | `UserRoles` | the caller's roles (bounded, comma-joined) | | `user.permissions` | `UserPermissions` | permission claims (the `AuthorizationOptions` permission claim type) | `user.id` and `user.roles` are [OpenTelemetry semantic-convention](https://opentelemetry.io/docs/specs/semconv/registry/attributes/user/) attributes; `user.permissions` mirrors them (no semantic convention exists for permissions). **Email is PII and off by default**; user identity is deliberately kept **off metrics** (unbounded cardinality) — it rides only the span and the log scope. The log-scope keys only appear in output if the host enables scopes on its logging exporter — e.g. `builder.Logging.AddOpenTelemetry(o => o.IncludeScopes = true)`, or `IncludeScopes = true` on the console formatter. The span tags need no such switch. ### Configuring or disabling the built-in enricher [#configuring-or-disabling-the-built-in-enricher] The built-in `UserContextEnricher` is registered by current-user support. Call `AddElarionUserContextEnrichment` to narrow the payload, opt into email, turn it off (host-registered enrichers keep running), or enable it for a host with a custom `ICurrentUser` that did not go through `AddElarionClaimsCurrentUser`: ```csharp using Elarion.Diagnostics; builder.Services.AddElarionUserContextEnrichment(o => { o.IncludeEmail = true; // opt into user.email / UserEmail (PII — you own redaction/retention) o.MaxItems = 32; // cap on roles/permissions joined into a tag (default 16) }); // or disable the built-in user enricher (a host-provided IHandlerContextEnricher still runs): builder.Services.AddElarionUserContextEnrichment(o => o.Enabled = false); ``` ### Contributing your own context [#contributing-your-own-context] Enrichment is an open seam. Implement `IHandlerContextEnricher` to add your own trace tags and log-scope items — a tenant id, a request source, a correlation value — alongside (or instead of) the built-in user context. Enrichers are resolved per handler execution, so they may inject scoped services such as `ICurrentUser`, and registrations **compose** rather than replace: ```csharp using Elarion.Abstractions.Diagnostics; using Elarion.Abstractions.Identity; public sealed class TenantContextEnricher(ICurrentUser user) : IHandlerContextEnricher { public void Enrich(HandlerEnrichmentContext context) { if (!user.IsAuthenticated) return; // anonymous transports run enrichers too foreach (var tenant in user.GetClaimValues("tenant")) { context.SetTag("tenant.id", tenant); // OTel-style key on the span context.AddScopeItem("TenantId", tenant); // PascalCase key in the log scope break; } } } // register — composes with the built-in user enricher builder.Services.AddElarionHandlerContextEnricher(); ``` Keep the two key styles idiomatic to their sink — OpenTelemetry semantic-convention keys on tags (`tenant.id`), PascalCase keys in the scope (`TenantId`) — and keep `Enrich` cheap and non-throwing: it runs on every handler invocation. See [ADR-0033](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0033-user-context-trace-and-log-enrichment.md). ## Logging a failure without its message [#logging-a-failure-without-its-message] An exception's message is written by whoever threw it and often quotes what the operation handled: a database provider puts the conflicting key into a unique violation, a parser the text it could not read. Code that works on personal data or content (mail, contacts, imported files) and catches an exception to go on must keep that message out of the log. Log the exception's **outline** instead, and pass no exception object to the logger: ```csharp using Elarion.Diagnostics; catch (Exception exception) when (exception is not OperationCanceledException) { // Not logger.LogWarning(exception, …): a logging provider would write the message. logger.LogWarning("Mailbox {MailboxId}: the read state was not recorded: {Failure}", mailboxId, exception.Outline()); } ``` ```text Mailbox 7: the read state was not recorded: Microsoft.EntityFrameworkCore.DbUpdateException <- Npgsql.PostgresException [SqlState 23505] ``` `exception.Outline()` is one line: the full type names from the outermost to the innermost exception, each followed by the code its provider attaches: the SQLSTATE of a `DbException`, the `SocketErrorCode` of a `SocketException`, the status code of an `HttpRequestException`. An `AggregateException` is followed through its first inner exception and says how many it holds; a chain is cut after eight exceptions. `exception.Outline(stackTrace: true)` appends the stack trace of every exception in the chain, which names methods and source locations. The outline never reads `Message`, `Data` or `ToString()` of an exception. Its text is built when the line is formatted. A structured sink records it as text, not as an exception, so exception-based grouping and alerting do not see these failures; where the message cannot hold such content, `logger.LogError(exception, …)` stays the right call. The decision is [ADR-0133](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0133-an-exception-outline-is-what-a-log-line-may-say-about-a-failure.md). ## Client-side telemetry [#client-side-telemetry] A frontend call can join the same distributed trace as the server work it triggers. The server side needs nothing Elarion-specific: a host running OpenTelemetry with `AddAspNetCoreInstrumentation()` extracts the W3C `traceparent` header from the incoming request, so the request span — and the JSON-RPC dispatch, `[HttpEndpoint]`, and handler-pipeline spans under it — nest beneath the client's span. The client just has to start that span and inject the header: * **JSON-RPC client** — the generated TypeScript client stays OpenTelemetry-package-free and exposes an optional `instrumentation` hook (`RpcInstrumentation`) on `createRpcClient`/`createRpcApi`: supply an adapter over `@opentelemetry/api` (or a hand-rolled `traceparent` generator) to start a span per request/batch, inject trace-context headers, and record the outcome. See [TypeScript client › Tracing with OpenTelemetry](/docs/capabilities/transports/typescript-client#tracing-with-opentelemetry). * **REST / OpenAPI client** — the recommended [`@hey-api/openapi-ts`](https://heyapi.dev) client is `fetch`-based, so `@opentelemetry/instrumentation-fetch` (browser) or `@opentelemetry/instrumentation-undici` (Node) auto-injects `traceparent`; a request interceptor can also inject it by hand. See [OpenAPI › Trace client requests](/docs/capabilities/transports/openapi#trace-client-requests-with-opentelemetry). Either way the generated client never imports a tracing SDK, so client-side tracing stays a host decision. # Time series (/docs/capabilities/time-series) Device samples, sensor readings, metrics: append-heavy, time-ordered, queried in buckets, expired by age. The reflex is to reach for a second database; Elarion's posture is that **[a PostgreSQL extension is composition, not scale-out](/docs/capabilities/postgres-extensions)** — [TimescaleDB](https://www.timescale.com/) turns the Postgres you already run into the time-series store. Accordingly there is deliberately no `Elarion.TimeSeries` package: this page is a **recipe**, composing the extension with the framework pieces you already know — bulk insert, keyset paging, scheduled jobs, client events — over your existing EF model ([ADR-0056](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0056-postgres-extensions-posture.md)). ## Prerequisite: TimescaleDB in the server image [#prerequisite-timescaledb-in-the-server-image] Run the official image everywhere — dev, Testcontainers, production (see [PostgreSQL extensions](/docs/capabilities/postgres-extensions) for the image guidance, including combining several extensions in one image): ```yaml services: db: image: timescale/timescaledb:latest-pg17 ``` Activate the extension and convert the table in a normal EF migration — extension setup is schema, and it belongs in the same migration history as everything else: ```csharp migrationBuilder.Sql("CREATE EXTENSION IF NOT EXISTS timescaledb;"); migrationBuilder.Sql("SELECT create_hypertable('device_samples', by_range('recorded_at'));"); ``` ## 1. The sample table is an ordinary entity [#1-the-sample-table-is-an-ordinary-entity] Nothing about the entity or its configuration knows the table is a hypertable: ```csharp public sealed class DeviceSample { public Guid DeviceId { get; set; } public DateTimeOffset RecordedAt { get; set; } public double Value { get; set; } } [EntityConfiguration] public sealed class DeviceSampleConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { builder.ToTable("device_samples"); builder.HasKey(s => new { s.DeviceId, s.RecordedAt }); builder.Property(s => s.DeviceId).HasColumnName("device_id"); builder.Property(s => s.RecordedAt).HasColumnName("recorded_at"); builder.Property(s => s.Value).HasColumnName("value"); } } ``` The one rule TimescaleDB imposes: **every unique constraint — the primary key included — must contain the partition column** (`recorded_at` here). A surrogate `Id`-only key would be rejected at `create_hypertable` time. The composite `(DeviceId, RecordedAt)` key satisfies the rule and buys the dedup below for free. ## 2. Ingest: bulk insert, idempotent by constraint [#2-ingest-bulk-insert-idempotent-by-constraint] Telemetry arrives in batches and retransmits after connection drops — device gateways resend what they are not sure was received. [Bulk insert](/docs/capabilities/bulk-operations) with `DoNothing` conflict handling makes ingestion both fast (binary `COPY`) and naturally idempotent (a replayed batch hits the primary key and inserts nothing): ```csharp [Handler("telemetry.ingest")] public sealed class IngestSamples(AppDbContext db, IIntegrationEventBus events) : IHandler { public sealed record Command : ICommand { public required Guid DeviceId { get; init; } public required IReadOnlyList Points { get; init; } } public sealed record Point(DateTimeOffset RecordedAt, double Value); public async ValueTask HandleAsync(Command command, CancellationToken ct) { var rows = command.Points.Select(p => new DeviceSample { DeviceId = command.DeviceId, RecordedAt = p.RecordedAt, Value = p.Value, }); await db.DeviceSamples.ExecuteInsertAsync(rows, new BulkInsertOptions { OnConflict = BulkInsertConflictBehavior.DoNothing }, ct); await events.PublishAsync(new SamplesIngested { DeviceId = command.DeviceId }, ct); await db.SaveChangesAsync(ct); // COPY bypasses SaveChanges — this flushes only the outbox row return Result.Success(); } } public sealed record SamplesIngested : IIntegrationEvent { public required Guid DeviceId { get; init; } } ``` The `COPY` runs on the context's own connection inside the handler's ambient transaction, so the batch and the [outbox](/docs/capabilities/events/backends) row commit or roll back together. The explicit `SaveChangesAsync` is not for the samples — bulk insert never touches the change tracker — it persists the recorded integration event. ## 3. Query: `time_bucket` rollups and keyset feeds [#3-query-time_bucket-rollups-and-keyset-feeds] Aggregation is what the extension is *for* — use it directly. The database is application logic in Elarion ([no repository layer](/docs/capabilities/entity-framework)), so a provider function in raw SQL is the intended path, not an escape hatch: ```csharp public sealed record Bucket(DateTimeOffset BucketStart, double Avg, double Max); var buckets = await db.Database .SqlQuery($""" SELECT time_bucket('5 minutes', recorded_at) AS "BucketStart", avg(value) AS "Avg", max(value) AS "Max" FROM device_samples WHERE device_id = {deviceId} AND recorded_at >= {since} GROUP BY 1 ORDER BY 1 """) .ToListAsync(ct); ``` Interpolated values become parameters — this is not string concatenation. For raw sample feeds (newest-first scroll in a dashboard), declare a [keyset ordering](/docs/capabilities/pagination) like any other entity; descending same-direction columns get the Npgsql row-value seek: ```csharp [Keyset("-RecordedAt", "-DeviceId")] public sealed partial class SamplesNewestFirst; ``` ## 4. Retention: a scheduled job dropping chunks [#4-retention-a-scheduled-job-dropping-chunks] Because a hypertable is chunked by time, expiring old data is a metadata operation (`drop_chunks`), not a million-row `DELETE`. Own the policy as a normal [scheduled job](/docs/capabilities/scheduling) — the retention window lives in your configuration and [runtime settings](/docs/concepts/settings), the run shows up in your job telemetry and inspector, and on a cluster the [per-occurrence claims](/docs/capabilities/scheduling/multi-node) make exactly one node run it: ```csharp public sealed class TelemetryRetentionJob(AppDbContext db, TimeProvider timeProvider) { [ScheduledJob( "telemetry.retention", Cron = "0 0 4 * * *")] public async ValueTask RunAsync(CancellationToken ct) { var cutoff = timeProvider.GetUtcNow().AddDays(-90); await db.Database.ExecuteSqlAsync( $"SELECT drop_chunks('device_samples', older_than => {cutoff})", ct); } } ``` TimescaleDB can also run retention in-database (`add_retention_policy`) with zero application code. The application-owned job is the recommended default because the policy stays where the rest of your operational configuration lives; reach for the native policy when the database is operated separately from the application anyway. ## 5. Live dashboards: client events [#5-live-dashboards-client-events] A telemetry dashboard is the textbook [client events](/docs/capabilities/events/client-events) shape: the pushed fact is a **hint** ("device X has new samples"), and the client converges by re-running the bucket query above. A dropped hint costs staleness until the next batch, never correctness — which is exactly the at-most-once contract: ```csharp [RequirePermission("telemetry", Verbs.Read)] [AllowAnyResource] // the device id routes, the permission gates public sealed record DeviceSamplesArrived : IClientEvent { public required Guid DeviceId { get; init; } } [Service] internal sealed class TelemetryClientProjections(IClientEventPublisher clientEvents) { [ConsumeEvent] public ValueTask On(SamplesIngested evt, CancellationToken ct) => clientEvents.PublishAsync( new DeviceSamplesArrived { DeviceId = evt.DeviceId }, ClientEventScope.Resource($"device:{evt.DeviceId}"), ct); } ``` The consumer runs after commit, so a rolled-back batch never pushes a ghost update; publishing one hint per *batch* (not per sample) keeps the browser tier light no matter the ingest rate. ## Where this recipe stops [#where-this-recipe-stops] TimescaleDB comfortably holds far more data than the 1–10 node tier Elarion targets ever produces, so outgrowing it is rare. If a workload genuinely needs a dedicated time-series cluster, that is an infrastructure decision above the framework — the entity, handlers, and events here stay; only the storage SQL moves. And the recipe *shape* generalizes to other extensions — pgvector, PostGIS, Apache AGE — see [PostgreSQL extensions](/docs/capabilities/postgres-extensions). ## The EF-free variant [#the-ef-free-variant] The same composition on the AOT tier — `CREATE EXTENSION` + `create_hypertable` + `add_retention_policy` in one ADR-0057 migration, `time_bucket` rollups read through ADR-0058 generated mappers, published NativeAOT — is the runnable [`samples/EdgeTelemetry`](https://github.com/swimmesberger/Elarion/tree/main/samples/EdgeTelemetry). # Writing a custom transport (/docs/capabilities/transports/custom-transports) Elarion's HTTP, JSON-RPC, and MCP surfaces are thin adapters over transport-neutral handler seams. A custom adapter has four responsibilities: 1. Authenticate the caller and produce a `ClaimsPrincipal`. 2. Create a fresh dispatch scope seeded with boundary state. 3. Invoke the handler through DI so the full decorator pipeline runs. 4. Translate `Result` and `AppError` to the wire protocol. For unary or request-driven server-streaming gRPC service methods, use the shipped [gRPC adapter](/docs/capabilities/transports/grpc): it owns the scope seeding, cancellation flow, and default `RpcException` mapping while the generated service override retains explicit protobuf/application mapping. Other transports can follow this guide directly. JSON-RPC and MCP are protocols; ASP.NET Core is one possible host. A gRPC server, CLI, queue consumer, or custom socket host can invoke the same handlers without referencing `Elarion.AspNetCore`. ## Choose typed or name-based dispatch [#choose-typed-or-name-based-dispatch] Use `HandlerInvoker` when the adapter knows the request and response types at compile time. Use the transport-neutral `HandlerDispatcher` when messages route by operation name. | Seam | Package | Purpose | | ---------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `IHandler`, `Result`, `AppError` | `Elarion.Abstractions` | Application contract and error model | | `HandlerDispatcher` | `Elarion.Abstractions` (namespace `Elarion.Abstractions.Dispatch`) | Named request/reply bus with no wire format | | `DispatchScopeContext`, `CreateDispatchScope`, `SeedScope` | `Elarion.Abstractions` (namespace `Elarion.Abstractions.Dispatch`) | Per-call scope-seeding rail | | `HandlerInvoker` | `Elarion` | Typed scope + resolve + invoke + dispose helper | | `IStreamHandler`, `StreamHandlerInvoker` | `Elarion.Abstractions`, `Elarion` | Typed startup + scoped server-streaming invocation | | `ConnectionHandlerInvoker` | `Elarion` | Connection-boundary variant of the invokers, bound once per connection: each call captures one `ClientConnection` snapshot, seeds it (plus its `ClaimsPrincipal`) under exact types so adapter enrichment cannot spoof framework identity, and filters named dispatch through `HandlerTransports.Connection` | | `ICurrentUser`, `IAuthorizer` | `Elarion.Abstractions` | Transport-neutral identity and authorization | | `IAppErrorTranslator` | `Elarion.Abstractions` | Protocol-specific error translation | `JsonRpcDispatcher` and `McpDispatcher` filter one generated operation registry by `HandlerTransports.JsonRpc` and `HandlerTransports.Mcp`. REST `[HttpEndpoint]` is route/verb based and is not part of the named bus. ## Seed each call scope [#seed-each-call-scope] A child DI scope does not inherit scoped instances from its parent. Capture boundary state into a `DispatchScopeContext`; `CreateDispatchScope` runs every registered `IDispatchScopeInitializer`: ```csharp var context = new DispatchScopeContext(); context.Set(principal); await using var scope = rootProvider.CreateDispatchScope(context); // Resolve and invoke inside scope.ServiceProvider. ``` Use `SeedScope(context)` when the host already owns the correct scope, as the ASP.NET middleware does for the request scope. Do not hand-roll propagation of individual scoped services. ## Seed current user off HTTP [#seed-current-user-off-http] Authentication belongs at the adapter boundary. Once it has validated the caller and built a principal, the core claims implementation maps that principal to `ICurrentUser`: ```csharp services.AddElarionClaimsCurrentUser(o => o.UserIdClaimType = "sub"); services.AddElarionAuthorization(); ``` Putting `ClaimsPrincipal` in `DispatchScopeContext` then gives the handler the same authorization behavior as an HTTP request. Without an authenticated principal, `[Require*]` handlers fail as unauthorized. ## Invoke the handler [#invoke-the-handler] Typed adapters such as gRPC and CLIs usually use: ```csharp var result = await HandlerInvoker.InvokeAsync( rootProvider, command, context, ct); // Requests declaring their response type via a self-typed marker (ICommand / // IQuery) need no explicit generic arguments: var inferred = await HandlerInvoker.InvokeAsync(rootProvider, command, context, ct); ``` Bidirectional connection adapters (the codec of an `Elarion.Connections` transport) bind a `ConnectionHandlerInvoker` once per connection instead of hand-rolling the scope: each call captures the connection's immutable identity snapshot exactly once, so an identity promotion racing the dispatch affects the next message rather than the scope underneath the current one: ```csharp var invoker = new ConnectionHandlerInvoker(rootProvider, connectionSink); var result = await invoker.InvokeAsync(new StartCommand(...), ct); // inferred via self-typed marker var explicitResult = await invoker.InvokeAsync(decoded, ct); // Decoded named traffic is filtered to routes exposed with HandlerTransports.Connection; unknown and // other-transport names return the same generic NotFound so exposure is never leaked. var named = await invoker.InvokeNamedAsync(dispatcher, name, decodedRequest, ct); ``` Dynamic adapters map and dispatch names: ```csharp dispatcher.Map("clients.create"); dispatcher.MapDelegate("ping", (request, services, ct) => HandlePing(request, ct)); var response = await dispatcher.DispatchAsync( "clients.create", command, scope.ServiceProvider, ct); ``` Both paths resolve the decorated handler and therefore retain tracing, validation, authorization, feature gates, resilience, caching, idempotency, transactions, and auditing configured for that handler. ## Invoke a server-streaming handler [#invoke-a-server-streaming-handler] For an explicit server-streaming-capable transport (including Elarion's gRPC server-streaming adapter), invoke the typed seam. Startup errors are normal `AppError`s; keep the accepted invocation alive while writing items: ```csharp var started = await StreamHandlerInvoker.InvokeAsync(provider, request, context, ct); if (!started.IsSuccess) return MapError(started.Error); await using var stream = started.Value; await foreach (var row in stream.WithCancellation(ct)) await WriteItemAsync(row, ct); ``` The ASP.NET SSE adapter is `ElarionHttpResults.ToStreamResult(request)`: return it from a direct `MapGet` lambda in the host compilation, where ASP.NET Core owns binding. The lazy result uses native `TypedResults.ServerSentEvents` framing and does not start the handler until ASP.NET executes it. JSON-RPC and MCP are deliberately single-response; client and duplex streams belong to a transport-specific protocol or `Elarion.Connections`, not this contract. ## Answer denials before payload errors [#answer-denials-before-payload-errors] If your transport binds a wire payload into the request type itself, call `route.EvaluateGateAsync(scope.ServiceProvider, ct)` (or `HandlerGates.EvaluateAsync(scope, ct)`) when binding fails and, for a non-`null` `AppError`, translate that instead of reporting the payload error — so an unauthenticated or forbidden caller gets the 401/403 equivalent and never learns the parameter requirements. When binding succeeds, dispatch as usual; the decorator pipeline enforces authorization on the bound request. See [Authorization](/docs/concepts/authorization#401403-before-400). ## Map application errors [#map-application-errors] Implement `IAppErrorTranslator` or map `ErrorKind` directly. Keep protocol status codes stable: | `ErrorKind` | JSON-RPC | HTTP | Suggested gRPC | Suggested CLI exit | | -------------- | -------- | ---- | -------------------- | ------------------ | | `Validation` | `-32602` | 400 | `InvalidArgument` | 2 | | `NotFound` | `-32001` | 404 | `NotFound` | 3 | | `Conflict` | `-32002` | 409 | `AlreadyExists` | 4 | | `Forbidden` | `-32003` | 403 | `PermissionDenied` | 5 | | `Unauthorized` | `-32005` | 401 | `Unauthenticated` | 6 | | `BusinessRule` | `-32004` | 422 | `FailedPrecondition` | 7 | | `Internal` | `-32603` | 500 | `Internal` | 70 | `AppErrorMapper` and `HttpAppErrorMapper` are the shipped reference implementations. ## Exposing a handler you do not own [#exposing-a-handler-you-do-not-own] Attributes can only decorate handler classes you own. For framework or third-party handlers, or when the host chooses exposure at startup, map imperatively (ADR-0031): ```csharp dispatcher.Map( "my.operation", HandlerTransports.JsonRpc | HandlerTransports.Mcp); ``` The named bus has a generic map because its schema and serialization metadata are explicit. REST has no generic equivalent: a concrete per-endpoint registration keeps the request/response types visible to the trimmer and to OpenAPI, and its binding code concrete and AOT-safe (ADR-0071). A reusable feature therefore ships a concrete `MapElarionX(route)` extension. ## Packaging boundary [#packaging-boundary] A non-HTTP adapter references `Elarion` and `Elarion.Abstractions`. Add `Elarion.JsonRpc` only when serving its JSON-RPC/MCP protocol adapters, `Elarion.Grpc` for its injected unary/server-streaming gRPC invokers, and `Elarion.AspNetCore` only when hosting in ASP.NET Core. Core must never reference the new adapter. ## Complete console example [#complete-console-example] ```csharp using System.Security.Claims; using Elarion; using Elarion.Abstractions.Dispatch; using Elarion.Authorization; using Elarion.Identity; using Microsoft.Extensions.DependencyInjection; var services = new ServiceCollection(); services.AddElarion(configuration); services.AddElarionClaimsCurrentUser(); services.AddElarionAuthorization(); await using var provider = services.BuildServiceProvider(); var principal = new ClaimsPrincipal(new ClaimsIdentity( [new Claim("sub", userArg)], authenticationType: "cli")); var context = new DispatchScopeContext(); context.Set(principal); var result = await HandlerInvoker.InvokeAsync( provider, new CreateClientCommand(/* parsed arguments */), context, CancellationToken.None); return result.IsSuccess ? 0 : (int)MapExitCode(result.Error.Kind); ``` # gRPC (/docs/capabilities/transports/grpc) Elarion's gRPC support has two layers. `Elarion.Grpc` is the host-neutral unary and request-driven server-streaming adapter; `Elarion.Grpc.AspNetCore` is the recommended convention layer for the standard grpc-dotnet ASP.NET Core server. Neither generates `.proto` files, scans services, or infers wire fields. Each service override owns its protobuf-to-application mapping, while Elarion owns the easy-to-miss boundary mechanics: a fresh dispatch scope, the calling principal, the exact `ServerCallContext`, cancellation, the decorated handler pipeline, and stable error translation. ## Install and register the transport [#install-and-register-the-transport] ```xml ``` Compose Elarion onto grpc-dotnet's normal server builder. ASP.NET Core authentication populates `HttpContext.User`; Elarion adopts that principal for every handler dispatch: ```csharp using Elarion.Grpc.AspNetCore; builder.Services.AddGrpc().AddElarion(); ``` Continue to map generated services normally with `app.MapGrpcService()`; Elarion does not scan or map service classes. Register an `IAppErrorTranslator` before this call to replace the default mapping. For a non-ASP.NET host, reference `Elarion.Grpc` directly and call `services.AddElarionGrpcTransport(context => principal)` (or pass an `IGrpcPrincipalFactory`). Inject `GrpcHandlerInvoker` or `GrpcStreamHandlerInvoker` into the service and use their equivalent `InvokeUnaryAsync(request, context)` or `InvokeServerStreamingAsync(request, context)` methods. Requests carrying a self-typed marker (`IQuery`, `ICommand`, or `IStreamRequest`) need no explicit generic arguments: `InvokeUnaryAsync(request, context)` and `InvokeServerStreamingAsync(request, context)` infer both. ## Map a generated service explicitly [#map-a-generated-service-explicitly] The generated service base remains a normal host concern. Map the protobuf request into the application request, dispatch it, then map the application response into the protobuf reply. With grpc-dotnet, the supplied `ServerCallContext` resolves the configured invoker from `HttpContext.RequestServices`, so the service has no Elarion constructor dependency and neither mapping needs a delegate: ```csharp using Elarion.Grpc.AspNetCore; using Grpc.Core; public sealed class ClientsGrpcService : Clients.ClientsBase { public override async Task GetClient( GetClientRequest request, ServerCallContext context) { var application = await context.InvokeElarionAsync( new GetClient.Query { Id = Guid.Parse(request.Id) }); return new GetClientReply { Id = application.Id.ToString(), Name = application.Name, }; } } ``` C# does not use a method's return type to infer generic arguments, so the application response type must appear in this delegate-free call. The request/response pair is the same pair declared by `IHandler>`; resolving it remains compile-time typed and reflection-free. For a short expression-bodied override, the mapper overload remains available: ```csharp return context.InvokeElarionAsync( request, static wire => new GetClient.Query { Id = Guid.Parse(wire.Id) }, static (GetClient.Response application) => new GetClientReply { Id = application.Id.ToString(), Name = application.Name, }); ``` That call resolves the invoker from the current grpc-dotnet request services, captures the already authenticated `HttpContext.User`, creates a fresh `DispatchScopeContext`, stores that principal and the exact `ServerCallContext`, and invokes `HandlerInvoker`. The handler is therefore resolved from DI through its generated decorator chain—authorization, validation, transactions, resilience, and observability stay identical to the other transports. `ServerCallContext.CancellationToken` is the handler cancellation token. A host that uses `AddElarionClaimsCurrentUser()` gets its usual `ICurrentUser` mapping from the captured principal. The service method remains the deliberate seam for proto-field presence, versioning, and application DTO choices. Do not expose generated protobuf messages in a handler and do not add a generic automatic field mapper: both obscure wire-contract decisions and undermine AOT friendliness. ## Failures [#failures] A failed `Result` becomes an `RpcException` through `IAppErrorTranslator`. The default mapping is stable: | `AppError.Kind` | gRPC status | `elarion-error-kind` trailer | | --------------- | -------------------- | ---------------------------- | | `Validation` | `InvalidArgument` | `validation` | | `NotFound` | `NotFound` | `not-found` | | `Conflict` | `AlreadyExists` | `conflict` | | `Forbidden` | `PermissionDenied` | `forbidden` | | `Unauthorized` | `Unauthenticated` | `unauthorized` | | `BusinessRule` | `FailedPrecondition` | `business-rule` | | `Internal` | `Internal` | `internal` | `RpcException.Status.Detail` is the `AppError.Message`. Every error also carries its stable [`AppError.Code`](/docs/reference/result-and-errors#error-codes) in the `elarion-error-code` trailer (for example `not_found`, `seat.taken`); codes are lower-case ASCII by construction, so it is always a text trailer. The lower-case `elarion-error-kind` and `elarion-error-code` metadata keys are the machine-readable compatibility surface. An unknown future `ErrorKind` maps fail-safe to `Internal` and `internal`; it is never exposed as an unknown wire value. `AppError.Data` payloads (including validation field errors) are not serialized in phase one: gRPC does not carry the typed `data` the other transports do. They are not serialized as `google.rpc.Status` or any other rich protobuf detail. Such data needs a stable, versioned protobuf contract. The kind and code trailers are preserved now; structured details remain a future additive transport decision. ## Server streaming [#server-streaming] Request-driven `IStreamHandler` is available as a gRPC **server stream**. It is a cold, request-bound stream: the handler accepts the application request once and returns either an upfront `Result` failure or an accepted `IAsyncEnumerable`. It is not a generic projection of `StreamHub` or a client-event feed. Keep the application mapping in the generated service override and hold the returned invocation for the whole enumeration: ```csharp public override async Task WatchClients( WatchClientsRequest request, IServerStreamWriter responseStream, ServerCallContext context) { await using var stream = await context.InvokeElarionStreamAsync< WatchClients.Query, WatchClients.Item>( new WatchClients.Query { TenantId = Guid.Parse(request.TenantId) }); await foreach (var item in stream.WithCancellation(context.CancellationToken)) { await responseStream.WriteAsync(new ClientChangedReply { Id = item.Id.ToString(), Name = item.Name, }); } } ``` `GrpcStreamHandlerInvoker` seeds the same principal and exact `ServerCallContext` as unary dispatch, then calls `StreamHandlerInvoker`. The accepted invocation owns its fresh dispatch scope until normal completion, cancellation, fault, or disposal; `await using` is therefore required. The gRPC cancellation token is passed when the handler starts and when the stream is enumerated. The optional writer overload can keep a conventional override short: ```csharp return context.InvokeElarionStreamAsync( request, responseStream, static wire => new WatchClients.Query { TenantId = Guid.Parse(wire.TenantId) }, static (WatchClients.Item item) => new ClientChangedReply { Id = item.Id.ToString(), Name = item.Name, }); ``` A failed stream startup is translated through `IAppErrorTranslator` before any item is written. Once grpc-dotnet has started the response, a lazy enumeration exception terminates that gRPC call; the adapter does not try to retrofit it into an `AppError` response. Make item-level failures explicit in the stream item contract when a consumer must observe them. Client and duplex streaming remain out of scope. They need a distinct inbound-message and scope-lifetime model, including how caller messages participate in handler decoration and how bidirectional cancellation, backpressure, and post-response failures are represented. Use unary/batched commands, staged blobs, `Elarion.Connections`, or a purpose-built protocol adapter until that design exists. ## Boundaries [#boundaries] * `Elarion.Grpc` references `Elarion`, `Elarion.Abstractions`, `Grpc.Core.Api`, and the dependency-light `Microsoft.Extensions.DependencyInjection.Abstractions` contract package. * `Elarion.Grpc.AspNetCore` references `Elarion.Grpc`, `Grpc.AspNetCore.Server`, and the ASP.NET Core shared framework. Only this composition package calls `GetHttpContext()`. * `Elarion` core and `Elarion.Abstractions` do not reference gRPC. * No `HandlerTransports` value is added: gRPC overrides are typed and application-owned, rather than entries in the name-routed JSON-RPC/MCP bus. * Authentication stays host-owned. `IGrpcPrincipalFactory` is deliberately only the synchronous capture seam for a principal the host has already authenticated. The ASP.NET convention supplies it from `HttpContext.User`; custom hosts configure it once rather than per method. For a non-gRPC adapter, see [writing a custom transport](/docs/capabilities/transports/custom-transports). # HTTP endpoints (/docs/capabilities/transports/http-endpoints) HTTP/REST is a first-class, optional transport in Elarion — the sibling of [JSON-RPC](/docs/capabilities/transports/json-rpc). Mark a handler with `[HttpEndpoint]` and the module bootstrapper generator emits the matching minimal-API registration: it unwraps the nested `Query`/`Command` into route/query/body parameters and translates the handler's [`Result`](/docs/concepts/results-and-errors) into a response — `200`/`204` (or [`201 Created`](#creation-responses-201--location)) on success, or an RFC 7807 ProblemDetails with the right status code on failure. Like JSON-RPC, the mapping lives in `Elarion.AspNetCore` (plus the `[HttpEndpoint]` attribute in `Elarion.Abstractions`), so applications that don't need it pay nothing, and handlers stay transport-neutral — the same handler can carry both `[HttpEndpoint]` and `[Handler]`. REST is a separate exposure model from JSON-RPC and MCP. Those two are adapters over one named request/reply bus (`HandlerDispatcher`), keyed by operation name; `[HttpEndpoint]` is route- and verb-based, so it stays its own opt-in rather than a flag on `[Handler]`. A handler can carry both without conflict. ## Marking a handler [#marking-a-handler] Add `[HttpEndpoint]` to a handler. The verb is **inferred from the request's CQRS marker** — `IQuery` maps to `GET`, `ICommand` maps to `POST` — and the route is explicit: ```csharp [HttpEndpoint("clients/{id}")] // GET (inferred from IQuery) public sealed class GetClient(BillingDbContext db) : IHandler> { public sealed record Query : IQuery { public required Guid Id { get; init; } } public sealed record Response(Guid Id, string Name); public ValueTask> HandleAsync(Query query, CancellationToken ct) { /* ... */ } } [HttpEndpoint("clients")] // POST (inferred from ICommand) public sealed class CreateClient : IHandler> { /* ... */ } ``` Verb precedence is: an explicit verb wins; otherwise the request's `ICommand`/`IQuery` marker decides; otherwise the generator reports `ELHTTP004` (a request that is neither marked nor given an explicit verb cannot be mapped). Naming or nesting the request `Command`/`Query` has **no** effect on the verb. ```csharp [HttpEndpoint(HttpVerb.Delete, "clients/{id}")] // explicit verb; request needs no marker public sealed class DeleteClient : IHandler> { /* ... */ } ``` The generator reads the request and response from the `IHandler>` interface (the success type is unwrapped from `Result`); the types may be nested or top-level. A `Response` with no properties returns `204 No Content`; a [`Result`](#files-downloads-and-uploads) response is served as a binary file download, a [`Result`](#streamed-files-http-only-endpoints) response is streamed to the body; a [`Result>`](#creation-responses-201--location) response returns `201 Created`; otherwise success returns `200 OK` with the JSON response body. ## Creation responses: 201 + Location [#creation-responses-201--location] A resourceful create answers `201 Created` by declaring the created-resource envelope as its response type — the same declare-once pattern as [`ElarionFile`](#files-downloads-and-uploads) (ADR-0072). The generated mapping peels the envelope: the response body is the **inner** value, the envelope's optional `Location` becomes the `Location` header, and the OpenAPI document truthfully advertises `201` with the inner type's schema. Failures keep the central `AppError` → RFC 7807 translation unchanged. ```csharp [HttpEndpoint("clients")] // POST (inferred from ICommand) public sealed class CreateClient(BillingDbContext db) : IHandler>> { public sealed record Command : ICommand { public required string Name { get; init; } } public sealed record Response(Guid Id, string Name); public async ValueTask>> HandleAsync(Command command, CancellationToken ct) { var client = new Client { Id = Guid.CreateVersion7(), Name = command.Name }; db.Clients.Add(client); await db.SaveChangesAsync(ct); return new ElarionCreated(new Response(client.Id, client.Name)) { Location = $"clients/{client.Id}", // optional; omit for 201 without a Location header }; } } ``` The envelope never appears on the HTTP wire. On the name-routed JSON surfaces (a handler that also carries `[Handler]`) there is no status code to express, so there it serializes as a plain object carrying `value` and `location` — prefer a plain response type for operations designed for JSON-RPC/MCP. ## Request-driven SSE responses [#request-driven-sse-responses] `[HttpEndpoint]` generates a unary request/reply route. A response that is itself a lazy sequence instead implements `IStreamHandler` and is mapped explicitly in the owning module's `MapEndpoints` hook with a direct `MapGet` and `ElarionHttpResults.ToStreamResult`. Because that call site is hand-written in your compilation, ASP.NET Core owns its route/query binding (and the Request Delegate Generator can compile it ahead of time in an AOT host); it is intentional, not a missing generated endpoint. ```csharp endpoints.MapGet("reports/{reportId}/export", static (Guid reportId) => ElarionHttpResults.ToStreamResult(new() { ReportId = reportId, })); ``` The request stream still uses canonical source-generated JSON after `AddElarionHttpJson()`, but it is not an OpenAPI/JSON-RPC/MCP operation. Read [request-driven server streaming](/docs/capabilities/transports/server-streaming) for the choice between this cold per-request shape, client events, and actor-owned ordered streams, plus its scope and failure semantics. ## Hosting [#hosting] `[HttpEndpoint]` handlers are mapped through the generated module bootstrapper, so they are **feature-flag-gated** like everything else a module owns ([modules are the single hosting path](/docs/capabilities/hosting)). `MapElarionEndpoints` calls each enabled module's `MapEndpoints` hook and its generated `Map{Module}Http` method; a module disabled with `Modules:{Name}:Enabled = false` drops its routes: ```csharp [assembly: Elarion.AspNetCore.GenerateModuleBootstrapper] // Program.cs builder.Services.AddElarionHttpJson(); // canonical JSON + RFC 7807 responses (see below) var app = builder.Build(); app.MapElarionEndpoints(app.Configuration); // module routes, gated per module ``` `MapElarionEndpoints` maps everything inside one prefix-less route group and returns it, so a host attaches a convention to every Elarion endpoint at once: ```csharp // Deny by default: every route this maps requires a signed-in user unless its handler is [AllowAnonymous]. app.MapElarionEndpoints(app.Configuration).RequireAuthorization(); ``` The group holds module `MapEndpoints` hooks and generated `[HttpEndpoint]` routes. `MapElarionJsonRpc` and `MapElarionMcp` map their own endpoints; give them the same convention where the host wants it. The generated registration is a concrete, per-handler `RequestDelegate` whose binding code the generator emits at compile time (ADR-0071): no open generics, no reflection, and no dependency on ASP.NET Core's reflection-based `RequestDelegateFactory` or its Request Delegate Generator — RDG is itself a source generator and can never see another generator's output, so Elarion does its own binding and the endpoints stay Native-AOT/trim-safe by construction. Each endpoint also carries its response metadata (`ProducesResponseTypeMetadata`), the full set of ProblemDetails error responses, its owning module as an OpenAPI **tag**, an inert idempotency marker for an `[Idempotent]` handler, and a metadata-only "API shape" method that keeps ApiExplorer describing the endpoint's parameters and request body, so it shows up correctly in OpenAPI. Add the opt-in [`Elarion.AspNetCore.OpenApi`](/docs/capabilities/transports/openapi) package to turn that into a served OpenAPI document (and a generated client) — the REST analog of the JSON-RPC schema and TypeScript client. ### JSON serialization with reflection off [#json-serialization-with-reflection-off] The `[HttpEndpoint]` transport serializes **both directions** — request-body binding (a POST/PUT/PATCH JSON body) and the success value (`ElarionHttpResults` uses `TypedResults.Ok`) — through ASP.NET's global `Microsoft.AspNetCore.Http.Json` options, which Elarion otherwise leaves at their defaults. With `JsonSerializerIsReflectionEnabledByDefault=false` (the AOT-friendly default) those options have no resolver for your DTOs, so (de)serialization fails. Call `AddElarionHttpJson()` once to fix it: ```csharp builder.Services.AddElarion(builder.Configuration); // contributes the module JSON contexts builder.Services.AddElarionHttpJson(); // aligns ASP.NET's HTTP JSON options with the canonical config ``` It mirrors the canonical naming knobs and source-generated resolver chain onto the HTTP JSON options, so requests, responses (and your host's own minimal-API endpoints) resolve through the same contexts every transport uses — and REST output matches the JSON-RPC/MCP transports for the same DTO. It is a deliberate, **global** alignment of the app's minimal-API JSON, is idempotent, and runs in registration order — a host that needs different behavior calls `ConfigureHttpJsonOptions(…)` **after** it and wins (applying to both directions consistently). It also calls ASP.NET's `AddProblemDetails()` for you: the RFC 7807 **error** legs (`ElarionHttpResults` renders an `AppError` via `Results.Problem`/`Results.ValidationProblem`) serialize through ASP.NET's own source-generated `ProblemDetailsJsonContext`, which only that call contributes — without it, every error response 500s with reflection off while the success legs work. A host that wants `CustomizeProblemDetails` just calls `AddProblemDetails(configure)` itself; the two registrations compose in either order. `AddElarionOpenApi()` already calls `AddElarionHttpJson()`, so a host that adds [OpenAPI](/docs/capabilities/transports/openapi) does not need a separate call. ### Per-module authorization and route conventions [#per-module-authorization-and-route-conventions] `MapElarionEndpoints` maps every enabled module's routes into the same route group, leaving authentication and authorization to the host's middleware, global policies, and the conventions it adds to the returned group. There are no per-module URL prefixes by default — each `[HttpEndpoint("...")]` carries its own complete route template, so modules share a flat URL space and any module can declare a route under any path (the generator only guards against duplicate `verb + route` pairs). When a module needs its own authorization policy or route conventions, that is a **module concern**: the module declares an optional `ConfigureEndpointGroup` hook that returns the builder its generated routes (and its `MapEndpoints` hook) are mapped onto. The host keeps calling `MapElarionEndpoints` once; the module owns its group: ```csharp [AppModule("Billing")] public static partial class BillingModule { // Applies this module's conventions/policy to its generated [HttpEndpoint] routes. public static IEndpointRouteBuilder ConfigureEndpointGroup(IEndpointRouteBuilder root) => root.MapGroup("").RequireAuthorization("billing"); // policy only — no prefix } ``` A conventions-only group (`MapGroup("")`) attaches a policy or metadata **without** a prefix, so the module's routes keep their full templates and the flat URL space is preserved. A module that wants to own a URL segment can instead return `root.MapGroup("/billing")` — that prefixes *all* of its generated routes, the explicit trade for a module that wants its own path. This is the same seam as a module's own `MapEndpoints` hook: the host owns global middleware order and the module owns its group. When a *single* endpoint needs its own conventions, declare a [`CustomizeEndpoint` hook](#per-endpoint-conventions-the-customizeendpoint-hook) on the handler instead of moving it off the generated path. ### Public handlers stay public [#public-handlers-stay-public] The generator infers exactly one thing about ASP.NET authorization from a handler: a handler marked Elarion's `[AllowAnonymous]` (declared or inherited) gets `.AllowAnonymous()` on its route. A host `FallbackPolicy`, a `RequireAuthorization()` on the returned group, or a module group's policy therefore leaves it open, exactly as the handler pipeline does — no path-prefix exception list in `Program.cs`. Nothing else is inferred: a guarded handler's route carries no `RequireAuthorization()`, because which ASP.NET policy guards a route (and whether the host runs ASP.NET authorization at all) is the host's decision; the handler's `[Require*]` attributes are enforced by the handler pipeline on every transport regardless. ### Per-endpoint conventions: the CustomizeEndpoint hook [#per-endpoint-conventions-the-customizeendpoint-hook] A handler may declare a static convention hook that the generated registration calls **after** the emitted metadata chain (ADR-0072). It receives the endpoint's `IEndpointConventionBuilder`, so the handler can attach per-endpoint host conventions — an authorization policy, rate limiting, output caching, extra metadata — while keeping generated binding, ProblemDetails translation, and OpenAPI description: ```csharp [HttpEndpoint("exports/{list}")] public sealed class GetExport(IMasterDataExporter exporter) : IHandler> { // Called once at mapping time, after the generated metadata chain; conventions added here land last. public static void CustomizeEndpoint(IEndpointConventionBuilder endpoint) => endpoint.RequireRateLimiting("exports").CacheOutput(); // ... } ``` The contract is exactly `public static void CustomizeEndpoint(IEndpointConventionBuilder)` — `public` because the call site is emitted into the referencing host's compilation (the same visibility a cross-assembly handler already needs for its DTOs), and `IEndpointConventionBuilder` (not `RouteHandlerBuilder`) because the AOT-safe `RequestDelegate` registrations return the interface (ADR-0071). A method named `CustomizeEndpoint` with any other shape warns `ELHTTP006` and is ignored. Declaring the hook opts the handler's assembly into an ASP.NET Core reference — the same deliberate trade as the [`[From*]` binding opt-ins](#customizing-binding); a strictly web-free module assembly attaches conventions through its module group or a `[ModuleEndpoints]` contributor instead. The hook attaches **host/transport conventions**. Business authorization stays declarative in the handler pipeline (`[Require*]` — see [authorization](/docs/concepts/authorization)); the hook is where an HTTP-tier policy (`RequireAuthorization("policy")`) goes when one endpoint genuinely differs from its module's group. ## Binding [#binding] The generator classifies every bindable request member at compile time and emits the binding code itself (ADR-0071). The defaults cover the common cases with no annotation: * `GET`/`DELETE` bind the request from **route tokens and the query string**: a constructor parameter or settable/init property whose name matches a route token (case-insensitively) binds from the route; everything else binds from the query string. * `POST`/`PUT`/`PATCH` bind the request from the **JSON body**. Requiredness follows the DTO: a `required` member or a non-nullable member without a default must be present on the wire; a nullable member is optional (absent → `null`); a constructor parameter default or a property initializer is preserved when the wire says nothing. Supported member types for route/query/header/ form values are `string`, enums (parsed case-insensitively), and any `IParsable` value type such as `Guid`, `int`, or `DateTimeOffset` (invariant culture), plus their nullable forms and — from repeated query keys — arrays of those. Anything else is a compile-time `ELHTTP005` diagnostic, not a runtime surprise. A request that fails to bind never reaches the handler: malformed or missing values produce the same RFC 7807 `ValidationProblem` shape as handler-tier validation — status `400` with a field-keyed `errors` map — and a body with the wrong content type is rejected with `415`. The request DTO stays the host's responsibility to keep in a `JsonSerializerContext` (the same requirement as JSON-RPC, since reflection-based JSON is off by default); body binding reads the minimal-API `Http.Json` options, so `AddElarionHttpJson()` puts it on the canonical source-generated contexts. ### Customizing binding [#customizing-binding] When you need more control — a header value, a renamed query parameter, or a file upload — opt the DTO into ASP.NET Core's binding-source attributes by adding a `Microsoft.AspNetCore.App` framework reference (which carries the `[From*]` attributes and `IFormFile`). Decorating any property switches that endpoint to `[AsParameters]` binding: ```csharp [HttpEndpoint("clients/{id}/avatar")] // multipart upload public sealed class UploadAvatar : IHandler> { public sealed record Command : ICommand { public required Guid Id { get; init; } // from the route token public required IFormFile File { get; init; } } public sealed record Response(string Url); } ``` The generator detects `IFormFile`/`IFormFileCollection` and `[FromForm]` members, binds them from the request form (a non-form content type is a `415`), and marks the endpoint `.DisableAntiforgery()` — generator-bound endpoints don't participate in ASP.NET's automatic form antiforgery, so a host that wants antiforgery on a form post enforces it deliberately. A form post is a cross-site "simple" request, so a host whose browsers authenticate with a cookie installs `UseElarionCrossOriginProtection()` (see [CSRF and cookie authentication](/docs/capabilities/hosting#csrf-and-cookie-authentication)). For a mutation that mixes a path id with a JSON payload, nest the payload in a `[FromBody]` property: ```csharp public sealed record Command { [FromRoute] public required Guid Id { get; init; } [FromBody] public required UpdateClientBody Body { get; init; } } ``` This opt-in is the deliberate tradeoff: the DTO's assembly references ASP.NET Core only when it needs HTTP-specific binding, and only then. ## Files: downloads and uploads [#files-downloads-and-uploads] A **small** file (an `.xlsx` export, a generated PDF, an avatar — as a rule of thumb, up to \~4 MB) is plain handler data: `ElarionFile` in `Elarion.Abstractions` carries the content bytes, the content type, and an optional file name. Declaring it says "this handler receives/returns a file" once, and every transport does its best with it — HTTP serves a file response, the JSON surfaces carry a [base64 envelope](/docs/capabilities/transports/json-rpc#file-payloads), and the generated TypeScript client speaks native `File`. Authorization, feature gating, and module scoping apply exactly like every other handler; failures still map to RFC 7807: ```csharp [HttpEndpoint("exports/{list}")] [RequirePermission("exports", "read")] public sealed class GetExport(IMasterDataExporter exporter) : IHandler> { public sealed record Query : IQuery { public required string List { get; init; } } public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var bytes = await exporter.BuildXlsxAsync(query.List, ct); if (bytes is null) return AppError.NotFound($"unknown export '{query.List}'"); return new ElarionFile(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileName = $"{query.List}.xlsx", // Content-Disposition: attachment; omit for inline content }; } } ``` Uploads are the same type on the request side: an `ElarionFile` property binds from the JSON body's base64 envelope, so one client code path covers every transport. When you specifically want HTTP **multipart** binding (a plain ``, FilePond), keep using `IFormFile` in the DTO ([customizing binding](#customizing-binding)) — that is the HTTP-native escape hatch; `ElarionFile` is the transport-neutral default. In the OpenAPI document a file response advertises `application/octet-stream` with `type: string, format: binary` (the concrete content type is per-payload at run time), so off-the-shelf generated clients return a blob. Every file response of the framework — `ElarionFile`, `ElarionStreamedFile` and the [blob transfer endpoints](/docs/capabilities/blob-uploads) — carries `X-Content-Type-Options: nosniff`: a file is often somebody's upload served from your own origin, so the browser must take its declared content type and never sniff the bytes into a type it renders. ### Streamed files: HTTP-only endpoints [#streamed-files-http-only-endpoints] Some files are too large to buffer and only ever reach a browser: a stored document, a ZIP built from many of them, a report rendered while it is sent. A handler mapped with `[HttpEndpoint]` alone (no `[Handler]`) returns `Result`, and its content is written to the response body after the pipeline has run — `[RequirePermission]`, the module's feature gate, validation and the declared errors apply before the first byte, as for any handler: ```csharp [HttpEndpoint("documents/{id}/content")] [RequirePermission("documents", "read")] public sealed class DownloadDocument(AppDbContext db, IBlobStore blobs) : IHandler> { public sealed record Query : IQuery { public required Guid Id { get; init; } public bool Inline { get; init; } } public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var document = await db.Documents.FindAsync([query.Id], ct); var download = document is null ? null : await blobs.OpenReadAsync(document.Blob, ct); if (download is null) return AppError.NotFound("No such document."); // The download (its stream and the database reader behind it) is disposed with the response. return ElarionStreamedFile.FromStream(download.Content, download.Metadata.ContentType, owner: download) with { FileName = document!.FileName, Disposition = query.Inline ? FileDisposition.Inline : FileDisposition.Attachment, EntityTag = download.Metadata.ContentSha256, CacheControl = "private, max-age=3600", }; } } ``` `FromWriter` builds the content while it is sent; the writer gets the response body and the request's cancellation: ```csharp return ElarionStreamedFile.FromWriter(async (body, ct) => { await using var zip = await ZipArchive.CreateAsync(body, ZipArchiveMode.Create, leaveOpen: true, null, ct); foreach (var document in documents) { await using var download = await blobs.OpenReadAsync(document.Blob, ct); if (download is null) continue; var entry = zip.CreateEntry(document.FileName, CompressionLevel.Fastest); await using var entryStream = await entry.OpenAsync(ct); await download.Content.CopyToAsync(entryStream, ct); } }, "application/zip") with { FileName = "documents.zip" }; ``` When only reading the content tells whether the file is there — an attachment found while parsing a stored message — or what its name and type are, return `ElarionStreamedFile.Deferred`. Its open runs where the content would and answers either the file or an `AppError`; since nothing is written yet, the error is the ordinary problem response (`404` with its code), and the file is read once: ```csharp return ElarionStreamedFile.Deferred(async ct => { var download = await blobs.OpenReadAsync(message.Blob, ct); var part = download is null ? null : await MimeAttachments.FindAsync(download.Content, query.Part, ct); if (part is null) { if (download is not null) await download.DisposeAsync(); // an open that refuses disposes what it opened return AppError.NotFound("No such attachment.", "mail.attachment_not_found"); } return ElarionStreamedFile.FromStream(part.Content, part.ContentType, owner: download) with { FileName = part.FileName, Length = part.SizeBytes, // the part decodes forward-only, but its size is known: the browser shows progress }; }); ``` The answered file states everything the response carries; a property set on the deferred file itself has no effect. Authorization and whether the record exists stay in the handler. In process (a test, a module API), `OpenAsync` answers the file or the refusal. | Property | Response | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ContentType` | `Content-Type` | | `FileName`, `Disposition` | `Content-Disposition: attachment` (the default) or `inline`, with the name as UTF-8 and an ASCII fallback. A streamed file always states a disposition. | | `EntityTag` | a strong `ETag`; a matching `If-None-Match` answers `304` without writing the content | | `LastModified` | `Last-Modified`, honoured for `If-Modified-Since` | | `CacheControl` | `Cache-Control`; keep files behind authorization `private` | | `Length` | `Content-Length`, for content that cannot state it itself (a forward-only stream, a writer); checked against the bytes written. Unset, a seekable stream states its own length and anything else is sent chunked. | What happens around the bytes: * **When the content runs.** After the pipeline, in the request's service scope but after the handler's transaction has committed. Open what the content needs in the handler, where a missing record still answers `404`; a blob read opened outside a transaction streams from the database without buffering. * **Failures.** Before the first byte, an exception is an ordinary unexpected error, and a deferred file's refusal is its ordinary error response. After it, the status is already sent, so the connection is aborted: the client sees a failed download, never a truncated file that looks complete. * **A stated length.** `Length` is sent as `Content-Length` with the body (not on a `304`), and the bytes written are counted: a content that writes past it fails at that write, one that writes fewer fails at its end, and either aborts the connection like any failure after the first byte. On a seekable stream the length must equal what is left from its position, or the response fails before the first byte. * **Synchronous writes.** The server refuses synchronous writes to the body. `ZipArchive` makes a few even through its async API: an entry stream from `OpenAsync` flushes its compressed trailer and data descriptor in the synchronous `Dispose` that `await using` falls back to. The body a writer receives holds such writes (up to 1 MiB at a time) and sends them with the next asynchronous write, so the code above needs no `AllowSynchronousIO`. Write the bulk of the content asynchronously; a writer that writes everything synchronously fails at that limit. On .NET 11 the entry stream disposes asynchronously and `ZipArchive` writes nothing synchronously; the holding is what keeps the same code working on .NET 10. * **Inline disposition.** Show in place only content types the browser renders safely (PDF, raster images). A user-supplied `text/html` or `image/svg+xml` served inline from your origin runs as part of it; `nosniff` does not change that. * **Only HTTP carries it.** The JSON surfaces and the replaying decorators need a payload that serializes: a `[Handler]` responding with `ElarionStreamedFile` is error `ELRPC005`, an `[Idempotent]` or `[Cacheable]` one `ELHTTP007`. A file a JSON-RPC client must receive stays an `ElarionFile` or a pending blob. ### Large files: the staged-blob tier [#large-files-the-staged-blob-tier] `ElarionFile` is deliberately in-memory — the payload is buffered end to end (and base64-inflated on JSON transports), which is wrong past a few megabytes. Large files move through the [staging blob area](/docs/capabilities/blob-storage) instead, and the handler only sees a **pointer**: * **Import**: the client uploads through `MapElarionResumableBlobUploads` (resumable) or `MapElarionBlobUploads` into the pending area, then passes the returned blob reference to the handler as an [`UploadedFile`](/docs/capabilities/blob-uploads#passing-an-upload-to-a-handler), which streams it from `IUploadedFiles.OpenAsync` (the caller's own pending upload only). A blob the handler never commits is garbage-collected after its TTL. * **Export**: the handler streams the artifact into the store as a pending blob owned by the current user and returns its `BlobRef`; the client streams it down from `MapElarionBlobDownloads`. An export nobody downloads expires on its own — the pending state doubles as temp-file semantics. See [ADR-0039](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0039-binary-file-responses.md) for the full two-tier rationale, and [ADR-0098](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0098-streamed-files-for-http-only-endpoints.md) for the streamed tier of HTTP-only endpoints. ## Errors map once, centrally [#errors-map-once-centrally] Handlers stay transport-agnostic and return [`Result`](/docs/concepts/results-and-errors); the generated endpoint translates a failed `AppError` to an RFC 7807 ProblemDetails response. The status code comes from `AppError.Kind`, mirroring how JSON-RPC maps the same kinds to its error codes: | `ErrorKind` | HTTP status | | -------------- | -------------------------------------------------------------------- | | `Validation` | `400` (validation errors surface in the ProblemDetails `errors` map) | | `Unauthorized` | `401` | | `Forbidden` | `403` | | `NotFound` | `404` | | `Conflict` | `409` | | `BusinessRule` | `422` | | `Internal` | `500` | Every ProblemDetails carries the error's stable `code` (and a `data` member for a typed payload), so a client branches on the same string as over JSON-RPC — see [OpenAPI › Typed errors](/docs/capabilities/transports/openapi#typed-errors). Binding-tier failures use the same contract before the handler runs: an unparseable route/query/header/form value or a missing required member is a `400` `ValidationProblem` (`code: "validation"`) keyed by the wire name, and a request body with a non-JSON content type is a bare `415`. An exception that escapes the handler pipeline — from the handler or from any decorator — is caught by the generated endpoint itself and answered as a `500` ProblemDetails with `code: "internal"`, the configured message as `detail`, and a support `reference`, the same answer JSON-RPC and MCP give (see [Unexpected errors](/docs/concepts/results-and-errors#unexpected-errors)). It is logged with that reference and does not reach the host's exception-handling middleware; a request the client aborted is not answered. ## HTTP or JSON-RPC? [#http-or-json-rpc] Both transports map the same handlers, so the choice is per-handler, not per-app. Reach for `[HttpEndpoint]` when you want resourceful URLs, HTTP caching/CDN semantics, file uploads, or third-party/public consumers; reach for [`[Handler]`](/docs/capabilities/transports/json-rpc) when one team owns both ends and wants an operation-shaped, end-to-end-typed contract with a generated TypeScript client. A handler can expose both. # Transports (/docs/capabilities/transports) A handler is transport-neutral: it accepts an application request with no knowledge of how it was called. A unary handler returns `Result`; an explicit server-stream handler returns a lazy response sequence. A **transport** is what puts that handler on the network. HTTP, JSON-RPC, and MCP are peer surfaces selected from one unary handler definition. gRPC is an additional typed adapter: its generated service override deliberately owns protobuf mapping while `Elarion.Grpc` preserves the same dispatch pipeline; `Elarion.Grpc.AspNetCore` supplies the conventional grpc-dotnet host composition. REST-style routes generated from `[HttpEndpoint]` — verbs, route binding, and RFC 7807 errors. A cold, lazy response to one request over SSE or gRPC — exports, token output, and tail queries. An OpenAPI document for the `[HttpEndpoint]` routes — schema and client parity with JSON-RPC. Operation-shaped methods from `[Handler]`, with a build-time schema and a typed TypeScript client. Explicit unary and request-driven server-streaming protobuf mappings over the standard ASP.NET Core grpc-dotnet host. The same `[Handler]` operations exposed to AI agents as Model Context Protocol tools. ## The shared handler shape [#the-shared-handler-shape] Unary transports invoke `IHandler>`; the request and response types may be nested inside the handler or declared top-level — the nesting carries no meaning. The transport unwraps the success value from `Result` and maps an `AppError` to its own failure representation centrally, so the handler never encodes protocol concerns. HTTP/SSE and gRPC can also explicitly invoke `IStreamHandler` for a [cold request-driven response](/docs/capabilities/transports/server-streaming). gRPC adds explicit generated protobuf-to-application mapping in the service override; see [gRPC](/docs/capabilities/transports/grpc). JSON-RPC and MCP share a single identity. A handler opts into them with one `[Handler("module.action")]` attribute (the operation name is optional — `[Handler]` alone is valid and the name is inferred by convention), and the `Transports` flag (`HandlerTransports.JsonRpc`, `HandlerTransports.Mcp`, `HandlerTransports.Connection`, or `HandlerTransports.All`, the default) selects which name-routed surfaces expose it. HTTP is a separate opt-in via `[HttpEndpoint]` because it needs route, verb, and parameter binding that do not fit a flags enum. Under the hood, JSON-RPC and MCP are not two parallel stacks. There is one transport-neutral **named request/reply bus** — `HandlerDispatcher` — that maps an operation name to a handler and invokes it through the full decorator pipeline. JSON-RPC and MCP are thin **adapters** over that one bus: each serves only the operations flagged for its surface. The generator builds one registry; both adapters resolve it. So a handler is *define once, choose surfaces via the `Transports` flag*. The bus is a **transport seam**, not an in-process call path: it exists because JSON-RPC and MCP carry an operation *name* on the wire. HTTP doesn't use it — a `[HttpEndpoint]` route resolves its handler typed-directly, since the route already pins the type. To call a handler from your own code, prefer the typed paths in [Calling a handler from code](/docs/concepts/handlers#calling-a-handler-from-other-code). ## Which transport should I use? [#which-transport-should-i-use] Choose when you need resource-shaped URLs, standard verbs and status codes, or you are serving a public or third-party API where REST conventions are expected. Choose for internal, first-party APIs where one team owns both ends. A method maps one-to-one to a handler, and the generated typed client makes a frontend call feel like invoking the handler directly. Choose to expose your operations to AI agents as tools, with names, descriptions, and input schemas generated from your handlers — no separate tool layer. They are not exclusive. A handler can be a REST endpoint, a JSON-RPC method, and an MCP tool at once. ## Wiring [#wiring] HTTP, JSON-RPC, and MCP are **module-scoped and feature-flag-gated** when a host opts into `[GenerateModuleBootstrapper]`: a disabled module disappears from every transport at once. See [Hosting & composition](/docs/capabilities/hosting) for how the generated bootstrapper maps each transport into the host. # JSON-RPC (/docs/capabilities/transports/json-rpc) JSON-RPC is a first-class, optional transport in Elarion. It lives outside the core framework package (`Elarion.JsonRpc` plus `Elarion.AspNetCore`) so applications that don't need it pay nothing for it. What makes it worthwhile is that the pipeline is **end-to-end and typed**, from a C# handler to a generated TypeScript client — with no hand-written DTOs in between. ## Why JSON-RPC? [#why-json-rpc] Elarion's application model is a set of **handlers** — named use cases that take a request and return a `Result`. JSON-RPC is the transport that mirrors that model most directly: it exposes **operations**, not resources. A method name like `clients.create` maps one-to-one to a handler. The transport reflects your application instead of forcing a resource/CRUD shape on top of it. That choice removes an entire category of API design work. With REST you decide, for every endpoint: * the **URL path** and how to model nesting and collections, * which **HTTP verb** fits (`GET`/`POST`/`PUT`/`PATCH`/`DELETE`) and what that implies, * how to map an outcome onto a **status code** (and what `200` vs `201` vs `204` vs `409` means here), * resource representations, content negotiation, and partial-update semantics. With JSON-RPC, none of that is a decision. `clients.create` is a method that takes a `Command` and returns a `Result`. Failures map once, centrally, from [`AppError.Kind`](/docs/concepts/results-and-errors#mapping-to-a-transport) to a JSON-RPC error code — not per endpoint. ### It feels like calling the handler directly [#it-feels-like-calling-the-handler-directly] Because the [generated TypeScript client](/docs/capabilities/transports/typescript-client) is produced from the same schema the server dispatches, a frontend call is about as close as a network round-trip gets to invoking the C# handler — same parameter shape, same result type, validated by Zod: ```ts // Frontend — the call mirrors the server-side GetClient handler const client = await rpc.clients.get({ id }) // ^? { id: string; name: string } (typed from the C# Response) ``` ```csharp // Backend — the handler the call above resolves to [Handler("clients.get")] public sealed class GetClient(AppDbContext db) : IHandler> { /* ... */ } ``` The iteration loop is short: add a handler, mark it `[Handler]`, regenerate the client, and call it as a typed method. There is no route to design, no DTO to duplicate on the client, and no transport plumbing to write. ### Where it fits — and where it doesn't [#where-it-fits--and-where-it-doesnt] This makes JSON-RPC an excellent fit for **internal, first-party APIs** where one team controls both the backend and the client (a web app talking to its own backend, a BFF, service-to-service calls). You trade REST's broad-ecosystem conventions for speed and a contract that tracks your code. Reach for REST/HTTP instead when you have **third-party or public consumers**, need HTTP caching / CDN semantics, resourceful URLs, or the wider tooling ecosystem around them. Elarion supports this too: JSON-RPC is optional and outside the core package, and modules can expose ordinary [Minimal API endpoints](/docs/concepts/modules#endpoints-in-modules) alongside — or instead of — JSON-RPC methods. You are not locked into one transport. ## One bus, thin adapters [#one-bus-thin-adapters] JSON-RPC is not a self-contained dispatcher. The transport-neutral core is a single **named request/reply bus** — `HandlerDispatcher` (in `Elarion.Abstractions`, namespace `Elarion.Abstractions.Dispatch`) — that maps an operation name to a handler and invokes it through the full decorator pipeline. It owns no serialization or wire format. `JsonRpcDispatcher` (in `Elarion.JsonRpc`) is the **JSON-RPC adapter** over that bus: it adds the JSON-RPC envelope and serialization and serves only the operations flagged `HandlerTransports.JsonRpc`. MCP is a second adapter over the *same* bus. The generator builds one registry of handlers (`RegisterHandlers`) and both adapters resolve it — so a handler is *define once, choose surfaces via the `Transports` flag*, never registered separately per transport. ## The end-to-end pipeline [#the-end-to-end-pipeline] 1. Application handlers declare `[Handler("module.action")]` (the operation name is optional — see [name inference](#marking-a-handler)). 2. `AppModuleDiscoveryGenerator` (via `[GenerateModuleBootstrapper]`) emits the gated handler registration map (`RegisterHandlers`). 3. `AddElarionJsonRpc` registers the `JsonRpcDispatcher`, which reads the canonical [`IElarionJsonSerialization`](/docs/capabilities/serialization) options (the same serializer the whole app uses) and adapts the shared `HandlerDispatcher` registry to the JSON-RPC wire format. 4. `JsonRpcSchemaExporter` (or the [build-time package](/docs/capabilities/transports/schema-generation)) exports `rpc-schema.json` from the registered dispatcher — including the request DTOs' DataAnnotations constraints as JSON Schema keywords (see [Validation](/docs/concepts/validation)). 5. [`elarion-jsonrpc-client-generator`](/docs/capabilities/transports/typescript-client) converts that schema into TypeScript types, constraint-aware Zod params/result schemas, and a typed fetch client that pre-validates request params. 6. The frontend uses the generated client directly or wraps it in framework-specific helpers. Each stage has a single owner, which keeps the reusable contract small: * `Elarion.Abstractions` owns the transport-neutral `HandlerDispatcher` bus. * `Elarion.JsonRpc` owns the JSON-RPC adapter, runtime dispatch, telemetry, and schema export. * `Elarion.AspNetCore` owns HTTP endpoint mapping and ASP.NET Core transport behavior. * `Elarion.AspNetCore.SchemaGeneration` owns build-time schema export. * `elarion-jsonrpc-client-generator` owns schema-to-TypeScript generation. * Applications own server-function/auth/cache adapters around the generated client. ## Marking a handler [#marking-a-handler] Add `[Handler]` to a handler that follows the conventional shape: ```csharp [Handler("clients.create")] public sealed class CreateClient : IHandler> { public sealed record Command(string Name); public sealed record Response(Guid Id); public ValueTask> HandleAsync(Command command, CancellationToken ct) { // ... } } ``` The handler generator reads the request and response types from the `IHandler>` implementation. Nesting the DTOs inside the handler (as above) is a tidy convention, not a requirement — request and response types may be nested or top-level, and their names carry no semantic weight. ### The operation name is optional [#the-operation-name-is-optional] The operation name is **optional** — `[Handler]` alone is valid. When omitted, the name is inferred by convention as `{module}.{operation}`, where `operation` is the handler type name with a trailing `Handler`/`Command`/`Query`/`Request` suffix removed, then camelCased. So in a `Clients` module, `CreateClient` becomes `clients.createClient`: ```csharp [Handler] // inferred: clients.createClient public sealed class CreateClient : IHandler> { /* ... */ } ``` An explicit name is **recommended for stable public or wire contracts**, since a type rename would otherwise change the operation name. Use the inferred name for internal handlers where the convenience is worth more than name stability. The generated map registers each operation on the shared `HandlerDispatcher` registry with its transport flags: ```csharp registry.Map("clients.create", HandlerTransports.JsonRpc); ``` In hand-written or test code you map directly onto a `HandlerDispatcher` with the convenience overloads — `dispatcher.Map("name")` resolves the handler from DI, while `dispatcher.MapDelegate("name", fn)` maps an inline delegate: ```csharp dispatcher.Map("clients.create"); dispatcher.MapDelegate("diagnostics.ping", (req, services, ct) => /* ... */); ``` ## File payloads [#file-payloads] `ElarionFile` — the in-memory small-file payload shared with the [HTTP transport](/docs/capabilities/transports/http-endpoints#files-downloads-and-uploads) — is a first-class citizen here too, **both directions**. On every JSON surface it rides a fixed base64 envelope (canonical, independent of the host's naming policy): ```json { "contentType": "text/csv", "fileName": "clients.csv", "data": "aWQ7bmFtZQ==" } ``` A `Result` handler returns the envelope as its result; an `ElarionFile` **property in a request DTO is an upload** — the client sends the same envelope and the handler receives decoded bytes. No registration needed: the type is seeded into the canonical serializer's framework context ([ADR-0039](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0039-binary-file-responses.md)). The exported schema marks the envelope with `x-elarion-file`, and the [generated TypeScript client](/docs/capabilities/transports/typescript-client) turns that into a **native `File`** — callers never see base64: ```ts // Upload: pass a File (e.g. from an ); the client encodes the envelope. const receipt = await rpc.documents.import({ container: 'invoices', file: input.files[0] }) // Download: the result is a real File, ready for URL.createObjectURL or a save dialog. const exported: File = await rpc.exports.get({ list: 'clients' }) ``` The trade against HTTP is buffering: base64 adds \~33% and the payload sits in memory on both ends. That is the deliberate scope of `ElarionFile` — small files, up to a few megabytes. Past that, switch to the staged-blob tier. For an upload, declare the member as an [`UploadedFile`](/docs/capabilities/blob-uploads#passing-an-upload-to-a-handler): the bytes are streamed once to the upload endpoint, the request carries only the blob id (a string, marked `x-elarion-upload` in the schema), and the handler reads it through `IUploadedFiles`, which answers only the caller's own pending upload. A multi-step flow passes the same reference to every step instead of resending the file: ```csharp public sealed record Command : ICommand { public required UploadedFile Statement { get; init; } // "0193…" on the wire } ``` For an export, write a pending blob and return its reference for a streamed download (see [blob uploads](/docs/capabilities/blob-uploads#streaming-downloads-and-temp-file-flows)). ## Requests must be JSON [#requests-must-be-json] `/rpc` only accepts a request whose `Content-Type` is `application/json` (or an `application/*+json` type); anything else, a missing header included, is refused with HTTP `415` and a JSON-RPC `invalid_request` envelope before the body is read. A cross-site `` whose field spells out a JSON-RPC envelope would otherwise reach the dispatcher with the browser's cookies attached. The generated TypeScript client sends the header; add `-H 'content-type: application/json'` to a `curl` call. See [CSRF and cookie authentication](/docs/capabilities/hosting#csrf-and-cookie-authentication) for the opt-out (`JsonRpcOptions.RequireJsonContentType`) and the cross-origin protection middleware. ## Errors map once, centrally [#errors-map-once-centrally] Handlers stay transport-agnostic and return [`Result`](/docs/concepts/results-and-errors); the dispatcher translates `AppError.Kind` into a JSON-RPC error code through the default `IAppErrorTranslator` (`AppErrorMapper`). A host that needs different codes registers its own `IAppErrorTranslator`, which the JSON-RPC and MCP adapters resolve instead of the default. Every error, application or protocol, carries `error.data = { "code": "", "data": }` (`data` omitted when the error has no payload); the numeric `error.code` is only the coarse kind. Handlers declare the codes and payloads they produce with [`[ProducesError]`](/docs/reference/result-and-errors#produceserror--the-declared-error-contract), and the schema export lists them per method. An exception that escapes the handler pipeline is not an `AppError`: the dispatcher answers it with `-32603`, `error.data.code: "internal"`, the configured message and a support `error.data.reference`, and logs the exception with that reference (see [Unexpected errors](/docs/concepts/results-and-errors#unexpected-errors)). Each method in the exported schema also says what a client may know before calling it — `requires` (`anonymous`, or `authenticated` with its `permissions` and `roles`), `readOnly` for queries, and `[ClientTag]` hints under `tags` — which the generated client exposes as [`rpcMethodInfo`](/docs/capabilities/transports/typescript-client#method-requirements-and-ui-gating). ## In this section [#in-this-section] Map the endpoint and freeze the dispatcher in ASP.NET Core. Compose module JSON contexts into the runtime serializer. Export `rpc-schema.json` during `dotnet build` . Generate a typed, portable fetch client and Zod schemas. # MCP server (/docs/capabilities/transports/mcp) `Elarion.AspNetCore.Mcp` exposes the `[Handler]` operations you already write as tools on an [MCP](https://modelcontextprotocol.io) server, over Streamable HTTP. It is the only Elarion package that references the `ModelContextProtocol` SDK, so plain JSON-RPC hosts never pull it in. MCP is a peer of the JSON-RPC and HTTP endpoints, but it is **not a separate stack**. JSON-RPC and MCP are both thin **adapters over one transport-neutral bus** — the `HandlerDispatcher` (in `Elarion.Abstractions`) that maps an operation name to a handler and invokes it through the full decorator pipeline. `McpDispatcher` (in `Elarion.JsonRpc.Mcp`) is the **MCP adapter**: it serves only the operations whose `[Handler(Transports = ...)]` flag includes `HandlerTransports.Mcp`, surfacing each as a tool. A handler therefore declares its operation **once** and chooses which surfaces expose it — JSON-RPC only, MCP only, or **both** (the default) — and the generator builds a single registry both adapters resolve. You never have to mount (or even register) the public JSON-RPC endpoint to use MCP. ## Package reference [#package-reference] ```xml ``` ## Setup [#setup] The MCP server is wired through the generated `ElarionBootstrapper` ([modules are the single hosting path](/docs/capabilities/hosting)), which exposes the gated MCP peers alongside the JSON-RPC and HTTP ones: ```csharp using Elarion.AspNetCore; using Elarion.AspNetCore.Mcp; // The public JSON-RPC endpoint (optional, independent of MCP): the JSON-RPC adapter over the shared bus, // serving the JSON-RPC-surfaced operations of enabled modules at /rpc. builder.Services.AddElarionJsonRpc(ElarionBootstrapper.RegisterHandlers); // The MCP server: the MCP adapter over the same bus, serving the MCP-surfaced operations as one tool each. // Both adapters read the canonical IElarionJsonSerialization (contributed by AddElarion). builder.Services.AddElarionMcp( builder.Configuration.GetMcpMetadata(), // reflection-free, gated tool table ElarionBootstrapper.RegisterHandlers, // the single, gated handler registry both adapters resolve o => o.ServerName = "MyApp"); var app = builder.Build(); app.MapElarionMcp(); // mounts /mcp — calling MapElarionJsonRpc() is optional and independent app.Run(); ``` `GetMcpMetadata` is generated alongside `RegisterHandlers` by the [source generator](/docs/concepts/source-generation): a reflection-free tool table plus the single handler registration delegate (`RegisterHandlers`) that builds the one shared registry both adapters filter by transport flag. The MCP adapter sees only the MCP-surfaced operations of enabled modules. A module disabled with `Modules:{Name}:Enabled = false` drops its tools entirely, and there is no assembly scanning at runtime. MCP and JSON-RPC are two adapters over **one** `HandlerDispatcher` registry, each filtered by the `Transports` flag — not two separate dispatcher instances. `AddElarionMcp` builds the `McpDispatcher` adapter, serving only MCP-flagged operations. `MapElarionMcp()` does not require `MapElarionJsonRpc()` — you can expose MCP without exposing (or even registering) the public JSON-RPC endpoint at all. ## Tool and parameter descriptions [#tool-and-parameter-descriptions] Descriptions come from `[System.ComponentModel.Description]`, read at compile time: ```csharp using System.ComponentModel; using Elarion.Abstractions; [Handler("clients.create")] [Description("Creates a new client record.")] // → tool description public sealed class CreateClient(AppDbContext db) : IHandler> { public sealed record Command { [Description("Human-readable client name.")] // → input-schema property description public required string DisplayName { get; init; } } public sealed record Response(Guid Id); } ``` The generator records the .NET property name; the JSON name is resolved at startup from your serializer's `PropertyNamingPolicy`, so descriptions attach correctly under any naming policy. Tool **input schemas** also carry the request DTO's DataAnnotations constraints (`[Range]`, the length attributes, `[RegularExpression]`, `[EmailAddress]`, `[Url]`, `[Base64String]`) as JSON Schema keywords — they share the JSON-RPC schema builder, so an agent sees the same shape contract the server enforces. See [Validation](/docs/concepts/validation). ## Choosing which transports expose a handler [#choosing-which-transports-expose-a-handler] A handler declares its operation once with `[Handler]` (the name is optional — see [name inference](/docs/capabilities/transports/json-rpc#the-operation-name-is-optional)) and selects its adapter surfaces with the `HandlerTransports` flags (`JsonRpc`, `Mcp`, `Connection`, or `All`). The default is `All` — JSON-RPC, MCP, and bidirectional connection adapters: ```csharp using Elarion.Abstractions; [Handler("clients.create")] // both (default) public sealed class CreateClient : IHandler<...> { ... } [Handler("clients.list", Transports = HandlerTransports.JsonRpc)] // JSON-RPC only — absent from MCP public sealed class ListClients : IHandler<...> { ... } [Handler("ai.summarize", Transports = HandlerTransports.Mcp)] // MCP only — absent from /rpc and the schema public sealed class Summarize : IHandler<...> { ... } ``` Both adapters resolve the **same** `HandlerDispatcher` registry, filtered by each operation's transport flag: the MCP adapter serves only MCP-flagged operations, so an MCP-only handler is genuinely absent from `/rpc` and the exported JSON-RPC schema, and a JSON-RPC-only handler is never surfaced as a tool. REST is a separate opt-in via `[HttpEndpoint]`, since it needs route, verb, and parameter binding that don't fit a flags enum. A handler can be on all three attribute-selected transports at once — see [HTTP endpoints](/docs/capabilities/transports/http-endpoints). ### Renaming a tool [#renaming-a-tool] The optional `[McpHandler]` attribute customizes the MCP projection — currently the tool name. It is purely additive; absent, the tool name is derived from the operation name via `ToolNameTransform`. ```csharp [Handler("clients.create"), McpHandler(ToolName = "create_client")] public sealed class CreateClient : IHandler<...> { ... } ``` ## Options [#options] ```csharp builder.Services.AddElarionMcp( builder.Configuration.GetMcpMetadata(), ElarionBootstrapper.RegisterHandlers, o => { o.ServerName = "MyApp"; // required o.ServerVersion = "1.0"; o.EndpointPath = "/mcp"; o.ToolNameTransform = m => m.Replace('.', '_'); // default o.IncludeErrorDetails = true; // surface JSON-RPC error code/data as structured content }); ``` `MapElarionMcp()` returns the endpoint builder, so you apply authorization yourself: ```csharp app.MapElarionMcp().RequireAuthorization(); ``` ## How tool calls work [#how-tool-calls-work] Each tool call runs through the MCP adapter onto the shared `HandlerDispatcher`, in its own service scope (so scoped services such as a pooled `DbContext` are managed correctly) — the same handler and decorator pipeline a JSON-RPC request invokes, just entered through the MCP adapter instead of the JSON-RPC one. A successful handler result is returned as JSON text; a failure maps to an MCP error, preserving the JSON-RPC error code and data as structured content when `IncludeErrorDetails` is enabled. An exception answers with the configured [unexpected-error](/docs/concepts/results-and-errors#unexpected-errors) message as the tool text and `{ "code": "internal", "reference": "…" }` as structured content — the structured content is part of the error details, so with `IncludeErrorDetails = false` the tool result carries the message alone. If two operations collapse to the same tool name (for example `a.b` and `a_b` under the default transform), tool building throws at startup. Disambiguate with `[McpHandler(ToolName = ...)]` or a custom `ToolNameTransform`. # OpenAPI (/docs/capabilities/transports/openapi) The [JSON-RPC transport](/docs/capabilities/transports/json-rpc) ships a build-time schema and a typed TypeScript client. `Elarion.AspNetCore.OpenApi` gives the [HTTP transport](/docs/capabilities/transports/http-endpoints) the same story with the tools the REST world already expects: a standard **OpenAPI document** you can feed to Swagger UI, Scalar, Kiota, or `openapi-typescript`. It is a thin, opt-in sibling of `Elarion.AspNetCore` over [`Microsoft.AspNetCore.OpenApi`](https://learn.microsoft.com/aspnet/core/fundamentals/openapi/aspnetcore-openapi) — Elarion adds only the wiring Microsoft can't ([ADR-0026](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0026-openapi-http-transport.md)). ## Enable it [#enable-it] ```xml ``` ```csharp builder.Services.AddElarion(builder.Configuration); // contributes the module JSON contexts builder.Services.AddElarionOpenApi(); // wires OpenAPI over the canonical JSON var app = builder.Build(); app.MapElarionEndpoints(app.Configuration); // the generated [HttpEndpoint] routes app.MapOpenApi(); // GET /openapi/v1.json ``` That is the whole runtime setup. `AddElarionOpenApi()` registers `AddOpenApi()` plus the Elarion transformers; `MapOpenApi()` (from `Microsoft.AspNetCore.OpenApi`) serves the document. Expose `MapOpenApi()` and any UI (Swagger UI, Scalar) in development only — the document describes your whole API surface. Gate it with `if (app.Environment.IsDevelopment())` in production hosts. ## What Elarion adds [#what-elarion-adds] Because the generator already annotates every `[HttpEndpoint]` with `.Produces(...)`, the ProblemDetails `.ProducesProblem(...)` set, and a name and description, most of the document is correct out of the box. On top of that `AddElarionOpenApi()` contributes the parts that make it *Elarion's* contract: * **Canonical JSON, reflection-free.** OpenAPI schema generation (and minimal-API request-body binding) read ASP.NET's `Microsoft.AspNetCore.Http.Json` options. `AddElarionOpenApi()` calls [`AddElarionHttpJson()`](/docs/capabilities/transports/http-endpoints#json-serialization-with-reflection-off), which mirrors the canonical [`IElarionJsonSerialization`](/docs/capabilities/serialization) configuration onto them — the naming knobs and the **source-generated** `TypeInfoResolverChain` — so body schemas resolve through the same contexts every other transport uses, with `JsonSerializerIsReflectionEnabledByDefault=false`. A DTO missing from every source-gen context throws (surfacing a missing `[JsonSerializable]`) instead of silently reflecting, and the emitted schema matches the JSON-RPC/MCP wire shape for the same type. * **Validation constraints, for free.** The DataAnnotations attributes on your request DTOs (see [Validation](/docs/concepts/validation)) appear in the document natively — Microsoft's schema generation maps `[Range]`, `[MinLength]`/`[MaxLength]`/`[Length]`/`[StringLength]`, `[RegularExpression]`, `[Url]`, and `[Base64String]` onto the JSON Schema keywords, verified to work reflection-off. Elarion adds small schema transformers for `[EmailAddress]` → `format: "email"` and `[AllowedValues]` → `enum` parity, so the OpenAPI document and the JSON-RPC schema never diverge on the same DTO. * **Module tags.** Each operation is tagged with its owning `[AppModule]`, so tools group your API by module — the REST analog of JSON-RPC's module grouping. * **Clean operation ids.** The handler's fully-qualified type name (`Billing.Invoicing.GetInvoice`) is normalized to a readable `operationId` (`GetInvoice`), so generated clients get sensible method names. Colliding names keep their original id, so ids stay unique. * **The error contract's `code` and `data`.** The ProblemDetails schemas declare the stable `code` every Elarion failure carries and its optional `data` payload, so generated clients can [branch on the code](#typed-errors). * **Uploaded files.** An [`UploadedFile`](/docs/capabilities/blob-uploads#passing-an-upload-to-a-handler) member is documented as what it is on the wire, a string (the staged upload's id) marked `x-elarion-upload: true` like in the JSON-RPC schema, instead of an opaque schema; a list of them gets its `items`. A member's declared [`[UploadLimits]`](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member) are written as `x-elarion-max-bytes`, `x-elarion-content-types` and `x-elarion-file-extensions` (on the items of a list), so such a member has its own inline schema while every other one shares the `UploadedFile` component, which never carries a member's limits. * **The idempotency contract** (below). ## Idempotency parity [#idempotency-parity] A handler marked [`[Idempotent]`](/docs/concepts/idempotency) is safe to retry: the same `Idempotency-Key` returns the original outcome instead of running again. Over HTTP the server already honors the `Idempotency-Key` header (`app.UseElarionIdempotencyKey()` feeds it to the pipeline). The OpenAPI package makes that contract **discoverable**: for every idempotent operation it adds * an optional `Idempotency-Key` **header parameter**, and * an `x-elarion-idempotent: true` **vendor extension** — the OpenAPI analog of the JSON-RPC schema's `idempotent` flag, which lets a generated client auto-attach the key (see [below](#automatic-idempotency-keys)). Non-idempotent operations carry neither, so the document tells a client exactly which calls are safe to retry. ## Export the document at build time [#export-the-document-at-build-time] For a committed contract (the REST analog of `rpc-schema.json`), reuse Microsoft's build-time exporter — Elarion does not ship its own for OpenAPI: ```xml true $(MSBuildProjectDirectory) ``` `dotnet build` then emits `{ProjectName}.json` next to the project. Like Elarion's JSON-RPC schema tool, this boots the host with an inert server to read runtime metadata. The build-time launch runs your program up to `app.Run()`. If the host does side-effecting startup work — e.g. `db.Database.MigrateAsync()` — guard it (skip when there's no server request pipeline) or export at runtime from a running instance via `MapOpenApi()` instead. The two build-time exporters are intentionally parallel — both launch the host and dump a contract file. They differ only in surface: | Concern | JSON-RPC (`Elarion.AspNetCore.SchemaGeneration`) | OpenAPI (`Microsoft.Extensions.ApiDescription.Server`) | | ---------------- | ------------------------------------------------------ | ------------------------------------------------------ | | Enable | `ElarionJsonRpcGenerateSchema=true` | `OpenApiGenerateDocuments=true` | | Output directory | `ElarionJsonRpcSchemaOutputDirectory` (default `obj/`) | `OpenApiDocumentsDirectory` (default project dir) | | File name | `rpc-schema.json` | `{ProjectName}.json` | | Mechanism | inert host launch + document cache | inert host launch + document cache | ## Generate a typed client [#generate-a-typed-client] An OpenAPI document works with the whole client-generation ecosystem, so Elarion ships no bespoke HTTP client generator — pick the off-the-shelf tool that fits your stack. **Recommended: [`@hey-api/openapi-ts`](https://heyapi.dev).** It generates a **discoverable SDK grouped by module** — you type `sdk.` and IntelliSense walks you to `sdk.clients.getClient(...)`, the same ergonomics as the JSON-RPC client. Elarion emits the module as an OpenAPI **tag** and a clean **operationId**, so the grouping lands on module → operation with no extra work. It is built on `fetch` (so it runs in the browser and Node, and works with OpenTelemetry), takes request interceptors for cross-cutting headers, and has an optional **Zod** plugin — mirroring the JSON-RPC client's typed + validated feel. | Tool | Emits | Reach for it when | | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | **[`@hey-api/openapi-ts`](https://heyapi.dev)** (recommended) | A discoverable SDK grouped by module (`sdk.clients.getClient(...)`), `fetch`-based, optional Zod | You want the JSON-RPC client's `.`-drill-down over REST, in the browser or Node | | [`openapi-typescript`](https://openapi-ts.dev) + [`openapi-fetch`](https://openapi-ts.dev/openapi-fetch/) | Types only + a \~6 kB typed `fetch` wrapper (`api.GET("/clients/{id}", …)`) | You want the tiniest runtime and no generated method code — the operation is the path string | | [Kiota](https://learn.microsoft.com/openapi/kiota/) | A full SDK in C#, TypeScript, Python, Go, Java, … with a single fluent root (`client.clients.byClientId(id).get()`) | You need a non-TypeScript client, or a first-party Microsoft-supported generator | ### Generate [#generate] **Get the document.** Either export it at build time (the [section above](#export-the-document-at-build-time) — `{ProjectName}.json`), or fetch it from a running host: ```bash curl http://localhost:5000/openapi/v1.json -o openapi.json ``` **Install** the generator (dev) and the `fetch` runtime client: ```bash npm install -D @hey-api/openapi-ts npm install @hey-api/client-fetch ``` **Configure and generate.** Group operations by their tag so the SDK nests by module. Re-run `gen:http` whenever the API changes (wire it into CI next to the JSON-RPC `gen:rpc` step): ```ts // openapi-ts.config.ts import { defineConfig } from "@hey-api/openapi-ts"; export default defineConfig({ input: "./openapi.json", output: "./src/generated", plugins: [ "@hey-api/client-fetch", "zod", // optional runtime validation, like the JSON-RPC client's Zod schemas { name: "@hey-api/sdk", // Nest by the module tag Elarion emits → sdk... operations: { strategy: "byTags", nesting: (operation) => [operation.tags?.[0] ?? "default", operation.id], }, }, ], }); ``` ```jsonc // package.json { "scripts": { "gen:http": "openapi-ts" } } ``` Hey API's `operations` grouping options move occasionally — treat the config above as a starting point and check the [SDK plugin docs](https://heyapi.dev/openapi-ts/plugins/sdk) for the current option names. The exact generated export/nesting names come from your `operationId`s and tags. ### Use [#use] Configure the client's base URL once, then drill in: `sdk.` lists the modules, each module lists its operations, and params, body, and response are all typed. Errors come back in the result (`{ data, error }`) instead of throwing: ```ts import { client } from "./generated/client.gen"; import { sdk } from "./generated/sdk.gen"; client.setConfig({ baseUrl: "/" }); // sdk.clients.getClient — discovered by typing `sdk.clients.` const { data, error } = await sdk.clients.getClient({ path: { id } }); if (error) { // `error` is the typed RFC 7807 ProblemDetails body from ProducesElarionErrors(). console.error(error.title, error.status); } else { console.log(data.name); // `data` is the response DTO, fully typed. } // A command — the body is typed to the handler's Command. const created = await sdk.clients.createClient({ body: { name: "Acme", email: "billing@acme.test" } }); ``` The client is built on `fetch`, so the same generated SDK runs in the **browser** and in **Node** (18+, on the global `fetch`; pass a custom `fetch` via `client.setConfig({ fetch })` for other runtimes). Because the SDK is generated from the same document your server produces, a renamed field or a changed route is a compile error in the client — the end-to-end typing the JSON-RPC client gives you, over REST. Prefer the tiniest possible runtime and don't mind addressing operations by path string? `openapi-typescript` * `openapi-fetch` stays a fine choice — `createClient({ baseUrl }).GET("/clients/{id}", { params: { path: { id } } })`. It just trades the `sdk.` drill-down for a \~6 kB library and no generated method code. ### Typed errors [#typed-errors] Every Elarion failure over HTTP is an RFC 7807 ProblemDetails that carries the error contract's stable `code` ([ADR-0080](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0080-errors-are-a-declared-contract-with-a-stable-code.md)) — the same string a JSON-RPC client branches on (`not_found`, `validation`, `seat.taken`, …) — plus a `data` member when the error carries a typed payload. Validation failures, binding-tier ones included, use `code: "validation"` and keep their field messages in the standard `errors` map. An unexpected exception answers `500` with `code: "internal"` and a support `reference` ([Unexpected errors](/docs/concepts/results-and-errors#unexpected-errors)). `AddElarionOpenApi()` declares `code`, `data` and `reference` on the document's ProblemDetails schemas, so the generated `error` type has them and a client branches on the code directly instead of parsing `detail`: ```ts const { data, error } = await sdk.invitations.getInvitationByToken({ path: { token } }); if (error) { switch (error.code) { case "not_found": return renderExpiredLink(); case "invitation.already_answered": return renderAlreadyAnswered(answeredSchema.parse(error.data)); // your own Zod schema for the payload default: throw new Error(error.detail ?? error.title ?? "Request failed"); } } render(data); // typed (and, with the Zod plugin, validated) response DTO ``` Both members are optional in the schema, because the ProblemDetails component is shared with every route in the document, including hand-written ones whose problems an Elarion translator did not produce. The per-operation set of declared codes and their payload types is part of `rpc-schema.json` only, so over REST `code` is a `string` and `data` is untyped: validate a payload with your own schema at the branch that reads it, or expose the handler over JSON-RPC as well to get the [typed error union](/docs/capabilities/transports/typescript-client#error-handling). ### Automatic idempotency keys [#automatic-idempotency-keys] The JSON-RPC client auto-attaches an idempotency key for `[Idempotent]` methods. Reproduce that over HTTP with a request **interceptor** that keys off the `x-elarion-idempotent` extension. First emit the idempotent operations from the document (a \~15-line build step — read each operation, keep the `{method, path-template}` of those whose `x-elarion-idempotent` is `true`, turning each template into a `RegExp`), then register the interceptor once: ```ts // idempotency.ts import { client } from "./generated/client.gen"; // [{ method, pattern }] where the OpenAPI operation carries x-elarion-idempotent: true. import { idempotentOperations } from "./generated/idempotent-operations"; const newKey = () => crypto.randomUUID(); client.interceptors.request.use((request) => { const path = new URL(request.url).pathname; const idempotent = idempotentOperations.some( (op) => op.method === request.method && op.pattern.test(path), ); if (idempotent && !request.headers.has("Idempotency-Key")) { request.headers.set("Idempotency-Key", newKey()); } return request; }); ``` That gives an idempotent HTTP call the same exactly-once-on-retry behavior as the JSON-RPC client — a key attached by default, or pass your own via a per-call header to reuse it across your retries — with the `Idempotency-Key` header that is idiomatic for HTTP rather than JSON-RPC's `params._meta`. ## Trace client requests with OpenTelemetry [#trace-client-requests-with-opentelemetry] A generated client call should appear in the same distributed trace as the server work it triggers. The server already does its part: an ASP.NET Core host running OpenTelemetry with `AddAspNetCoreInstrumentation()` extracts the W3C `traceparent` header from the incoming request, so the REST endpoint and the handler-pipeline spans nest under whatever client span sent it (see [Telemetry & observability](/docs/capabilities/telemetry)). The client's job is to **create that span and inject the header**. Because the hey-api client is built on `fetch`, the simplest path is to instrument `fetch` itself — every request gets a client span and a `traceparent`, with no per-call code. In the **browser** use [`@opentelemetry/instrumentation-fetch`](https://www.npmjs.com/package/@opentelemetry/instrumentation-fetch); in **Node** (18+) the global `fetch` is undici-based, so use [`@opentelemetry/instrumentation-undici`](https://www.npmjs.com/package/@opentelemetry/instrumentation-undici) instead. The browser setup: ```ts import { WebTracerProvider, BatchSpanProcessor } from "@opentelemetry/sdk-trace-web"; import { ZoneContextManager } from "@opentelemetry/context-zone"; import { registerInstrumentations } from "@opentelemetry/instrumentation"; import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch"; import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http"; const provider = new WebTracerProvider({ spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter({ url: "/v1/traces" }))], }); provider.register({ contextManager: new ZoneContextManager() }); registerInstrumentations({ instrumentations: [ new FetchInstrumentation({ // Send the trace header to your API origin. Cross-origin also needs the server's CORS to allow it. propagateTraceHeaderCorsUrls: [/./], }), ], }); ``` Prefer to own propagation (or skip the `fetch` auto-instrumentation)? Inject the active context yourself with a request **interceptor** — it composes with the idempotency interceptor above and works the same in the browser and Node: ```ts import { context, propagation } from "@opentelemetry/api"; import { client } from "./generated/client.gen"; client.interceptors.request.use((request) => { propagation.inject(context.active(), request.headers, { set: (h, k, v) => h.set(k, v) }); return request; }); ``` The **JSON-RPC client** carries a dedicated `RpcInstrumentation` hook instead of relying on `fetch` instrumentation — see [TypeScript client › Tracing with OpenTelemetry](/docs/capabilities/transports/typescript-client#tracing-with-opentelemetry). ## HTTP or JSON-RPC? [#http-or-json-rpc] Both remain first-class — the choice is [per-handler](/docs/capabilities/transports/http-endpoints#http-or-json-rpc), and a handler can expose both. Reach for OpenAPI when you serve third-party or public consumers who expect REST + Swagger tooling; reach for the JSON-RPC client when one team owns both ends and wants an operation-shaped, end-to-end-typed contract. With this package, neither transport is the "typed" one and the other the "loose" one — both carry a machine-readable contract. # Schema generation (/docs/capabilities/transports/schema-generation) `rpc-schema.json` is the contract that drives the [TypeScript client](/docs/capabilities/transports/typescript-client). You can export it in code with `JsonRpcSchemaExporter`, or — more conveniently — have it written automatically during `dotnet build`. Beyond each operation's request/response shapes, the exported schema carries `[Description]` texts, the `idempotent` flag for [`[Idempotent]`](/docs/concepts/idempotency) operations, and the request DTOs' DataAnnotations constraints as JSON Schema keywords (`minLength`/`maxLength`, `minimum`/`maximum`, `pattern`, `format` — see [Validation](/docs/concepts/validation)), so the generated client can pre-validate requests against exactly what the server enforces. An attribute's explicit `ErrorMessage` rides along under `x-elarion-error-messages`, keyed by constraint keyword (see [Error messages](/docs/concepts/validation#error-messages)). Each method also lists its **declared error contract** (ADR-0080) under `errors`: stable code → `kind` (the kind's default code such as `not_found`) and, when the error carries a typed payload, the `data` schema. Handlers declare errors with [`[ProducesError]`](/docs/reference/result-and-errors#produceserror--the-declared-error-contract); the framework adds validation, authorization, feature-gate and idempotency failures where they are statically known. The block is omitted for a method that declares none. ```json "errors": { "not_found": { "kind": "not_found" }, "token.malformed": { "kind": "validation", "data": { "type": "object", "properties": { "reason": { "type": "string" } }, "required": ["reason"] } } } ``` A method also says what a client may know **before** calling it, each member omitted when empty: `requires` — either `anonymous`, or `authenticated` with the `permissions` and `roles` the handler requires (all of them), the `memberPermissions` a client decides from a call's params (below), and `serverChecks` for a policy, claim or resource requirement only the server can evaluate; `readOnly` for an `IQuery` request; and `tags`, the handler's [`[ClientTag]`](/docs/reference/attributes#clienttag) hints. They are computed at compile time from the same declarations the authorization decorator enforces (an `[ElarionAuthorizationDefaults]` in scope sets `authenticated`), and the generated client exposes them as [`rpcMethodInfo`](/docs/capabilities/transports/typescript-client#method-requirements-and-ui-gating). The schema ships with the client, so it shows every method's required permission names, the same vocabulary the `capabilities` block lists. ```json "invoices.approve": { "params": { "…": "…" }, "result": { "…": "…" }, "requires": { "authenticated": true, "permissions": ["invoices.approve"], "serverChecks": true }, "tags": { "timeout": "60s" } } ``` A [member-scoped permission](/docs/concepts/authorization#permissions-that-depend-on-a-request-member) (`[RequirePermissionFor]`) is exported as one `memberPermissions` entry: `member`, the params member as one wire name per segment; `permissions`, each enum value's wire form mapped to the permission it requires, in ordinal order; and `anyOf`, the permissions that satisfy it instead (omitted when there are none). The wire names come from the serializer options, so a `[JsonPropertyName]` or a renamed enum value is exported as the client sends it. A member the wire does not carry (`[JsonIgnore]`) cannot be read from params and is exported as `serverChecks: true` instead. ```json "customFields.list": { "requires": { "authenticated": true, "memberPermissions": [ { "member": ["kind"], "permissions": { "property": "properties.read", "tenant": "tenants.read" }, "anyOf": ["settings.read"] } ] } } ``` The schema also carries **values** the server declares, so the client stops copying them (ADR-0100). Each is omitted when nothing declares it, so a schema without declarations is byte-identical: | Where | What | Declared by | | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | `methods.{m}.presets.{name}` | A named params value: every required member, and every other member that differs from the request's default (`null` where the preset clears one), in the wire form. | [`[RequestPreset]`](/docs/reference/attributes#requestpreset) on a static readonly field of the handler | | `methods.{m}.sortKeys` | The keys of the handler's sort map in declaration order: `key`, `direction` (`ascending`/`descending`, what a bare key applies) and `default: true` on the default key. | One static [`SortMap`](/docs/capabilities/pagination#offset-pagination) field on the handler | | `methods.{m}.maxSortLevels` | How many keys one sort may combine (the map's `MaxLevels`, 3 unless the builder sets another). Exported with `sortKeys`. | The same `SortMap` | | `constants.{module}.{name}` | A module's exported constants, module and member camel-cased (`Billing.MaxAmount` → `constants.billing.maxAmount`). | [`[ClientConstants]`](/docs/reference/attributes#clientconstants) on a static class of the module | | an upload member's `x-elarion-max-bytes`, `x-elarion-content-types`, `x-elarion-file-extensions` | Its declared limits, next to `x-elarion-upload` (on the items of a collection). The method's `errors` then list `upload.not_found` and, per declared limit, `upload.too_large`, `upload.content_type` or `upload.file_extension` with the limit as typed `data`. | [`[UploadLimits]`](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member) | ```json "invoices.list": { "params": { "…": "…" }, "result": { "…": "…" }, "presets": { "notExported": { "status": "Approved", "exported": false }, "toTransfer": { "toTransfer": true } }, "sortKeys": [ { "key": "createdAt", "direction": "descending", "default": true }, { "key": "number", "direction": "ascending" } ], "maxSortLevels": 3 } ``` The export reads presets and sort keys from each method's handler type, which the schema tool takes from the host's handler registrations, and constants from the enabled modules' registrations; values are written with the canonical JSON configuration, so names and enum spellings match calls. The generated client gives them typed accessors — `rpcPresets`, `rpcSortKeys` with `rpcMaxSortLevels`, `rpcConstants` — and turns every member's limit keywords into `rpcLimits` (see [Limits, presets, sort keys and constants](/docs/capabilities/transports/typescript-client#limits-presets-sort-keys-and-constants)). ### Requiredness [#requiredness] One rule, in both directions ([ADR-0082](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0082-requiredness-comes-from-nullability-in-both-directions.md)): a **non-nullable** property is `required` on the wire, a **nullable** property is optional. The C# `required` modifier and `[JsonRequired]` do not change the schema. For **request** types a non-nullable property with a default is also optional to send: a constructor parameter default (`int Size = 10`) or an initializer that yields a non-default value (`List Tags { get; init; } = []`). An initializer equal to the CLR default (`= 0`, `= false`) is indistinguishable from none, so give such a member a constructor default or make it nullable. For **response**, event and error-payload types, every non-nullable member is always written, so it is required. Result and event types must therefore not opt members out with `[JsonIgnore(Condition = WhenWritingDefault)]` (or `WhenWritingNull` on a non-nullable reference): the generator reports `ELRPC004` for a handler response graph, and the exporter fails with the member name for event payloads and custom serializer options. Make the member nullable to declare it optional. The canonical serializer enforces the contract it exports (`RespectNullableAnnotations` and `RespectRequiredConstructorParameters`), so a `null` for a non-nullable member and a missing non-nullable constructor parameter without a default are rejected rather than silently accepted. The reverse holds too: a **nullable** member is optional to send everywhere — `record Search(string Query, string? Note)` accepts `{"query":"q"}` and binds `Note` to `null`, with no `= null` needed — including a nullable member marked `required` or `[JsonRequired]`, which stays a construction-site aid for the compiler only. #### Nullable members that must be sent [#nullable-members-that-must-be-sent] An omitted nullable member binds `null`, and for a command that replaces a stored record that clears data: when `cylinders.update` gains `decimal? LengthMm`, a caller that predates it — a browser tab with the old bundle, a script — leaves it out, and the handler writes `null` over the stored length. Mark such a command (or one member) [`[PresenceRequired]`](/docs/reference/attributes#presencerequired) ([ADR-0129](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0129-an-update-command-may-refuse-an-omitted-member.md)): ```csharp [PresenceRequired] public sealed record Command( Guid Id, string? Notes, // must be sent; null clears decimal? LengthMm, // must be sent, also by a client that predates it IReadOnlyList? Decisions = null) // has a default: may be left out : ICommand; ``` A nullable member that System.Text.Json itself requires — a constructor parameter without a default, a `required` or `[JsonRequired]` member — then stays required: leaving it out fails with invalid params (`-32602`, or 400 over HTTP) before the handler runs, and an explicit `null` still clears. A member with a default (`= null`, or a plain `init` property) stays optional. The schema lists the member in `required` with a type that admits `null`, so MCP clients see it and the generated client types it `T | null` (Zod `.nullable()`): a current client must pass it. Requests without the marker keep the rule above. ## Build-time export [#build-time-export] Add the schema generation package as private build tooling in the host project: ```xml true $(MSBuildProjectDirectory)/../../rpc-schema.json ``` The package imports MSBuild targets that run after the host compiles. The target launches the built application, captures the host immediately after `builder.Build()`, resolves the registered `JsonRpcDispatcher`, and writes the schema using the dispatcher's runtime serializer options. **Application code after `builder.Build()` does not run** during generation. ## Properties [#properties] | Property | Default | Purpose | | ------------------------------------------ | ---------------------------------------------- | -------------------------------------------------------------------------------- | | `ElarionJsonRpcGenerateSchema` | `false` | Enables the package targets. | | `ElarionJsonRpcGenerateSchemaOnBuild` | same as `ElarionJsonRpcGenerateSchema` | Controls automatic generation during `dotnet build`. | | `ElarionJsonRpcSchemaOutputPath` | `$(BaseIntermediateOutputPath)rpc-schema.json` | Exact schema file path. | | `ElarionJsonRpcSchemaOutputDirectory` | `$(BaseIntermediateOutputPath)` | Used with `ElarionJsonRpcSchemaFileName` when no explicit path is set. | | `ElarionJsonRpcSchemaFileName` | `rpc-schema.json` | File name used with the output directory. | | `ElarionJsonRpcSchemaEnvironment` | `Development` | Value for `DOTNET_ENVIRONMENT` / `ASPNETCORE_ENVIRONMENT` while loading the app. | | `ElarionJsonRpcSchemaApplicationArguments` | empty | Arguments passed to the app entry point after `--`. | | `ElarionJsonRpcSchemaGenerationOptions` | empty | Extra tool arguments for advanced scenarios. | ## Manual generation [#manual-generation] The same target can be invoked directly: ```bash dotnet msbuild src/MyApp.Api/MyApp.Api.csproj \ -t:GenerateElarionJsonRpcSchema \ -p:ElarionJsonRpcGenerateSchema=true ``` ## Guarding startup work [#guarding-startup-work] Because the application is loaded during the build, guard expensive or external startup work. `JsonRpcSchemaGeneration.IsRunning` checks the Elarion marker environment variable and the schema generation tool's entry assembly name: ```csharp var app = builder.Build(); if (!JsonRpcSchemaGeneration.IsRunning) { await app.Services.GetRequiredService().RunAsync(); } ``` ## Requirements [#requirements] Schema generation requires the host to register a **frozen** `JsonRpcDispatcher` before `builder.Build()`. If the dispatcher is missing, unfrozen, or empty, the build target fails with an actionable error instead of writing a stale schema. See [Hosting](/docs/capabilities/hosting) for the registration. # Request-driven server streaming (/docs/capabilities/transports/server-streaming) `IStreamHandler` serves a **cold, request-driven response**: one caller starts one lazy sequence. Use it when the response itself is a sequence — a row-by-row export, token output, or a tail/watch query. It is not a catch-all realtime API. ## Choose the delivery contract [#choose-the-delivery-contract] The word “stream” describes several intentionally different contracts. Start with the recovery behavior the consumer needs, not the wire protocol: | Need | Choose | Producer and lifetime | What the consumer can rely on | It does **not** provide | | -------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------- | | One request returns a deferred sequence | **`IStreamHandler`** | Cold; each request owns a new enumeration | Upfront accept/reject, then lazy completion, cancellation, and faults | Shared producer, ordering across requests, replay, or resume | | Every item from one live producer matters | [Actor-owned `StreamHub`](/docs/capabilities/events/streams) | Hot; one sequencer per key owns the hub | Ordered items, completion, bounded replay, and reconnect resume | Durable history beyond the retained hub and its activation epoch | | A browser should refresh after a change | [Client events](/docs/capabilities/events/client-events) | Hot fan-out from any publisher/node | At-most-once hint; an authorized re-query converges | Replay, gap-free sequence delivery, or a delivery receipt | | The conversation itself is interactive or stateful | [Client connections](/docs/capabilities/connections) | Long-lived, codec-owned link | Per-connection conversation and explicit request/reply when the protocol supports it | A pub/sub, ordered-stream, or durable-message guarantee | Use this selection flow: 1. Is the output the deferred response to **one request**? Use `IStreamHandler`. 2. Otherwise, does a missed item make the consumer **wrong**, and can one live producer own the sequence? Use an actor-owned `StreamHub`. 3. Otherwise, can a recipient re-query authoritative state after a loss? Use client events. 4. Separately, if either direction needs an interactive/stateful conversation, add a connection as the carrier. A connection does not replace the delivery contract above. For machine consumers that must process every independently durable business fact, use an [integration event](/docs/capabilities/events) and its outbox instead of holding a client connection. ## The handler contract [#the-handler-contract] A stream handler is a distinct shape, rather than a widened unary handler: ```csharp using System.Runtime.CompilerServices; public sealed class ExportRows(AppDbContext db) : IStreamHandler { public sealed record Query : IQuery { public required Guid ReportId { get; init; } } public sealed record Row(Guid Id, string Value); public ValueTask>> HandleAsync(Query query, CancellationToken ct) { if (query.ReportId == Guid.Empty) { return ValueTask.FromResult>>( AppError.Validation("A report id is required.")); } return ValueTask.FromResult(Result>.Success(ReadRows(query, ct))); } private async IAsyncEnumerable ReadRows( Query query, [EnumeratorCancellation] CancellationToken ct) { await foreach (var row in db.ExportRows(query.ReportId).WithCancellation(ct)) { yield return new Row(row.Id, row.Value); } } } ``` `HandleAsync` accepts or rejects the request **before** a transport commits its response. On success, the `IAsyncEnumerable` remains lazy: completion, cancellation, and faults belong to its enumeration. The generator discovers the handler under its module and gives it a separate, module-gated stream pipeline. A stream handler is not exposed by \[Handler] over JSON-RPC/MCP and it is not a generated \[HttpEndpoint] route. JSON-RPC and MCP remain single-response. HTTP/SSE and gRPC expose this contract explicitly. ## HTTP/SSE: map the request directly [#httpsse-map-the-request-directly] Put the explicit route in the owning module's `MapEndpoints` hook. The direct `MapGet` call is deliberate: it is hand-written in your compilation, so ASP.NET Core owns the route and query binding, while Elarion owns typed stream invocation, canonical JSON, and SSE framing. ```csharp [AppModule("Reports")] public static partial class ReportsModule { public static void MapEndpoints(IEndpointRouteBuilder endpoints) { endpoints.MapGet("reports/{reportId}/export", static (Guid reportId) => ElarionHttpResults.ToStreamResult(new() { ReportId = reportId, })); } } ``` The host still maps all module-owned routes through `MapElarionEndpoints`, and it calls `AddElarionHttpJson()` so minimal APIs use the same canonical, source-generated JSON resolver chain as the rest of Elarion. Register the item type in the module or host JSON context as usual. `ToStreamResult` starts the decorated handler only when ASP.NET executes the result: * A validation, authorization, feature-gate, or not-found failure becomes the normal Elarion problem response **before** SSE headers are committed. * Once accepted, normal completion ends the stream; a disconnect cancels it; a lazy fault ends the connection. There is no second `Result` envelope after items begin. * The accepted invocation retains its fresh DI/dispatch scope until enumeration completes, faults, cancels, or is disposed. A stream can therefore retain its `DbContext` and reader for its full duration; use a finite, intentional resource lifetime rather than an accidental infinite response. * Normal SSE items have no shared sequence, replay ring, or `Last-Event-ID` resume behavior. If those are required, the response is a hot producer-owned `StreamHub`, not this contract. See [HTTP endpoints](/docs/capabilities/transports/http-endpoints) for ordinary generated unary routes. The complete working cold-export example is [EdgeTelemetry](https://github.com/swimmesberger/Elarion/tree/main/samples/EdgeTelemetry), which contrasts its unbuffered `/history/stream` response with a buffered JSON query. ## Pipeline and transport boundaries [#pipeline-and-transport-boundaries] Stream handlers retain the request gates that decide whether a stream may begin: * **Applies:** authorization, feature gates, validation, observability, and context enrichment. * **Does not apply automatically:** unary transactions, caching and invalidation, idempotency, resilience, and audit. Do not infer a retry or transaction around a long lazy enumeration from attributes intended for a unary request. For a custom server-streaming transport, call `StreamHandlerInvoker.InvokeAsync`. On success, `await using` its returned invocation while writing items; it owns the fresh scope until enumeration ends. Dispose an accepted invocation that you never enumerate, and never return its bare sequence after releasing the scope. The [custom transports guide](/docs/capabilities/transports/custom-transports) shows the adapter shape. HTTP/SSE and [gRPC server streaming](/docs/capabilities/transports/grpc#server-streaming) support this cold request shape. gRPC uses the same invocation lifetime, but maps a startup `AppError` to gRPC status before it writes an item. Client and duplex streaming are deliberately out of scope. ## When to use the neighbouring realtime APIs instead [#when-to-use-the-neighbouring-realtime-apis-instead] * **Client events:** use for committed facts, live progress, or latest-wins state when a missed message only leaves a browser stale and re-querying repairs it. They remain the default browser-push tier. * **`StreamHub`:** use when each item is data, completion matters, and a single actor can sequence a live producer per key. The [LiveQuotes sample](https://github.com/swimmesberger/Elarion/tree/main/samples/LiveQuotes) deliberately uses client events for its dashboard and a resumable `StreamHub` for every accepted tick. * **Connections:** use only when the link itself is stateful or client input is latency-interactive. They can carry client-event subscriptions, but they do not turn an at-most-once hint into an ordered replayable stream. # TypeScript client (/docs/capabilities/transports/typescript-client) `elarion-jsonrpc-client-generator` turns an exported [`rpc-schema.json`](/docs/capabilities/transports/schema-generation) into a typed TypeScript client. The frontend gets full type safety and runtime validation without hand-writing DTOs, and the generated runtime stays portable across browsers and Node.js. ## Generating the client [#generating-the-client] ```bash npm install --save-dev @swimmesberger/elarion-jsonrpc-client-generator npx elarion-jsonrpc-client-generator --schema rpc-schema.json --out src/generated ``` It always emits the three core files, plus conditional outputs when the schema calls for them: | File | Purpose | | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `rpc-types.ts` | `RpcMethods` interface mapping method names to params/result types. | | `rpc-schemas.ts` | `rpcParamsSchemas` and `rpcResultSchemas` Zod maps for runtime params/result validation, plus the [limits, presets, sort keys and constants](#limits-presets-sort-keys-and-constants) the schema declares. | | `rpc-client.ts` | Typed fetch client for single calls and batches. | | `session-client.ts` | Client-capability snapshot client and OpenFeature provider — emitted **only** when the schema exposes the `elarion.session` operation (rename it with `--session-client `). | | `events-client.ts` | Topic-typed [client-event subscription client](#client-event-subscriptions) — emitted **only** when the schema declares client-event topics. | An opt-in [`start-adapter.ts`](#tanstack-start) joins them under `--framework tanstack-start`. A schema that declares neither session nor events produces byte-identical output to before — the conditional files simply do not exist. The schema and client files import `zod` (v3 and v4 are both supported), so install it as a runtime dependency in the consuming app. The generated files import each other with `.js` specifiers (`from './rpc-schemas.js'`), which a bundler and `tsc` under `moduleResolution: NodeNext` resolve to the `.ts` files. Plain Node does not: to load the generated modules without a build step — a module that calls `decisionQuestion` under `node --test`, a script — generate with `--import-extension ts` (`importExtension: 'ts'`), which names the `.ts` files themselves. Node runs them with its type stripping (unflagged since Node 23.6); `tsc` then needs `allowImportingTsExtensions` with `noEmit`, or `rewriteRelativeImportExtensions`. **Pin the generator to the backend's version.** The npm `latest` dist-tag tracks stable releases and can lag behind the backend packages, which publish a `-preview.N` build from every push to `main`. When your host runs a preview version, install the **matching exact preview version** of the generator rather than a `^` range — otherwise the generator reads a newer `rpc-schema.json` with an older code path and silently emits less than the schema describes (a missing emitted file such as `session-client.ts`, or absent params schemas, are the usual symptoms): ```bash # Substitute the exact version your host's Elarion packages resolve to — # the full preview string, e.g. ..-preview.. npm install --save-dev --save-exact \ @swimmesberger/elarion-jsonrpc-client-generator@ ``` Move both sides together: bump the backend packages and the generator in the same change. The emitted Zod schemas are **constraint-aware**: the DataAnnotations attributes on the server's request DTOs flow through the exported schema into the client (see [Validation](/docs/concepts/validation)) — `minLength`/`maxLength` become `.min()`/`.max()`, `pattern` becomes `.regex(new RegExp(...))`, `minimum`/`maximum` become `.gte()`/`.lte()` (exclusive bounds `.gt()`/`.lt()`), `minItems`/`maxItems` become array `.min()`/`.max()`, integers get `.int()`, and the `uuid`/`email`/`uri` formats become `.uuid()`/`.email()`/`.url()`. An attribute's explicit message (`x-elarion-error-messages`, see [Error messages](/docs/concepts/validation#error-messages)) becomes the check's message argument, so the local failure reads like the server's: ```ts code: z.string().max(20, "Code must be at most 20 characters.").regex(new RegExp("^[A-Z]{3}$"), "Code must be three capital letters."), mode: z.enum(["fast", "slow"], { message: "Pick fast or slow." }), ``` Checks take the plain-string message and schema constructors (`z.enum`, `z.literal`, `z.union`) take `{ message }` — the forms Zod v3 and v4 share. One difference remains on Zod v3: it applies a constructor message to `z.enum` but not to the `z.literal`/`z.union` emitted for a non-string `[AllowedValues]`, which keeps Zod's default text there. Constraints without an explicit message keep Zod's default text on both versions. ### Watch mode [#watch-mode] For a tight dev loop, pass `--watch` to regenerate whenever `rpc-schema.json` changes: ```bash npx elarion-jsonrpc-client-generator --schema rpc-schema.json --out src/generated --watch ``` It generates once, then watches the schema file and regenerates on every write — surviving the transient states a build tool leaves the file in mid-write (a partial or momentarily-invalid schema is logged and skipped, never fatal). Paired with a server that re-exports the schema on save, an edit to a C# handler flows straight to the typed frontend: ```bash # terminal 1 — API: re-export rpc-schema.json on every change (see Schema generation) dotnet watch # terminal 2 — regenerate the TS client whenever the schema lands npx elarion-jsonrpc-client-generator --schema ../api/rpc-schema.json --out src/generated --watch ``` The two stay decoupled: the .NET build owns [schema export](/docs/capabilities/transports/schema-generation), the generator owns the client — no Node/npm dependency is baked into the server build. For a permanent setup, wire the watch command into a `package.json` script (e.g. `"rpc:watch"`). ## Calling methods [#calling-methods] Dotted JSON-RPC method names become nested properties, so `clients.get` is `rpc.clients.get(...)`: ```ts import { createRpcApi } from './generated/rpc-client' const rpc = createRpcApi({ url: '/rpc', headers: { Authorization: `Bearer ${token}` }, }) const abort = new AbortController() const client = await rpc.clients.get({ id }, { signal: abort.signal }) ``` The client uses `globalThis.fetch` in browsers and modern Node.js. The lower-level `createRpcClient(...)` generic transport is also exported for advanced cases. ## File payloads map to native `File` [#file-payloads-map-to-native-file] A handler parameter or result typed [`ElarionFile`](/docs/capabilities/transports/json-rpc#file-payloads) is exported with an `x-elarion-file` marker, and the generated client surfaces it as a **native `File`** on both sides — the base64 wire envelope never leaks into application code: ```ts // Upload: pass the File from an straight through. const receipt = await rpc.documents.import({ container: 'invoices', file: input.files[0] }) // Download: the result is a real File (name, type, bytes) — hand it to URL.createObjectURL. const exported = await rpc.exports.get({ list: 'clients' }) window.open(URL.createObjectURL(exported)) ``` Params validate the `File` instance (Zod `z.instanceof(File)`); the client encodes it to the base64 envelope after validation and decodes result envelopes back into `File` objects before validation — so the conversion also runs when validation is disabled. Everything used is standard in browsers and Node 20+; schemas without file payloads generate byte-identical output. Remember `ElarionFile` is the small-file tier — for large uploads use [uploaded files](#uploaded-files), for large downloads the [staged-blob flows](/docs/capabilities/blob-uploads#streaming-downloads-and-temp-file-flows). ## Uploaded files [#uploaded-files] A handler member typed [`UploadedFile`](/docs/capabilities/blob-uploads#passing-an-upload-to-a-handler) travels as the blob id of a staged upload and is exported with an `x-elarion-upload` marker. The generated client types it `File | Blob | UploadedFileRef` in params and `UploadedFileRef` (an exported `string` alias in `rpc-types.ts`) in results. Pass a `File` and the client uploads it before the call, then sends the reference: ```ts // One call: the client streams the file to the upload endpoint, then calls the method with its reference. const analysis = await rpc.statements.analyze({ statement: input.files[0] }) // A multi-step flow: upload once, pass the reference to every step. const statement = await rpc.$uploadFile(input.files[0]) const preview = await rpc.statements.preview({ statement, mapping }) await rpc.statements.commit({ statement, mapping }) ``` The default uploader POSTs the raw file to the direct-upload endpoint (`MapElarionBlobUploads`) with the client's `fetch` and `headers` (a `headers` function sees an empty `methods` list), its `type` as `Content-Type` and its name in `X-Elarion-File-Name` (or the `fileName` query parameter for a name outside printable ASCII), and reads the reference from the `text/plain` answer. It posts to `/_elarion/blobs` on the origin of `url`, or relative to the page for a relative `url`; the call's `AbortSignal` cancels its uploads too. Two client options change that: ```ts const rpc = createRpcApi({ url: '/api/rpc', uploadUrl: '/api/_elarion/blobs', // a host that mounts the endpoints under a path base uploadFile: (file, { fileName, signal }) => tusUpload(file, { fileName, signal }), // any uploader → reference }) ``` `$uploadFile(file, { policy, resourceId })` stages the file under an [upload policy](/docs/capabilities/blob-uploads#upload-policies-a-larger-limit-for-one-kind-of-upload) — a larger limit for one kind of upload, checked against the record it is for — and the default uploader sends both as query parameters; a configured `uploadFile` receives them in its options. Staging the `File` params of a call uses no policy, so a member that needs one is uploaded with `$uploadFile` first and called with the reference. `$uploadFile(file, { fileName, signal })` (also `$client.uploadFile`) names a `Blob` that has no name of its own. Params validation accepts a `Blob` or a string at an upload position, before the upload. When the member declares [`[UploadLimits]`](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member), the `Blob` must also fit them: a larger file, another media type or a name without an accepted extension fails params validation with the server's message (`RpcParamsValidationError`) and is never uploaded. The media type is compared as the server compares it — case-insensitively, parameters ignored, an untyped `Blob` as `application/octet-stream` — and the extension against the end of the file's name, case-insensitively (a `Blob` has no name). A reference passes; the server checks the file it names. A failed upload rejects the call with `RpcTransportError` and the method is not called. A retry that passes the `File` again uploads it again and sends a new reference, so for an `[Idempotent]` operation upload once with `$uploadFile` and retry with the reference — otherwise the retried request differs from the first one and answers `idempotency.key_reused`. Schemas without upload members generate byte-identical output. ### Upload limits in the user's language [#upload-limits-in-the-users-language] A refused file is reported by error code with the limit as data, never only as English text, on every path: * **The server** answers `upload.too_large` with `{ maxBytes, length }`, `upload.content_type` with `{ contentTypes, contentType }` and `upload.file_extension` with `{ fileExtensions, fileName }`. A method whose request declares `[UploadLimits]` has those codes in its contract, so `isRpcMethodError(method, error)` narrows `error.data` by `error.code`. * **`$uploadFile(file, { method, member })`** checks the file against the limits of that method's upload member before uploading it and throws `RpcUploadLimitError`: an `RpcError` with the code, message and data the server would answer, plus `method` and `member`. One handler words both. The pair is typed — `method` is a method that takes an upload, `member` one of its upload members by path (a list by its own path) — and the check is skipped when `validateParams` is `false`. * **Params validation** before a call adds the code and the limit to the Zod issue as `params` (`{ code: 'upload.too_large', maxBytes }`, likewise `contentTypes` and `fileExtensions`), so a Zod error map words it; `RpcParamsValidationError.cause` carries the issues. ```ts try { const workbook = await rpc.$uploadFile(file, { method: 'contacts.import', member: 'workbook' }) await rpc.contacts.import({ workbook }) } catch (error) { if (!isRpcMethodError('contacts.import', error)) throw error switch (error.code) { // the client's check and the server's answer alike case 'upload.too_large': return showError(t('upload.tooLarge', { max: formatBytes(error.data.maxBytes) })) case 'upload.file_extension': return showError(t('upload.extension', { accepted: error.data.fileExtensions.join(', ') })) default: return showError(error.message) } } ``` `rpcUploadLimits` in `rpc-schemas.ts` lists every upload member of each method with its declared `maxBytes`, `contentTypes` and `fileExtensions` (`{}` when it declares none); `$uploadFile` reads it, and a page can build an `` from it. ## C# unions map to TypeScript unions [#c-unions-map-to-typescript-unions] On .NET 11 a request or response property can be a C# 15 union. System.Text.Json writes the active case with no wrapper or discriminator and exports the union as `anyOf`, one schema per case; the generator turns that into a TypeScript union and a Zod `z.union`: ```csharp public sealed record Found(string Name, int Stock); public sealed record Missing(int Reason); [JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))] public union ProductLookup(Found, Missing); public sealed record Response(ProductLookup Result); ``` ```ts // rpc-types.ts result: { name: string; stock: number } | { reason: number } // rpc-schemas.ts result: z.union([z.strictObject({ ... }), z.strictObject({ ... })]) ``` * **Object cases need a classifier on the server.** Out of the box System.Text.Json picks a case by JSON token kind only, so a union of two object cases cannot be deserialized. `JsonUnionTypeStructuralClassifier` picks the case by its property names; give each case a property the others lack (or mark distinguishing properties `required`). * **Object cases are strict on the client.** They are emitted as `z.strictObject`, so like the server's classifier a payload carrying another case's property matches no case instead of being stripped into the first one. * **Nullability follows the declaration**, like any other property: a `ProductLookup` property is required, a `ProductLookup?` one optional and nullable. A `default` union holds no case and serializes as `null`, so give a non-nullable union property a value. * **Not inside unions:** [file payloads](#file-payloads-map-to-native-file) and [uploaded files](#uploaded-files) — which case is active is only known per value, so the client could not convert them at a fixed path; the generator rejects that schema. Validation attributes on the case types are enforced on the active case, at the property's path (see [Validation](/docs/concepts/validation)). ## Batching [#batching] Batch requests are built through generated `$request` helpers and preserve input order even when the server responds out of order. Each item resolves independently, so one failure does not reject the whole batch: ```ts const [clientResult, projectsResult] = await rpc.$batch([ rpc.$request.clients.get({ id }), rpc.$request.projects.list({ clientId: id }), ] as const) ``` ## Client-event subscriptions [#client-event-subscriptions] When the schema declares an `events` block (the host registers [client-event topics](/docs/capabilities/events/client-events)), the generator also emits `events-client.ts`: a topic-typed subscription client that multiplexes every subscription over one `EventSource`, validates payloads with the same generated Zod schemas, and exposes `$client.onConnected` as the "re-query now" signal. A connection the `EventSource` gave up on (a 401, a login page, a 502 mid-deploy) is reopened with a backoff (`reconnectDelay`). A schema without events produces byte-identical output — the file simply doesn't exist. ```ts import { createElarionEvents } from './generated/events-client.js' const events = createElarionEvents({ url: '/events' }) events.invoicing.invoiceChanged.subscribe((evt) => refetch(evt.invoiceId)) ``` ## Server-side and SSR usage [#server-side-and-ssr-usage] Pass an injected `fetch` and dynamic headers for SSR, edge, or server-function deployments — for example to forward request-scoped authentication without forking the generated client: ```ts const rpc = createRpcApi({ url: process.env.API_INTERNAL_URL + '/rpc', fetch, headers: () => ({ Authorization: `Bearer ${forwardedJwt}` }), transformResult: normalizeRpcResultForSchema, }) ``` ### TanStack Start [#tanstack-start] During SSR you usually need to forward the incoming request's `cookie` (or another identity header) so the RPC call runs as the signed-in user. Generate with `--framework tanstack-start` to emit an **opt-in** `start-adapter.ts` next to the neutral core client (it needs the `@tanstack/react-start` peer dependency): ```bash npx elarion-jsonrpc-client-generator --schema rpc-schema.json --out src/generated --framework tanstack-start ``` `createStartRpcApi` is a turnkey `createRpcApi` with request-scoped cookie forwarding pre-wired; any `headers` you pass are layered on top: ```ts import { createStartRpcApi } from './generated/start-adapter' export const rpc = createStartRpcApi({ url: '/rpc' }) ``` #### Forwarding other request headers [#forwarding-other-request-headers] An app behind an authenticating reverse proxy (Cloudflare Access, Google IAP, oauth2-proxy, …) authenticates from a header the proxy sets on the incoming request rather than from a cookie, and an SSR call to the API has to carry that header too. Name the headers to forward with `forwardHeaders`: ```ts export const rpc = createStartRpcApi({ url: '/rpc', forwardHeaders: ['cookie', 'cf-access-jwt-assertion'], // e.g. Cloudflare Access }) ``` The list **replaces** the default `['cookie']` — keep `'cookie'` in it when the session cookie should still travel, and pass `[]` to forward nothing. Names match case-insensitively and are sent lower-case; a header the incoming request does not carry is skipped. In the browser nothing is forwarded (the browser attaches its own cookies), and explicitly passed `headers` win over a forwarded header of the same name. Forward identity and correlation headers only, never hop-by-hop or framing headers such as `host`, `connection`, or `content-length`. For finer control the adapter also exports the isomorphic headers functions on their own — `forwardRequestHeaders(names)` and `forwardRequestCookie` — so you can compose them into a plain `createRpcApi` call, or into any other `fetch`-based client that runs during SSR: ```ts import { createRpcApi } from './generated/rpc-client' import { forwardRequestHeaders } from './generated/start-adapter' const rpc = createRpcApi({ url: '/rpc', headers: () => forwardRequestHeaders(['cookie', 'authorization']) }) ``` #### The status of a failed SSR render [#the-status-of-a-failed-ssr-render] A page rendered on the server answers `200` unless something sets another status, so a page whose loader met a refusal would answer `200` with the error view. The adapter exports what a server entry needs to answer the right status: `ssrStatusFor(error)` maps an error to `401`, `403` or `404` for the server's unauthorized, forbidden and not-found answers, to `503` when the service (or the platform or proxy in front of it) answered `503 Service Unavailable` — maintenance, a stopped installation — and to `undefined` otherwise. `withResponseStatus(result, status, headers?)` returns the rendered result with that status and the given headers set over the rendered ones (the body streams unchanged, and a `503` gets `Cache-Control: no-store` unless a header states one). Your API wrapper may throw its own error types, which the built-in mapping cannot know. Pass `classify` to map them: it is consulted first, for the error and each `cause` (outermost first). The first status it returns wins, and `undefined` leaves the error to the built-in mapping. `withResponseStatus` takes what TanStack Start's handler callback returns: a `Response`, or the stream result `{ response, serverSsrCleanup, dispose }`. It returns the same shape. For the stream result only `response` is replaced, so `dispose` stays attached and still cancels the stream and cleans up the render when the request is aborted. Never unwrap the stream result and return a bare `Response`: that drops the cleanup. Record the error a loader or error boundary met in a place your server entry can read for the request, then rewrite: ```ts import { createStartHandler, defaultStreamHandler } from '@tanstack/react-start/server' import { createServerEntry } from '@tanstack/react-start/server-entry' import { ssrStatusFor, withResponseStatus } from './generated/start-adapter' import { AppUnavailableError, ForbiddenError } from './lib/errors' const classify = (error: unknown) => error instanceof AppUnavailableError ? 503 : error instanceof ForbiddenError ? 403 : undefined export default createServerEntry({ fetch: createStartHandler(async (ctx) => { const result = await defaultStreamHandler(ctx) const status = ssrStatusFor(renderError(ctx), { classify }) // the error your loader or boundary recorded if (status === undefined) return result return withResponseStatus(result, status, status === 503 ? { 'retry-after': '30' } : undefined) }), }) ``` In the page itself, `isServiceUnavailable(error)` (from the core client, also through a mapped error's `cause`) tells a "back soon" state from a failure. The header read must stay inside `createIsomorphicFn().server(...)`. Importing `@tanstack/react-start/server` from any module the client bundle can reach — even a dynamic import behind a `typeof window` guard — fails `vite build` with `[import-protection] Import denied`. The emitted adapter is structured so the Start compiler strips the import (and the read) from the client build; keep that shape if you hand-roll it instead. Because the frontend rarely rebuilds in CI, this is easy to get wrong unnoticed. ## Error handling [#error-handling] A JSON-RPC error returned by the server is thrown as a typed `RpcError`. Every error carries a stable string `code` (the contract to branch on, for example `not_found` or `token.malformed`), a typed `data` payload, the human-readable `message`, and `rpcCode` — the numeric JSON-RPC code, which only encodes the coarse `AppError` kind and is why it is not called `code`. The wire shape is always `error.data = { code, data? }` ([ADR-0080](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0080-errors-are-a-declared-contract-with-a-stable-code.md)). Handlers declare the errors they produce with `[ProducesError]` (on the handler, or once on a decorator, module or assembly for errors that many operations share), and the generator emits them per method: each method's `errors` entry in `RpcMethods` maps a code to its kind and payload type, and the client exports `RpcMethodError`, a union of `RpcError` variants discriminated by `code`, with `data` typed per variant: ```ts import { isRpcMethodError, type RpcMethodError } from './generated/rpc-client' function describe(error: RpcMethodError<'tokens.redeem'>) { switch (error.code) { case 'token.malformed': return `Malformed: ${error.data.reason}` // data is typed from the declared payload case 'not_found': return 'Unknown token' } } try { await rpc.tokens.redeem({ token }) } catch (error) { if (isRpcMethodError('tokens.redeem', error)) return describe(error) // narrows by the declared codes throw error } ``` A declared payload is validated against its generated Zod schema (`rpcErrorDataSchemas`) unless `validateResults: false`; a mismatch throws `RpcProtocolError` instead of surfacing a mistyped error. Batch items report `error: RpcError`; narrow them with `isRpcMethodError`. Without a `{ code, data }` envelope (a foreign server) `code` falls back to the default code of the numeric kind. Beyond the standard JSON-RPC codes, Elarion maps its transport-agnostic `AppError` kinds onto the server-reserved range, and the generated `RpcError` exposes a getter per kind (reading `rpcCode`) — a quick way to branch on the kind alone: ```ts import { RpcError, ElarionErrorCodes } from './generated/rpc-client' try { await rpc.clients.get({ id }) } catch (error) { if (error instanceof RpcError) { if (error.isNotFound) return renderNotFound() if (error.isForbidden || error.isUnauthorized) return redirectToLogin() if (error.isConflict) return showConflictToast(error.message) } throw error } ``` | Getter | Code | `AppError` kind | | -------------------- | -------- | ------------------ | | `isInvalidParams` | `-32602` | `Validation` | | `isNotFound` | `-32001` | `NotFound` | | `isConflict` | `-32002` | `Conflict` | | `isForbidden` | `-32003` | `Forbidden` | | `isBusinessRule` | `-32004` | `BusinessRule` | | `isUnauthorized` | `-32005` | `Unauthorized` | | `isDecisionRequired` | `-32006` | `DecisionRequired` | | `isInternalError` | `-32603` | `Internal` | The application codes are also exported as `ElarionErrorCodes` for `switch` statements, and the standard JSON-RPC getters (`isParseError`, `isInvalidRequest`, `isMethodNotFound`) stay available. These codes are the framework default from [`AppErrorMapper`](/docs/reference/result-and-errors); a host that registers a custom `IAppErrorTranslator` changes the wire codes, so keep the frontend aligned. A network or HTTP-level failure throws `RpcTransportError` and a malformed JSON-RPC envelope throws `RpcProtocolError`. ### Timeouts, error mapping and retries [#timeouts-error-mapping-and-retries] `RpcClientOptions` bounds every request and gives the application one place to word failures: ```ts import { createRpcApi, isRetryable, RpcError, RpcTimeoutError } from './generated/rpc-client' export const rpc = createRpcApi({ url: '/rpc', timeoutMs: 30_000, // every request timeoutFor: (method) => method === 'reports.export' ? 180_000 : undefined, mapError: (error) => new AppFailure(localize(error), { cause: error }), }) // TanStack Query: retry only what a retry can clear. const queryClient = new QueryClient({ defaultOptions: { queries: { retry: (count, error) => count < 3 && isRetryable(error) } }, }) ``` * **Timeouts.** A request still unanswered after its timeout is aborted and throws `RpcTimeoutError` (`timeoutMs`, `methods`). The timeout of a method is, first to last: the call's `timeoutMs` option (`false` sends it without one), `timeoutFor(method)`, the handler's `[ClientTag("timeout", "180s")]` (`rpcMethodInfo[m].tags.timeout`, in `ms`, `s` or `m`; a bare number is seconds), and the client's `timeoutMs`. A tag value must be above zero and at most 2147483647 ms; the build refuses any other value with `ELRPC013`, so a typo cannot silently fall back to the client's default. A batch waits for the longest of its methods. The caller's own `AbortSignal` still cancels, and its abort is never reported as a timeout. * **Error mapping.** `mapError(error, context)` receives every error a call or batch throws — `RpcError`, `RpcTransportError`, `RpcTimeoutError`, a params or protocol error, a network failure — and what it returns is thrown instead (`undefined` keeps the original). Keep the original as `cause`: `isRetryable`, `isServiceUnavailable` and the decision helpers look through it. The errors inside a batch's item results are not mapped. * **Retries.** `isRetryable(error)` is true for a network failure, a timeout, a `408`, `429` or `5xx` transport answer, an unexpected server error (`code: "internal"`) and `idempotency.in_progress`, and false for every answer the server decided (validation, not found, conflict, forbidden, unauthorized, business rule, a decision), a params or protocol error and a call the caller aborted. An unexpected server error (an exception, `code: "internal"`) carries a support reference in `error.reference` — the server's configured [unexpected-error](/docs/concepts/results-and-errors#unexpected-errors) answer. Show it next to the message instead of matching the message text; it is `undefined` for every other error: ```ts if (error instanceof RpcError && error.code === 'internal') return showError(`${error.message} (reference ${error.reference ?? 'unavailable'})`) ``` ### Answering decisions [#answering-decisions] A method whose handler declares [`[RequiresDecision]`](/docs/concepts/results-and-errors#asking-the-caller-to-decide) lists each decision in its `errors` with kind `decision_required`, its `options` and `perItem`, and its request's `decisions` member is typed with exactly those answers: a declared code, one of its options, and for a per-item decision the item. An undeclared code or option is a compile error, and the generated params schema rejects it before the call is sent: ```ts // RpcParams<'banking.imports.commit'>['decisions'], also available as RpcMethodDecisionAnswer[] decisions?: ( | { code: 'banking.closed_period'; option?: 'confirm' } // a confirmation | { code: 'banking.possible_duplicate'; item: string; option: 'import' | 'skip' } // a choice per item )[] | null ``` `withDecisions` runs the call; when the server needs a decision the method declares, it hands your dialog a typed question and calls again with the answer added to `decisions`, until the call succeeds or fails otherwise: ```ts import { withDecisions } from './generated/rpc-client' const outcome = await withDecisions(client, 'banking.imports.commit', { statement }, async (question) => { switch (question.code) { case 'banking.closed_period': return (await confirm(question.message)) ? 'confirm' : undefined // undefined cancels case 'banking.possible_duplicate': // perItem: one option per item key the data lists, typed "import" | "skip" return await askPerLine(question.data.lines) // Record } }) ``` The question carries `code`, `message`, the declared `options`, `perItem`, the typed `data` and the `RpcError`. Returning `undefined` cancels: `withDecisions` throws `RpcDecisionCancelledError` (with the `question` and, as its `cause`, the decision error), so a caller tells a cancel from a failure of the call. The first call sends the params as given, without an empty `decisions` list. A later answer for the same code and item replaces an earlier one, and `maxQuestions` (default 10) stops a server that keeps asking. Each resend is a new request, so an idempotent method gets a new idempotency key unless the options fix one. The first argument is the generated client or your own call seam, any function shaped `(method, params, options?) => Promise` (`RpcCall`), so the calls keep going through the timeouts, error mapping and localization of your application: ```ts const outcome = await withDecisions(rpc, 'banking.imports.commit', { statement }, askImportDecision) ``` When the dialog is declarative state rather than an awaited promise (its saving state and the resend's failure shown inside it, a query library's mutation sending the call), use the two primitives `withDecisions` is built on: `decisionQuestion(method, error)` recognizes a question the method declares and returns it typed (or `undefined` for any other error), and `answerDecision(decisions, question, answer)` returns the request's `decisions` with the answer added, replacing an earlier answer for the same code and item: ```ts import { answerDecision, decisionQuestion } from './generated/rpc-client' // When the call fails: keep the question and the params it answers. const question = decisionQuestion('banking.imports.commit', error) if (question) setPending({ question, params }) // When the user answers: resend through your own mutation, with the answer added. commit.mutate({ ...pending.params, decisions: answerDecision(pending.params.decisions, pending.question, answer) }) ``` Both recognize the `RpcError` itself or an error whose `cause` chain holds it, so a seam that wraps errors keeps working. `withDecisions`, the primitives and the `RpcDecision*` types are emitted only when a method declares a decision. ## Method requirements and UI gating [#method-requirements-and-ui-gating] `rpcMethodInfo` holds, for every method, what the schema says before the method is called — exported from the handler's own declarations, so the UI never repeats them: | Field | From | | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `requires.anonymous` | `[AllowAnonymous]` | | `requires.authenticated` | any requirement, or an `[ElarionAuthorizationDefaults]` in scope | | `requires.permissions` / `requires.roles` | `[RequirePermission]` / `[RequireRole]` (all required) | | `requires.memberPermissions` | `[RequirePermissionFor]` (all required; present only on a method that declares one) — decided from the call's params | | `requires.serverChecks` | `[RequirePolicy]`, `[RequireClaim]` or `[RequireResource]` — only the server can tell | | `readOnly` | the request is an `IQuery` | | `idempotent` | `[Idempotent]` | | `tags` | `[ClientTag(key, value)]` hints, e.g. `[ClientTag("timeout", "180s")]` | Pair it with `canCall` from `@swimmesberger/elarion-contributions` to grey out an action the current user cannot call, without naming the permission at the call site: ```tsx import { canCall } from '@swimmesberger/elarion-contributions' import { rpcMethodInfo } from './generated/rpc-client' const decision = canCall(rpcMethodInfo['invoices.approve'], capabilities) // the session capabilities ``` `canCall` returns `{ allowed: false, reason, missing? }` for the first unmet requirement (`unauthenticated`, `permission`, `role`), or `{ allowed: true, serverChecks }`. Like a contribution's `when`, it is a UX projection: the server authorizes every call. A [member-scoped permission](/docs/concepts/authorization#permissions-that-depend-on-a-request-member) depends on the call: pass its params, and `canCall` reads the member and requires the permission its value maps to, or one of the `anyOf` permissions. Without params it stays conservative — allowed only when the caller holds an `anyOf` permission or the permission of every value — and refuses with `{ allowed: false, reason: 'params', member }`: ```tsx // Show the custom-fields tab of a tenant only to callers who may list the tenant's fields. const fields = canCall(rpcMethodInfo['customFields.list'], capabilities, { params: { kind: 'tenant' } }) {fields.allowed && } // Without params: true for a settings.read holder, or for one holding every kind's read permission. const anyKind = canCall(rpcMethodInfo['customFields.list'], capabilities).allowed ``` A value that maps to no permission, or a member missing from the params, refuses with `reason: 'params'` too; a value whose permission the caller lacks names it (`reason: 'permission', missing: 'tenants.read'`). The same map answers other per-method questions — `rpcMethodInfo[m].tags.timeout` for a slow operation's client timeout, `readOnly` for which actions a read-only session may still use. ## Invalidating queries after a command [#invalidating-queries-after-a-command] A successful command makes some queries stale. The client knows which ones without a hand-kept list: every method has **resources**, and a command invalidates every query that reads a resource it writes ([ADR-0124](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0124-commands-invalidate-the-queries-that-read-what-they-write.md)). * **The default is the method name's prefix up to the last dot.** `invoices.list` reads `invoices`, `invoices.finalise` writes `invoices`, `invoices.catalog.save` writes `invoices.catalog`; a name without a dot has none. So every invoice command invalidates every invoice query with no declaration at all. * **Across areas, declare it on the handler.** A query states what it shows, a command what it changes; neither names the other: ```csharp [Handler("notifications.list"), Reads("invoices.approvals")] // reads notifications and invoices.approvals public sealed class ListNotifications(…) : IHandler>> { … } [Handler("invoices.finalise"), Writes("ledger", "invoices.approvals")] // writes invoices, ledger, invoices.approvals public sealed class FinaliseInvoice(…) : IHandler> { … } ``` Both attributes add to the name's resource; `IncludeNameResource = false` replaces it. A misspelt `[Writes]` that no query reads is warning [`ELRPC014`](/docs/reference/diagnostics#elrpc--json-rpc-method-generation). The generated `rpc-client.ts` exports: | Export | What it is | | -------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `RpcResource` | The union of every resource in the schema, so a resource in application code is a checked string. | | `rpcMethodResources[method]` | What the method reads (a query) or writes (any other method). | | `queriesInvalidatedBy(method)` | The queries that read a resource `method` writes; empty for a query. | | `invalidationKeys(method, { invalidate?, also? })` | Those queries as query keys `[query]`, then `also`; `invalidate: false` keeps only `also`. | `invalidationKeys` returns one `[query]` key per stale query. TanStack Query matches keys by prefix, so it reaches every cached call of the query when you key queries `[method, params]`. Use it as the default of your mutation hook: ```ts import { useMutation, useQueryClient } from '@tanstack/react-query' import { invalidationKeys, type RpcInvalidationOptions, type RpcMethod, type RpcParams } from './generated/rpc-client.js' export function useRpcMutation(method: M, options: RpcInvalidationOptions = {}) { const queryClient = useQueryClient() return useMutation({ mutationFn: (params: RpcParams) => rpc(method, params), onSuccess: () => Promise.all( invalidationKeys(method, options).map((queryKey) => queryClient.invalidateQueries({ queryKey }))), }) } useRpcMutation('invoices.finalise') // every query of invoices, ledger, invoices.approvals useRpcMutation('invoices.rename', { also: [['portal.page', { slug }]] }) // and one key outside the schema's set useRpcMutation('drafts.autosave', { invalidate: false }) // nothing ``` Invalidation is per method, not per record: renaming one invoice refetches every cached `invoices.get`. The schema exports `resources` only for a method that declares `[Reads]`/`[Writes]`; without a declaration the generator applies the same default, so a schema without declarations does not change. ## Limits, presets, sort keys and constants [#limits-presets-sort-keys-and-constants] Four more exports at the end of `rpc-schemas.ts` carry values the server declares, so a page shows or sends them instead of copying them. Each is emitted only when the schema has an entry for it; `rpc-types.ts` and `rpc-client.ts` never change. (`rpcUploadLimits`, emitted whenever params take an uploaded file, is described under [upload limits](#upload-limits-in-the-users-language).) | Export | What it holds | Declared by | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `rpcLimits` | Every params member's limits by method and member path, as literal types: `minLength`, `maxLength`, `minimum`, `exclusiveMinimum`, `maximum`, `exclusiveMaximum`, `multipleOf` (a decimal scale, `[MaxDecimalPlaces]`), `minItems`, `maxItems`, `pattern` (anchored, as the server matches it), `notBlank: true` for a string the server refuses when empty or blank (`[Required]`), and an upload member's `maxBytes`, `contentTypes` and `fileExtensions`. A nested member is reached through its parent, a list's elements through `items`. `rpcLimitsOf(method, path)` reads one member's. | The DataAnnotations the schema already exports, and [`[UploadLimits]`](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member) | | `rpcPresets` | Named request values per method, each typed as the method's params. | [`[RequestPreset]`](/docs/reference/attributes#requestpreset) on the handler | | `rpcSortKeys` | The keys the handler's sort map allows, in declaration order, with the direction a bare key applies and which one is the default. | The handler's [`SortMap`](/docs/capabilities/pagination#offset-pagination) | | `rpcMaxSortLevels` | How many of those keys one sort may combine (`+city,-name`), per method in `rpcSortKeys`. | The same `SortMap` (`MaxLevels`) | | `rpcConstants` | Each module's exported constants, as literal types. | [`[ClientConstants]`](/docs/reference/attributes#clientconstants) | ```ts import { rpcConstants, rpcLimits, rpcMaxSortLevels, rpcPresets, rpcSortKeys } from './generated/rpc-schemas' // "up to 10 receipts" and the disabled button read the server's [MaxLength(10)], typed as 10. const maxReceipts = rpcLimits['documents.upload'].receipts.maxItems const maxReceiptBytes = rpcLimits['documents.upload'].receipts.items.maxBytes // A chip opens exactly the request the server counted. const page = await rpc.invoices.list({ ...rpcPresets['invoices.list'].toTransfer, page: 2 }) // A column header toggles between +key and -key for the keys the handler allows. const sortable = rpcSortKeys['invoices.list'].map((sortKey) => sortKey.key) // Shift-click adds a sort level until the handler's cap (3 unless its SortMap sets MaxLevels). const maxSortLevels = rpcMaxSortLevels['invoices.list'] const currencies = rpcConstants.billing.currencies // readonly ["EUR", "CHF"] ``` A rule shared by several modules lives outside any module (a domain class), where `[ClientConstants]` cannot go. Export it through a small class of the module that owns the client screen, assigning the domain constants rather than copying them; messages and a search pattern are strings like any other. Keep the pattern's text in a constant that the server's `[GeneratedRegex]` reads too, and write it in the syntax both engines share (`[0-9]` rather than `\d`, which matches non-ASCII digits in .NET); pass its options to the client as their own constant, since ECMAScript has no inline `(?i)`: ```csharp namespace MyApp.Keys; [ClientConstants] internal static class CylinderRules { public const decimal LengthMinMm = CylinderLength.MinMm; // rpcConstants.keys.lengthMinMm public const decimal LengthMaxMm = CylinderLength.MaxMm; public const string LengthRangeMessage = CylinderLength.RangeMessage; public const string LengthSearchPattern = CylinderLength.SearchPatternText; } ``` ```ts const lengthSearch = new RegExp(rpcConstants.keys.lengthSearchPattern, 'i') ``` A form field reads its limits from the contract instead of repeating them. `rpcLimitsOf(method, path)` returns one params member's limits for a dotted path (`items` for a list's elements) as an `RpcMemberLimits` — every key optional, present only when declared — and `{}` when the member, the path or the method declares none. The path is typed with the declared paths for completion and accepts any other string, so a generic field component can ask for whatever member it renders: ```tsx import { rpcLimitsOf, type RpcLimitPath } from './generated/rpc-schemas' import type { RpcMethod } from './generated/rpc-client' // [StringLength(200, MinimumLength = 1)] [Required] string Name on the request: const name = rpcLimitsOf('properties.create', 'name') // { minLength: 1, maxLength: 200, notBlank: true } function TextField(props: { method: M; member: RpcLimitPath | (string & {}) }) { const limits = rpcLimitsOf(props.method, props.member) … } ``` `pattern` is the regular expression the whole value must match, in ECMAScript syntax: test it with `new RegExp(limits.pattern, 'u')`. It is not guaranteed to be valid in an HTML `pattern` attribute, which compiles with the `v` flag. The params schemas already enforce every limit; `rpcLimitsOf` is for showing them (a counter, a hint, `maxLength` on the input). A preset carries the members the server needs to see that request: every required member, and every other member whose value differs from the request's default — `null` where the preset clears a default. Spread it into the params and add the page, size or search the UI owns. Labels stay in the client's language files; the schema carries values only. A server change to any of these reaches the client as a type change, so a page that relied on the old value fails to compile instead of drifting. ## Params validation [#params-validation] The client **pre-validates request params by default** through `rpcParamsSchemas`, before anything touches the wire. A tier-1 violation — a too-long name, a malformed email — throws a local `RpcParamsValidationError` (carrying the method name and the underlying Zod error) instead of costing a round trip; batch items are validated the same way. Because the schemas are generated from the same attributes the server enforces, a request that passes the pre-flight can only fail server-side on business rules (which come back as field-keyed validation errors using the same wire-named paths). Set `validateParams: false` to opt out when another layer owns input validation. `RpcParamsValidationError.fieldErrors` groups the Zod issue messages by field path in the server's [`fieldErrors` notation](/docs/concepts/validation#field-keyed-errors) — member names joined with `.`, array indexes as `[i]` (`"lines[1].sku"`), `""` for the params object itself — so one form helper marks fields for a local failure and for a server validation error alike. `cause` still carries the Zod error. ```ts function fieldErrorsOf(error: unknown): Record | undefined { if (error instanceof RpcParamsValidationError) return error.fieldErrors if (error instanceof RpcError && error.isInvalidParams) { return (error.data as { fieldErrors?: Record } | undefined)?.fieldErrors } return undefined } ``` ## Result validation [#result-validation] Result validation runs by default through `rpcResultSchemas`. Use `transformResult` for app-specific normalization before validation, or set `validateResults: false` when another layer validates responses. ## Tracing with OpenTelemetry [#tracing-with-opentelemetry] The client stays OpenTelemetry-package-free — it never imports a tracing SDK. To make a call appear in a distributed trace, pass an `instrumentation` adapter that starts a span per request/batch and injects the W3C `traceparent` header. An ASP.NET Core host running OpenTelemetry with `AddAspNetCoreInstrumentation()` extracts that header, so the server request span, the JSON-RPC dispatch, and the handler-pipeline spans all nest **under your client span** — one end-to-end trace. Implement `RpcInstrumentation` over `@opentelemetry/api`: ```ts import { context, propagation, trace, SpanKind, SpanStatusCode } from '@opentelemetry/api' import { createRpcApi, type RpcInstrumentation } from './generated/rpc-client' const instrumentation: RpcInstrumentation = { startSpan(ctx) { const span = trace .getTracer('rpc-client') .startSpan(ctx.batch ? 'rpc batch' : `rpc ${ctx.methods[0]}`, { kind: SpanKind.CLIENT }) // Inject traceparent for this span into the headers the client is about to send. const headers: Record = {} propagation.inject(trace.setSpan(context.active(), span), headers) return { headers, setError: (error) => { span.recordException(error as Error) span.setStatus({ code: SpanStatusCode.ERROR }) }, end: () => span.end(), } }, } const rpc = createRpcApi({ url: '/rpc', instrumentation }) ``` `RpcRequestContext` gives you `methods` (one per call, several for a `$batch`) and a `batch` flag for span naming; the span's `headers` are applied **last**, so trace propagation stays authoritative over your static or dynamic `headers`. The adapter above is the only Elarion-specific piece — wire the rest of the browser SDK (`WebTracerProvider`, an OTLP exporter, `ZoneContextManager`) as shown for the [HTTP client](/docs/capabilities/transports/openapi#trace-client-requests-with-opentelemetry), and see [Telemetry & observability](/docs/capabilities/telemetry) for the server side. ## Handlers exposed only over REST [#handlers-exposed-only-over-rest] The generator reads `rpc-schema.json`, and that schema lists the operations the JSON-RPC transport serves — handlers carrying `[Handler]` with `HandlerTransports.JsonRpc`. A handler that carries only [`[HttpEndpoint]`](/docs/capabilities/transports/http-endpoints) (a public link answered without a session, a route that must live outside `/rpc`, an endpoint for third-party callers) is not on the JSON-RPC bus, so the generated client has no function, no types, and no Zod schemas for it. That is deliberate. REST's machine-readable contract is the **OpenAPI document**, and Elarion leaves REST client generation to the off-the-shelf OpenAPI tooling instead of owning a second, bespoke HTTP client generator ([ADR-0026](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0026-openapi-http-transport.md)). Folding routes, verbs, and route/query/header/body binding into `rpc-schema.json` would make this generator re-implement what OpenAPI already describes and what those tools already consume. Pick one of two paths instead — never hand-copy the response DTO into a Zod schema, because a C# rename then still compiles and silently breaks the page: * **The operation does not need to be a REST route.** Add `[Handler]` next to (or instead of) `[HttpEndpoint]`. It joins `rpc-schema.json` and gets the generated function, params/result Zod schemas, and the typed [error union](#error-handling) for its declared codes. Authorization and validation stay on the handler, so an anonymous handler stays anonymous on either transport. * **It must stay REST-only.** Add `Elarion.AspNetCore.OpenApi`, export the document, and generate a client from it — the [recommended setup](/docs/capabilities/transports/openapi#generate-a-typed-client) uses `@hey-api/openapi-ts` with its Zod plugin for typed params and runtime-validated responses. Errors arrive as RFC 7807 ProblemDetails with the same stable `code` and `data` members as an `RpcError`; the OpenAPI document declares both, so [branch on `error.code`](/docs/capabilities/transports/openapi#typed-errors) without a cast. Both clients run side by side: the JSON-RPC client for the operation-shaped API, the OpenAPI-generated one for the handful of REST-only routes. Regenerate each from its own contract file in the same build step. ## Design boundaries [#design-boundaries] The generated runtime stays framework-neutral: it uses standard `fetch`, accepts an injected transport and `AbortSignal`, validates with Zod, and supports batching — but never imports React, TanStack, Vite, or any downstream framework. Applications own the adapter layer: server functions, auth forwarding, UI-framework hooks, and result normalization wrap `createRpcApi(...)` rather than replacing the transport. The one exception is an **opt-in** framework adapter (`--framework tanstack-start`), emitted as a separate `start-adapter.ts` that the core client never imports. A consumer that does not pass the flag gets byte-identical, framework-free output — the neutrality boundary is about what the core client pulls in, not about whether a separate opt-in file may exist. The generator interprets the framework's schema format and does not support arbitrary JSON Schema composition. `anyOf` is supported in the shape the server exports for [C# unions](#c-unions-map-to-typescript-unions); `oneOf` and `allOf` are rejected — adjust the exported DTO shape or extend the generator deliberately. Re-run the generator whenever `rpc-schema.json` changes, or the frontend types go stale. # Web Push (/docs/capabilities/web-push) [Client events](/docs/capabilities/events/client-events) reach a user who has the app **open**. Web Push (RFC 8030, encrypted per RFC 8291, authenticated with VAPID per RFC 8292) reaches one who does **not**: a browser or installed PWA subscribes once, and the server can notify it later with the app closed — "your deploy failed", "time to feed the starter". It is what an installed PWA on a phone needs to be useful. Every piece of that is framework-shaped, so Elarion owns it (ADR-0076): the VAPID key pair, the subscription store, the send loop with cleanup, the subscribe endpoints, and the browser and service-worker plumbing. **Who** receives a notification, **when**, and **what** it says stay in the application. | Package | Role | | ------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `Elarion.WebPush` | `IWebPushSender`, `WebPushSubscriptionService`, VAPID keys, the store seams, in-memory defaults. | | `Elarion.WebPush.EntityFrameworkCore` | Durable `elarion_push_subscriptions` and `elarion_vapid_keys` tables (PostgreSQL or SQLite). | | `Elarion.WebPush.AspNetCore` | `MapElarionWebPush()` — HTTP bindings for the three subscription handlers your application declares. | | `@swimmesberger/elarion-webpush` | Availability detection, permission and subscription helpers, and the service-worker module. | ## Wiring [#wiring] ```csharp // The DbContext maps the two tables: [GenerateDbSets] [GenerateElarionWebPush] public partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } builder.Services.AddElarionSettingsDataProtection(); // protects the VAPID private key at rest (any ISettingValueProtector) builder.Services.AddElarionWebPushEntityFrameworkCore(options => options.Subject = "mailto:ops@example.com"); // required: the VAPID contact app.MapElarionWebPush().RequireAuthorization(); // GET public-key, POST subscribe/unsubscribe under /webpush ``` plus the three handlers below, which `MapElarionWebPush()` dispatches to. The EF stores write with `INSERT … ON CONFLICT` statements, which run on **PostgreSQL** and **SQLite** (3.24+). Their parameters are created from the model's own type mappings, so a context-wide value converter applies to them as it does to a tracked insert — a SQLite application that stores `DateTimeOffset` as a sortable integer keeps doing so. Another provider implements `IPushSubscriptionStore` and `IVapidKeyStore` itself. The subscription store is **scoped and works on the caller's own context**. Inside a unit of work — a command handler under the transaction decorator — a subscribe, an unsubscribe, or the cleanup of a dead subscription during a send joins that transaction and commits or rolls back with the handler's other writes; outside one (an endpoint, a job) each statement commits on its own. So the subscribe handlers below need no special pipeline, on PostgreSQL or on SQLite, where a second connection would wait for the handler's write lock. `AddElarionWebPush(...)` alone registers the same services over **in-memory** stores — fine for tests and a single-node demo, but both the subscriptions and the key pair vanish on restart. ### The VAPID key pair [#the-vapid-key-pair] Browsers bind every subscription to the server's public key, so the key pair must be **stable**: rotating it invalidates every subscription. `IVapidKeyProvider` resolves it in this order: 1. **Configuration** — `options.PublicKey` and `options.PrivateKey` (base64url; set both or neither). Use this to keep the private key in a secret store. 2. **The store** — the `elarion_vapid_keys` row. 3. **Generated on first use** and stored. Two nodes racing the first start both insert with `ON CONFLICT DO NOTHING` and read the row back, so they agree on one pair. With the EF stores the pair is resolved **when the host starts**, not in the first request that needs it. Once resolved it is cached for the life of the process, so it must be stored for good before it is used — never inside a request's transaction, whose rollback could un-store a key browsers already subscribed against. If the tables do not exist yet at start, that is logged and the pair is resolved on first use instead. The private key is **protected at rest** (ADR-0078's seam): the EF store writes it through the registered `ISettingValueProtector` — `AddElarionSettingsDataProtection()` is the shipped implementation over ASP.NET Core Data Protection, whose key ring you must persist and share between nodes — bound to the pair's public key, with the protector's scheme in the row's `protection` column. The store **fails closed**: without a protector it cannot be resolved, and a payload that does not decrypt (a lost key ring) throws instead of minting a replacement pair, which would invalidate every subscription. A row written before protection existed (no `protection` value) is accepted once and re-protected in place, as is a payload under a retired Data Protection key. Upgrading adds the nullable `protection` column and widens `private_key` to 1024 characters — add an EF migration. Keys configured through `options.PublicKey`/`PrivateKey` never touch the store, and an application with its own `IVapidKeyStore` (a vault, a KMS) registers it after `AddElarionWebPushEntityFrameworkCore` and needs no protector. `VapidKeys.Generate()` mints a pair if you want to pin one from the start. To move an existing pair into the store (so browsers' current subscriptions keep working), call `IVapidKeyStore.ImportAsync(keys)` once, before the first push is sent. The EF store protects the private key with its own purpose, so you never build the protection format yourself. The result is `Imported`, `Unchanged` when the identical pair is already stored (safe to run on every start), or `Refused` when a **different** pair is stored — replacing it would invalidate every subscription, so it takes an explicit `overwrite: true` (`Replaced`). Concurrent nodes importing different pairs leave exactly one winner. The provider caches the pair per process, so restart other nodes after an overwrite. ## Sending [#sending] Resolve `IWebPushSender` (scoped) wherever the trigger lives — a handler, an integration-event consumer, a scheduled job: ```csharp [ConsumeEvent] public sealed class NotifyOnFailedDeploy(IWebPushSender push, AppDbContext db) : IHandler { public async ValueTask HandleAsync(DeployFailed e, CancellationToken ct) { var operators = await db.Operators.Select(o => o.UserId).ToListAsync(ct); await push.SendToUsersAsync(operators, new WebPushMessage { Title = "Deploy failed", Body = $"{e.Service}@{e.Version} failed its health check.", Url = $"/deploys/{e.DeployId}", Tag = $"deploy-{e.DeployId}", Urgency = WebPushUrgency.High, }, ct); return Result.Success(); } } ``` The sender loads the users' subscriptions, encrypts the `{title, body, url, tag}` payload for each, and sends them with bounded concurrency (`MaxConcurrentSends`, default 8). The returned `WebPushResult` counts what happened: | Push service answer | Outcome | Subscription | | ------------------------------------------- | ----------- | ------------------------------------------------------------------ | | 2xx | `Delivered` | kept | | 404 / 410 | `Removed` | **deleted** — the browser unsubscribed or the subscription expired | | malformed keys, disallowed endpoint | `Removed` | **deleted** — it can never be delivered to | | 429, 5xx, timeout, network error, other 4xx | `Failed` | kept | A refused message (any non-2xx other than 404/410) is logged as a warning with the push service's own reason from the response body — Apple answers with `{"reason":"…"}`, FCM and Mozilla with a sentence — capped at 256 characters and flattened to one line. That reason is the only place a push service says *why*. Web Push is **best-effort**: "delivered" means the push service accepted the message, not that the device showed it, and a failed send is not retried. If a notification must not be lost, send it from a durable trigger (an integration event through the outbox, a job) so the retry is yours. Message fields map onto the protocol: * `Tag` replaces rather than stacks: the browser replaces a displayed notification with the same tag. It is deliberately **not** sent as the RFC 8030 `Topic` header — Apple's push service (`web.push.apple.com`) rejects every request that carries one with `400 BadWebPushTopic`, whatever its value — so the push service keeps each undelivered message, and a device coming back online receives them in turn, each replacing the last. Keep `TimeToLive` short for messages that go stale. * `Urgency` (`VeryLow` … `High`) tells the device how urgently to wake up. `High` costs battery; reserve it. * `TimeToLive` is how long the push service holds the message for an offline device; it defaults to `options.DefaultTimeToLive` (one day). `TimeSpan.Zero` means "now or never". * The payload must fit one 4 KiB push message (about 3,990 bytes of JSON); a longer one throws. Put the details behind `Url`. `SendToCurrentUserAsync(message)` sends to the caller's own devices — the "send a test notification" button. To address an **audience**, ask the store rather than its table: `IPushSubscriptionStore.ListSubscribedUserIdsAsync()` returns the distinct ids of every user that owns a subscription, `ListSubscribedUserIdsAsync(candidates)` narrows a candidate list to those with at least one device, and `ListByUsersAsync(userIds)` returns the subscriptions themselves. A custom store implements all three. ## Subscribing [#subscribing] Subscribing is an **operation of your application**, so it runs through your handler pipeline like every other one: global authorization rules, tenant and realm rules, audit, rate limiting and validation apply to it. The framework therefore ships the request types and the shared logic, not the handlers. Declare three `[Handler]`s that delegate to `WebPushSubscriptionService` — they appear in the JSON-RPC schema and the generated TypeScript client like any other: ```csharp [Handler("webPush.subscribe")] public sealed class SubscribeToPush(WebPushSubscriptionService subscriptions) : IHandler { public ValueTask HandleAsync(PushSubscriptionRequest request, CancellationToken ct) => subscriptions.SubscribeAsync(request, cancellationToken: ct); } [Handler("webPush.unsubscribe")] public sealed class UnsubscribeFromPush(WebPushSubscriptionService subscriptions) : IHandler { public ValueTask HandleAsync(WebPushUnsubscribeRequest request, CancellationToken ct) => subscriptions.UnsubscribeAsync(request.Endpoint, ct); } [Handler("webPush.publicKey")] public sealed class GetPushPublicKey(WebPushSubscriptionService subscriptions) : IHandler> { public async ValueTask> HandleAsync(WebPushPublicKeyRequest request, CancellationToken ct) => new WebPushPublicKeyResponse(await subscriptions.GetPublicKeyAsync(ct)); } ``` Subscriptions belong to the current user (`ICurrentUser`); the service insists the caller is authenticated, so a subscription always has an owner, and add `[RequirePermission]` or any other attribute to the handlers to restrict who may subscribe. `MapElarionWebPush()` is the **HTTP binding** for exactly those handlers — it resolves the registered `IHandler`s for `PushSubscriptionRequest`, `WebPushUnsubscribeRequest` and `WebPushPublicKeyRequest` and calls them, so the decorators the generator wrapped around them decide every call. It fails at startup, naming the missing handlers, if one is not registered; there is deliberately no undecorated fallback that could bypass the pipeline by accident. The wire shapes are the browser package's fixed contract: | Endpoint | Body | Result | | --------------------------- | ----------------------- | ----------------------------------------------------------------- | | `GET /webpush/public-key` | — | `200 {"publicKey":"…"}` | | `POST /webpush/subscribe` | `subscription.toJSON()` | `204`; `400` invalid or refused; `401` anonymous; `403` forbidden | | `POST /webpush/unsubscribe` | `{"endpoint":"…"}` | `204`; `401` anonymous; `403` forbidden | A handler failure maps to a bodyless status by its error kind (`Validation` 400, `Unauthorized` 401, `Forbidden` 403, …). A malformed body is answered `401`/`403` by the handler's admission gate when the caller may not call it at all, and `400` otherwise — an anonymous caller never learns the request shape. The endpoint copies the request's `User-Agent` header into `PushSubscriptionRequest.UserAgent` (a property that is not part of the JSON contract). Apply endpoint-level conventions (`.RequireAuthorization()`, a rate-limiter policy) to the returned group as for any minimal API. Subscribing is an upsert **by endpoint**: the same device re-subscribing refreshes its keys and last-seen time, and re-subscribing under a *different* account reassigns the row instead of colliding on the unique endpoint. The reassignment requires the subscription's stored `auth` secret, which the same browser always sends. A request for an endpoint another user owns, with other keys, writes nothing and fails with the same `Validation` error (`400`, code `web_push.subscription_invalid`, `WebPushErrorCodes.SubscriptionInvalid`) as an invalid subscription, so a user who learned someone else's endpoint cannot redirect it to keys of their own. The check is part of the store's single `INSERT … ON CONFLICT … DO UPDATE … WHERE` statement, not a read before the write, so concurrent subscribes for one endpoint leave exactly one owner. The secret is compared with plain SQL equality rather than in constant time. That is acceptable because it is 16 random bytes and each guess costs an authenticated request and a database round trip. A custom `IPushSubscriptionStore` must apply the same rule atomically and return from `UpsertAsync` whether it wrote the row. Unsubscribing only ever deletes the caller's own subscription. ### Endpoint allow-list [#endpoint-allow-list] The server POSTs to whatever endpoint a browser hands it, so an unrestricted endpoint would let any signed-in user aim server-side requests at an internal address. Subscriptions are therefore accepted only for **https** endpoints on the known push services (Google FCM, Mozilla, Apple, Windows) and their subdomains, and the delivery client does not follow redirects. Add a host to `options.AllowedEndpointHosts` for another push service, or set `options.AllowAnyEndpointHost` only if every caller that can subscribe is trusted. The deliveries use the named `HttpClient` `WebPushOptions.HttpClientName`; configure it (`services.AddHttpClient(WebPushOptions.HttpClientName)…`) to add a proxy or resilience handler. ## Browser [#browser] ```ts import { enablePush, fetchWebPushApi, pushAvailability, refreshOnStart } from '@swimmesberger/elarion-webpush' const api = fetchWebPushApi() // the MapElarionWebPush endpoints void refreshOnStart(api) // every app start: heals rotated or cleaned-up subscriptions switch (pushAvailability()) { case 'available': // offer the switch toggle.onclick = async () => showOutcome(await enablePush(api)) // 'subscribed' | 'denied' | 'dismissed' break case 'install-first': // iOS/iPadOS Safari outside a Home Screen app hint.textContent = 'Add this app to your Home Screen to turn on notifications.' break case 'unsupported': // hide the switch } ``` * `pushAvailability()` returns `install-first` on iOS/iPadOS 16.4+ Safari outside a Home Screen install, where `PushManager` does not exist yet — say "add to Home Screen first" instead of offering a switch that can never turn on. Before 16.4 it is `unsupported`. * `enablePush` requests permission **before its first `await`**, because Safari only honours a permission request made synchronously inside the user gesture. Call it straight from the click handler. * `subscribe`, `unsubscribe`, and `isSubscribed` are the building blocks; `refreshOnStart` never prompts. * They subscribe through the page's **active service-worker registration** — or the `registration` option, where you pass what `navigator.serviceWorker.register(...)` returned. Otherwise they wait for a worker to activate for at most `registrationTimeoutMs` (10 s) and throw a `WebPushRegistrationError`; `navigator.serviceWorker.ready` alone never settles when no worker is registered, as on a dev server that does not serve one. * `fetchWebPushApi()` targets the `MapElarionWebPush()` endpoints. To use the handlers over JSON-RPC instead, adapt the generated client: ```ts const api: WebPushServerApi = { getPublicKey: async () => (await rpc.webPush.publicKey({})).publicKey, subscribe: async (subscription) => { await rpc.webPush.subscribe(subscription) }, unsubscribe: async (endpoint) => { await rpc.webPush.unsubscribe({ endpoint }) }, } ``` ### Service worker [#service-worker] ```ts import { registerWebPushHandlers } from '@swimmesberger/elarion-webpush/sw' registerWebPushHandlers(self, { icon: '/icons/192.png', badge: '/icons/badge.png' }) ``` * **`push`** shows the notification (a push that shows nothing is penalized by browsers, so an unreadable payload still shows its text). * **`notificationclick`** focuses a window already at the notification's URL, otherwise navigates an open app window there, otherwise opens one. * **`pushsubscriptionchange`** re-subscribes when the push service rotates the subscription and sends the new one to the server. It authenticates with same-origin cookies; a bearer-token app passes `api: null` and relies on `refreshOnStart`. The module is ESM: bundle the worker (for example vite-plugin-pwa `injectManifest`) or register it with `navigator.serviceWorker.register('/sw.js', { type: 'module' })`. The same worker usually also makes the app installable: [Installable apps (PWA)](/docs/capabilities/pwa) composes `registerShellRouter(self)` from `@swimmesberger/elarion-pwa/sw` — offline shell and asset caching that never touch the API — with these handlers, and shows how to bundle the worker into one script. ## Limits [#limits] * One node sends from one database: the fan-out is in-process and bounded, which covers the 1–10 node tier. A mass-notification service (millions of devices, campaigns, analytics) is a job for a dedicated provider. * Delivery is at-most-once per send and there is no read receipt — Web Push has none. * A user who is online still gets the push; choosing between a client event and a push per call site is the application's decision for now. # Actors (/docs/concepts/actors) `Elarion.Actors` turns a plain `[Actor]` class into a keyed, mailbox-protected state machine with a source-generated typed facade. It is deliberately a small-to-mid application primitive: virtual activation, sequential execution, idle passivation, and optional PostgreSQL snapshots, single-homing, and fixed virtual-shard placement, without a clustered actor runtime. Most applications need zero actors. If the solution sketches cleanly as a table with a version column, use optimistic concurrency, constraints, idempotency, jobs, and the outbox. An actor is justified only when the consistency unit is a live in-memory thing. ## When (not) to use an actor [#when-not-to-use-an-actor] An actor earns its place in exactly three shapes: 1. **It owns a stateful external resource** — a TCP session, device command channel, IMAP connection, or per-tenant API client whose calls must be ordered. You cannot row-lock a socket. 2. **Its state is hot, ephemeral, and loss-tolerant** — live telemetry, presence, progress, or a write-behind buffer. Restart loss is acceptable or naturally repaired by the next reading. 3. **It is an event-driven decide-once coordinator** — a small state machine that reacts over time and must act once. This is the only shape that normally combines snapshots and single-homing, and a versioned state row may still be simpler. | Symptom | Reach for | | ------------------------------------ | ------------------------------------------ | | Two users race to update a record | Optimistic concurrency | | A webhook can arrive twice | `[Idempotent]` or the consumer inbox | | A follow-up must survive the request | Outbox integration event | | One import per tenant | Scheduled job claims | | One ordered TCP/API session per key | Actor owning the resource | | Live, disposable per-key readings | Actor with no snapshot | | Act once after a sequence of events | Actor + snapshot, or a versioned state row | For common loss-tolerant batching and latest-wins publishing, prefer the ready-made [data-rate shaping helpers](/docs/capabilities/data-rate-shaping) before writing an actor. For allocation-sensitive simulation state where only the latest value per entity matters, use the [dirty-flag-and-sweep shape](/docs/capabilities/data-rate-shaping#below-the-helpers-dirty-flag-and-sweep-for-simulation-state) with the actor as the state owner. ## The basic shape [#the-basic-shape] ```csharp [Actor] public sealed class DeviceSessionActor( IActorContext context, IDeviceConnection connection) { public Task Send(DeviceCommand command, CancellationToken ct) => connection.SendAsync(context.Key, command, ct); } ``` The generator emits `IDeviceSession : IActorFacade`. Callers keep a cheap address, not a live activation handle: ```csharp var device = actors.Get(deviceId); var reply = await device.Send(command, ct); ``` `Get` never activates anything. The first call activates the actor, calls are serialized through its mailbox, and a cold activation passivates after five minutes by default. A facade remains valid across passivation, and actor method renames fail at compile time at every call site. Generated contracts, keying, mailboxes, reentrancy, lifecycle, configuration, and worker pools. PostgreSQL snapshots, query semantics, conflict retry, multi-instance topology, and the actor home. Generated event relays, ordered facade streams, activation retention, traces, and metrics. ## The migration seam [#the-migration-seam] The generated facade is intentionally the same kind of contract as an Orleans grain interface: a key-addressed interface of `Task`-shaped methods resolved through a factory. | Elarion.Actors | Orleans | | -------------------------- | -------------------------------------------- | | `IActorFacade` | `IGrainWithGuidKey` | | `actors.Get(id)` | `grainFactory.GetGrain(id)` | | `[Reentrant]` | `[Reentrant]` | | `IActorState` | `[PersistentState] IPersistentState` | Migration is still real work: arguments and results must become serializable, the actor class becomes a grain implementation, custom keys need mapping, and placement moves to Orleans. Serializable DTO-shaped method signatures keep that seam honest. {/* Compatibility anchors for links to the former single-page guide. */} # Actor events, streams, and telemetry (/docs/concepts/actors/integrations) ## Integration events [#integration-events] Put `[ConsumeEvent]` on a public actor method and the generator emits an inbox-deduped integration-event relay that extracts the key and calls the typed facade: ```csharp [Actor] public sealed class OrderFulfillmentActor(IActorContext context) { [ConsumeEvent] [ActorKey(nameof(OrderShipped.OrderId))] // optional when key inference is unambiguous public Task OnShipped(OrderShipped message) => Task.CompletedTask; } ``` The event must expose exactly one property assignable to the actor key, or name it with `[ActorKey]`. Singleton actors need no key. `ELACT008` reports an ambiguous/missing key and `ELACT009` rejects a non-public consumed method because the relay uses the same public facade a hand-written relay would. Only integration events may enter an actor this way (`ELACT010`). Domain events execute inside the emitting handler's transaction and scope, while an actor has its own scope and schedule. Publish an integration event after commit, or call the actor directly after the transaction. The generated relay composes inbox deduplication before mailbox enqueue. If the actor call fails, outbox delivery retries; successful prior delivery remains deduped. Inside the actor, call sibling methods on `this`—calling the same actor through its facade re-enqueues and deadlocks a non-reentrant activation. Use a hand-written relay when one event fans out to several actors or key derivation is non-trivial. ## Ordered facade streams [#ordered-facade-streams] An actor method returning `IAsyncEnumerable` becomes an Orleans-shaped facade stream. The mailbox is the sequencer; attach is a turn, but enumeration runs off-mailbox: ```csharp private readonly StreamHub _quotes = new(new() { ReplayCapacity = 256 }); public IAsyncEnumerable> Watch(long? resumeAfter) => _quotes.SubscribeSequenced(new StreamSubscribeOptions { ResumeAfterSequence = resumeAfter }); ``` `ELACT012` enforces two rules: the actor stream method has no `CancellationToken` parameter (the facade adds the consumer token), and it cannot also be an event consumer. A live enumeration retains the activation against idle passivation. Correctness passivation—snapshot conflict and shutdown—still wins, so complete or fail every hub in `OnDeactivateAsync`; otherwise a consumer can wait forever on an abandoned channel. Reactivation creates a new hub and sequence epoch. See [ordered streams](/docs/capabilities/events/streams) for resume semantics and the SSE adapter. Use streams when a lost item makes the consumer wrong and one sequencer exists. Use client events when a lost hint merely makes a view stale and re-query repairs it. ## Observability [#observability] Register the `Elarion.Actors` ActivitySource and Meter with OpenTelemetry. Each facade call emits a client-side `actor.call` span that parents an actor-side `actor.process` span. Actor name, method, and key are span attributes; the high-cardinality key is intentionally absent from metrics. | Metric | Meaning | | -------------------------- | ----------------------------------------------------------- | | `actor.message.count` | Outcomes: `ok`, `error`, `canceled`, `timeout`, `abandoned` | | `actor.message.duration` | Execution time, excluding queue wait | | `actor.message.queue_wait` | Time waiting for the mailbox | | `actor.mailbox.pending` | Enqueued or executing calls | | `actor.activations.active` | Current live activations | | `actor.activations.count` | Total activations and reactivation churn | | `actor.activations.failed` | Constructor or activation-hook failures | | `actor.snapshot.conflicts` | Snapshot conflicts; sustained values suggest double-hosting | Durations are seconds. Exceptions are not wrapped, and activations are not silently restarted, so there are no dead-letter or restart metrics. # Actor runtime and facades (/docs/concepts/actors/runtime) ## Generated facades [#generated-facades] For `OrderFulfillmentActor`, the generator emits a public facade in the actor's namespace: ```csharp public interface IOrderFulfillment : IActorFacade { Task> Ship( ShipmentInfo info, CancellationToken cancellationToken = default); } ``` The rules are mechanical: * The name is the class name without a trailing `Actor`, prefixed with `I`; override it with `[Actor(Name = ...)]`. * `IActorContext` makes the actor keyed and the facade extends `IActorFacade`; without a key, it extends `IActorFacade` and is a process singleton. * Every public `Task`, `Task`, `ValueTask`, `ValueTask`, or `IAsyncEnumerable` method is mirrored. Lifecycle methods stay private to the runtime. * The facade appends an optional caller-side `CancellationToken` when the actor method has none. * Results pass through untouched and exceptions rethrow unwrapped with the actor-side stack trace. Use `Get(key)` for `string`, `Guid`, `long`, and `int` keys, or `GetByKey(key)` for another `notnull` key. Each activation owns a DI scope. ## Execution model [#execution-model] Actors are non-reentrant by default: one method runs start-to-finish before the next, and an `await` holds the mailbox. Every method body is therefore a critical section. A facade call has a 30-second default timeout so an A→B→A call cycle fails visibly instead of hanging forever. Use `[Reentrant]` only when turns must interleave while a call awaits I/O: ```csharp [Actor] [Reentrant] public sealed class DeviceSessionActor { /* ... */ } ``` Turns still never execute concurrently, but state can change across an `await`. Do not use `ConfigureAwait(false)` in actor code that touches actor state; `ELACT006` flags it. Prefer events or short, acyclic actor calls over relying on reentrancy to hide call cycles. ## Mailbox, cancellation, and lifecycle [#mailbox-cancellation-and-lifecycle] Mailboxes are unbounded by default. A positive `MailboxCapacity` bounds work per activation: * `ActorMailboxFullMode.Wait` applies asynchronous backpressure. * `ActorMailboxFullMode.Fail` throws `ActorMailboxFullException` for deliberate load shedding. There are no drop modes because every message is request/reply. Cancellation removes a queued call or flows into the running method, linked with the call timeout and `IActorContext.Stopping`. Implement `IActorLifecycle` when activation needs setup or teardown. `OnActivateAsync` runs before the first turn; `OnDeactivateAsync` runs after the mailbox drains on passivation or shutdown. Passivation drops ordinary fields, so durable state belongs in [`IActorState`](/docs/concepts/actors/state-and-placement). ## Configuration [#configuration] | Option | Default | Use it when | | -------------------- | ------------------- | ----------------------------------------------------------------------------------------- | | `Name` | Derived facade name | Class and public actor identity should differ | | `KeyType` | Inferred | The actor is keyed but does not need `IActorContext` | | `MailboxCapacity` | Unbounded | A hot key can grow an unsafe backlog | | `MailboxFullMode` | `Wait` | Fast failure is better than queued work | | `IdleTimeoutSeconds` | 300 s | Reload cost or memory pressure justifies another lifetime; `-1` disables idle passivation | | `CallTimeoutSeconds` | 30 s | A legitimate call needs another deadline; `-1` disables the backstop | Keep defaults unless the matching pressure is measured. In particular, disabling the call timeout can turn an actor cycle into a permanent hang. ## Wiring and boundaries [#wiring-and-boundaries] Reference `Elarion.Actors` and the generator-bearing `Elarion` package, then opt the assembly in: ```csharp [assembly: GenerateActors] // or [assembly: UseElarion] ``` With `[GenerateModuleBootstrapper]`, actors register through generated `Add{Module}Actors` hooks inside their module feature gate. Otherwise call that method yourself. Actors outside a module warn with `ELACT003` and are not registered. Actors are module-internal implementation machinery. They have no handler decorator pipeline, so the transport-facing handler remains the validation, authorization, feature-gate, transaction, and audit boundary. Share a facade across modules only through a `[ModuleContract]`. ## Worker pools without routers [#worker-pools-without-routers] Actor keys are the routing function. Common router patterns become ordinary key selection: ```csharp // Identity affinity: all work for one device is serialized. var twin = actors.Get(deviceId); // Partition-affine pool: bounded parallelism while preserving per-entity ordering. const int poolSize = 8; var worker = actors.Get( (int)((uint)entityId.GetHashCode() % poolSize)); ``` Prefer partition affinity to round-robin. If ordering or per-worker state does not matter, use a handler or service with `Task.WhenAll`/`Parallel.ForEachAsync`; stateless parallelism does not need an actor. # Actor state and placement (/docs/concepts/actors/state-and-placement) ## Durable state with snapshots [#durable-state-with-snapshots] Declaring `IActorState` loads one snapshot before the first turn and exposes an explicit durable commit point: ```csharp public sealed record FulfillmentState { public required string Stage { get; init; } public int Attempts { get; init; } public bool IsStuck => Attempts >= 3 && Stage != "shipped"; public FulfillmentState Shipped() => this with { Stage = "shipped" }; } [Actor] public sealed class OrderFulfillmentActor(IActorState state) { public async Task Ship(CancellationToken ct) { state.State = (state.State ?? new() { Stage = "new" }).Shipped(); await state.WriteStateAsync(ct); // publication and durability point // Non-repeatable side effects belong after the successful write. } } ``` The surface mirrors Orleans `IPersistentState`: `State`, `RecordExists`, `Etag`, `ReadStateAsync`, `WriteStateAsync`, and `ClearStateAsync`. Passivation never writes implicitly. `TState` must participate in Elarion's canonical source-generated JSON options. The PostgreSQL provider stores canonical JSON in `elarion_actor_snapshots.payload` (`jsonb`) and a monotonic version as the ETag: ```csharp [GenerateDbSets] [GenerateElarionActorSnapshots] public partial class AppDbContext(DbContextOptions options) : DbContext(options); services.AddElarionPostgreSqlActorSnapshots(); ``` ## The state record is the query contract [#the-state-record-is-the-query-contract] Snapshot state is published state, not a private serialization detail: 1. Put constants, derived interpretation, and pure transitions on `TState`, not in actor methods. 2. Make actor turns apply a transition, write it, then perform side effects. 3. Treat `WriteStateAsync` as publication: before it, readers cannot see the mutation and a crash loses it. 4. Send commands through the facade; read published state with `IActorStateReader` from any instance. 5. Evolve records shape-tolerantly with optional/defaulted properties. Activation-time migration only fixes the home's view and leaves readers and SQL behind. Write cadence defines query meaning: * **Write-through:** the reader is database-fresh after each completed turn and is a first-class query path. * **Checkpointing:** the reader is bounded-stale and exists for warm restart, not a live UI. * **No snapshot:** state is intentionally ephemeral and has no pull-based read path. Observe hot in-memory state by pushing [client events](/docs/capabilities/events/client-events), not by polling a checkpoint. If services on arbitrary nodes need live pull access to another node's actor memory, the application has crossed the placement boundary and should use Orleans. ## Conflict recovery [#conflict-recovery] Every write is ETag-guarded. On a conflict, the runtime passivates the stale activation and transparently re-runs the turn once against a fresh snapshot. A second consecutive conflict surfaces as `ActorSnapshotConcurrencyException` and every conflict increments `actor.snapshot.conflicts`. No call starts on the stale activation after its conflict: calls queued behind the conflicted turn, and the next call of a caller that saw the exception, run on the fresh activation, so none of them reads the failed write's state. The retried turn executes twice. Express mutation as a pure transition from loaded state, and put side effects after the successful write or make them idempotent. Snapshot writes are separate commits; state that must be atomic with business entities belongs in the handler transaction instead. ## Multiple instances and single-homing [#multiple-instances-and-single-homing] Without placement, `Get(key)` activates locally. Multiple instances can therefore host the same key; snapshots prevent lost writes but do not make turns globally sequential. Choose deliberately: 1. **Per-instance:** caches, rate windows, and buffers intentionally live independently on each node. 2. **Single-homed:** `[Actor(Placement = ActorPlacementMode.SingleHome)]` makes one leased instance authoritative. 3. **Virtual-sharded:** `[Actor(Placement = ActorPlacementMode.VirtualShards)]` assigns each keyed actor to one of a fixed set of role-lease partitions. 4. **Optimistic multi-writer:** low-contention keys use conflict retry; side effects remain retry-safe. The recommended authoritative shape uses the PostgreSQL-backed `"actors"` role lease: ```csharp [GenerateDbSets] [GenerateElarionActorSnapshots] [GenerateElarionRoleLeases] public partial class AppDbContext(DbContextOptions options) : DbContext(options); services.AddElarionPostgreSqlActorHome(); services.AddElarionOutbox(); ``` Facade calls on a non-home instance fail with `ActorNotHomedException`; they are never silently forwarded. Each generated actor-consumer target group records the `"actors"` target role, so only the holder can claim it. HTTP/SSE routes that must execute on the home can use the [role-holder proxy](/docs/capabilities/coordination). During failover, deliveries wait until a home exists. ## Fixed virtual-shard placement [#fixed-virtual-shard-placement] Virtual shards provide a deliberately simple spread for keyed actors without requiring the process count up front or introducing activation rebalancing. Register the same role set on every process: ```csharp [Actor(Placement = ActorPlacementMode.VirtualShards)] public sealed class OrderActor(IActorContext context) { /* ... */ } services.AddElarionPostgreSqlActorSharding(); // 16 shards by default ``` The PostgreSQL recipe creates `actors:partition-0` through `actors:partition-15` as ordinary role leases. A process may own multiple shards, and a new process can acquire unowned shards after failover. The shard is selected by a stable hash of the actor name and canonical key text; the process count is irrelevant. There is no rebalancing, activation draining, or transparent actor-call forwarding. Generated `[ConsumeEvent]` relays resolve the event's actor key and persist their partition role on that consumer's outbox delivery. HTTP can use `UseElarionPartitionHolderProxy` with the same affinity key. If calls must be transparently routed to arbitrary actor homes, keys need partitioned placement, or the deployment exceeds roughly ten nodes, replace this runtime with Orleans, Akka.NET, or Proto.Actor rather than extending Elarion's default. # Audit trail (/docs/concepts/auditing) Auditing in Elarion answers the question every application eventually gets asked: **who did what?** You annotate a handler with `[Auditable]` and it records one structured `AuditRecord` per invocation — actor, action, resource, outcome, timestamp, correlation. **That is the whole feature, and it needs nothing on your entities.** A successful command's record commits **atomically with the handler's business writes**; denied and failed attempts are recorded on a detached path that survives the rollback. Under every transport identically. Automatic **field-level change capture** (`Street: "Old" → "New"` in the record) is a *separate, optional* layer you turn on per entity — it is not required for auditing to work. It is the same declarative shape as [authorization](/docs/concepts/authorization) and [idempotency](/docs/concepts/idempotency): a class-level attribute, generated decorators, a seam-in-Abstractions / impl-in-package split ([ADR-0045](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0045-handler-action-audit-trail.md)). ## The three axes [#the-three-axes] Auditing has three **independent** switches — turn on only what a handler needs. None depends on the others: you can capture field changes without naming a resource, name a resource without capturing changes, or record nothing but the bare who/what/outcome. | Axis | Question it answers | Turn on with | | ---------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | **The record** | *who did which action, with what outcome?* | `[Auditable]` on the handler (or assembly-wide `[ElarionAuditDefaults]`) — **always**, nothing on your entities | | **The resource** | *which thing was the action about?* (the indexed "browse by resource" view) | `[Auditable(Resource = "properties")]` (type only) and/or `IAuditScope.SetResource("properties", id)` (type + id) | | **The changes** | *which fields changed, old → new?* | `[Audited]` on the entity (automatic), or `IAuditScope.AddChange(…)` (manual) | ### The resource: type vs. id [#the-resource-type-vs-id] This is the part that trips people up. The record has **two** resource columns, filled from **two** places — and `Resource` on the attribute only fills the first: | Column | Filled by | Example | | -------------- | -------------------------------------------------------------------- | -------------- | | `ResourceType` | `[Auditable(Resource = "properties")]` **or** `SetResource(type, …)` | `"properties"` | | `ResourceId` | **only** `SetResource(type, id)` | `"42"` | * `[Auditable(Resource = "properties")]` **alone** → *"someone updated **a** property"* — a resource *type* label with zero handler code and no `IAuditScope`, so the log is filterable as "all property actions" but the record isn't tied to a specific row. * `audit.SetResource("properties", "42")` → *"…property **#42**"* — type **and** id, so it appears on that one property's history. `SetResource`'s type argument wins, so **don't repeat `Resource` on the attribute when you call `SetResource`** — the attribute's `Resource` is purely the fallback type for handlers that *don't* call it. **What do you put for the type?** Use the **same resource string your handler already declares in `[RequirePermission(resource, …)]`** — so *who may act on `properties`* and *who did* speak one vocabulary. Elarion permissions follow K8s-RBAC, so it is the plural resource name (`clients`, `invoices`, `properties`), and the audit type should match it exactly. Keep it **stable** (it is a search key over historical records) and **identical across every handler** that touches that resource, and use the **aggregate** the record is about — even when the write touched child rows (editing an invoice's line item is `resourceType: "invoices"`, with the line item showing up in `Changes`), not the C# class or table name. ## Usage [#usage] The minimum is one attribute — the record writes itself, no `IAuditScope`, nothing on your entities. `Resource` tags it with a resource *type*: ```csharp [Auditable(Resource = "properties")] // same word as the handler's [RequirePermission("properties", …)] public sealed class UpdatePropertyHandler(AppDbContext db) : IHandler> { public async ValueTask> HandleAsync(UpdatePropertyCommand request, CancellationToken ct) { var property = await db.Properties.SingleAsync(p => p.Id == request.Id, ct); property.Street = request.Street; return Result.Success(new() { Id = property.Id }); } } ``` That records *"user X performed `properties.update` on a property, succeeded, at T"* — searchable by action and by resource type, but not tied to a specific row. To pin **which** property *and* capture the changed fields, inject `IAuditScope`, call `SetResource` with the id, and mark the entity `[Audited]` — note the resource type is the same `"properties"` the handler already uses for authorization: ```csharp [RequirePermission("properties", Verbs.Write)] // who may act on properties [Auditable] // no Resource — SetResource below supplies the type (and id) public sealed class UpdatePropertyHandler(AppDbContext db, IAuditScope audit) : IHandler> { public async ValueTask> HandleAsync(UpdatePropertyCommand request, CancellationToken ct) { var property = await db.Properties.SingleAsync(p => p.Id == request.Id, ct); property.Street = request.Street; // captured old → new automatically ([Audited] on Property) audit.SetResource("properties", property.Id.ToString()); // ResourceType + ResourceId (optionally a parent) return Result.Success(new() { Id = property.Id }); } } ``` ## When to use what [#when-to-use-what] * **Just `[Auditable]`** — you need who/action/outcome and nothing more (e.g. *"someone exported the report"*). * **`[Auditable(Resource = "x")]`** — add a resource *type* so the log filters as "all x actions", when you don't have (or don't need) a specific id, or don't want to inject `IAuditScope`. * **`[Auditable]` + `SetResource("x", id)`** — you want *"everything done to **this** x"* on x's own history screen. Add a parent — `SetResource("equipment", id, parentType: "properties", parentId: propertyId)` — to also surface the record on the parent aggregate's audit tab. * **`[Audited]` on the entity** — you want the before/after field values, and the write goes through the EF change tracker. **Independent of the resource axis** — diffs are captured whether or not you named a resource. * **`audit.AddChange(…)`** — the write bypasses the change tracker (`ExecuteUpdate`/`ExecuteDelete`/raw SQL), so auto-capture can't see it; the handler records the change explicitly. Wire the durable sink over your `DbContext`, and let the generator map the table: ```csharp // Host services.AddElarionAuditingEntityFrameworkCore(); // Data layer — the generator emits the DbSet and table mapping (ELAUD001 without [GenerateDbSets]) [GenerateDbSets] [GenerateElarionAuditing] public sealed partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } ``` Attachment is **soft**: without a registered `IAuditTrail` the decorators never attach and the pipeline is unchanged, so a module using `[Auditable]` runs fine in a host without auditing. To flip a whole assembly to audited-by-default, opt in once — every **command** handler in scope is audited unless it opts out; queries stay explicit-only (read auditing is a deliberate, per-handler decision): ```csharp [assembly: ElarionAuditDefaults] [Auditable(Enabled = false)] // the per-handler opt-out under defaults public sealed class ImportLegacyDataHandler : IHandler<…> { … } ``` ## What a record contains [#what-a-record-contains] One append-only row per audited invocation, with the searchable facts as structured, indexed columns: | Field | Content | | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Action` / `Module` | The handler's wire name (`properties.update`) — resolved at compile time exactly like the RPC schema name, so audit records and the exported schema agree. | | `UserId` | The actor from `ICurrentUser` (`null` for anonymous/system callers). | | `ResourceType` / `ResourceId` | What was acted on, from `IAuditScope.SetResource` (falling back to `[Auditable(Resource = …)]`). | | `ParentResourceType` / `ParentResourceId` | Optional aggregate reference — "fire extinguisher X **on property Y**" — so the record surfaces on the parent's audit view without joining domain tables. | | `Outcome` / `ErrorKind` | `Succeeded`, `Failed`, or `Denied` (unauthorized/forbidden), plus the error kind. | | `CorrelationId` | The current trace id, linking the record to its span. | | `Changes` | Field-level `{entity, entityId, property, oldValue, newValue, kind}` diffs (JSON). Empty unless the entity is `[Audited]` or the handler adds them — the [optional layer below](#automatic-change-capture-optional). | | `Details` | App-supplied string facts (display names, rule ids — keep values free of secrets). | The classic search — *"alle Änderungen an Feuerlöschern durch Max, letzte Woche"* — is a plain indexed `WHERE` over those columns plus [keyset pagination](/docs/capabilities/pagination); querying and display stay app-owned (the framework never renders audit UI). ## Automatic change capture (optional) [#automatic-change-capture-optional] Everything above works without this section. This layer only **populates the `Changes` column** — turn it on where a record needs "which fields changed," leave it off everywhere else. Opt an entity in with `[Audited]`, exclude sensitive columns with `[AuditIgnore]`: ```csharp [Audited] public sealed class Property { public required Guid Id { get; init; } public required string Street { get; set; } [AuditIgnore] // never captured, even when it changes public string? InternalNote { get; set; } } ``` While an audited handler runs, a `SaveChangesInterceptor` invokes the registered `IAuditChangeContributor`s at **every flush** — the only point where EF still holds original values (a mid-handler `SaveChangesAsync` resets them, so a single "read the change tracker before commit" would be lossy. The sink also flushes pending writes before materializing the record, so the common "mutate and let the commit flush persist" handler still gets its diffs). The default contributor diffs `[Audited]` entities: modified properties as old → new pairs, creations and deletions as entity-level facts. Capture is **opt-in per entity** on purpose: auto-capturing every column is how password hashes end up in audit logs, and opt-in keeps framework tables (outbox, idempotency, the audit log itself) out of capture. Contributors are **additive** (`IEnumerable<>` multi-registration, like `IHandlerContextEnricher`) — the composition levers are plain DI: ```csharp services.AddElarionAuditChangeContributor(); // add a specialist // …or remove the default IAuditChangeContributor descriptor for action-records-only auditing. ``` **The known hole:** `ExecuteUpdate`/`ExecuteDelete`/raw SQL bypass the change tracker, so the interceptor never sees them. The handler covers those paths itself — same scope, same record: ```csharp var moved = await db.Properties.Where(p => p.PortfolioId == source) .ExecuteUpdateAsync(s => s.SetProperty(p => p.PortfolioId, target), ct); audit.AddChange(new AuditChange { Entity = "Property", Property = "PortfolioId", OldValue = source.ToString(), NewValue = target.ToString(), Kind = AuditChangeKind.Modified, }); audit.AddDetail("affectedRows", moved.ToString()); ``` ## Outcome semantics [#outcome-semantics] The transaction makes the outcome paths physically asymmetric, so two thin decorators cooperate: * **Success** — recorded *inside* the unit of work: the row commits atomically with the business writes. A record can never claim an action that rolled back, and a committed action can never lose its record. "Recorded" means **durably committed**: an enlisted success record only counts once its transaction commits (the EF sink promotes it from a transaction interceptor at that moment). A commit-phase failure — connection drop, serialization conflict — therefore falls through to the detached failure path below instead of leaving no trace, while a failure *after* a successful commit (say, a cache-invalidation hiccup) never fabricates a spurious failure record for an action that durably succeeded. * **Failure / denial** — recorded *detached* (own scope and connection): the caller's transaction is gone or rolling back, and the record must survive it. Denials (`Unauthorized`/`Forbidden`) are observed outside the authorization gate, so rejected attempts are audited too. Failure records carry the changes from flushes that actually happened — attempted, not applied; the `Outcome` says which. * **Idempotent replay** — deliberately records nothing: the action executed once, the trail says so once. * **Cancellation** — cooperative cancellation is not an auditable outcome. ## Retention [#retention] **Off by default** — an audit trail that silently deletes itself is a compliance bug. Opt in deliberately: ```csharp services.AddElarionAuditingEntityFrameworkCore(o => { o.RetainFor = TimeSpan.FromDays(365 * 2); }); ``` A hosted worker then purges older rows on an indexed probe (idempotent; safe on every node). ## Scale and non-goals [#scale-and-non-goals] The append-only one-Postgres table serves the framework's 1–10-node tier. Past that — or for SIEM shipping, tamper-evidence chains, long-term archival — replace the `IAuditTrail` registration; the attributes, scope, and capture seams are unchanged. Full temporal entity history (point-in-time reconstruction, undo) is a non-goal: the trail records *actions with their diffs*, not versioned state. It is also **not an application activity log.** The audit trail is a compliance record — framework-owned, write-once, read by operators. When *the app itself* needs to show users a queryable history (a "recent activity" feed on a screen), that is ordinary **domain data your module owns and reads back** — a different concern that only looks similar. Use the audit trail for compliance; model an activity log as domain data (recorded and queried through your own handlers, published cross-module via a `[ModuleContract]` if another module records into it) when the history is a product feature. # Authorization (/docs/concepts/authorization) Authorization in Elarion is **declarative and transport-neutral**. You annotate a handler with what it requires; a generated decorator enforces it before the handler runs, under every transport (JSON-RPC, MCP, HTTP) identically. It depends only on the claims of the current user — never on the authentication provider or an `HttpContext` — so ASP.NET Core Identity, Entra ID, or any OIDC/JWT setup all work with the same attributes. ## Authentication vs authorization [#authentication-vs-authorization] * **Authentication** — *who you are.* The host's ASP.NET middleware validates a cookie, JWT, or OIDC token and produces a `ClaimsPrincipal`. This is the host's job; Elarion does not issue credentials, with two exceptions for devices and apps that cannot sign in through a browser: [device keys](/docs/capabilities/devices) and [app passwords](/docs/capabilities/app-passwords) for calendar apps and feeds. * **Authorization** — *what you may do.* Elarion's job, per handler. The request flow: ``` authentication middleware → ICurrentUser snapshot → handler pipeline └─ AuthorizationDecorator → IAuthorizer → handler ``` `UseElarionCurrentUser()` snapshots the authenticated principal's claims into the scoped [`ICurrentUser`](/docs/concepts/handlers); the generated authorization decorator reads the handler's requirements and asks an `IAuthorizer` to evaluate them against that snapshot. ## Declaring requirements [#declaring-requirements] Annotate the handler class: ```csharp [Handler("tenants.create")] [RequirePermission("tenants", Verbs.Write)] public sealed class CreateTenant(AppDbContext db) : IHandler> { /* ... */ } ``` | Attribute | Requires | | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `[RequireClaim(type, values…)]` | A claim of `type`. With values, at least one must match (**OR**); with none, the claim must merely be present. The general form. | | `[RequirePermission("x", Verbs.Read)]` | Sugar for `[RequireClaim(PermissionClaimType, "x.read")]` — the composed `{resource}.{verb}` claim over the configured permission claim type (default `"permission"`). The common case. | | `[RequirePermissionFor(nameof(Query.Kind), Verbs.Read)]` | The `{resource}.{verb}` permission of the resource a request member's enum value names, or one of `AnyOf` — see [permissions that depend on a request member](#permissions-that-depend-on-a-request-member). | | `[RequireRole("Admin")]` | Role membership (`ICurrentUser.IsInRole`). | | `[RequirePolicy("AtLeast21")]` | A named [`IAuthorizationPolicy`](#named-policies) — custom logic over the user and the request. | | `[AllowAnonymous]` | Nothing — the handler is public (see [secure-by-default](#secure-by-default)). | ### Combining requirements [#combining-requirements] * **Different attribute kinds combine with AND.** `[RequirePolicy("AtLeast21")]` + `[RequireRole("Admin")]` requires both. * **Multiple of the same kind combine with AND.** Two `[RequirePermission]` requires both permissions. * **OR lives inside a single `[RequireClaim]`'s value list.** `[RequireClaim("scope", "read", "write")]` passes if the user has either. A `[RequirePermissionFor]` names its alternatives in `AnyOf`. * **`[AllowAnonymous]` wins** over any `Require*`. ## Authenticated, forbidden, unauthorized [#authenticated-forbidden-unauthorized] A denied request short-circuits the pipeline with an `AppError` — the handler never runs, and neither does caching, validation, or a transaction: * An **unauthenticated** caller → `AppError.Unauthorized` → HTTP **401** / JSON-RPC `-32005`. * An **authenticated but not permitted** caller → `AppError.Forbidden` → HTTP **403** / JSON-RPC `-32003`. This mirrors ASP.NET's 401-vs-403 split, mapped centrally — see [Results & errors](/docs/concepts/results-and-errors). The default forbidden message is a generic `"Access denied."` — it deliberately does not name the unmet permission/role/policy, so a forbidden caller cannot probe the permission vocabulary (the same opacity the feature-gate 404 applies). The default authorizer logs the unmet requirement at debug level for operators; a host that wants the detail on the wire sets `AuthorizationOptions.ForbiddenMessageFormat` to a format containing `{0}` (e.g. `"Missing required permission: {0}"`). ### 401/403 before 400 [#401403-before-400] A caller who may not call an operation never learns its parameter requirements. When a transport that binds a wire payload itself (JSON-RPC, MCP tool calls, the generated HTTP endpoints) **fails to bind** the request, it first asks the handler's *admission gate* (`IHandlerGate`, registered by the generator for every handler with an authorization decorator) and answers with the authentication/authorization error — `-32005`/`401` for an unauthenticated caller, `-32003`/`403` for one missing a declared permission, role or claim — instead of `-32602`/`400`. An admitted caller still gets the payload error. The gate covers only what does not depend on the payload: the authentication gate and the declared `[RequirePermission]`, `[RequireRole]` and `[RequireClaim]`. Named policies, global rules and `[RequireResource]` receive the request and are evaluated by the decorator after binding, exactly as before. The gate is not an early exit in front of the pipeline: when the payload binds, the full pipeline runs, so denials stay audited and traced. gRPC and the stream endpoints take an application-mapped, already typed request, so there is no framework binding step to order. ## Opt-in by default [#opt-in-by-default] By default the authorization decorator is attached **only to handlers that carry a `Require*` or `[RequirePolicy]` attribute** — apps that don't use authorization pay nothing. Attachment is decided at compile time by the generator inspecting the handler, so an unguarded handler is genuinely unwrapped. ### Secure-by-default [#secure-by-default] To flip to deny-by-default, declare `[ElarionAuthorizationDefaults]` at assembly or `[AppModule]` scope (resolved most-specific-wins, like [`[DefaultPipeline]`](/docs/concepts/decorator-pipelines)): ```csharp [assembly: ElarionAuthorizationDefaults] // RequireAuthenticated = true ``` Now **every** in-scope handler requires an authenticated principal unless it carries `[AllowAnonymous]`. A handler with explicit `Require*` attributes keeps those; an unannotated one just requires authentication. Deny-by-default does **not** implicitly attach to **event-consumer handlers** (a handler whose request implements `IDomainEvent`/`IIntegrationEvent`). Consumers are dispatched on a delivery scope with no authenticated user, so an implicit authenticated-by-default gate would fail every consumer. An **explicit** `Require*` on a consumer is a deliberate app choice and still attaches; only the implicit default is skipped. Because `Require*`/`[AllowAnonymous]` are `Inherited = true`, a requirement declared on a **base** handler class also attaches the decorator to a derived handler (mirroring the runtime `HandlerMetadata` `GetCustomAttributes(inherit: true)` path), and an `[AllowAnonymous]` on the derived handler wins over an inherited base requirement. ## The authorizer seam [#the-authorizer-seam] `IAuthorizer` is the single decision point. The default `ClaimsAuthorizer` (registered by `AddElarionAuthorization()`) evaluates every requirement against `ICurrentUser` and the registered policies — no `HttpContext`, no ASP.NET dependency: ```csharp public interface IAuthorizer { // null => authorized; AppError.Unauthorized/Forbidden otherwise. ValueTask AuthorizeAsync(AuthorizationRequirements requirements, object? resource, CancellationToken ct); // The payload-independent part (authentication, permissions, roles, claims), used by the admission gate. ValueTask AuthorizeGateAsync(AuthorizationRequirements requirements, CancellationToken ct); } ``` The `resource` is the **handler request** — a typed domain object, which is what named policies authorize against (no digging route values out of an `HttpContext`). ### Named policies [#named-policies] A named policy is a transport-neutral `IAuthorizationPolicy`. Mark it with `[AuthorizationPolicy("name")]` and it is **auto-registered per module** (like `[Service]`) — no manual wiring, and the name is the compile-time metadata `[RequirePolicy("name")]` references: ```csharp [AuthorizationPolicy("AtLeast21")] public sealed class AtLeast21Policy(TimeProvider clock) : IAuthorizationPolicy { public ValueTask EvaluateAsync(AuthorizationContext context, CancellationToken ct) { var birthDate = context.User.GetClaimValues("birthdate").FirstOrDefault(); // compute age against clock.GetUtcNow() ... return ValueTask.FromResult(/* age >= 21 */); } } ``` The name lives on the attribute (or the registration call), never on the implementation — one source of truth. A policy under an `[AppModule]` namespace is registered by that module's `ConfigureDefaultServices`; the generator reports `ELPOL001` if `[AuthorizationPolicy]` is on a type that isn't an `IAuthorizationPolicy`, and `ELPOL002` if a policy isn't under any module. For policies you'd rather wire by hand (or inline), register manually: ```csharp services.AddElarionAuthorization(); services.AddElarionAuthorizationPolicy(); // reads the [AuthorizationPolicy] name services.AddElarionAuthorizationPolicy("AtLeast21", (ctx, ct) => ...); // inline delegate ``` ### Global rules — one condition across every handler [#global-rules--one-condition-across-every-handler] A named policy answers "does *this* handler's declared requirement hold". Some conditions are not per-handler at all: a suspended tenant, a lapsed subscription, a read-only maintenance window. Register an `IGlobalAuthorizationRule` and it runs for **every** authorized invocation — after the authenticated gate, before the declared permission/role/claim/policy/resource checks: ```csharp public sealed class ActiveSubscriptionRule(ITenantContext tenant, ITenantDirectory directory) : IGlobalAuthorizationRule { public async ValueTask EvaluateAsync(AuthorizationContext context, CancellationToken ct) { // ITenantDirectory is app-owned; ITenantContext only carries the ambient TenantId. var suspended = tenant.TenantId is { } id && await directory.IsSuspendedAsync(id, ct); return suspended ? AppError.Forbidden("This workspace is suspended.") : null; // null => pass } } builder.Services.AddElarionGlobalAuthorizationRule(); ``` Rules are additive and run in **registration order**; the first non-null `AppError` wins and reaches the caller **unchanged**, so the rule — not the framework — chooses the outcome kind. A rule that must not disclose a resource returns `AppError.NotFound(...)`; one that states the denial plainly returns `AppError.Forbidden(...)`. The `AuthorizationContext` carries the current user and the handler request, so a rule can scope itself to a request shape (e.g. only writes) without touching the handler. On the **client-event subscription** path there is no request, so `context.Resource` is `null` — a rule that branches on the request shape will fall through to its denial there, which is fail-closed but may not be what you meant. Handle `null` explicitly if a rule should treat subscribes differently from commands. `context.HandlerType` names the concrete handler being authorized (independent of decorator order, also `null` on the subscription path), so a rule keys off the handler's **own markers** instead of a second registry of handler types. A rule that requires every write to declare whether it is allowed in some session mode, and refuses an undeclared one (among the commands the authorization decorator sees — see the note on where it is attached below): ```csharp public sealed class ViewAsRule(IViewAsSession session) : IGlobalAuthorizationRule { public ValueTask EvaluateAsync(AuthorizationContext context, CancellationToken ct) { if (!session.IsActive || context.Resource is not ICommand) return ValueTask.FromResult(null); // GetHandlerAttribute reads HandlerType's attributes, inherited ones included. return ValueTask.FromResult(context.GetHandlerAttribute() is null ? AppError.Forbidden("Not available while viewing as another user.") : null); } } ``` Named policies receive the same `HandlerType`. A rule only runs **where the authorization decorator is attached**, and the generator attaches it at compile time only for handlers carrying a `Require*` attribute or in scope of `[ElarionAuthorizationDefaults]`. For broad coverage, pair the rule with the assembly-level default: ```csharp [assembly: ElarionAuthorizationDefaults] // RequireAuthenticated = true ``` That reaches every handler **except event-consumer handlers**, which the deny-by-default section above exempts from *implicit* attachment (they run on a delivery scope with no authenticated user). A consumer carrying an **explicit** `Require*` still gets the decorator — and is then rejected as unauthenticated on that scope, before any rule is consulted. Rules always run **behind the authentication gate**: a handler that declares any requirement rejects an unauthenticated caller with `Unauthorized` before rules are reached, so a rule never has to defend against a missing principal. `[AllowAnonymous]` handlers opt out of authorization entirely, global rules included — that attribute means "this operation is outside authorization", and a rule must not resurrect a gate the handler declined. A check that must also cover anonymous traffic belongs in an application decorator ([below](#a-rule-that-sees-the-outcome-or-anonymous-handlers-too-a-decorator)), the handler or host middleware. Client-event **subscriptions** are covered: any topic declaring a requirement is decided by the same `IAuthorizer`, so a rule that denies a request also denies the corresponding subscribe. ### A rule that sees the outcome, or anonymous handlers too: a decorator [#a-rule-that-sees-the-outcome-or-anonymous-handlers-too-a-decorator] A global rule decides *before* the declared requirements are checked and never runs for an `[AllowAnonymous]` handler. A condition that has to come **after** them (a refusal that must not hide the permission denial the caller would otherwise get), cover **anonymous** operations as well, or **observe the outcome** (an audit record of what was done, including a failure or a throw) is an application decorator in your `[DecoratorList]`. That position already has all three properties — there is no separate seam for it: * it runs **after** authorization, the feature gate and validation (the [decorator order](/docs/concepts/decorator-pipelines#order-matters)), so a caller who may not call the handler gets the declared denial, never your refusal; * it runs for **every** handler in the pipeline's scope, `[AllowAnonymous]` ones included; * it wraps the call, so it sees the result and any exception, and, listed outside your transaction decorator, it sees whether the transaction committed. Read the handler's markers from the `HandlerMetadata` constructor parameter, never from `inner.GetType()`: ```csharp public sealed class ViewAsDecorator( IHandler inner, HandlerMetadata handler, IViewAsSession session, IViewAsAudit audit) : IHandler where TResponse : IResultFailureFactory, IResultLike { public async ValueTask HandleAsync(TRequest request, CancellationToken ct) { if (!session.IsActive || request is not ICommand) return await inner.HandleAsync(request, ct); if (handler.GetAttribute() is null) return TResponse.Failure(AppError.Forbidden("Not available while viewing as another user.", "view_as.refused")); try { var response = await inner.HandleAsync(request, ct); await audit.RecordAsync(handler.HandlerType, succeeded: response.IsSuccess, ct); return response; } catch { await audit.RecordAsync(handler.HandlerType, succeeded: false, CancellationToken.None); throw; } } } ``` Declare the code it adds once on the decorator with `[ProducesError]` ([Declaring the errors a decorator adds](/docs/concepts/decorator-pipelines#declaring-the-errors-a-decorator-adds)). Reach for a global rule when the condition is a plain decision that may run first; reach for a decorator when it must come after the declared requirements, include anonymous handlers or see the outcome. ### Replacing or decorating the authorizer [#replacing-or-decorating-the-authorizer] Every registration in `AddElarionAuthorization()` uses `TryAdd`, and the concrete `ClaimsAuthorizer` is registered as its own service with the `IAuthorizer` registration resolving it. That pins two seams: * **Replace** — register your own `IAuthorizer` **before** calling `AddElarionAuthorization()`; the framework then adds nothing for that service. * **Decorate** — do the same, and inject the concrete `ClaimsAuthorizer` as your inner authorizer. Both resolve to the same scoped instance, so there is no second authorizer and no `RemoveAll` gymnastics: ```csharp public sealed class AuditingAuthorizer(ClaimsAuthorizer inner, IAuditSink sink) : IAuthorizer { public async ValueTask AuthorizeAsync( AuthorizationRequirements requirements, object? resource, CancellationToken ct) { var error = await inner.AuthorizeAsync(requirements, resource, ct); if (error is not null) await sink.RecordDenialAsync(error, ct); return error; } public ValueTask AuthorizeGateAsync(AuthorizationRequirements requirements, CancellationToken ct) { return inner.AuthorizeGateAsync(requirements, ct); } } builder.Services.AddScoped(); // registered first — TryAdd defers to it builder.Services.AddElarionAuthorization(); // still registers ClaimsAuthorizer itself ``` Reach for a global rule when the condition is a *decision*; reach for decoration when you need to observe or reshape decisions the shipped authorizer already makes. Only `ClaimsAuthorizer` evaluates `IGlobalAuthorizationRule`. **Wholesale replacement** of `IAuthorizer` makes every registered rule inert unless the replacement consults them itself — decoration keeps them running, because the inner `ClaimsAuthorizer` still does the work. ## Provider neutrality [#provider-neutrality] Authorization depends only on `ICurrentUser`, so the same `[Require*]` handlers work under any authentication provider. Two setups, identical handlers: ### ASP.NET Core Identity [#aspnet-core-identity] The optional Identity packages wire Identity onto a **plain** `DbContext` (no `IdentityDbContext` inheritance) and map the current user to the Identity claim types — `[GenerateElarionIdentity]` (the web-free model, in `Elarion.EntityFrameworkCore.Identity`) on the context, `AddElarionIdentity` (the host wiring, in `Elarion.AspNetCore.Identity`) in `Program.cs`: ```csharp [GenerateDbSets] [GenerateElarionIdentity(SnakeCase = true)] public sealed partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } // Program.cs builder.Services.AddElarionIdentity(); builder.Services.AddDbContext(o => o.UseNpgsql(connectionString)); // cookie policy, AddAuthorization policies, UseAuthentication/UseElarionCurrentUser stay host-owned ``` The generator emits the Identity `DbSet`s (`db.Users`, `db.Roles`, …) and the snake\_case model, so the context never inherits `IdentityDbContext` — see the [Identity capability](/docs/capabilities/identity). ### Entra ID (no ASP.NET Identity) [#entra-id-no-aspnet-identity] Swap the authentication provider; the authorization is unchanged — and no Identity package: ```csharp builder.Services.AddAuthentication().AddMicrosoftIdentityWebApi(builder.Configuration); // or .AddJwtBearer builder.Services.AddElarionCurrentUser(o => { o.UserIdClaimType = "oid"; // Entra object id o.RoleClaimType = "roles"; // Entra app roles }); builder.Services.AddElarionAuthorization(); ``` The very same `[RequireRole("Admin")]` / `[RequirePolicy("AtLeast21")]` handlers are now enforced against Entra's token claims — and would behave identically over JSON-RPC or MCP. That independence is the point: authentication is a host concern, authorization is a handler concern, and they meet only at `ICurrentUser`. An app behind an authenticating reverse proxy (Cloudflare Access, Google IAP, oauth2-proxy) swaps in [proxy identity](/docs/capabilities/proxy-identity) the same way: `AddElarionProxyIdentity` validates the forwarded token and maps `ICurrentUser`, and the handlers stay unchanged. ## Permission catalog [#permission-catalog] A handler declares the permission it needs as a **(resource, verb)** pair — the Kubernetes-RBAC shape — `[RequirePermission("properties", Verbs.Read)]`, enforced as the composed claim `properties.read`. No central registry to edit. But the **set of all permissions** is still needed: to **seed** permission claims onto roles, and to drive role→permission policy. Hand-maintaining that `All`/`ReadOnly` list is the one file that grows per feature — the "edit-for-every-module" smell the generators otherwise eliminate. The generator removes it. It discovers every `[RequirePermission(resource, verb)]`/`[RequireRole]` and emits two surfaces, both keyed on the two Kubernetes axes — **resource** and **verb**. ### `ElarionPermissions` — compile-time [#elarionpermissions--compile-time] A static class in your assembly's **root namespace** (above every `[AppModule]`, so referencing it never trips the `ELMOD002` module-boundary analyzer), aggregated **cross-assembly** from the Elarion manifest. Reference it from static role policy, which then reads like Kubernetes role rules: ```csharp // Roles.cs — no All/ReadOnly list to maintain [Admin] = ElarionPermissions.All, [PropertyAdmin] = ElarionPermissions.ByResource["properties"], // every verb on properties [Viewer] = ElarionPermissions.ByVerb["read"], // read-only across everything ``` * `All` / `Roles` — the deduplicated, ordinally sorted universe. * `ByResource["properties"]` — Kubernetes "all verbs on a resource". * `ByVerb["read"]` — Kubernetes "this verb across all resources". * `ByModule["Properties"]` — the per-`[AppModule]` view. * typed accessors — `ElarionPermissions.Properties.Read` (resource → nested class, verb → const member). The verb vocabulary is **open** (Kubernetes allows custom verbs too): use the `Verbs` constants (`Read`/`Write`/`List`/`Create`/`Update`/`Delete`/`Manage`) or any string. The enforced claim is composed as `{resource}.{verb}`, so your identity provider issues `properties.read` claims. ### `IPermissionCatalog` — runtime [#ipermissioncatalog--runtime] For code that enumerates permissions dynamically (a permissions admin screen), inject the DI catalog: ```csharp public sealed class IdentitySeeder(IPermissionCatalog catalog, RoleManager roles) { public async Task SeedAdminAsync(AppRole admin) { foreach (var permission in catalog.Permissions) // every permission across all modules await roles.AddClaimAsync(admin, new Claim("permission", permission)); } } ``` It exposes the same `Permissions`/`Roles`/`ByResource`/`ByVerb`, plus a per-module `Modules` breakdown, populated the same way services and event consumers are — each module contributes through its generated `ConfigureDefaultServices`, **gated by module enablement**, so a disabled module's permissions never appear and a referenced module library's are included automatically. `AddElarionAuthorization` registers it. Generation is on under `[assembly: UseElarion]` (or the narrower `[assembly: GeneratePermissionCatalog]`); a guarded handler under no module is reported (`ELPERM001`). The attributes are read off any `class` or `record` (for example a client-event contract), not only handlers. ### Permissions no handler requires [#permissions-no-handler-requires] Some permissions are not the whole gate of any handler: a row-level rule reads them on top of a coarser requirement ("the author **or** a manager may delete a comment" — the handler requires `comments.write`, the rule also accepts `comments.manage`). Adding a second `[RequirePermission]` to the handler is wrong, because requirements AND together and would lock the author out. But the permission must still be in the catalog, or role policy derived from it never grants it and the rule is dead code. Declare it on the type that reads it: ```csharp [DeclarePermission("comments", Verbs.Manage)] // in the catalog, enforced nowhere public sealed record CommentAccess(ICurrentUser User, IPermissionChecker Permissions) { public bool CanDelete(Comment comment) => comment.AuthorId == User.UserId || Permissions.Holds(ElarionPermissions.Comments.Manage); } ``` `[DeclarePermission]` joins the owning module's catalog exactly like `[RequirePermission]` (same `ElarionPermissions` accessors, same `IPermissionCatalog` entries, cross-assembly through the manifest) and has no runtime effect. ## Permissions that depend on a request member [#permissions-that-depend-on-a-request-member] One operation sometimes serves several kinds of record, each with its own permission: a list of custom fields, notes or documents whose request names the record kind. The caller needs the read permission of the kind it asks for — `properties.read` for properties, `tenants.read` for tenants — or a permission that covers every kind. Declare it instead of checking inside the handler: the enum names the resource of each value, the handler names the member and the verb. ```csharp public enum RecordKind { [PermissionResource("properties")] Property, [PermissionResource("tenants")] Tenant } [Handler("customFields.list")] [RequirePermissionFor(nameof(Query.Kind), Verbs.Read, AnyOf = [ElarionPermissions.Settings.Read])] public sealed class ListCustomFields(AppDbContext db) : IHandler>> { public sealed record Query(RecordKind Kind) : IQuery; … } ``` A caller holding `tenants.read` may list the tenant fields; one holding only `properties.read` gets `Forbidden` for them; a `settings.read` holder may list every kind. An unauthenticated caller gets `Unauthorized`, as with every requirement. The decision is [`IPermissionChecker`](#checking-a-permission-in-code)'s, so a host's "administrators hold everything" applies here too. * **The member is referenced, never computed** (ADR-0012): `nameof(Query.Kind)`, or a dotted path to a nested member (`nameof(Query.Owner) + "." + nameof(Owner.Kind)`). The generator emits a typed accessor with a `switch` over the enum, so the check uses no reflection. * **Fail closed.** A null member, a null member on the way to it, or a value the enum does not declare is satisfied only by an `AnyOf` permission. * **It combines with AND**, like every requirement: `[RequirePermission("notes", Verbs.Read)]` next to it requires both, and so do two `[RequirePermissionFor]`. * **The verb belongs to the handler, the resource to the enum**, so one `RecordKind` serves `notes.list` (`Verbs.Read`) and `notes.create` (`Verbs.Write`). * **Build errors, not silent gaps:** a path that does not resolve is `ELAUTH007`, a member that is not an enum (or a nullable enum) `ELAUTH008`, an enum value without `[PermissionResource]` `ELAUTH009` — so a new kind cannot reach the handler without a decision about its permission — and an argument the generator cannot read `ELAUTH010`. `ElarionPermissions.Resource.Verb` in `AnyOf` is read even though another generator emits it. * **Streams too.** A stream handler with `[RequirePermissionFor]` is refused before the stream starts. The schema exports the requirement in the method's `requires` (`memberPermissions`, with the member and each value in their wire form), and `canCall` decides it from the call's params — see [method requirements](/docs/capabilities/transports/typescript-client#method-requirements-and-ui-gating). The mapped permissions join the catalog only through a handler that requires them; declare one no handler requires with [`[DeclarePermission]`](#permissions-no-handler-requires). A custom `IAuthorizer` evaluates the resolved requirements in `AuthorizationRequirements.MemberPermissions`, as it evaluates `Resources`; one that ignores them lets these handlers through. `ClaimsAuthorizer`, and every authorizer that wraps it, evaluates them after the declared permissions, roles and claims. `AuthorizeGateAsync` does not: they read the payload. ## Checking a permission in code [#checking-a-permission-in-code] Some decisions are not a gate: a handler every `banking.write` holder may run still shows the matched stored bookings only to `banking.read` holders, or a list adds a column for managers. Ask `IPermissionChecker` — a synchronous `bool`, the same decision the `[RequirePermission]` gate makes: ```csharp [Handler] [RequirePermission("banking", Verbs.Write)] public sealed class PreviewImport(IPermissionChecker permissions, AppDbContext db) : IHandler> { public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var withBookings = permissions.Holds(ElarionPermissions.Banking.Read); // permissions.Holds("banking", Verbs.Read), HoldsAny(…) and HoldsAll(…) compose the same strings … } } ``` Pass the generated `ElarionPermissions` accessors, not string literals: a renamed permission then fails the build instead of denying silently. `AddElarionAuthorization()` registers the default, `ClaimsPermissionChecker`: an authenticated caller holds a permission when it carries a claim of the configured `PermissionClaimType` with that value, exactly what the gate checks; an unauthenticated caller holds nothing. Do not read the claim yourself (`ICurrentUser.HasClaim("permission", …)`): that repeats the claim type and bypasses a host's replacement checker. ### One place for "administrators hold everything" [#one-place-for-administrators-hold-everything] `ClaimsAuthorizer` evaluates every `[RequirePermission]` through `IPermissionChecker`, and so do [`[VisibleWith]`](#members-only-some-callers-see) members and the [client snapshot](/docs/concepts/client-capabilities). A host whose administrators hold every permission says so once, in a checker registered before `AddElarionAuthorization()` (which uses `TryAdd`), instead of adding `IsInRole("admin")` next to each check: ```csharp public sealed class AdminHoldsEverything(ClaimsPermissionChecker claims, ICurrentUser user) : IPermissionChecker { public bool Holds(string permission) => user.IsInRole("admin") || claims.Holds(permission); } builder.Services.AddScoped(); builder.Services.AddElarionAuthorization(); // still registers ClaimsPermissionChecker for the inner check ``` The session snapshot lists the permission claims plus every catalog permission the checker grants, so the client's `permissions` stay what the gate answers. Generated SQL filters (`[ResourceFilter]`'s `BypassPermission`, `QueryAuthorizers.WhenPermission`) read the claims themselves; grant those permissions as claims (seed them onto the role) when a replacement checker should cover them too. ## Members only some callers see [#members-only-some-callers-see] A recurring shape: a caller may run a handler, but one member of its answer belongs to a narrower audience. A bank import preview runs for `banking.write` holders, but the stored booking a line resembles goes only to `banking.read` holders; a list shows an opening balance or payments only to those who may read them. Declare it on the member instead of nulling it in each handler: ```csharp public sealed record ImportPreviewLine { public required int Row { get; init; } public required decimal Amount { get; init; } [VisibleWith(ElarionPermissions.Banking.Read)] // or [VisibleWith("banking", Verbs.Read)] public StoredBooking? Resembles { get; init; } } public sealed record ImportPreview( IReadOnlyList Lines, [property: VisibleWith("banking", Verbs.Read)] decimal? OpeningBalance); ``` The handler fills every member for everybody. The generator finds the marked members through the handler's response type — nested records and structs, arrays, `List`, `ImmutableArray`, the read-only collection interfaces, `Nullable`, `Page` and `ElarionCreated` — and attaches a `VisibilityDecorator` just inside authorization. For a caller who does not hold every permission the response uses, the decorator answers a copy (made with `with` expressions it generates, no reflection) whose marked members are `null`, so the transport omits them; a caller who holds them all gets the handler's value unchanged. The decision is [`IPermissionChecker`](#checking-a-permission-in-code)'s, the one the gate uses; without a registered checker every marked member is hidden. A member several audiences may see names each of them with `AnyOf`; a caller holding any one sees it: ```csharp public sealed record BankAccountRow( string Name, [property: VisibleWith(AnyOf = [ ElarionPermissions.Settings.Read, ElarionPermissions.Settings.Write, ElarionPermissions.Banking.Read])] decimal? OpeningBalance); ``` Next to a constructor permission, `AnyOf` adds alternatives to it: `[VisibleWith("banking", Verbs.Write, AnyOf = [ElarionPermissions.Audit.Read])]`. Because the decorator sits outside caching, idempotency and the transaction, a cached or replayed answer is stored whole and hidden per caller, and an in-process call through the pipeline is hidden the same way. `rpc-schema.json` marks the member with `x-elarion-visible-with: "banking.read"` (an array for an `AnyOf` member), and the generated TypeScript documents it on the property (`/** Present only for callers holding the `banking.read` permission. */`), so a client knows why it may be missing; like every client-side projection that is a hint, not the authority. Rules the generator enforces, as build errors rather than a member silently disclosed: * A marked member must be nullable (`ELAUTH003`). * Every type on the way to a marked member must be a record or a struct whose rewritten members have an accessible `init` or `set`, and every collection on the way one of the shapes above (`ELAUTH004`); a `HashSet` or a dictionary holding marked members is reported, not passed through. * The handler must answer `Result` (`ELAUTH004`), and a singleton handler cannot use it (`ELSG013`), because the checker is per caller. * The generator must be able to read the permission (`ELAUTH005`): a string constant, `(resource, verb)`, or `ElarionPermissions.Resource.Verb`. The catalog of the handler's own assembly is emitted by another generator, which the handler generator cannot see, so it recognises that form by its shape and refers to the generated constant from its output; any other argument it cannot read is an error. A member declared as a base type follows the derived types its `[JsonDerivedType]` attributes declare — exactly the types System.Text.Json writes with their own members — and the copy dispatches on the runtime type, most-derived first. An interface without `[JsonDerivedType]` that reaches a marked member is a build error (`ELAUTH004`), since no copy of it can be made. A member declared as `object` is written by its runtime type and is not looked into; keep marked members out of `object`-typed values. The permission belongs in the catalog like any other — usually a handler requires it already; if none does, declare it with [`[DeclarePermission]`](#permissions-no-handler-requires). ### A member that also depends on the record [#a-member-that-also-depends-on-the-record] `[VisibleWith]` decides by permission only. It asks nothing about the record a member shows, so on its own it is enough exactly while every holder of the permission may see every record of that kind. When the kind has a row rule (a [resource filter](/docs/concepts/resource-authorization)), the two legs divide the work: the handler reads the linked record through the rule, and `[VisibleWith]` keeps the permission. ```csharp public sealed record Response( Guid Id, string Title, [property: VisibleWith(ElarionPermissions.Prospects.Read)] LinkedRecord? Prospect); // In the handler: a prospect the caller's row rule hides is not read, so the member is null. var prospect = await db.Prospects .WhereAuthorized(prospectAccess, currentUser) // IQueryAuthorizer .Where(p => p.Id == appointment.ProspectId) .Select(p => new LinkedRecord(p.Id, p.Name)) .FirstOrDefaultAsync(ct); ``` The row rule runs where the row is read, as one predicate in the query that loads it; a caller without the permission never sees the member, whatever the rule says. A row rule declared on the member instead would have to ask the database again for every marked member of every item, after the handler had already loaded what it must then hide. A handler whose answer is [cached](/docs/capabilities/caching) for every caller (a shared cache scope, not the default per-user one) must not read through one caller's row rule; keep such a member out of that answer. ## See also [#see-also] * [Resource authorization](/docs/concepts/resource-authorization) — per-resource (read/write) checks and efficient database-level filtering. * [Decorator pipelines](/docs/concepts/decorator-pipelines) — where the authorization decorator sits. * [Results & errors](/docs/concepts/results-and-errors) — how `Unauthorized`/`Forbidden` map per transport. * [Why Elarion → Composition over inheritance](/docs/why-elarion#composition-over-inheritance). # Client capabilities (/docs/concepts/client-capabilities) A frontend usually needs to hide or adapt UI based on **what the backend actually offers for the current user and deployment**: which modules are enabled, which feature flags/variants are on, and the user's roles and permissions. Elarion ships a single, framework-owned **client-capability bootstrap** that returns all of that in one snapshot, and a generated TypeScript client (plus an OpenFeature provider) that the frontend reads. The backend stays the source of truth — the client *reflects* it, it never re-evaluates flags or re-hosts provider config. This is a **read-only UX projection, not an enforcement boundary.** A hidden button is not a secured operation — the real gate is the handler's `[RequirePermission]`/`[FeatureGate]`, enforced server-side on every call. Use the snapshot to adapt the UI; never to authorize. ## The snapshot [#the-snapshot] The bootstrap returns one object for the current user and deployment: ```jsonc { "user": { "id": "u-123", "isAuthenticated": true, "roles": ["admin"], "permissions": ["billing.write"] }, "modules": { "Billing": true, "Experiments": false }, "flags": { "new-checkout": true }, "variants": { "ForecastAlgorithm": "neural" } } ``` It composes existing seams only — the generated `IsModuleEnabled`, [`IFeatureFlagService`](/docs/concepts/feature-flags), the declared feature-flag catalog, and [`ICurrentUser`](/docs/concepts/handlers) — so module enablement is deployment-scoped while flags, variants, and grants are per-user. See [ADR-0030](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0030-client-capability-bootstrap.md). ## Exposing flags — `ExposeToClient` [#exposing-flags--exposetoclient] A flag is exposed to the client by declaring it so: `ExposeToClient = true` on its `[FeatureFlag]` or `[BackendFeatureFlag]` declaration (see [feature flags](/docs/concepts/feature-flags)). Nothing reaches the wire unless its declaration says so, so exposure is leak-safe by construction: ```csharp [AppModule("Billing")] [BackendFeatureFlag("new-checkout", ExposeToClient = true)] [BackendFeatureFlag("dashboard-v2", ExposeToClient = true)] public static class BillingModule { } ``` The bootstrap evaluates **only the exposed flags of enabled modules** (a disabled module registers no flags), through the same `IFeatureFlagService` and one `FeatureEvaluationContext` the handler gates use, so the snapshot cannot disagree with a gate. A flag needs **no** server-side `[FeatureGate]`/`[FeatureVariant]` behind it — a pure UI flag is first-class. A flag whose owner allocates a variant also appears under `variants`. `GetClientCapabilityManifest()` is emitted for **every** host and carries only the module map (name and enabled state); the flags come from the runtime catalog. A host with no exposed flags gets module enablement plus the user's grants, with empty `flags`/`variants`. Using the session bootstrap purely for grants + module enablement is a fully supported case. ## Wiring the host [#wiring-the-host] The bootstrap handler is framework-shipped (you don't own its class), so it is exposed **imperatively** — see [exposing a handler you don't own](/docs/capabilities/transports/custom-transports#exposing-a-handler-you-do-not-own) and [ADR-0031](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0031-imperative-handler-transport-mapping.md). A host opts in and chooses surfaces: ```csharp // DI — registers the handler and the deployment manifest. builder.Services.AddElarionSession(builder.Configuration.GetClientCapabilityManifest()); // Named bus (JSON-RPC + MCP) — chain MapElarionSession into the same RegisterHandlers delegate, so the // shared dispatcher is still built once. var registerHandlers = (HandlerDispatcher dispatcher, IConfiguration configuration) => ElarionBootstrapper.RegisterHandlers(dispatcher, configuration).MapElarionSession(); builder.Services.AddElarionJsonRpc(registerHandlers); builder.Services.AddElarionMcp(configuration.GetMcpMetadata(), registerHandlers, configure); // REST — a concrete, framework-authored endpoint (AOT/trim-safe; see ADR-0031). app.MapElarionSession(); // GET /session ``` Nothing else is needed for Native AOT: `AddElarionSession` contributes the framework-owned `SessionJsonContext` to the canonical [`IElarionJsonSerialization`](/docs/capabilities/serialization) itself (ADR-0023), so the session's wire types serialize reflection-free on every transport — the same self-registration every other subsystem's `Add…` performs. ## On the client — one mechanism over OpenFeature [#on-the-client--one-mechanism-over-openfeature] When the schema exposes `elarion.session`, the TypeScript generator emits a self-contained `session-client.ts` alongside the RPC client: a typed `ClientSnapshot`, synchronous `SessionCapabilities` accessors, and an [OpenFeature web-SDK](https://openfeature.dev) provider. The provider is hydrated from one fetched snapshot and answers **every** key from the cache via reserved namespaces, so React only ever uses OpenFeature: | OpenFeature key | resolves from | | -------------------------- | ----------------------------------------- | | `module.Billing` | `modules["Billing"]` (deployment-scoped) | | `permission.billing.write` | `user.permissions.includes(...)` | | `role.admin` | `user.roles.includes(...)` | | `new-checkout` | `flags[...]` (the `ExposeToClient` flags) | | `ForecastAlgorithm` | `variants[...]` (string / `.variant`) | ```ts import { createElarionOpenFeatureProvider, Keys } from './generated/session-client' const snapshot = await rpc.elarion.session({}) // typed, via the generated RPC client OpenFeature.setProvider(createElarionOpenFeatureProvider(snapshot) as unknown as Provider) // then, anywhere — one API for modules, flags, variants, and grants: client.getBooleanValue(Keys.module('Billing'), false) client.getBooleanValue(Keys.permission('billing.write'), false) client.getStringValue('ForecastAlgorithm', 'control') ``` Teams that don't want OpenFeature can use `SessionCapabilities` (`isModuleEnabled`, `hasPermission`, `hasRole`, `isFlagEnabled`, `getVariant`, `getSection`) directly. ### Keeping the snapshot live [#keeping-the-snapshot-live] Capabilities change *during* a session — a login, a tenant switch, a subscription upgrade, an admin granting a role. `createSessionCapabilitiesStore` wraps the fetch in a **store**: the same synchronous reads, plus `refresh()` and `subscribe()`. Its identity is stable while its answers change, so it is placed once and every later read sees the current snapshot: ```ts import { createSessionCapabilitiesStore, type ClientSnapshot } from './generated/session-client' import { createContributionRegistryStore } from '@swimmesberger/elarion-contributions' export const capabilities = createSessionCapabilitiesStore( async () => (await rpc.elarion.session({})) as ClientSnapshot ) await capabilities.refresh() // boot // The router context holds the store itself — `redirectUnless` re-reads it on every navigation. const router = createRouter({ routeTree, context: { caps: capabilities } }) // Slots re-render when the snapshot changes; resolution still goes through the pure registry. const registry = createContributionRegistryStore(manifests, capabilities) // (React) | provideContributions(registry) (Angular) await capabilities.refresh() // after a mutation that changes what the user may see ``` Every read **before the first successful refresh fails closed** — modules, permissions, roles, and flags answer `false` — so gated UI stays hidden while the snapshot is in flight instead of flashing and retracting. A failed refresh rejects and leaves the previous answers in place. Contributor-fed sections ride along automatically, since they are part of the same snapshot. Applications without a session snapshot get the same reactivity from `createCapabilityStore(createStaticCapabilities(...))`, and applications that prefer to own the fetch can keep building a fresh `SessionCapabilities`/provider per refresh — the store is opt-in, not a replacement. See [ADR-0074](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0074-reactive-client-capabilities.md). There is deliberately **no** server push for capability changes yet. A `session.changed` client-event topic needs per-user targeting and its own authorization story; `refresh()` after a mutation covers the demand today, and a push topic would call the same `refresh()` when it lands. ## Contributing session sections [#contributing-session-sections] The snapshot's fixed shape — user, modules, flags, variants — is framework-owned. Application bootstrap data that a frontend would otherwise fetch with a second round trip (the current tenant, branding, a server clock, an onboarding state) rides along as a **named section**. Implement `IClientSnapshotContributor`, declare its payload in a source-generated context, and register both together: ```csharp public sealed record TenantSection { public required string Name { get; init; } public required string Theme { get; init; } } [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] [JsonSerializable(typeof(TenantSection))] public sealed partial class TenantSectionJsonContext : JsonSerializerContext; public sealed class TenantSectionContributor(ITenantContext tenant, ITenantDirectory directory) : IClientSnapshotContributor { public string SectionName => "tenant"; public async ValueTask GetSectionAsync(CancellationToken ct) { if (tenant.TenantId is not { } id) return null; var info = await directory.FindAsync(id, ct); // app-owned lookup; ITenantContext only carries the id return info is null ? null : new TenantSection { Name = info.Name, Theme = info.Theme }; } } // Program.cs — the resolver argument contributes the payload types to the canonical serialization chain. builder.Services.AddElarionClientSnapshotContributor(TenantSectionJsonContext.Default); ``` The snapshot then carries a `sections` object keyed by section name: ```jsonc { "user": { … }, "modules": { … }, "flags": { … }, "variants": { … }, "sections": { "tenant": { "name": "Acme", "theme": "dark" } } } ``` Contributors are **scoped**, so they may inject the current user or a `DbContext`. Returning `null` omits the section entirely rather than emitting a null, so a section can be conditional on the caller without the frontend having to tell "absent" from "null". A host with no contributors keeps the exact pre-existing wire shape — `sections` is omitted, not empty. Two contributors declaring the same name is a wiring bug and throws: section names are wire keys, and a silent shadow would hand the frontend the wrong payload under a name it trusts. **Re-export the schema and regenerate the client after adding a contributor.** The generated result validators are `z.object(...)`, which **strips unknown keys** — so against a `rpc-schema.json` exported before the contributor existed, `sections` is silently removed client-side and `getSection` always returns `undefined`. Re-run the [schema export](/docs/capabilities/transports/schema-generation) and the client generator whenever the snapshot's shape changes: ```bash dotnet msbuild src/MyApp.Api/MyApp.Api.csproj \ -t:GenerateElarionJsonRpcSchema \ -p:ElarionJsonRpcGenerateSchema=true npx elarion-jsonrpc-client-generator --schema rpc-schema.json --out src/generated ``` Read a section through the generated accessors — the type parameter is your assertion about the contributor's payload, since the wire carries no runtime type information: ```ts interface TenantSection { readonly name: string; readonly theme: string } const tenant = capabilities.getSection('tenant') // undefined when not contributed ``` A section is the same **read-only UX projection** as the rest of the snapshot. Put in it exactly what the UI needs to render, and nothing whose absence you would rely on as a control: the operation is still gated server-side by the handler's `[RequirePermission]`/`[FeatureGate]`. Sections are explicit and named — the framework never reflects over your services to decide what to publish. Because section payloads are serialized from their **runtime** type, the payload type must be reachable through a source-generated context; that is what the resolver argument to `AddElarionClientSnapshotContributor` wires, and it keeps the snapshot reflection-free under Native AOT. ## Typed vocabulary — no stringly-typed capability checks [#typed-vocabulary--no-stringly-typed-capability-checks] The exported schema carries the application's **capability vocabulary** (module names, each module's client-exposed flags, and the `[RequirePermission]`/`[RequireRole]` catalog) in an optional `capabilities` block — resolved automatically by the schema tool from the app's own registrations. The generator turns it into typed constants and literal unions in `session-client.ts`, so a typo is a compile error instead of a silent `false`: ```ts import { Modules, Permissions, Keys, createSessionCapabilities } from './generated/session-client' caps.hasPermission(Permissions.invoices.read) // typed — 'invocies.read' would not compile client.getBooleanValue(Keys.module(Modules.Invoicing), false) ``` `ModuleName`/`FlagName`/`PermissionName`/`RoleName` are literal unions when the vocabulary is present and fall back to `string` on older schemas; accessors accept `Name | (string & {})`, so out-of-vocabulary names remain expressible. This is the frontend analog of the generated `ElarionPermissions` static — one vocabulary, compile-checked on both sides of the wire (see [ADR-0032](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0032-frontend-contribution-model.md)). ## See also [#see-also] * [Frontend modules](/docs/concepts/frontend-modules) — the contribution model whose `when` clauses evaluate against this snapshot. * [ADR-0030: Client capability bootstrap](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0030-client-capability-bootstrap.md) * [ADR-0031: Imperative handler transport mapping](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0031-imperative-handler-transport-mapping.md) * [ADR-0032: Frontend contribution model and the typed capability vocabulary](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0032-frontend-contribution-model.md) * [ADR-0074: Reactive client capabilities](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0074-reactive-client-capabilities.md) * [Feature flags](/docs/concepts/feature-flags) — the flag/variant seams the snapshot reads. * [Custom transports](/docs/capabilities/transports/custom-transports) — declarative vs. imperative exposure. # Cross-module communication (/docs/concepts/cross-module-communication) Modules collaborate **asynchronously** through the [event planes](/docs/capabilities/events). For **direct, synchronous** module-to-module calls — the in-process analog of a gRPC call — Elarion's answer is a **published contract**: a module exposes an interface, keeps the implementation internal, and other modules depend on the contract, never on the module's internals. The framework owns the convention (`[ModuleContract]`) and an analyzer that enforces it. Mapping between a contract's DTOs and a module's handler DTOs is the **module's concern** — write it by hand or with any mapper. There is no generated forwarder for the contract and no mapper dependency. ## The contract [#the-contract] Mark a module's published surface with `[ModuleContract]` and keep the implementation `internal`: ```csharp using Elarion.Abstractions; using Elarion.Abstractions.Modules; namespace Sales; // Module A — the published contract (stable, public). [ModuleContract] public interface ICustomerLookup { ValueTask> GetAsync(CustomerId id, CancellationToken ct = default); } ``` ```csharp namespace Orders; // Module B — depends only on the contract. [Service] internal sealed class OrderPricer(ICustomerLookup customers) { // ... } ``` The boundary analyzer (`ELMOD002`, a warning) is purely **location-based**: everything under an `[AppModule]` is module-internal, and everything outside every module is shareable. So injecting another module's internal type — an entity, DTO, `[Service]`, handler, or `[EntityConfiguration]` placed inside it — is flagged, while a `[ModuleContract]` is allowed. It inspects only the dependency surface (constructor parameters, fields, properties). Resolve a flag one of three ways: * **A `[ModuleContract]`** — for a genuine cross-module *domain* call (e.g. a foundation module publishing an account-standing/credit policy another module consults before invoicing). Use it sparingly and deliberately; it is a published surface, not a default reach. It is *not* for cross-cutting concerns the framework already solves (auditing via `[Auditable]`, validation, authorization) — those attach in the handler pipeline, with no contract to publish. * **A platform-capability port** — an intent-only abstraction (sending email, storing a blob) that lives *outside* the modules with its adapter in infrastructure (the port/adapter pattern). Shared by location, not by contract. (A write-only external *sink* — a webhook, a log shipper — belongs here; a decision the app's own domain owns, like the credit policy above, is the contract instead.) * **The shared kernel** — data and value types (entities, `Money`) live outside every module and are freely referenceable. A shared-kernel entity is shareable because of *where it lives*, not because entities are special: place an entity inside a module and it becomes module-owned and flagged. The recommended layout keeps each entity's `[EntityConfiguration]` in the shared `Persistence` layer (under no `[AppModule]`), so it is shareable too; an `[EntityConfiguration]` is flagged only when deliberately placed *inside* a module. Foundation (`Core`) modules are **no exception** — the analyzer reads only the module name, never its `Kind`, so a core module exports through a `[ModuleContract]` (or a platform port outside the modules) just like any other. Making "what a module exports to the outside world" explicit is the point, core included. ## Mental model: module-private namespaces [#mental-model-module-private-namespaces] If you know Java or Kotlin, `ELMOD002` is essentially **package-private for C#**. A module owns a namespace the way a Java package owns its types, and the analyzer enforces the same visibility split: | Java / Kotlin | Elarion | | ------------------------------ | ---------------------------------------------------------- | | a package | a module's namespace (`[AppModule]` + everything under it) | | `public` (or a JPMS `exports`) | a `[ModuleContract]` — the exported surface | | package-private (the default) | everything else in the module — *module-internal* | | the **compiler** enforces it | the **analyzer** (`ELMOD002`) enforces it | Elarion has to synthesize this because **C#'s `internal` is assembly-scoped, not namespace-scoped** — within one assembly the language has no "visible only inside this module." The analyzer fills that gap on top of namespaces. Two deliberate differences from Java's version: it checks only the **dependency surface** (constructor parameters, fields, properties) rather than every reference, and **data is a shared carve-out** — entities live outside modules on purpose (feature, not data, separation), so it is "module-private for *code*, shared kernel for *data*." It also has a hard upgrade: when a module graduates to its **own assembly** (a [bounded context](/docs/concepts/solution-structure#graduating-to-a-bounded-context)), real C# `internal` takes over and the boundary becomes **compiler**-enforced. So the progression is exactly *package-private (soft, co-located) → a real module boundary (hard, separate assembly)* — the analyzer is the in-assembly tier C# lacks, and the assembly split is the upgrade. ## Implementing a contract with the typed module API [#implementing-a-contract-with-the-typed-module-api] A `[ModuleContract]` implementation is a small, hand-written adapter: it forwards to the module's handlers and maps to/from the contract's DTOs. To call handlers by name instead of resolving verbose `IHandler<,>` types, opt the module into a generated **typed in-process API** with `[GenerateModuleApi]`: ```csharp namespace Sales; // Generated: one method per handler in this module, dispatched typed-direct to IHandler<,>. [GenerateModuleApi] public partial interface ISalesApi; // The contract implementation — internal, auto-registered and module-gated via [Service]. [Service] internal sealed class CustomerLookup(ISalesApi api) : ICustomerLookup { public async ValueTask> GetAsync(CustomerId id, CancellationToken ct = default) { var result = await api.GetCustomer(new GetCustomer.Query(id.Value), ct); // full handler pipeline if (!result.IsSuccess) return result.Error; // AppError converts to Result var r = result.Value; return new Customer(r.Id, r.Name); // module-owned mapping } } ``` The typed module API is **not a transport**. It dispatches typed-direct to the decorated `IHandler<,>` (so the full decorator pipeline runs), crosses no serialization boundary, and is absent from the JSON-RPC/MCP schema. Because its methods expose handler DTOs it is module-internal — never inject it across a module boundary. Handlers are resolved **lazily, per call**, from the service provider — a default facade can span the whole module, so the forwarder never builds a handler's pipeline until you invoke that method. ### What a contract's consumer must know [#what-a-contracts-consumer-must-know] * **Declare the dependency.** The implementation is registered with the module that owns the contract, so it is gone when that feature module is disabled, and a consumer that injects it fails when it is resolved. Name the owner in the consumer's `[AppModule(..., DependsOn = "Owner")]`; the analyzer reports an undeclared one as `ELMOD008` (a Core module's contract needs none, Core modules are never disabled). `DependsOn` orders the modules and documents the dependency; it does not switch the consumer off with its owner. Two modules that inject each other's contracts name each other, a cycle the generator accepts and reports as `ELMOD009` (Info); see [Modules that depend on each other](/docs/concepts/modules#modules-that-depend-on-each-other). * **A contract that returns `IQueryable` shares the caller's `DbContext`.** The query is composed by the caller and runs when the caller enumerates it, on the scoped `DbContext` the implementation was resolved with — the caller's request scope, its transaction and its change tracker. That is what lets the caller join, filter and page it in one SQL statement; it also means the implementation must not dispose or save that context, and that the query cannot outlive the scope (return a materialized list, or a `Result`, from a contract that crosses a scope or a transport). * **Module-private types stay internal.** A handler may be `internal` like the services it injects: the generators register and expose an internal handler (its request and response included) exactly like a public one, so a module-private service need not be made public to be injected (no `CS0051`). ## Choosing which handlers appear [#choosing-which-handlers-appear] Membership is **opt-out** and uses the same scope vocabulary as `[EntityConfiguration]`/`[GenerateDbSets]`: * A default `[GenerateModuleApi]` facade includes **every handler** in the owning module. * `[ModuleApi(Exclude = true)]` on a handler removes it from every facade. * `[ModuleApi("Reporting")]` tags a handler into the `Reporting` scope (additively — it stays in the default facade). A `[GenerateModuleApi("Reporting")]` facade then includes only handlers whose tags intersect, which is the ISP-friendly way to expose a narrow surface to one collaborator. ```csharp [ModuleApi("Reporting")] public sealed class GetRevenue : IHandler> { /* ... */ } [GenerateModuleApi("Reporting")] // only [ModuleApi("Reporting")] handlers public partial interface IReportingApi; ``` | Diagnostic | Meaning | | ---------- | ------------------------------------------------------------------------------------------- | | `ELAPI001` | `[GenerateModuleApi]` interface must be `partial`. | | `ELAPI002` | `[GenerateModuleApi]` interface must be top-level (not nested). | | `ELAPI003` | Interface namespace is under no `[AppModule]`; left empty (warning). | | `ELAPI004` | Two handlers map to one method name on the facade. | | `ELMOD002` | A type depends on another module's internal type instead of a `[ModuleContract]` (warning). | ## Error handling on the contract surface [#error-handling-on-the-contract-surface] A contract method's **error channel** is part of its public shape, so choose it deliberately. **Prefer returning `Result`** — it matches the handler layer (the implementation is a pure map, no `try/catch`), makes the success/error union explicit and total in the signature, and carries the transport-neutral `AppError`/`ErrorKind` taxonomy that survives a later move out of process. ```csharp [ModuleContract] public interface ICustomerLookup { ValueTask> GetAsync(CustomerId id, CancellationToken ct = default); // preferred } ``` You **can** instead publish an exception-based contract — return the bare value and throw on failure — to keep the interface free of the `Result` dependency. `Result` then leaves the interface and the in-process implementation maps the handler's `Result` to value-or-throw: ```csharp [ModuleContract] public interface ICustomerLookup { ValueTask GetAsync(CustomerId id, CancellationToken ct = default); // throws on failure } [Service] internal sealed class CustomerLookup(ISalesApi api) : ICustomerLookup { public async ValueTask GetAsync(CustomerId id, CancellationToken ct = default) { var result = await api.GetCustomer(new GetCustomer.Query(id.Value), ct); if (!result.IsSuccess) throw MapToException(result.Error); // module-owned mapping var r = result.Value; return new Customer(r.Id, r.Name); } } ``` Either way the **interface stays stable across a later gRPC extraction** — only the implementation's mapping changes. A `Result` contract maps elegantly to a protobuf `oneof` response (success *or* error, the on-the-wire `Result`); an exception contract maps to the [Google Rich Error Model](https://grpc.io/docs/guides/error/) (`google.rpc.Status`), with `ErrorKind` mapping onto `google.rpc.Code`. **Prefer `Result`; only drop it when a concrete need calls for it.** ## Data owned across modules [#data-owned-across-modules] Some data belongs to records of other modules: notes or files attached to a property, a contact, a request. Keep the reference in the database, not in a cleanup call in every deleting handler. Modules share one schema, so a foreign key to another module's table breaks no boundary. For data that attaches to several kinds of records, use an exclusive arc (one nullable foreign key per kind) or a shared identity table, and let `ON DELETE CASCADE` remove it with its owner. [Polymorphic references](/docs/concepts/polymorphic-references) compares the patterns. Records in another bounded context announce their deletion with an integration event instead. ## Why not just call the handler (`IHandlerSender`/`IHandler`)? [#why-not-just-call-the-handler-ihandlersenderihandler] A typed in-process call to another module's handler ([by type](/docs/concepts/handlers#calling-a-handler-from-other-code)) couples you to that module's request/response types — which the boundary analyzer flags (`ELMOD002`) when they are module-internal — and it does not survive extraction. A `[ModuleContract]` is the stable seam that does: to split a module out of process later, keep the interface and swap the in-process implementation for a generated client — consumers never change. (The event bus is no help here either: it is pub/sub-only, see [events](/docs/capabilities/events).) # Decorator pipelines (/docs/concepts/decorator-pipelines) Elarion registers handlers through generated factories that wrap the handler in an ordered pipeline of decorators. Decorators are how you apply cross-cutting behavior — logging, validation, transactions, idempotency, tenancy — without putting it inside handlers. ## Pipeline scopes [#pipeline-scopes] Pipeline attributes can be applied at three scopes, from least to most specific: 1. **Assembly** 2. **Module class** 3. **Handler class** The most specific pipeline wins. This lets you set a default pipeline for the whole application and override it for individual modules or handlers. ## Defining named pipelines [#defining-named-pipelines] The framework **does** ship built-in decorators for the common cross-cutting concerns — [transactions](/docs/concepts/persistence-and-transactions), [request validation](/docs/concepts/validation), [idempotency](/docs/concepts/idempotency), [previews](/docs/concepts/previewable-commands), [authorization](/docs/concepts/authorization), [feature gating](/docs/concepts/feature-flags), [caching](/docs/capabilities/caching), [resilience](/docs/capabilities/resilience), tracing, and the async-resolved handler proxy — and the generator auto-attaches them from the handler's own attributes (validation from the attributes on the handler's *request* type, previews from the request implementing `IPreviewableRequest`). The one exception is the [transaction decorator](#transaction-decorator), which you list once in your `[DecoratorList]`. You still add your own for app-specific behavior (your logging, your tenancy model): define your decorators in the application and expose named pipeline attributes with `[DecoratorList]`: ```csharp using MyApp.Application.Decorators; using Elarion.Abstractions.Pipeline; namespace MyApp.Application.Pipeline; [DecoratorList( typeof(LoggingDecorator<,>), typeof(Elarion.Pipeline.TransactionDecorator<,>), typeof(DbConstraintDecorator<,>))] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class)] public sealed class DefaultPipelineAttribute : Attribute; // Bulk imports write thousands of rows in one command: the same decorators, plus a longer database // command timeout for the call (an app decorator that calls db.Database.SetCommandTimeout). [DecoratorList( typeof(LoggingDecorator<,>), typeof(Elarion.Pipeline.TransactionDecorator<,>), typeof(LongCommandTimeoutDecorator<,>), typeof(DbConstraintDecorator<,>))] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class)] public sealed class BulkImportPipelineAttribute : Attribute; ``` Apply the default at the assembly level: ```csharp using MyApp.Application.Pipeline; using Elarion.Abstractions; [assembly: DefaultPipeline] [assembly: UseElarion] ``` And override it on a specific handler: ```csharp [BulkImportPipeline] [Handler("contacts.import")] public sealed class ImportContacts : IHandler> { // ... } ``` A named pipeline **replaces** the default rather than adding to it, so it lists every decorator it keeps. Use one for an axis the request type cannot express. An import is a command like any other, and nothing on its request type says it needs a longer database timeout, so a named pipeline is the right place to say so. **Do not use one for the read/write split.** The request kind (`IQuery`/`ICommand`) already carries that split. A pipeline named after it ("read-only", "query") becomes a second source of truth: it has to be remembered on every new handler, and it drifts from the type the day someone forgets. Instead, let the decorator itself decide, in one of two ways: * with a compile-time generic constraint, see [Filtering by request kind](#filtering-by-request-kind); * with an [`AppliesTo` predicate](#conditional-attachment-with-appliesto), as the transaction decorator does. Either way, one default pipeline is correct for commands, queries, and both kinds of event handler. ## Writing a decorator [#writing-a-decorator] A decorator implements `IHandler` and takes the inner handler as a constructor parameter. Any additional constructor parameters are resolved from DI by the generated factory. ```csharp using Microsoft.Extensions.Logging; using Elarion.Abstractions; public sealed class LoggingDecorator( IHandler inner, ILogger> logger ) : IHandler { public async ValueTask HandleAsync(TRequest request, CancellationToken ct) { logger.LogDebug("Handling {RequestType}", typeof(TRequest).Name); var response = await inner.HandleAsync(request, ct); logger.LogDebug("Handled {RequestType}", typeof(TRequest).Name); return response; } } ``` ### Transaction decorator [#transaction-decorator] The framework ships this one for you: `Elarion.Pipeline.TransactionDecorator` commits on success and rolls back on failure, using `IResultLike` to inspect the outcome without knowing the concrete response type. It wraps the handler in a single [`IUnitOfWork`](/docs/concepts/persistence-and-transactions) boundary rather than a raw `DbContext`, so every feature composes the same unit of work. Wire it with `AddElarionUnitOfWork()` and list it once in your application's `[DecoratorList]`; its `AppliesTo` predicate then decides per handler whether it attaches. "Should this handler open a unit of work?" is true for **commands** and false for **queries and domain-event handlers** (which run inside the publisher's transaction) — a rule no `where` clause can express. A [`static bool AppliesTo`](#conditional-attachment-with-appliesto) predicate states it exactly, and also excludes handlers whose pipeline already owns the unit of work — [`[Idempotent]`](/docs/concepts/idempotency) commands and integration-event consumers under the default-on inbox (only an `[AllowDuplicates]` opt-out gets the plain transaction back) — so a handler is never wrapped in two nested transactions. A command marked `[NoTransaction]` opts out too. The shape, simplified (the shipped decorator also hands an exception from the handler or the commit to the registered `IUnitOfWorkFailureTranslator`s, see [constraint violations as results](/docs/concepts/persistence-and-transactions#constraint-violations-as-results)): ```csharp namespace Elarion.Pipeline; public sealed class TransactionDecorator( IHandler inner, IUnitOfWork unitOfWork ) : IHandler { // Attach only where a new unit of work is needed. The generator calls this once per handler type. public static bool AppliesTo(HandlerMetadata handler) { if (handler.GetAttribute() is not null || handler.GetAttribute() is not null) return false; // The default-on inbox owns an integration consumer's unit of work; [AllowDuplicates] opts out of it. if (handler.RequestType.IsAssignableTo(typeof(IIntegrationEvent))) return handler.GetAttribute() is not null; return handler.RequestType.IsAssignableTo(typeof(ICommand)); } public async ValueTask HandleAsync(TRequest request, CancellationToken ct) { await using var scope = await unitOfWork.BeginAsync(UnitOfWorkOptions.Default, ct); var response = await inner.HandleAsync(request, ct); // The handler already succeeded, so the finalizing commit is deliberately uncancellable. // ResultInspection, not an inline `is IResultLike` pattern: no boxing of the struct Result (ADR-0092). if (ResultInspection.IsSuccess(response)) { await scope.CommitAsync(CancellationToken.None); } else { await scope.RollbackAsync(CancellationToken.None); } return response; } } ``` | Handler | `AppliesTo` | Result | | ------------------------------------------------------------------------ | ----------- | ----------------------------------------------------------------------------------------------------------- | | Command (`ICommand`) | true | opens a transaction | | Command marked `[NoTransaction]` | false | not attached — the handler owns its transactions | | Query (`IQuery`) | false | not attached | | Domain-event handler (`IDomainEvent`, inline in the command) | false | not attached — rides the publisher's transaction | | Integration-event handler (`IIntegrationEvent`, fresh post-commit scope) | false | not attached — the default-on inbox (idempotency decorator) owns the unit of work | | `[AllowDuplicates]` integration-event handler | true | opens its own transaction | | `[Idempotent]` command | false | not attached — the idempotency decorator owns the unit of work | | Previewable command (`IPreviewableRequest`) | true | opens a transaction nested in the preview decorator's scope (a savepoint), so a preview still rolls it back | No runtime check, no empty transaction on a query, and domain-event handlers get no decorator at all — the chains show exactly what attached. (The one residual wart: a *read-only* `[AllowDuplicates]` integration consumer still opens a transaction it never uses — harmless.) ### Turning an `AppError` into `TResponse` [#turning-an-apperror-into-tresponse] Generic decorators (like validation) sometimes need to construct a failure `TResponse` from an `AppError`. Both `Result` and the non-generic `Result` implement `IResultFailureFactory`, which exposes a `static abstract TSelf Failure(AppError)`. Constrain the decorator's `TResponse` to that interface and call `TResponse.Failure(error)` directly — **no reflection**. The framework's own [`ValidationDecorator`](/docs/concepts/validation) is exactly this shape: ```csharp namespace Elarion.Pipeline; public sealed class ValidationDecorator( IHandler inner, IRequestValidator validator ) : IHandler where TResponse : IResultFailureFactory { public async ValueTask HandleAsync(TRequest request, CancellationToken ct) { var errors = await validator.ValidateAsync(typeof(TRequest), request!, ct); if (errors is null) return await inner.HandleAsync(request, ct); var messages = ValidationErrorData.Flatten(errors.FieldErrors); return TResponse.Failure(AppError.Validation(string.Join("; ", messages), errors.FieldErrors)); } } ``` The `where TResponse : IResultFailureFactory` constraint does double duty: it makes the static `Failure` call type-safe **and** scopes the decorator at compile time to `Result`-returning handlers — the generator [skips it](#filtering-by-request-kind) for any handler whose response does not satisfy the constraint, so you never hit a runtime "this handler doesn't return `Result`" failure. Prefer this over a reflection-based helper. ### Declaring the errors a decorator adds [#declaring-the-errors-a-decorator-adds] A decorator that fails a request returns an `AppError` that no handler can declare, because the handler does not know which decorators wrap it. Put [`[ProducesError]`](/docs/reference/result-and-errors#declaring-errors-for-many-operations) on the decorator instead: the generator adds the declaration to every operation whose pipeline includes the decorator, so the schema and the generated client describe it and the development-time contract check does not report it. ```csharp [ProducesError("db.constraint", ErrorKind.Conflict, typeof(ConstraintViolation))] public sealed class DbConstraintDecorator(IHandler inner) : IHandler where TRequest : ICommand where TResponse : IResultFailureFactory { // Translates a unique-key violation into the declared conflict. } ``` The generator resolves the decorator list exactly as it builds the pipeline, so a decorator excluded by its `where` constraints (here: queries) adds nothing. An `AppliesTo` predicate runs at runtime, so the errors of a conditional decorator are declared for every operation it can wrap. A handler's own declaration of the same code wins. ## Order matters [#order-matters] Decorators run in the order listed in `[DecoratorList]`, outermost first. A pipeline of `[Logging, DbConstraint]` logs outermost and translates constraint violations closest to the handler. Choose the order deliberately; the generated code makes it explicit and inspectable. The framework's auto-attached decorators keep a fixed position around your list. Outermost first, each attached only when its trigger applies: 1. [Observability](/docs/capabilities/telemetry#user--request-context) — tracing + context enrichment (always). 2. [After-commit work](/docs/concepts/persistence-and-transactions#work-after-the-commit) — every scoped handler once `IAfterCommit` is registered (runs the enqueued work after the outermost handler succeeded). 3. [Audit](/docs/concepts/auditing) outcome observer — `[Auditable]`. 4. Authorization — `[Require*]` or `[ElarionAuthorizationDefaults]` in scope. 5. [Visibility](/docs/concepts/authorization#members-only-some-callers-see) — a response with `[VisibleWith]` members (hides them per caller, outside caching and idempotency). 6. [Feature gate](/docs/concepts/feature-flags) — `[FeatureGate]`. 7. [Validation](/docs/concepts/validation) — DataAnnotations on the request graph. 8. Cache invalidation — `[CacheInvalidate]`. 9. [Resilience](/docs/capabilities/resilience) — `[Resilient]`. 10. [Idempotency](/docs/concepts/idempotency) — `[Idempotent]` commands (owns the unit of work), or the inbox for integration-event consumers. 11. [Preview](/docs/concepts/previewable-commands) — commands whose request implements `IPreviewableRequest` (owns the unit of work of a preview or a fingerprinted commit; a savepoint under idempotency). 12. **Your `[DecoratorList]` decorators**, in list order. 13. [Audit](/docs/concepts/auditing) success recorder — `[Auditable]`, inside your transaction decorator. 14. [Cache](/docs/capabilities/caching) — `[Cacheable]`. 15. [Upload limits](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member) — a request with `[UploadLimits]` members (declares them for the request's files right before the handler reads them). 16. The handler. So a denied, gated, or invalid request never reaches your decorators or opens a transaction, a member only some callers may see is hidden from a cached or replayed answer too, a denied attempt is still audited, a replayed idempotent request never claims a key, a success audit record commits atomically with the handler's writes, and an `[Auditable]` cached query still records the read on a cache hit. ## Inspecting the resolved pipeline [#inspecting-the-resolved-pipeline] The decorators that actually wrapped a handler in the current process are available at run time on [`HandlerMetadata.Pipeline`](/docs/concepts/handlers) — an `IHandlerPipeline` exposing `Steps` (each a `PipelineStep(Type Decorator, bool Conditional)`, outermost first) and `Contains(typeof(SomeDecorator<,>))`. It reflects the *resolved* pipeline, including decorators that attach only when a backing service is registered (audit, the idempotency inbox) or when an `AppliesTo` predicate matched — those are flagged `Conditional`. It is empty until the handler is first resolved from DI (the composition is only known then), and reflects one composition per process. The framework surfaces the same list on every handler span as the `elarion.handler.pipeline` [tag](/docs/capabilities/telemetry#handler-tracing), so "why didn't caching apply here?" is answerable from a trace. ## Reading the handler's attributes (do not use `inner.GetType()`) [#reading-the-handlers-attributes-do-not-use-innergettype] A common need is a decorator that reads an attribute off the handler — for example an `[RequirePermission(...)]` for an authorization decorator. It is tempting to reach for `inner.GetType().GetCustomAttribute()`, but **this is a fail-open footgun**. Because decorators wrap innermost-first, `inner` is the *concrete handler* only when the decorator is the **innermost** wrapper (last in `[DecoratorList]`). At any other position — including the intuitive outermost "check authorization first" spot — `inner` is the *next decorator*, the attribute is invisible, and an authorization check **silently passes**. Never read the handler's attributes from `inner.GetType()`. It only sees the handler when the decorator happens to be innermost; positioned anywhere else it reads a decorator wrapper instead, so an attribute-driven check fails **open**. The failure is silent — there is no compiler error. Instead, declare a `HandlerMetadata` constructor parameter. The generator supplies it with the **concrete handler type**, so the decorator reads the handler's attributes correctly **regardless of its position** in the chain. (The generated factory passes the inner handler first, then any DI dependencies and the `HandlerMetadata` singleton in declaration order.) ```csharp using Elarion.Abstractions; using Elarion.Abstractions.Authorization; using Elarion.Abstractions.Identity; using Elarion.Abstractions.Pipeline; // Position-independent: works whether this decorator is outermost, innermost, or anywhere between. public sealed class AuthorizationDecorator( IHandler inner, HandlerMetadata metadata, ICurrentUser user ) : IHandler where TResponse : IResultFailureFactory { public ValueTask HandleAsync(TRequest request, CancellationToken ct) { var required = metadata.GetAttribute(); if (required is not null && !user.HasClaim("permission", required.Permission)) return ValueTask.FromResult(TResponse.Failure(AppError.Forbidden(required.Permission))); return inner.HandleAsync(request, ct); } } ``` `metadata.HandlerType` is the true handler type; `GetAttribute()`/`GetAttributes()` read its attributes. Attribute reads still use reflection, but on a single known `Type`, which is AOT/trim-safe as long as the attribute type is preserved. The `HandlerMetadata` singleton is generated once per handler (no per-request allocation). The seam offers a correct path but does not *prevent* the unsafe `inner.GetType()` pattern from compiling — prefer `HandlerMetadata` whenever a decorator depends on the handler's own type or attributes. ## Filtering by request kind [#filtering-by-request-kind] A decorator can constrain its `TRequest` type parameter, and the generator applies it **only to handlers whose request satisfies the constraint** — skipping it for the rest at compile time, with no runtime check and no allocation in the chains it doesn't apply to. This is the tool for a decorator that is meaningful for exactly one request kind, using the [`ICommand`/`IQuery` markers](/docs/concepts/handlers#command-vs-query): ```csharp // Compile-time filtered: only command handlers are throttled; queries skip it entirely. public sealed class ThrottleDecorator( IHandler inner, ICommandThrottle throttle ) : IHandler where TRequest : ICommand { public async ValueTask HandleAsync(TRequest request, CancellationToken ct) { using var lease = await throttle.AcquireAsync(typeof(TRequest).Name, ct); return await inner.HandleAsync(request, ct); } } ``` A query handler never has `ThrottleDecorator` in its generated chain — the filtering is resolved when the pipeline is emitted. Decorators with no constraints (the common case) apply to every handler. A `where` clause expresses a single bound (an AND of "implements X"). When attachment is a **union** or a **negation** — like the transaction decorator's "commands, but *not* `[Idempotent]` ones" — reach for `AppliesTo` below. ## Conditional attachment with `AppliesTo` [#conditional-attachment-with-appliesto] A decorator may declare a static predicate that the generator **calls once at pipeline-build time** to decide attachment per handler: ```csharp public static bool AppliesTo(HandlerMetadata handler); ``` When present, the decorator is attached only to handlers for which it returns `true`. The predicate is **called, not parsed**, so any C# is allowed — including reflection. The generator evaluates it **once per closed handler type** (caching the result in a generated `static readonly bool` initialized at type init), never per request, so it stays NativeAOT- and trim-safe. It composes with `where`: the constraint governs what the body may *call*; `AppliesTo` governs *whether to attach*. The predicate receives [`HandlerMetadata`](/docs/concepts/handlers) — the concrete `HandlerType`, `RequestType`, `ResponseType`, and `GetAttribute()`/`GetAttributes()` — so it can attach based on the request type, the response type, **or the handler's own attributes**. That is the same handler-attribute-driven attachment the framework's built-in decorators use; there is no privileged generator capability a custom decorator can't replicate. Attach on the request kind: ```csharp public static bool AppliesTo(HandlerMetadata handler) => handler.RequestType.IsAssignableTo(typeof(ICommand)) || handler.RequestType.IsAssignableTo(typeof(IIntegrationEvent)); ``` …or on a custom handler attribute: ```csharp public static bool AppliesTo(HandlerMetadata handler) => handler.GetAttribute() is not null; ``` There is a single supported signature on purpose. It must be `public static bool AppliesTo(HandlerMetadata)`; a non-`public` one is `ELPIPE001`, and a differently-shaped `AppliesTo` (e.g. the older `AppliesTo(System.Type)`) is `ELPIPE002` rather than silently ignored. Because it is plain runnable C#, you can unit-test it directly: `TransactionDecorator<,>.AppliesTo(new HandlerMetadata(typeof(CreateOrder), typeof(CreateOrder.Command), typeof(Result)))`. `AppliesTo` works for decorators shipped in **referenced packages** too — a `public static` method is callable across the metadata boundary even though its body isn't readable as source. Attachment is a **runtime** decision, so the decorator type is referenced (behind the cached `if`) in every in-scope handler's chain rather than compile-time elided. When the rule is a single interface bound and you want elision/trimming, prefer a `where` constraint. Built-in [caching](/docs/capabilities/caching) and [resilience](/docs/capabilities/resilience) are themselves decorators (`CacheDecorator`, `ResilienceDecorator`) inserted into this same pipeline by their attributes — so they compose with your application decorators in a deterministic order. # Feature flags & variants (/docs/concepts/feature-flags) Feature flags in Elarion gate a **handler** behind one or more flags. You annotate the handler with `[FeatureGate(...)]`; a generated decorator evaluates the flags before the handler runs, under every transport (JSON-RPC, MCP, HTTP) identically. A disabled feature short-circuits to a `404 Not Found` — a gated-off operation is indistinguishable from one that doesn't exist, so a flag doubles as a hide-the-roadmap switch. A flag is not a string you sprinkle around. It is **declared once** — name, description, whether the frontend may see it, and **who owns its value** — and the source generators build a catalog from those declarations, check every use against it at compile time, and wire it into DI. Exactly one owner answers for each flag, so there is no provider precedence to reason about. See [ADR-0079](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0079-every-feature-flag-is-declared-and-has-exactly-one-owner.md). ## Handler gates vs. module flags [#handler-gates-vs-module-flags] * **Module flags** (`Modules:{Name}:Enabled`) are **compose-time**: a disabled feature module disappears entirely — its services, endpoints, operations, jobs, consumers, **and declared feature flags** are never registered. See [modules](/docs/concepts/modules). * **Feature gates** (`[FeatureGate]`) are **runtime**: the handler is always registered, but each call is evaluated against the flag's owner, so you get gradual rollouts, targeting, and kill switches that flip without a redeploy. ## Declaring a flag [#declaring-a-flag] There are two kinds of owner. Declare each flag with exactly one of them, under the module that owns it. **Code-defined** — the class that carries `[FeatureFlag]` *is* the owner and implements `IFeatureFlagResolver`: ```csharp [FeatureFlag("beta-reports", Description = "Early access to the reports redesign.", ExposeToClient = true)] public sealed class BetaReportsFlag(IBetaRoster roster) : IFeatureFlagResolver { public async ValueTask IsEnabledAsync(FeatureEvaluationContext context, CancellationToken ct) => context.UserId is { } id && await roster.ContainsAsync(id, ct); } ``` The resolver is a scoped service, so it can inject a `DbContext`, settings, or a clock. **Backend-evaluated** — the value lives in an external system (Microsoft.FeatureManagement, LaunchDarkly, …) and the host's `IBackendFeatureFlagEvaluator` owns it. Declare the name on any class under the module: ```csharp [AppModule("Billing")] [BackendFeatureFlag("new-export", Description = "The streaming invoice export.")] [BackendFeatureFlag("dashboard-v2", ExposeToClient = true)] public static class BillingModule { } ``` A flag is a **variant flag** when its owner allocates a variant (`IFeatureFlagResolver.GetVariantAsync`, or the backend's allocation); `[FeatureVariant]` then selects service implementations by it (below). ### What the compiler checks [#what-the-compiler-checks] | Mistake | Diagnostic | | ----------------------------------------------------------------------------------- | --------------------- | | A name in `[FeatureGate]`/`[FeatureVariant]` that nothing declares | `ELFLAG001` | | The same name declared twice — in one assembly or across referenced assemblies | `ELFLAG002` | | `[FeatureFlag]` on a class that is not a concrete `IFeatureFlagResolver` (no owner) | `ELFLAG003` | | A declaration outside every `[AppModule]` namespace of its assembly | `ELFLAG004` | | A blank flag name | `ELFLAG005` | | Two names mapping to the same generated accessor | `ELFLAG006` (warning) | Declarations of referenced assemblies are read from the Elarion manifest, never by scanning symbols, so the checks cross assembly boundaries: declare a flag in the assembly that gates on it, or in one it references. ## Gating handlers [#gating-handlers] Annotate the handler class. The attribute mirrors the familiar ASP.NET MVC `[FeatureGate]`: ```csharp [Handler("billing.export")] [FeatureGate("new-export")] public sealed class ExportInvoices(AppDbContext db) : IHandler> { /* ... */ } ``` | Form | Gate is satisfied when | | ------------------------------------------------- | ------------------------------------------------------------------------ | | `[FeatureGate("a")]` | `a` is enabled | | `[FeatureGate("a", "b")]` | **both** `a` and `b` are enabled (the default, `FeatureRequirement.All`) | | `[FeatureGate(FeatureRequirement.Any, "a", "b")]` | **either** `a` or `b` is enabled | | `[FeatureGate("legacy", Negate = true)]` | `legacy` is **disabled** (fence off a legacy path during rollout) | The attribute is `AllowMultiple`, so stacking several `[FeatureGate]` attributes ANDs them. When any gate is unsatisfied the call returns `AppError.NotFound` and the handler never runs. The gate sits just inside the authorization gate, so an unauthenticated caller is never told whether a gated feature exists, and a disabled feature never touches caching, validation, or the handler. A handler whose response type cannot represent failure is reported as **`ELFEAT001`**; a `[FeatureGate]` with no feature name is **`ELFEAT002`**. ## Checking a flag at runtime [#checking-a-flag-at-runtime] `IFeatureFlagService` is the one entry point. It looks the flag up in the catalog and dispatches to its owner: ```csharp public sealed class Dashboard(IFeatureFlagService flags) { public async Task RenderAsync(CancellationToken ct) => await flags.IsEnabledAsync(ElarionFeatureFlags.DashboardV2, ct) ? RenderNew() : RenderClassic(); } ``` `[assembly: GenerateFeatureFlags]` (included in `[assembly: UseElarion]`) emits the **`ElarionFeatureFlags`** registry: a typed `FeatureFlagKey` per declared flag (so a misspelled or removed flag fails the build), a `Names` class of `const string`s for attribute arguments, and the descriptors aggregated across referenced assemblies. A raw string still works; a name the catalog does not contain — undeclared, or declared by a disabled module — evaluates as **disabled** and is logged once. ### Explicit evaluation context [#explicit-evaluation-context] Owners never reach into the ambient DI scope for *who is asking*; they receive a `FeatureEvaluationContext`: | Member | Meaning | | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `UserId` / `IsAuthenticated` | the subject (`null` for an anonymous caller) | | `Roles` | the subject's roles | | `TenantId` | the tenant, when [tenant scoping](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0075-ambient-tenant-scoping.md) resolved one and the scope is not a system scope | | `Attributes` | extra targeting attributes you supply | | `Services` | the scope's services, for resolvers that need them; **optional** — a context built by hand (`new FeatureEvaluationContext { UserId = "u-1" }`) carries an empty provider, `GetRequiredService` on it throws a message saying so, and it is never `null`. `flags.CreateContext()` always carries the real scope. | The overloads without a context use `flags.CreateContext()` (the current request). Pass your own to evaluate for someone else — an admin previewing another user's experience, a job acting for a user: ```csharp var asVip = flags.CreateContext() with { UserId = "u-vip" }; var enabled = await flags.IsEnabledAsync("beta-reports", asVip, ct); ``` `[FeatureGate]`, the session snapshot ([client capabilities](/docs/concepts/client-capabilities)), and your own checks all evaluate through the same service and catalog, so a flag cannot answer differently depending on the entry point. ## Choosing a backend [#choosing-a-backend] Backend-evaluated flags need exactly one `IBackendFeatureFlagEvaluator`. The host fails at startup if it declares backend flags and registers none. Two opt-in packages provide one; see [feature flag providers](/docs/capabilities/feature-flags): * **`Elarion.FeatureFlags.FeatureManagement`** — `builder.Services.AddElarionFeatureManagement(builder.Configuration);` reads flags from the `FeatureManagement` configuration section. * **`Elarion.FeatureFlags.OpenFeature`** — `AddOpenFeature(...)` + `AddElarionOpenFeature()` over any OpenFeature provider (LaunchDarkly, ConfigCat, flagd, …). The backend only ever sees flags declared with `[BackendFeatureFlag]`; it is never a fallback for a code-owned or undeclared name. ## Variant service injection [#variant-service-injection] Beyond on/off gating, a feature flag can allocate a **variant** to each user, and you can ship a different service *implementation* per variant (the A/B-tested-algorithm pattern). The consuming handler stays transparent — it injects the contract like any service; only the *implementations* are variant-aware: ```csharp [Service] // declare it like any service [FeatureVariant("ForecastAlgorithm")] // the default (no Variant) public sealed class LinearForecast : IForecastAlgorithm { /* ... */ } [Service] [FeatureVariant("ForecastAlgorithm", Variant = "neural")] public sealed class NeuralForecast : IForecastAlgorithm { /* ... */ } public sealed class RunForecast(IForecastAlgorithm algorithm) // no variant awareness : IHandler> { public ValueTask> HandleAsync(Command c, CancellationToken ct) => algorithm.RunAsync(c.Input, ct); } ``` The user allocated the `neural` variant gets `NeuralForecast`; everyone else gets the default `LinearForecast`. The named flag (`ForecastAlgorithm`) must be declared like any other (`ELFLAG001` otherwise), and whoever owns it allocates the variant: its resolver's `GetVariantAsync`, or the backend. **Vary behavior with a variant *service*, not a variant *handler*.** There is no "pick handler A vs handler B by flag" — a handler is chosen by its request type, so authorization, the route/transport contract, and the pipeline are fixed for that request. To make a command behave differently per variant, keep **one** handler and inject a variant **strategy service** (the `IForecastAlgorithm` above); only that one dependency changes between variants. This is the recommended way to apply variants to handler logic. **`[FeatureVariant]` is a modifier on `[Service]`.** A variant implementation is declared like every other service — with `[Service]` — and `[FeatureVariant]` only changes *how* it is resolved. The **contract is not repeated** on `[FeatureVariant]`: it is whatever `[Service]` registers under (the implemented interface, or explicit `[Service(typeof(IX))]` types), so a class that registers under several contracts is variant-resolved on each. So `[Service]` is **required** (a `[FeatureVariant]` without it is reported as `ELVAR007`) and stays the single, consistent way to register a service: with the modifier you get variant-keyed resolution, without it a plain registration. The service generator yields the contract to the variant path (keyed implementations + the binding + the imperative provider + the transparent registration the proxy reads), so the two never double-register. The DI lifetime comes from `[Service]` (`Scope = ServiceScope.Singleton`, etc.), and variant implementations may take their own constructor dependencies. **How it stays transparent.** Variant selection is an async flag evaluation, but constructor injection is synchronous. When a handler's constructor depends on a variant contract, the generator registers it behind an async-resolving proxy (`AsyncResolvedHandler`) that, on the first call, `await`s the variant for the current user into a per-scope cache and then builds the handler normally — so the handler injects the contract with no async ceremony, and handlers that use no variant pay nothing (their registration is unchanged). For cases the proxy doesn't cover — a variant injected *transitively* through another service, or needed outside a handler — inject the imperative escape hatch instead: ```csharp public sealed class Pricing(IVariantServiceProvider algorithms) { public async Task RunAsync(CancellationToken ct) { var algorithm = await algorithms.GetAsync(ct); // variant for the current user, or the default // ... } } ``` Variant service injection needs an OpenFeature provider that surfaces the allocated variant *name* (per spec §1.4.6) — flagd, LaunchDarkly, ConfigCat, and the in-memory provider do. The current `OpenFeature.Contrib.Provider.FeatureManagement` (preview) evaluates the variant's value but does **not** yet surface its name, so variant injection is unavailable through the `AddElarionFeatureManagement` default (boolean `[FeatureGate]` is unaffected). See [ADR-0019](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0019-variant-service-injection.md). ## Configuration-selected variants [#configuration-selected-variants] `[FeatureVariant]` selects per *user* — the answer can differ per request, so it is evaluated per scope and awaited. When the selection is a **process-global choice an admin or operator makes** — "which e-mail backend are we using?" — that machinery is pure overhead: the answer changes on a configuration edit, not per caller. Declare the selection axis instead with `[ConfigurationVariant]`, and a plain configuration value picks the implementation: ```csharp [Service] [ConfigurationVariant("Email:Backend", Value = "smtp", IsDefault = true)] // the named default public sealed class SmtpEmailSender : IEmailSender { /* ... */ } [Service] [ConfigurationVariant("Email:Backend", Value = "office365")] public sealed class Office365EmailSender : IEmailSender { /* ... */ } public sealed class SendInvoice(IEmailSender sender) // still no variant awareness : IHandler> { /* ... */ } ``` A **named default** (`Value` + `IsDefault = true`) is both the fallback *and* explicitly selectable by its value — so the default state has a writable name (an admin switches back to SMTP by writing `"smtp"`, not by removing the key), and the switch's whole vocabulary is declared. Prefer it for admin-facing switches; a default with no `Value` still works and simply has no selectable name. Because the configuration read is synchronous, there is **no async-resolving proxy and no per-scope warm-up**: the contract is injectable anywhere (handlers, services, across assemblies), each new DI scope observes the current value, and work already in flight keeps the implementation it started with. The configured value is matched case-insensitively; an absent key or a value matching no variant resolves the default implementation. A contract is selected by exactly one axis — mixing `[FeatureVariant]` and `[ConfigurationVariant]` on one contract is rejected (`ELVAR008`). Any configuration provider drives the switch, which is the point — the attribute knows nothing about where the value comes from: * **`appsettings.json`** — pinned per deployment; with `reloadOnChange`, an ops edit switches at run time. * **Environment variables** — a per-environment choice. * **The settings bridge** — `AddElarionSettingsConfiguration()` surfaces the runtime [settings store](/docs/concepts/settings) as live configuration, so an admin writes `Email:Backend = office365` through the settings API and (with `AddElarionPostgreSqlSettingsChanges`) the next scope on **every node** resolves `Office365EmailSender` — no restart, and no feature-flag provider involved. ## Feature-selected or configuration-selected? [#feature-selected-or-configuration-selected] The two attributes are the same substrate — keyed implementations, a default, transparent injection — with different **selection axes**, and the differences follow from one fact: a feature variant's answer can differ per caller, a configuration variant's cannot. | | `[FeatureVariant]` | `[ConfigurationVariant]` | | ------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | **Selected by** | *who is asking* — the flag backend's per-user allocation | *what is configured* — one `IConfiguration` value | | **Answer varies** | per user / per request | per process, until the value changes | | **Evaluation** | async, once per DI scope — the handler is wrapped in an async-resolving proxy that warms a per-scope cache | a synchronous configuration read at resolution — no proxy, no warm-up, no per-scope cache | | **Inject the contract** | transparently in handlers (same compilation); elsewhere use `IVariantServiceProvider` | anywhere — any service, any assembly | | **Requires** | an OpenFeature provider that surfaces variant names (flagd, ConfigCat, LaunchDarkly, …) | nothing beyond `IConfiguration`; add the [settings bridge](/docs/concepts/settings) for admin-writable runtime switching | | **A switch takes effect** | on the next scope, once the provider re-allocates | on the next scope after the value changes — cluster-wide with `AddElarionPostgreSqlSettingsChanges` | | **Reach for it when** | A/B experiments, gradual rollouts, per-user/percentage targeting | admin- or ops-chosen backends, environment-shaped choices, kill-switch-style implementation swaps | The decision rule: ask **who decides the answer**. If two concurrent requests could legitimately get *different* implementations, that is per-caller selection — `[FeatureVariant]`. If there is one answer for the whole process, that is configuration — `[ConfigurationVariant]`. **When in doubt, start configuration-selected.** It is the smaller machine — no flag provider to run, no async proxy, injectable anywhere — and an admin-writable switch already covers most "we might want to change this later" needs. If a switch later turns out to need per-user allocation, the migration is confined to the implementation classes' attributes (handler consumers are untouched; consumers outside handlers move to `IVariantServiceProvider`). ## The variant registry [#the-variant-registry] The generator already knows every switch you ship — its key, its value vocabulary, its default, its owning module — so it also emits that knowledge as the **`ElarionVariants` registry** (triggered by `[assembly: UseElarion]` or `[assembly: GenerateVariantCatalog]`), the variant analog of `ElarionPermissions`: one accessor class per switch with `const string` values, plus `VariantDescriptor` data, **aggregated across referenced assemblies** from the Elarion manifest — so the host's registry is the complete menu: ```csharp // generated into the assembly root namespace ElarionVariants.EmailBackend.Key // "Email:Backend" ElarionVariants.EmailBackend.Smtp // "smtp" — consts, usable in attributes ElarionVariants.EmailBackend.Office365 // "office365" ElarionVariants.All // every VariantDescriptor (axis, key, values, default, contract, module) ElarionVariants.ByKey / ByModule / Platform ``` The host seeds runtime consumers **explicitly** — the generator registers nothing in DI: ```csharp builder.Services.AddElarionVariantCatalog(ElarionVariants.All); // IVariantCatalog for handlers/UI builder.Services.AddElarionVariantValidation(); // startup + reload validation (see below) ``` `AddElarionVariantValidation()` checks, at startup and again on every configuration reload, that each configuration-selected switch's current value is one the registry offers (an unknown value otherwise falls back to the default *silently* — the fallback keeps requests serving; the validator makes the mismatch loud), and that each **platform** switch's contract actually resolves from DI (catching a forgotten host wiring call at boot). `Strict = true` fails startup on findings instead of warning. Because adding a variant implementation *is* the declaration, the write-DTO allowed set, the admin dropdown data, the exported schema `enum`, the client-side validation, and the startup checks all follow with **zero central edits** — `[AllowedValues(...)]` is exported as the JSON Schema `enum` keyword to the JSON-RPC schema, MCP tool schemas, and the OpenAPI document, and the generated TypeScript client turns it into `z.enum(...)` with string-union types (see [Validation](/docs/concepts/validation)). ## Who owns the switch [#who-owns-the-switch] Variant implementations often live in the **infrastructure** project — the adapter half of the port/adapter pattern, under no module. That is first-class: such descriptors carry `Module = null` and group under `ElarionVariants.Platform`; the host wires them with the generated per-contract call (`builder.Services.AddIEmailSenderVariantService()`). It also raises the real design question: **who owns the switch's vocabulary?** Three patterns, all of which keep the application in charge of its own settings APIs: | Pattern | Menu owner | Consumers use | Best for | | --------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | | **Module variant** | the module's own declarations — registry consts *are* the vocabulary | `ElarionVariants.X.Y` consts, `[AllowedValues]` | in-app strategies (a forecast algorithm) | | **Port-owned vocabulary** ⭐ recommended | app-declared consts beside the port; adapters reference them | the same app consts in DTOs and attributes | product-meaningful choices the app's UX presents | | **Platform offering** | infrastructure declarations; the host aggregates | `IVariantCatalog` — host-seeded *data*, no symbols | ops-flavored parameters, generic settings consoles | **The happy path: declare the menu where the port lives.** For an in-module strategy there is nothing to decide — the module's declarations are the vocabulary. For a switchable adapter, default to **port-owned vocabulary**: the port already owns the interface, so it owns the menu, and one set of consts then feeds the adapters' attributes, the admin DTO's `[AllowedValues]`, the 400s, every exported schema's `enum`, the generated client's `z.enum`, and the registry — convention over configuration, end to end. Reach for the **platform offering** pattern only when you genuinely want zero per-switch code (a generic settings console) or the application must not know the choices exist. **Port-owned vocabulary** resolves the layering constraint head-on: the application cannot reference infrastructure, so when it wants to *name* the choices (typed DTOs, schema enums), it declares the consts beside the port and the adapters reference them — the dependency direction that works: ```csharp // Application — the port owns the menu, so the application owns the API public static class EmailBackends { public const string Key = "Email:Backend"; public const string Smtp = "smtp"; public const string Office365 = "office365"; } public sealed record ConfigureEmailCommand : ICommand { [AllowedValues(EmailBackends.Smtp, EmailBackends.Office365)] // 400 + schema enum + client z.enum public required string Backend { get; init; } } // Infrastructure — adapters implement the menu [Service] [ConfigurationVariant(EmailBackends.Key, Value = EmailBackends.Smtp, IsDefault = true)] public sealed class SmtpEmailSender : IEmailSender { /* ... */ } ``` **Platform offering** covers switches the application handles *without* naming them: the host seeds the catalog, and an application handler validates against "what the platform offers" at runtime — its own route, DTO, authorization, and audit, with zero per-switch code: ```csharp [Handler("admin.platform.setSwitch")] [RequirePermission("settings", Verbs.Update)] public sealed class SetPlatformSwitch(IVariantCatalog catalog, ISettingsManager settings) : IHandler { public async ValueTask HandleAsync(SetPlatformSwitchCommand command, CancellationToken ct) { var descriptors = catalog.FindByKey(command.Key); if (descriptors.Count == 0) return AppError.NotFound($"No switch '{command.Key}' is offered."); if (!descriptors[0].Values.Contains(command.Value.ToLowerInvariant())) return AppError.Validation($"'{command.Value}' is not offered for '{command.Key}'."); // PlatformSwitches is a declared setting (see Settings) holding the chosen value per switch key. var chosen = new Dictionary( await settings.GetAsync(AppSettings.PlatformSwitches, cancellationToken: ct)) { [command.Key] = command.Value.ToLowerInvariant() }; var write = await settings.SetAsync(AppSettings.PlatformSwitches, chosen, cancellationToken: ct); return write.IsSuccess ? Result.Success() : write.Error; } } ``` The tradeoff between the last two is compile-time versus runtime knowledge: port-owned vocabularies buy typed DTOs, schema-exported enums, and client-side pre-validation at the cost of the application updating its consts when the menu grows; the platform offering buys zero-per-switch generality at the cost of dynamic-only validation (the values reach the UI through an enumerate call, not the schema). Elarion deliberately ships **no admin endpoint** — the registry is data handed to your code, which decides how it is exposed. ## Pinning a specific implementation [#pinning-a-specific-implementation] The variant registrations are ordinary **keyed services**, so a consumer can deliberately opt out of selection and pin one implementation — on either axis: ```csharp // This job must always use the SMTP relay, regardless of what the switch currently selects. public sealed class ComplianceExport( [FromKeyedServices(EmailBackends.Smtp)] IEmailSender alwaysSmtp) { /* ... */ } ``` Pinning bypasses the selection machinery entirely: no flag evaluation, no configuration read, and — on the feature axis — no async proxy or per-scope warm-up, so a pinned feature-variant implementation is injectable anywhere (the generator recognizes `[FromKeyedServices]` parameters and keeps such handlers on the plain synchronous registration). Lifetimes come from the implementation's `[Service]`, and when the pinned key matches what the switch currently selects, both consumers share the same scoped instance. Two rules keep pinning safe: * **Pin via the vocabulary consts** (`ElarionVariants.EmailBackend.Smtp`, or the port-owned consts) — never a raw string. Configuration-axis keys are the **lower-cased** declared values, and a direct keyed lookup does no normalization: `[FromKeyedServices("Office365")]` silently misses where the switch itself would have matched. The consts make a typo or rename a compile error. * **Name the default.** An unnamed default is keyed under the internal `VariantServiceKeys.Default` sentinel; if a consumer needs to pin it, give it a real name with `IsDefault = true` and pin that. Pinning is the escape hatch, not the path: it is **invisible to the switch** — the admin flips the value, the registry and validation say everything is consistent, and the pinned consumer doesn't follow. Reach for it only when a consumer *semantically* requires one backend (a compliance job that must always use the relay), for explicit fallback chains (try the selected implementation, fall back to a pinned one), and in tests. Everything else injects the contract and follows the switch. ## See also [#see-also] * [ADR-0079: Every feature flag is declared and has exactly one owner](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0079-every-feature-flag-is-declared-and-has-exactly-one-owner.md) — declaration as the single source, one owner per flag, explicit evaluation context. * [ADR-0016: Feature-flag gating](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0016-feature-flag-gating.md) — why a thin Elarion seam over OpenFeature rather than `IFeatureManager` directly. * [ADR-0019: Variant service injection](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0019-variant-service-injection.md) — transparent per-variant implementation injection via the async-resolving handler proxy. * [ADR-0028: Configuration-selected service variants](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0028-configuration-selected-service-variants.md) — the synchronous, proxy-free `[ConfigurationVariant]` axis and why it reads `IConfiguration` rather than the settings API or `IOptionsMonitor`. * [ADR-0029: The variant registry](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0029-variant-registry-and-catalog.md) — `ElarionVariants`, named defaults, the host-seeded `IVariantCatalog`, the validation worker, and the switch-ownership patterns. * [Decorator pipelines](/docs/concepts/decorator-pipelines) — how the gate composes with authorization, caching, and resilience. * [Authorization](/docs/concepts/authorization) — the sibling declarative gate the feature gate is modeled on. # Angular (/docs/concepts/frontend-modules/angular) The same [contribution kernel](/docs/concepts/frontend-modules) drives an Angular app through the `/angular` sub-export — idiomatic for Angular 20–22: signal-first, standalone, no NgModule. `provideContributions` is an environment provider (shaped like `provideRouter`); `injectContributions` returns a `Signal` your template tracks, so refreshing the snapshot re-resolves every slot by setting one signal. The bindings are deliberately decorator- and template-free, so they ship in the one package with no separate Angular build. ```ts title="main.ts" import { createContributionRegistry } from "@swimmesberger/elarion-contributions" import { provideContributions } from "@swimmesberger/elarion-contributions/angular" const registry = createContributionRegistry(appModules.map((m) => m.manifest), caps) bootstrapApplication(AppComponent, { providers: [provideContributions(registry)] }) // snapshot can change at runtime? provideContributions(createContributionRegistryStore(manifests, capabilityStore)) // and capabilityStore.set(...) on login (a Signal you drive yourself also works). ``` The sidebar is the same move as in React — wherever you'd `@for` over a hard-coded array, read the point instead: ```ts title="platform/app-sidebar.component.ts" import { Component } from "@angular/core" import { RouterLink, RouterLinkActive } from "@angular/router" import { injectContributions } from "@swimmesberger/elarion-contributions/angular" import { sidebarItems } from "@/platform/points" @Component({ selector: "app-sidebar", standalone: true, imports: [RouterLink, RouterLinkActive], template: ` `, }) export class AppSidebar { readonly items = injectContributions(sidebarItems) // filtered by `when`, deterministically ordered } ``` ## A self-owned `*extensionSlot` directive [#a-self-owned-extensionslot-directive] Prefer slot sugar over an inline `@for`? The package ships **no** directive — that would need the Angular compiler and a separate build. A `*extensionSlot` structural directive is instead a few lines you own on top of `injectContributions`, and because it's yours the rendering stays in your app while the kernel stays framework-agnostic: ```ts title="platform/extension-slot.directive.ts" import { Directive, effect, inject, Injector, input, runInInjectionContext, TemplateRef, ViewContainerRef, } from "@angular/core" import { injectContributions } from "@swimmesberger/elarion-contributions/angular" import type { Contribution, ExtensionPoint } from "@swimmesberger/elarion-contributions" @Directive({ selector: "[extensionSlot]", standalone: true }) export class ExtensionSlotDirective { // *extensionSlot="point" — the point token to render. readonly point = input.required>({ alias: "extensionSlot" }) private readonly tpl = inject }>>(TemplateRef) private readonly vcr = inject(ViewContainerRef) private readonly injector = inject(Injector) constructor() { // Re-render when the point changes or the snapshot refreshes; each item is the template's $implicit. // injectContributions() calls inject(), so it must run in an injection context — hence runInInjectionContext. effect(() => { const items = runInInjectionContext(this.injector, () => injectContributions(this.point())()) this.vcr.clear() for (const item of items) this.vcr.createEmbeddedView(this.tpl, { $implicit: item }) }) } } ``` The slot site then reads like the React bindings' ``, with the contribution as the template's implicit value: ```html {{ item.label }} ``` # Frontend modules (/docs/concepts/frontend-modules) Elarion's backend has a hard review-isolation property: adding a feature to a module touches only that module's code. The **frontend contribution model** ([ADR-0032](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0032-frontend-contribution-model.md), shipped as [`@swimmesberger/elarion-contributions`](https://www.npmjs.com/package/@swimmesberger/elarion-contributions)) extends that rule to the TypeScript app: a new sidebar item is one edit in the owning module's manifest, a new module is a new folder (its manifest glob-discovered; its routes one typed registration line — the `ProjectReference` grain), and a cross-module action is a manifest entry plus one token import — the shell never changes. ```bash npm install @swimmesberger/elarion-contributions ``` This page is the framework-agnostic model: points, manifests, `when` clauses, and the registry. The framework bindings and routing recipes are their own pages: The composition root, `useContributions`/`ExtensionSlot`, plain and shadcn/ui sidebars, Vite config. Module-owned route subtrees, the `redirectUnless` guard, and the TanStack Start SSR shim. `provideContributions`, signal-based slots, and a self-owned `*extensionSlot` directive. ## The model in one pass [#the-model-in-one-pass] * A frontend **module** is a folder that ships a **manifest** — plain data plus lazy component references — from its public entry. There is no import-time `registry.register(...)`: manifests are inspectable without executing module code, deterministic, and testable as plain arrays. * An **extension point** is a typed token (`defineExtensionPoint`). Exporting one from a module's public entry is the frontend [`[ModuleContract]`](/docs/concepts/cross-module-communication): contributors import the token — an explicit, compile-checked, correctly-directed dependency — without pulling the owner's components into their chunk. * Every contribution carries a **`when` clause** (`{ module?, permission?, flag?, role? }`) evaluated against the [client-capability snapshot](/docs/concepts/client-capabilities). The vocabulary is the generated literal unions, and clauses are checked **strictly** against it: `when: { permission: "invocies.read" }` fails to compile instead of silently hiding the item. Declare only the axes your app has — an omitted axis rejects every use, so a [no-auth app](#no-auth-no-session-snapshot-yet) binding `{ module: ModuleName }` gets a compile error on any stray permission/flag/role clause. * The **registry** resolves once per snapshot: filter by `when` (a manifest-level `when` is ANDed into every contribution), then sort deterministically by `order`, then id. Contribution ids double as render keys, so resolution **throws if two co-visible contributions to one point share an id** — prefix ids with the module name (`"invoicing.create-invoice"`) to stay collision-free. A slot renders the resolved list; server render and client hydration see identical trees. Contribution visibility is a **read-only UX projection, never an enforcement boundary**. A hidden sidebar item is not a secured operation — the handler's own `[RequirePermission]`/`[FeatureGate]` gates every call server-side (see [Authorization](/docs/concepts/authorization)). A `when` clause names a capability; an **action** usually maps to one RPC method, whose requirements the server already exports. `canCall(rpcMethodInfo['invoices.approve'], capabilities)` decides from those — all required permissions and roles, the signed-in state — so a button stays in step with the handler without repeating its permission (see [TypeScript client › Method requirements](/docs/capabilities/transports/typescript-client#method-requirements-and-ui-gating)). ## What you import vs. what you own [#what-you-import-vs-what-you-own] The package ships the *machinery* with fixed semantics; the application owns the *points* and the shell — Elarion deliberately ships no UI kit and no router integration: | You import (fixed semantics) | You own (copy from the sample) | | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | | `defineExtensionPoint`, `defineModule`, `contribute`, `ItemOf`/`ContextOf` | Your extension points (`sidebarItems`, …) and payload types | | The `when` evaluator and its strict AND semantics | The kit instantiation binding your (generated or hand-authored) vocabulary | | `createContributionRegistry` (filter + deterministic order + id validation) | The app shell that renders each slot | | `createStaticCapabilities` (the no-snapshot `CapabilityReader`) | The real snapshot wiring once `elarion.session` exists | | `ContributionProvider`, `useContributions`, `` (`/react`) | Route composition and module discovery (the glob) | | `provideContributions`, `injectContributions`→`Signal` (`/angular`) | Slot rendering — an `@for` block, or a self-owned `*extensionSlot` directive | | `redirectUnless` route guard (`/tanstack-router`) | Everything else routing — TanStack's own API | | `canCall(rpcMethodInfo[method], capabilities)` — action gating from the RPC contract | Which actions you grey out or hide | Keeping the machinery imported is what preserves review isolation: the semantics live in the framework and are not re-reviewed (or silently forked) in every application. Keeping the points app-owned is the same rule as the backend: Elarion ships the `[ModuleContract]` mechanism, never your contracts. ## Wiring it up [#wiring-it-up] Bind the kernel once to the generated capability vocabulary, in the app's platform folder: ```ts title="platform/contributions.ts" import { createContributionKit, type ModuleManifest } from "@swimmesberger/elarion-contributions" import type { FlagName, ModuleName, PermissionName, RoleName } from "@/generated/session-client" export interface AppVocabulary { module: ModuleName permission: PermissionName flag: FlagName role: RoleName } export type AppManifest = ModuleManifest export const { defineModule, defineExtensionPoint, contribute } = createContributionKit() ``` Declare only the axes your application has: `when` clauses are checked strictly, and an omitted axis rejects every value. A backend without permissions/flags/roles binds `{ module: ModuleName }` and any stray `when: { permission: … }` is a compile error — see [No auth, no session snapshot yet](#no-auth-no-session-snapshot-yet) for the full recipe. Declare points where the slot's owner lives — the shell for a sidebar, a module for its own surface. The payload shape is deliberately **yours**: whatever your shell needs to render an entry (keep `to` a plain string so the point stays router-agnostic data — the shell is the one place that hands it to a router link): ```ts title="platform/points.ts" import type { LucideIcon } from "lucide-react" import { defineExtensionPoint } from "@/platform/contributions" export interface SidebarItem { readonly label: string readonly icon: LucideIcon readonly to: string } export const sidebarItems = defineExtensionPoint("platform.sidebar") ``` A module declares everything it adds in its manifest. A backend-paired module gates itself once at the manifest level, so disabling the backend module removes the whole frontend module: ```ts title="modules/invoicing/module.tsx" export const invoicingManifest = defineModule({ name: Modules.Invoicing, when: { module: Modules.Invoicing }, contributes: [ contribute(sidebarItems, [{ id: "invoices", label: "Invoices", icon: ReceiptText, to: "/invoices", order: 20, when: { permission: Permissions.invoices.read }, }]), ], }) ``` How manifests are discovered and handed to the registry is the composition root's job — see [React & app shells](/docs/concepts/frontend-modules/react) (and the same wiring in [Angular](/docs/concepts/frontend-modules/angular)). ## No auth, no session snapshot yet [#no-auth-no-session-snapshot-yet] A common adoption shape — self-hosted apps behind an authenticating reverse proxy, or a backend that has not shipped the `elarion.session` operation yet — has **no generated `session-client.ts`**. The model supports this first-class; nothing about it requires the generator. Hand-author the vocabulary with only the axes you have (module names mirroring the backend's `[AppModule]` markers), and use the shipped static reader instead of a hand-rolled one: ```ts title="platform/session.ts — no snapshot yet" import { createStaticCapabilities } from "@swimmesberger/elarion-contributions" /** Mirrors the backend [AppModule] names. Replace with the generated ModuleName when the snapshot lands. */ export const Modules = { Core: "core", AiAgent: "ai-agent" } as const export type ModuleName = (typeof Modules)[keyof typeof Modules] // Modules/permissions/roles default to "all"; flags default to none (fail-closed, like the evaluator). // Env-driven module toggles are one map away: export const caps = createStaticCapabilities({ modules: { core: true, "ai-agent": import.meta.env.VITE_MODULE_AI_AGENT_ENABLED !== "false" }, }) ``` ```ts title="platform/contributions.ts — module-only vocabulary" export interface AppVocabulary { module: ModuleName // No permission/flag/role axes: any `when: { permission: … }` anywhere is now a compile error, // so the vocabulary can't silently rot ahead of the backend. } export const { defineModule, defineExtensionPoint, contribute } = createContributionKit() ``` The migration seam is the point of this shape: `createStaticCapabilities` returns the same structural `CapabilityReader` the generated `SessionCapabilities` satisfies. When the backend ships the session operation, regenerate the client, re-export `Modules`/`ModuleName` from the generated file, widen `AppVocabulary` with the new axes, and swap `caps` for `createSessionCapabilities(snapshot)` — no module or manifest changes. ## Cross-module contribution [#cross-module-contribution] A module publishes a point from its public entry; another module imports the token and contributes. Payloads carry **lazy component references**, so the contributed UI stays in the contributor's chunk and downloads on first use: ```ts title="modules/invoicing/module.tsx" import { clientRowActions } from "@/modules/clients" // the Clients module's published token contribute(clientRowActions, [{ id: "invoicing.create-invoice", // module-prefixed: ids must be unique within the point label: "New invoice for this client", icon: FilePlus2, component: lazy(() => import("./components/CreateInvoiceForClient") .then((m) => ({ default: m.CreateInvoiceForClient }))), when: { permission: Permissions.invoices.write }, }]) ``` The slot owner renders whatever resolved — if Invoicing is disabled, the action simply never appears; if Clients is disabled, its slot never renders and the contribution is inert. Neither module sees the other's internals: the boundary is the public entry (`modules/{name}/index.ts` by convention; workspace packages with `exports` maps enforce the same rule at scale — the `ELMOD002` analog). ### Slot context: delivering what the point promises (`TContext`) [#slot-context-delivering-what-the-point-promises-tcontext] A point's second type parameter declares what the slot site supplies to every contribution — `void` for context-free slots like a sidebar. It is not advisory: reference it from the payload with `ContextOf`, and supply it through the slot's `context` prop, and the payload's signature, the point's declaration, and the slot site can never drift apart: ```tsx title="modules/stacks/points.ts — a detail page's tab strip" import type { ContextOf } from "@swimmesberger/elarion-contributions" export interface StackTabContext { readonly stack: Stack } export interface StackTab { readonly value: string readonly label: string /** ContextOf pins this signature to the point's declaration — the two cannot diverge. */ readonly component: (context: ContextOf) => ReactNode } export const stackDetailTabs = defineExtensionPoint("stacks.detailTabs") ``` ```tsx title="modules/stacks/StackDetailPage.tsx — the tab host" ( {tab.component(context)} )} /> ``` Everything a contribution needs from its host belongs **in the context — callbacks included**. When the host later has more to offer (say a "view log" callback beside `stack`), widen `TContext` at the point: every slot site and every `ContextOf`-typed payload follows by compile error, instead of the extra value being smuggled through a separate React context beside the model. Slots that render only inert parts (buttons, menu entries) and mount the payload's component later — at invocation — keep the context-free `render={(item) => …}` form and hand the context over at the call site; the Billing sample's client row actions do exactly that. ### Pattern: one navigation point, a desktop sidebar and a phone tab bar [#pattern-one-navigation-point-a-desktop-sidebar-and-a-phone-tab-bar] A phone shell (bottom tab bar + a "More" sheet) does not need a second navigation point. Keep the one `sidebarItems` point and let each contribution say how it ranks on a phone — the shell picks the tabs: ```ts title="platform/points.ts" export interface SidebarItem { readonly label: string readonly icon: LucideIcon readonly to: string /** Phone tab-bar rank (lower first). Unranked items live only under "More". */ readonly mobileTab?: number } ``` ```ts title="platform/mobile-nav.ts — pure, unit-testable" export function mobileTabs(visible: readonly T[], max = 4): T[] { return visible .filter((item) => item.mobileTab !== undefined) .sort((a, b) => a.mobileTab! - b.mobileTab!) .slice(0, max) } ``` Rank rather than flag: `useContributions` has already dropped what the user may not see, so a narrowly scoped role whose top-ranked areas are hidden falls through to the next ranked ones and still gets a full tab bar — a boolean `mobile: true` leaves gaps instead. Don't promote unranked items to fill the bar; the "More" sheet renders every visible item, grouped exactly like the desktop sidebar, so nothing becomes unreachable. The rank stays app data on an app-owned payload (ADR-0032) — Elarion ships no shell. ## Reference usage [#reference-usage] The [Billing sample's web app](https://github.com/swimmesberger/Elarion/tree/main/samples/Billing/web) is the living reference: module folders, the shell-owned sidebar point, the cross-module row-action point, snapshot-gated routes, and the composition root — start a new app by copying its app-owned half. ## See also [#see-also] * [Client capabilities](/docs/concepts/client-capabilities) — the snapshot and typed vocabulary `when` clauses evaluate against. * [Cross-module communication](/docs/concepts/cross-module-communication) — the backend boundary model this mirrors. * [ADR-0032](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0032-frontend-contribution-model.md) — decisions and non-goals (no micro-frontends, no C#-declared UI, no UI kit, no bespoke router). # React & app shells (/docs/concepts/frontend-modules/react) The `/react` sub-export binds the [contribution model](/docs/concepts/frontend-modules) to React: `ContributionProvider` supplies the registry, `useContributions(point)` returns the resolved list, and `` renders a point with typed context. The `/react` bindings call hooks, so they must resolve to **your app's single React instance**. Vite's dependency optimizer can pre-bundle the package's subpath exports against a second React copy (they are discovered late, deep in the module graph), and the failure reads like an app bug, not a config gap: ``` Invalid hook call. Hooks can only be called inside of the body of a function component TypeError: Cannot read properties of null (reading 'useContext') at useContributions (@swimmesberger_elarion-contributions_react.js) ``` If you see this, add both hints to `vite.config.ts` (and clear `node_modules/.vite`): ```ts title="vite.config.ts" resolve: { dedupe: ["react", "react-dom"] }, optimizeDeps: { include: [ "@swimmesberger/elarion-contributions", "@swimmesberger/elarion-contributions/react", "@swimmesberger/elarion-contributions/tanstack-router", ], }, ``` There is no package-side lever that prevents this — Vite does not consult peer-dependency metadata when pre-bundling — so the sample ships this config and so should you. ## The composition root: discover manifests, register routes [#the-composition-root-discover-manifests-register-routes] Two different jobs meet at the composition root, and the recommended split treats them differently: * **Manifests are discovered** with a Vite glob. The high-frequency change — a new sidebar item, tab, section, or a route-less module — appears with zero central edits. * **Routes are registered statically**, one typed line per route-owning module — the same grain as a backend host adding a `ProjectReference`. This keeps TanStack Router's full inference; a glob-composed tree types as `AnyRoute[]` and silently degrades far more than navigation (see the callout below). The file layout matters because modules call `getParentRoute: () => rootRoute` while the composition root imports the modules — so `rootRoute` must live in its **own** file or the two form an import cycle: ```ts title="platform/router.tsx — owns the root route, imported by every module" import { createRootRouteWithContext } from "@tanstack/react-router" import { createRouteGuards } from "@swimmesberger/elarion-contributions/tanstack-router" export interface RouterContext { readonly caps: SessionCapabilities } export const rootRoute = createRootRouteWithContext()({ component: AppShell }) export const { redirectUnless } = createRouteGuards() ``` ```ts title="platform/modules.ts — what a module's public entry default-exports" import type { AnyRoute } from "@tanstack/react-router" import type { AppManifest } from "@/platform/contributions" export interface AppModule { readonly manifest: AppManifest /** The route subtrees this module owns; empty for a UI-only module. */ readonly routes: readonly AnyRoute[] } ``` A module bundles its manifest with the routes it owns — `satisfies` (not a type annotation, which would widen to `AnyRoute[]`) keeps the routes' concrete types for the static registration: ```ts title="modules/invoicing/index.ts" const invoicingModule = { manifest: invoicingManifest, routes: [invoicingRoute] } satisfies AppModule export default invoicingModule ``` ```tsx title="app.tsx — the composition root" import { createRouter } from "@tanstack/react-router" import clients from "@/modules/clients" import invoicing from "@/modules/invoicing" import { rootRoute } from "@/platform/router" import type { AppModule } from "@/platform/modules" // Manifest discovery: compile-time (Vite expands the glob into static imports), deterministic, zero // central edits for new contributions. const discovered = import.meta.glob("./modules/*/index.ts", { eager: true, import: "default" }) export const appModules: ReadonlyArray = Object.values(discovered) // Route registration: one typed line per route-owning module. const routeTree = rootRoute.addChildren([indexRoute, ...clients.routes, ...invoicing.routes]) export const router = createRouter({ routeTree, context: { caps: undefined! } }) declare module "@tanstack/react-router" { interface Register { router: typeof router } } ``` The entry point then wires **both** consumers of the capability snapshot in one place — the registry (for slots) and the router context (for `redirectUnless` guards): ```tsx title="main.tsx — one snapshot gates contributions and routes alike" import { createContributionRegistry } from "@swimmesberger/elarion-contributions" import { ContributionProvider } from "@swimmesberger/elarion-contributions/react" import { loadCapabilities } from "@/platform/session" import { appModules, router } from "./app" const caps = await loadCapabilities() // the /session snapshot (see Client capabilities) const registry = createContributionRegistry(appModules.map((m) => m.manifest), caps) createRoot(document.getElementById("root")!).render( ) ``` You *can* compose routes from the glob too — `rootRoute.addChildren(appModules.flatMap((m) => m.routes))` — and get zero-edit route discovery. Know the full price: the tree types as `AnyRoute[]`, so **`Link to` loses its literal union, and `useLoaderData`/`useParams` collapse to untyped fallbacks** — every consumer of route data, not just navigation, and under `noImplicitAny` a loader-using app surfaces dozens of errors. The workable escape is registering the router as `AnyRouter` (so `to`/`params` fall back to `string` instead of erroring), which trades away typed routing app-wide. Teams that don't use route loaders sometimes accept this deliberately; make it a decision, not a surprise. ## The approach: a modular sidebar [#the-approach-a-modular-sidebar] The division of labor for any shell surface: the **framework** ships the mechanics (the registry, `when` filtering, the slot bindings), the **app** owns the point's payload shape and one file of look, and **modules** supply data. The shell renders whatever resolved — it never knows the contributors, so it never changes when a module is added, and a disabled module's entries are simply absent. The integration is always the same single move, whatever the UI kit: **wherever your shell would map a hard-coded array of nav items, map `useContributions(point)` instead.** With plain elements: ```tsx title="platform/AppShell.tsx" import { Link, Outlet } from "@tanstack/react-router" import { useContributions } from "@swimmesberger/elarion-contributions/react" import { sidebarItems } from "@/platform/points" export function AppShell() { const items = useContributions(sidebarItems) // filtered by `when`, deterministically ordered return (
) } ``` ## With shadcn/ui's Sidebar [#with-shadcnuis-sidebar] [shadcn/ui's Sidebar](https://ui.shadcn.com/docs/components/sidebar) renders its menu from an items array in every one of its examples — that array is exactly where the contributions go. Add the component (`npx shadcn@latest add sidebar`), keep its structure, and swap the hard-coded `const items = [...]` for the resolved contributions: ```tsx title="platform/AppSidebar.tsx" import { Link } from "@tanstack/react-router" import { useContributions } from "@swimmesberger/elarion-contributions/react" import { Sidebar, SidebarContent, SidebarGroup, SidebarGroupContent, SidebarGroupLabel, SidebarMenu, SidebarMenuButton, SidebarMenuItem, } from "@/components/ui/sidebar" import { sidebarItems } from "@/platform/points" export function AppSidebar() { const items = useContributions(sidebarItems) // was: a hard-coded items constant return ( Application {items.map((item) => ( {item.label} ))} ) } ``` The shell wraps it exactly as shadcn documents — `
` as the root route's component — and collapsing, the mobile sheet, and theming all come from shadcn untouched. Sidebar *sections* are the same idea one level up: either group by a field your payload carries (`group: "main" | "admin"` on the item type, one `` per group), or define one extension point per section when the sections themselves are the contract between shell and modules. A module's sidebar entry is then one manifest item (the Invoicing example on the [concept page](/docs/concepts/frontend-modules)) — label, icon, target, `order`, `when` — and nothing else: no shell edit, no registration call. The same pattern serves any shell surface (top nav, settings sections, dashboards, command palettes): define a point, render `useContributions`/`` where it lives. The shell's *look* is deliberately yours — copy the sample's `AppShell` or shadcn's blocks as a starting point rather than importing one from Elarion (the no-UI-kit non-goal). # Routing (/docs/concepts/frontend-modules/routing) Routes are **module-owned router subtrees**, composed with the router's own API — Elarion adds no routing machinery (an ADR-0032 non-goal). With TanStack Router, each module exports the routes it owns (`routes: readonly AnyRoute[]` — real modules usually own several) and the composition root registers them statically, as shown on the [React & app shells page](/docs/concepts/frontend-modules/react#the-composition-root-discover-manifests-register-routes). Each module's pages are their own chunk (`lazyRouteComponent`); a disabled module's chunk never downloads. ## The `redirectUnless` guard [#the-redirectunless-guard] The one piece the framework does own is the guard semantics: the `/tanstack-router` sub-export ships `redirectUnless`, a `beforeLoad` guard that evaluates **the same `when` clause** as a contribution — same AND, same fail-closed behavior — so a route and its sidebar item can never gate differently. Bind it to your vocabulary once, next to the root route: ```ts title="platform/router.tsx" import { createRouteGuards } from "@swimmesberger/elarion-contributions/tanstack-router" export const { redirectUnless } = createRouteGuards() ``` ```ts title="modules/invoicing/module.tsx" export const invoicingRoute = createRoute({ getParentRoute: () => rootRoute, path: "/invoices", // The route-level mirror of the sidebar item's `when`: a deep link into a hidden module bounces home. beforeLoad: redirectUnless({ module: Modules.Invoicing, permission: Permissions.invoices.read }, "/"), component: lazyRouteComponent(() => import("./InvoicesPage"), "InvoicesPage"), }) ``` ## TanStack Start (SSR) [#tanstack-start-ssr] The sample is a plain Vite SPA. On TanStack **Start**, two of its build steps assume file-based routing and fail against a purely code-composed tree: * the router-generator errors without a `src/routes/` directory (`ENOENT: scandir '…/src/routes'`), and * the SSR-manifest plugin builds from the *generated* route tree (`start-manifest-plugin: Cannot convert undefined or null to object`). The production-proven shim: keep a **minimal file root** to satisfy the generator and the manifest, compose the real module tree in code inside the router factory, and gitignore the generated `routeTree.gen.ts`: ```tsx title="src/routes/__root.tsx — satisfies Start's generator; not used at runtime" import { createRootRoute } from "@tanstack/react-router" export const Route = createRootRoute() ``` ```ts title="src/router.tsx — the real, module-composed tree" export function getRouter() { const routeTree = rootRoute.addChildren([indexRoute, ...clients.routes, ...invoicing.routes]) return createRouter({ routeTree, context: { caps, queryClient, registry } }) } ``` On Start, the *real* root route (`platform/router.tsx`) also owns the SSR document shell — ``, `HeadContent`, `Scripts`, and the `` around the outlet — since no file route renders it. The shim is sound while the app ships as a single bundle: the root-only manifest carries no route chunks, so it has no practical effect. An app that wants Start's per-route code-splitting should instead describe the module-owned route files to the generator with TanStack's virtual file routes (`virtualRouteConfig`), so the generated tree and the SSR manifest stay real. Registry resolution is deliberately SSR-pure: the same (manifests, snapshot) input yields the same resolved lists, so a server render and the client hydration paint identical trees — build the registry once per request from that request's snapshot and hand it to both the provider and the router context. `redirectUnless` guards run in `beforeLoad` on the server exactly as in the SPA. # Handlers (/docs/concepts/handlers) A handler is the primary application use-case unit. It receives a request object and returns a response, usually a [`Result`](/docs/concepts/results-and-errors). Handlers contain business orchestration — not transport, serialization, or HTTP concerns. ## What is a use case? [#what-is-a-use-case] A **use case** is a single thing your application can *do*, named from the user's point of view: "get a client", "create an order", "cancel a subscription". It is one complete unit of behavior — it takes some input, does the work (reads or changes data, applies the rules), and produces a result. That is the whole idea. It is deliberately a smaller thing than a "service", a "controller", or a "screen". A use case is **not** an HTTP endpoint, a database table, or a class bundling loosely related methods — it is exactly one action. If you can phrase it as a short verb-plus-noun — *get client*, *list invoices*, *approve request* — it is most likely a single use case. If you have read about *Clean Architecture*, *Hexagonal/Ports-and-Adapters*, or *vertical slice* designs, a use case is the same thing those call an **interactor**, an **application-service method**, or a **slice**. You need none of that background to use Elarion — the plain definition above is all that matters here. ### How a use case materializes in Elarion [#how-a-use-case-materializes-in-elarion] In Elarion, one use case is **one handler class**. The three parts of the definition map directly onto the class: * the **input** is the handler's request type (the nested `Query` or `Command`), * the **work** is the body of `HandleAsync`, * the **output** is the `Result` it returns. Because the handler is a plain class — not tied to HTTP, JSON-RPC, MCP, or any specific database framework — the *same* use case can be exposed over several [transports](/docs/capabilities/transports) or called straight from a test, unchanged. The `GetClient` handler below is the entire "get a client" use case: input (`Query`), work (the EF Core query), output (`Result`). ```csharp using Elarion.Abstractions; using Microsoft.EntityFrameworkCore; [Handler("clients.get")] public sealed class GetClient(AppDbContext db) : IHandler> { public sealed record Query(Guid Id); public sealed record Response(Guid Id, string Name); public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var client = await db.Clients .Where(c => c.Id == query.Id) .Select(c => new Response(c.Id, c.Name)) .FirstOrDefaultAsync(ct); if (client is null) { return AppError.NotFound($"Client {query.Id} was not found."); } return client; } } ``` A handler may also be `internal`, with an internal request and response: the generators register and expose it exactly like a public one, so the module-private services it injects can stay internal too. ## The contract [#the-contract] A handler implements `IHandler`: ```csharp public interface IHandler { ValueTask HandleAsync(TRequest request, CancellationToken ct); } ``` `ValueTask` keeps synchronous and cached paths allocation-free. Constructor parameters are injected by DI through the generated handler factory. ## Conventions [#conventions] The generators discover and wire handlers from their shape and location: * The class lives **under a module namespace** so the module owns its registration. * It implements `IHandler`. * For transports (JSON-RPC, HTTP, MCP) the handler returns `Result`; the request and response types are read from the `IHandler<,>` interface itself, so they may be declared anywhere — nesting them (as `Command`/`Query`/`Response`) is an organizational convention, **not** a requirement. See [JSON-RPC usage](/docs/capabilities/transports/json-rpc). A handler exposes itself over the dispatcher transports with `[Handler]`. The operation name is **optional**: with `[Handler("clients.get")]` you name it explicitly; with a bare `[Handler]` the name is inferred by convention as `{module}.{operation}`, where `operation` is the handler type name with a trailing `Handler`/`Command`/`Query`/`Request` suffix removed and the rest camelCased — so a `CreateClient` handler in the `Clients` module becomes `clients.createClient`. Prefer an explicit name for stable public or wire-facing contracts. The handler registration generator emits an `Add{HandlerName}()` method and aggregates them into the module's `Add{Module}Handlers()` method. You never register a handler by hand. ### Lifetime and telemetry [#lifetime-and-telemetry] A handler is registered **scoped** by default — one instance per dispatch scope, the classical unit-of-work-per-message shape. Two opt-in declarations tune the hot path (ADR-0066): * `[Handler(Scope = ServiceScope.Singleton)]` — the same vocabulary as `[Service(Scope = …)]` — removes scope participation from dispatch entirely: the chain is built once from the root provider. It is compile-time verified: every constructor dependency must be provably singleton (`ELSG011`/`ELSG012` — the framework knows its own service lifetimes and reads `[Service(Scope = …)]` declarations in the compilation; anything unverifiable is an error, deliberately without an escape hatch), and the pipeline must not attach scope-dependent features such as transactions, idempotency, authorization, validation, caching, or auditing (`ELSG013`). Per-caller log enrichment is definitionally unavailable on a singleton handler; its span and execution metric remain. `[Resilient]` composes fine. * `[HandlerTelemetry(HandlerTelemetryMode.None)]` — on the handler, the module class, or the assembly (nearest wins) — makes the generator not emit the observability decorator at all: no span, metric, enrichment, or log scope, and no decorator object per call. A cold handler inside an opted-down module re-enables by declaring `Full` on itself. Failures are unaffected. Both exist for high-rate dispatch (a game-server-like connection); a classical web handler keeps the defaults. See [the low-allocation dispatch profile](/docs/capabilities/connections/low-allocation). ## Request-driven server streams [#request-driven-server-streams] A **cold, request-driven** operation with a deferred response implements `IStreamHandler`, not `IHandler`. Its upfront `Result>` accepts or rejects before a transport commits its response; thereafter items remain lazy and completion, cancellation, and faults belong to the enumerator. Use it when one request owns one response sequence; see [request-driven server streaming](/docs/capabilities/transports/server-streaming) for the full choice between this contract, client events, actor-owned `StreamHub`, and connections. Generated stream registration is module-gated like unary handlers, but has an independent pipeline. A mixed `[DecoratorList]` retains only decorators implementing `IStreamHandler<,>` and preserves their relative order. Authorization, feature gates, validation, observability, and context enrichment apply; caching, idempotency, transactions, audit, and unary resilience do not. Use `StreamHandlerInvoker.InvokeAsync` in a typed custom transport: its accepted invocation owns the DI scope until enumeration completes, faults, cancels, or is disposed. For SSE, bind the request in a direct minimal-API `MapGet` lambda and return `ElarionHttpResults.ToStreamResult(request)`. Keeping `MapGet` in the host compilation leaves route and query binding to ASP.NET Core (hand-written call sites are the ones its Request Delegate Generator can compile ahead of time in an AOT host); the lazy result owns decorated handler invocation, canonical JSON, startup-error translation, and native `TypedResults.ServerSentEvents` framing. ```csharp endpoints.MapGet("reports/{reportId}/export", static (Guid reportId) => ElarionHttpResults.ToStreamResult(new(reportId))); ``` JSON-RPC and MCP remain single-response. This cold request response is distinct from an actor `StreamHub`, which is the hot, sequenced, resumable model. ## Command vs. query [#command-vs-query] A request declares its CQRS kind by implementing a marker interface (optional, but it is the only thing the framework reads — naming and nesting carry no semantic weight): * **`ICommand`** — a state change. Maps to HTTP `POST`. * **`IQuery`** — a read. Maps to HTTP `GET`. ```csharp public sealed record Command(string Name) : ICommand; // CreateClient.Command public sealed record Query(Guid Id) : IQuery; // GetClient.Query ``` The marker is read structurally at compile time, so it drives HTTP verb inference, decorator generic constraints (`where TRequest : ICommand`), and runtime branching (`request is IQuery`) — see [decorator pipelines](/docs/concepts/decorator-pipelines). Naming the nested type `Command`/`Query` remains a useful readability convention, but a request without the marker is treated as kind-less. ### Self-typed markers: declaring the response type [#self-typed-markers-declaring-the-response-type] Each marker also has a self-typed generic form that additionally declares the request's success response type — `ICommand`, `IQuery`, `IRequest`, and `IStreamRequest` for stream requests: ```csharp public sealed record Command(string Name) : ICommand; // handler returns Result public sealed record Query(Guid Id) : IQuery; // handler returns Result ``` Requests carrying the self-typed form get **fully inferred dispatch** at every typed entry point — `IHandlerSender.SendAsync`, `HandlerInvoker`, `StreamHandlerInvoker`, and `ConnectionHandlerInvoker` all accept the request alone and infer both generic arguments: ```csharp var result = await sender.SendAsync(new GetClient.Query(id), ct); // instead of: await sender.SendAsync(new(id), ct); ``` Inference is purely compile-time — dispatch stays statically typed through the same `IHandler<,>` resolution with no reflection, registry, or boxing of class requests. One caveat for value types: the inferred overloads take the request through its marker interface, which boxes a `readonly record struct` request per call (C# constraints do not participate in inference). A hot value-type request should use the explicit-generic overload — `invoker.InvokeAsync(move, ct)` — which dispatches it unboxed (ADR-0066). The declared response type must match the handler's `Result`; the marker analyzer enforces both invariants at build time (`ELREQ001` when `TSelf` names a different type, `ELREQ002`/`ELREQ003` when a handler's response drifts from the declared `TResponse`/`TItem` — see [Diagnostics](/docs/reference/diagnostics#elreq--self-typed-request-markers)). Prefer the self-typed form for requests you dispatch by type (cross-handler sends, custom transports, connection codecs); the plain markers remain sufficient for requests only reached through generated transports. ## Accessing data [#accessing-data] Handlers query and persist through the concrete `AppDbContext`, injected like any other dependency. Elarion does **not** prescribe a repository layer — the [EF Core source generator](/docs/capabilities/entity-framework) generates the context's `DbSet`s and entity configuration so the `DbContext` *is* your data-access surface: ```csharp // Read: query the generated DbSet directly with EF Core async LINQ var client = await db.Clients .Where(c => c.Id == query.Id) .Select(c => new Response(c.Id, c.Name)) .FirstOrDefaultAsync(ct); // Write: add/modify entities and persist db.Clients.Add(new Client { Id = Guid.CreateVersion7(), Name = command.Name }); await db.SaveChangesAsync(ct); ``` The database is application logic, accessed directly — not an abstraction to hide behind. You abstract intent-only dependencies (sending email → `IEmailSender`); you do **not** abstract the database, because you depend on its specifics: constraints, indexes, raw SQL. So there is no repository *and* no context interface — handlers inject the `AppDbContext` itself, which lives in the application's shared persistence layer alongside its `[EntityConfiguration]` classes and migrations. See [Entity Framework Core](/docs/capabilities/entity-framework) for how the context's `DbSet`s and entity configuration are generated. Wrapping each table in a hand-written `IClientRepository` adds a layer that the `AppDbContext` already provides — with full LINQ, projections, and EF Core change tracking. Reach for a dedicated abstraction only when a query genuinely needs to be reused or hidden behind a domain operation. ## Keep handlers transport-agnostic [#keep-handlers-transport-agnostic] A handler should not know whether it was invoked over JSON-RPC, HTTP, a scheduled job, or a test. It returns a `Result`; the host decides how to map success and `AppError` failures onto the wire. Cross-cutting behavior — logging, validation, transactions, caching, resilience — belongs in [decorators](/docs/concepts/decorator-pipelines), not inside the handler body. ## Calling a handler from other code [#calling-a-handler-from-other-code] In-process, **call handlers typed-directly** — you keep compile-time safety, cross no serialization boundary, and still run the full decorator pipeline. Typed paths, in rough order of preference: * **Inject `IHandler>`** straight into another handler, a `[Service]`, or a test and call `HandleAsync`. The handler resolves fully decorated from DI. * **`IHandlerSender.SendAsync(request, ct)`** — a typed *mediator send*: it resolves the handler **by type** from the ambient scope (your transaction), so one injection dispatches several handlers without naming each `IHandler<,>`. Register it with `AddElarionHandlerSender()`. This is the in-process, in-transaction request/reply primitive (the typed replacement for the removed `IDomainEventBus.RequestAsync`). * **`HandlerInvoker.InvokeAsync(provider, request, …)`** when you only hold the root `IServiceProvider` — a custom transport, a gRPC/CLI adapter, a background job. It creates a seeded per-call scope, resolves the decorated handler, invokes it, and disposes the scope. * **`[GenerateModuleApi]`** for calling *another module* — a generated, typed facade over that module's handlers that a `[ModuleContract]` implementation invokes by method (still typed, still the full pipeline, no wire). This is the sanctioned cross-module path; see [Cross-module communication](/docs/concepts/cross-module-communication). Prefer these everywhere in application code. The whole point is that a rename or a signature change is a **compile error**, not a runtime surprise — the opposite of dispatching by string. ### The named bus is for transports, not application code [#the-named-bus-is-for-transports-not-application-code] `HandlerDispatcher` — the [named request/reply bus](/docs/capabilities/transports) — maps an operation **name** (a string) to a handler. It exists so that **name-keyed transports** (JSON-RPC and MCP, whose wire carries a method/tool name) can reach a handler without referencing its type. HTTP does *not* use it: a `[HttpEndpoint]` route resolves its handler typed-directly (`IHandler<…>` from the request services), because the route already pins the type at generation time. The bus is a registered singleton, so you *can* inject it and call `DispatchAsync(name, request, scope, ct)` — but it takes the request as `object` and returns `Result` (the value boxed, no compile-time response type), so you trade away type safety and the schema. Reach for it from application code only in the rare case where you must dispatch by a **dynamic or string-supplied name** and genuinely cannot reference the handler's type — the niche the classic *mediator* fills. To decouple one module from another's internals, use a `[ModuleContract]` (typed) instead: same "don't reference the handler" benefit, without losing compile-time safety. The [event bus](/docs/capabilities/events) is **pub/sub-only** (ADR-0010): `PublishAsync` for fan-out notifications, never request/reply. For a typed in-process reply (what `IDomainEventBus.RequestAsync` used to do) use `IHandlerSender`/`IHandler` above — not the event bus, and not the named bus. # Idempotency (/docs/concepts/idempotency) Idempotency in Elarion makes a **command handler** safe to retry: a client that times out and re-sends, or a duplicate that arrives concurrently, executes the operation **at most once** and gets back the first request's result. You annotate the handler with `[Idempotent]`; a generated decorator owns a single database transaction in which it writes the idempotency key **atomically with the handler's business writes**, lets a unique constraint reject a duplicate, and replays the stored result — under every transport identically. It is the same declarative shape as [authorization](/docs/concepts/authorization) and [feature flags](/docs/concepts/feature-flags): a class-level attribute, a generated decorator, a seam-in-Abstractions / impl-in-package split. ## The core guarantee [#the-core-guarantee] The key is stored and checked **atomically with the operation itself** — the safe pattern. A check-then-act approach races: two requests with the same key can both pass the check and both execute. Instead, the decorator inserts the key **in the same transaction** as the business writes and relies on a database **unique constraint** to reject the duplicate: ```text BEGIN INSERT key ── unique (scope, owner, key), ON CONFLICT DO NOTHING ├─ inserted → run handler (business writes share the tx) → mark completed → COMMIT (atomic) └─ conflict → key already completed → replay the stored result crash before COMMIT → nothing persists → the key is retryable ``` Because the key row and the business rows commit or roll back together, there is no window where one lands without the other, and — since the pending marker is never committed on its own — a crash leaves nothing behind and **needs no reaper**. This is the model the author of Stripe's reference implementation recommends whenever a handler only mutates local (ACID) database state. ## Usage [#usage] ```csharp [Idempotent] public sealed class CreatePaymentHandler : IHandler> { … } ``` Attribute options (all optional): | Option | Default | Meaning | | ------------------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `RetentionHours` | `24` | How long a completed key stays replayable before purge: 1 to 1 000 000 hours, or `IdempotentAttribute.Permanent` (never purged; see below). | | `KeyRequired` | `true` | Reject a request with no key (`400`), rather than run without idempotency. | | `Scope` | `CurrentUser` | Key namespace — per authenticated user, or `Global`. | | `Fingerprint` | `true` | Store a request hash and reject reusing the key with a **different** body (`422`). | | `ConflictBehavior` | `Conflict` | A concurrent in-flight duplicate fails fast with `409`, or `WaitThenReplay`. | | `StoreFailures` | `None` | Also store & replay **definitive** failures (`Definitive`), via a savepoint. | | `Operation` | none | Share one key space with every handler that names the same operation (see below). | ### One operation, two commands [#one-operation-two-commands] A key belongs to one handler: the store discriminates it by the handler's request type. When two commands do the same thing by two routes — finalising a draft directly, or by approving it, which finalises — a retry must replay whichever route ran first. Name one operation on both: ```csharp [Handler("invoices.finalise"), Idempotent(Operation = "invoices.finalise", Scope = IdempotencyScope.Global)] public sealed class FinaliseInvoice(…) : IHandler> { … } [Handler("invoices.approve"), Idempotent(Operation = "invoices.finalise", Scope = IdempotencyScope.Global)] public sealed class ApproveInvoice(…) : IHandler> { … } ``` * A key used with `invoices.finalise` replays its stored answer through `invoices.approve`, and the other way round; the second handler does not run. * The handlers of one operation replay each other's answers, so they must store the same success type and scope and match keys alike: the same `Result`, `Scope` and `Fingerprint`, or the build fails with `ELIDEM006`. * The fingerprint is the hash of the request's JSON. A retry through the other command matches when both requests serialize alike (here both carry `id` and `expectedVersion`); a different request is `idempotency.key_reused`, as it is within one handler. With differently shaped requests, either make them alike or set `Fingerprint = false` on both. ### How long a key lasts [#how-long-a-key-lasts] Retention decides what a late retry gets. Within it, the retry replays the stored answer. After the purge, the key is unknown, so the handler runs again and its own state check decides. For a command that cannot run twice (an invoice that is already finalised), that is an error where the retry expected the first answer. * Choose a retention longer than the latest retry you expect: a client's offline queue, a mobile app resumed days later, a batch that is re-run. * `RetentionHours = IdempotentAttribute.Permanent` keeps the key for good: the store writes no expiry and the purge skips the row. Each such key keeps one row and one stored answer forever, so use it for operations that happen a bounded number of times per entity (finalising, cancelling), not for every create. * Keep the key on your own row instead when the key is domain data: shown to a user, audited, or queried with the entity. The framework store is a replay cache keyed by `(operation, scope, owner, key)`; it knows nothing of your tables. ## When does a command need it? [#when-does-a-command-need-it] **Default: model the duplicate away with a natural key before reaching for machinery.** Most creates in a CRUD application have a natural identity if you ask *"what makes two of these the same?"* — often composite: `(TenantId, Email)`, `(CustomerId, ExternalOrderNo)`, `(InvoiceId, LineNo)`. Declare it as a **unique constraint/index** and translate the violation into a friendly `AppError.Conflict` in the handler (Tier-2 validation: the constraint *is* the TOCTOU-safe check — a pre-insert lookup alone would race). This is the default because it deduplicates **facts, not just requests**: it catches the same client retrying, but also the second browser tab (which carries a *different* idempotency key and walks straight past `[Idempotent]`), double data-entry by another user, and the import job run twice. It needs no client cooperation and costs nothing per call. Escalate to `[Idempotent]` when you can **name the reason** — the deviations, ranked by how often they occur: | Reason to escalate | Example | Why the constraint isn't enough | | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | **No natural key exists** — identical submissions are legitimately distinct | "add a note", an order where the same basket twice is a real second order | Only the *client* knows whether it's a retry; only a client key can dedup. | | **Replay beats rejection** — the retrying client should get the created resource, not an error | checkout confirmation after a timeout | A constraint *rejects* the retry (409, client must re-fetch); `[Idempotent]` *replays* the first success. | | **Money / non-repeatable effects** | payments, provisioning | The Stripe case — use `[Idempotent]` here even *with* a natural key (the key gives replay; the constraint backstops every non-retry duplicate). | | **Increment / accumulate** | "add credit", "consume quota" | Deltas never converge; a retry double-applies. (Or redesign to set-style.) | And the shapes that need **neither**: set-style updates ("rename", "set address" — last-write-wins converges), deletes by id (the second delete finds nothing; decide whether NotFound-on-retry is acceptable), and queries (idempotent by definition; `ELIDEM002` warns on non-commands). **The default path needs no justification; every `[Idempotent]` should be able to say which row of this table it is.** Two things follow from annotating: * **The client must send the key — and reuse it across retries of the same submit.** The `Idempotency-Key` header on HTTP, `params._meta` on JSON-RPC; minted when the user *intends* the action (form render, submit click), not per attempt — a key regenerated on every retry deduplicates nothing. The framework cannot invent the key: only the client can distinguish "retry of the same submit" from "a second, deliberate, identical command". `[Idempotent]` enforces and advertises the contract (the OpenAPI transformer marks the operation); it does not remove the client's half. * **Protecting the command protects the whole chain at its source.** A replayed command returns its stored result *without re-running the handler*, so it never re-publishes its integration events — the downstream consumers, PDFs, and emails of a client retry simply never happen twice. Consumers then only need to survive *delivery-level* duplicates, which the [default-on inbox](/docs/capabilities/events/consuming-events#handling-duplicates) absorbs. ## Behavior and status codes [#behavior-and-status-codes] The decorator short-circuits with `AppError`s that map to the IETF `Idempotency-Key` header draft and Stripe: * **Missing key** (when `KeyRequired`) → `400`, code `idempotency.key_required`. * **Concurrent in-flight duplicate** → `409`, code `idempotency.in_progress` (Conflict mode, the industry default) — the client retries shortly and then replays. `WaitThenReplay` blocks on the key lock and replays instead — but the wait is still **bounded** (a longer `lock_timeout` than the fast-fail path), so a stuck winner can never pin the duplicate's database connection forever; on timeout the duplicate degrades to the same `409`. * **Same key, different request body** → `422`, code `idempotency.key_reused` (fingerprint mismatch). Each answer carries its specific code (declared on every `[Idempotent]` operation's error contract), so a client branches on the code instead of the message. * **Retried after completion** → the stored result is replayed, without re-running the handler. **Success-only by default.** A failed result rolls back the transaction — discarding the key — so the same key stays retryable (a transient failure can succeed on retry). This matches the modern consensus (Stripe v2, AWS Powertools). Set `StoreFailures = Definitive` to also store and replay *definitive* failures (`Validation`, `BusinessRule`, `NotFound`, `Forbidden`) via a savepoint that discards the business writes while keeping the key row — one transaction, no atomicity loss; transient failures stay retryable. ## Transport-neutral — one layer, every transport [#transport-neutral--one-layer-every-transport] Idempotency is a pipeline decorator over `IHandler<,>`, the one code path every transport dispatches into, so HTTP idempotency keys and the messaging **inbox pattern** are the *same* mechanism, differing only in where the key comes from. The key is captured at the boundary into the dispatch-scope rail (like the current user): * **HTTP** — the `Idempotency-Key` header (or legacy `X-Idempotency-Key`), via `app.UseElarionIdempotencyKey()`. * **JSON-RPC / MCP** — `params._meta["dev.wimmesberger.elarion/idempotencyKey"]` (a per-call key, batch-correct); the HTTP header is accepted as single-call sugar **only for a single (non-batch) request**. The header applies to the whole HTTP request, so it cannot key a batch's distinct operations — a JSON-RPC batch that carries an `Idempotency-Key` header is rejected with `400` and a JSON-RPC `Invalid Request` (`-32600`) error; each batch item must carry its own key at `params._meta` instead. * **In-band** — a request implementing `IIdempotentRequest` carries its own key (AIP-155 style) — the natural source for event consumers. ## Generated TypeScript client [#generated-typescript-client] The JSON-RPC schema export marks each `[Idempotent]` operation with `"idempotent": true`, and the generated TypeScript client **attaches an idempotency key by default** to exactly those operations — a `crypto.randomUUID()` at `params._meta`, so a retry is deduplicated server-side. It only keys operations the server actually honors (queries never get a key), and it is fully overridable: ```ts createRpcApi({ fetch, idempotency: { enabled: true, generateKey: () => crypto.randomUUID() }, // on by default }) rpc.clients.create(params) // auto key on an idempotent op rpc.clients.create(params, { idempotencyKey: 'k-1' }) // supply your own (see retry note) rpc.clients.create(params, { idempotencyKey: false }) // opt this call out ``` **Retry lives above the client, and the retry layer owns key stability.** The generated client attaches keys but does **not** retry — that belongs to your data layer (TanStack Query's `retry`, a fetch middleware, …). For an idempotent retry to work, every attempt must reuse the *same* key, so generate it once at the operation boundary and pass it in (a key auto-generated per `call()` would change on each retry and defeat the purpose): ```ts const key = crypto.randomUUID() useMutation({ retry: 3, // TanStack owns retry mutationFn: (vars) => rpc.clients.create(vars, { idempotencyKey: key }), }) ``` ## Multi-node concurrency — no distributed lock [#multi-node-concurrency--no-distributed-lock] When two application nodes process the same key at once, they contend on the **same PostgreSQL row**, so the database itself is the cross-node serialization point — no Redis/Redlock. The unique constraint on `(operation, scope, owner, key)` makes one INSERT win; the other blocks on the uncommitted index entry and then either replays (the winner committed) or proceeds (the winner rolled back). This is exactly how MassTransit, NServiceBus, Stripe, and AWS handle it. A short `lock_timeout` (Npgsql) turns the wait into a fast `409` for the `Conflict` behavior. The key is discriminated by **operation** (the handler's request type) as well as scope/owner/key, so two different `[Idempotent]` handlers that happen to receive the same client-supplied key never collide on one record — the second operation claims its own row rather than replaying the first operation's stored response. ## Wiring [#wiring] Core ships an in-memory store for dev/test; the durable, atomic guarantee comes from the EF Core store: ```csharp // Register the durable store, the EF unit of work, and the retention purge worker. builder.Services.AddElarionIdempotencyEntityFrameworkCore(); // Or tune the purge worker's cadence: builder.Services.AddElarionIdempotencyEntityFrameworkCore( o => o.PollingInterval = TimeSpan.FromMinutes(30)); // Map the table (or call ApplyElarionIdempotencyKeys in OnModelCreating) and own the migration. [GenerateDbSets] [GenerateElarionIdempotencyKeys(SnakeCase = true)] public sealed partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } // Capture the HTTP header into the request scope (after authentication). app.UseElarionIdempotencyKey(); ``` Both mapping forms take the same overrides: `[GenerateElarionIdempotencyKeys]` accepts optional `TableName` and `Schema` properties alongside `SnakeCase`, and `modelBuilder.ApplyElarionIdempotencyKeys(tableName, schema, snakeCase)` mirrors them (defaults `elarion_idempotency_keys`, or `ElarionIdempotencyKeys` with `snakeCase: false`; the purge index name is derived from the table name — `ix_{table}_purge` / `IX_{table}_Purge`). `PollingInterval` (default `1h`) is how often the retention purge worker sweeps expired keys; it is complementary to the per-handler `RetentionHours` (which decides *when* a completed key becomes expired). The `[Idempotent]` decorator and the framework transaction decorator (`Elarion.Pipeline.TransactionDecorator`, for non-idempotent commands) share the one unit-of-work boundary — the key row commits **atomically inside the same transaction** as the handler's business writes. See [Persistence & transactions](/docs/concepts/persistence-and-transactions) for how handlers, decorators, and events share that transaction. Three properties of that shared EF Core unit of work are worth calling out: * **Commit flushes the change tracker.** The scope calls `SaveChangesAsync` before committing, so a handler that mutated the `DbContext` but forgot to save still has its writes persisted atomically with the transaction (a no-op when the handler already saved). * **Nested transactional handlers join, not clash.** A transactional command that invokes another transactional command through `IHandlerSender` on the **same** scope/`DbContext` does not open a second physical transaction (which the provider would reject). The inner scope joins the ambient transaction with a **savepoint**: its commit releases the savepoint, its rollback rolls back only the inner handler's writes, and the outer scope still owns the real commit. * **The commit is uncancellable.** Once the handler has returned success, the finalizing commit runs with `CancellationToken.None`, so a cancellation racing in between success and commit can never silently roll back a completed command (or leave its idempotency key claimable again). The core in-memory `IIdempotencyStore` and the no-op `IUnitOfWork` (registered by `AddElarionIdempotency` alone) are for single-process dev/test only — they are non-durable, non-cross-node, and non-transactional, and each logs a one-time warning on first use. Register `AddElarionIdempotencyEntityFrameworkCore` (which wires the durable store **and** the EF Core unit of work) for the production guarantees. ## The inbox: the same mechanism for event consumers [#the-inbox-the-same-mechanism-for-event-consumers] Command idempotency and the messaging **inbox** are the *same* mechanism — "record a unique id in the same transaction as the effect; skip if it already exists" — differing only in where the id comes from. A command sources a client `Idempotency-Key`; an integration-event consumer sources the **delivered message id** (`IEventContext.MessageId` — for the outbox, the row's id, stable across redeliveries). Because integration delivery is at-least-once, the inbox is **on by default** for every handler-form consumer: the generator attaches the same `IdempotencyDecorator` with a `Consumer`-scoped policy — owner = the consuming handler's identity (so each fan-out consumer of one event claims its own row), key = the message id, seeded into the delivery scope by the outbox dispatcher and the in-memory pump. A redelivered message replays the recorded success instead of re-running the consumer; a failed consumer rolls its claim back with its writes and retries. Opt out with `[AllowDuplicates]` — a positive declaration that redelivery is harmless (naturally idempotent effect, or the only effect is a call to a keyed downstream), the consumer-side mirror of `[AllowAnonymous]`. Rows share the idempotency table and purge loop under a `"consumer"` scope discriminator and expire after 24 h, well above the outbox's maximum retry window. See [Handling duplicates](/docs/capabilities/events/consuming-events#handling-duplicates) for the full model. ## Side effects and cooperative recipients [#side-effects-and-cooperative-recipients] The single-transaction model protects **database** state. A non-rollback-able foreign side effect (charging a card, sending mail) does not belong inline — record it as an **integration event in the outbox** in the same transaction as the key, and let the outbox deliver it after commit. The consumer's own database effect is then deduped by the built-in inbox (above), which leaves exactly one window: the foreign call itself re-runs if the process dies between the call and the consumer's commit. Closing it requires a **cooperative recipient service** that accepts an idempotency key and deduplicates — pass the delivered **message id** (the same value the inbox claims) as that key. For email, SendGrid does **not** accept idempotency keys, but newer providers — **Resend, Brevo, MailPace, Bird** — do; for payments use a keyed API (Stripe). A duplicate email is usually tolerable; a duplicate charge is not. ## Diagnostics [#diagnostics] * `ELIDEM001` (error) — an `[Idempotent]` handler whose response is not `Result`/`Result` (the decorator can't synthesize the `400`/`409`/`422`/replay outcomes). * `ELIDEM002` (warning) — `[Idempotent]` on a non-`ICommand` handler (no effect). * `ELIDEM003` (error) — `RetentionHours` is neither 1 to 1 000 000 nor `IdempotentAttribute.Permanent`. * `ELIDEM004` (warning) — a handler that is both `[Idempotent]` and `[Cacheable]`. * `ELIDEM005` (error) — `[Idempotent(Operation = …)]` with an empty or blank name. * `ELIDEM006` (error) — handlers of one operation declare a different success type, `Scope` or `Fingerprint`. * `ELINBX001` (warning) — `[AllowDuplicates]` on a handler whose request is not an `IIntegrationEvent` (no effect). * `ELIDEMEF001` (error) — a context annotated with `[GenerateElarionIdempotencyKeys]` but not `[GenerateDbSets]` (add `[GenerateDbSets]` so the keys `DbSet` and model-configuration seam are generated). # Concepts (/docs/concepts) Elarion separates an application into three responsibilities and uses compile-time generation to connect them. Understanding this split makes every other concept fall into place. ## The three responsibilities [#the-three-responsibilities] 1. **Application module composition** lives beside the feature code. A module decides which handlers, JSON metadata, and module-owned services it exposes. 2. **Compile-time discovery** replaces reflection-heavy startup scanning. Generators emit deterministic registration methods from attributes and conventions. 3. **Platform wiring** stays in the host. The host owns `WebApplication`, authentication, middleware, capability providers, database setup, telemetry exporters, and endpoint publication. This keeps modules independent of the final host while still allowing real platform abstractions where they matter. For example, modules may declare Minimal API endpoints with `IEndpointRouteBuilder` directly, so ASP.NET Core endpoint conventions and source generation still work. ## Why auto-detection is the default [#why-auto-detection-is-the-default] Elarion prefers **declaring application intent near the type** over maintaining a second registration list elsewhere. A handler already says "I handle this request"; an annotated request DTO already says "this is what a valid command looks like"; a `[Service]` class already says "this is a module service". Repeating those facts in `Program.cs` or hand-written `AddXyz()` methods creates a parallel model that drifts from the code it describes. This buys practical advantages: * **The module owns its application surface.** Adding a handler, JSON context, or service under a module namespace is enough to publish it through generated `Add{Module}…()` methods. * **Registration drift becomes a compile-time problem.** Missing trigger attributes, invalid service contracts, wrong hosted-service lifetimes, and unsupported generic services produce generator diagnostics instead of startup surprises. * **The host stops knowing feature internals.** It wires platform capabilities and transports; it does not remember every application handler or module service. * **Generated code stays inspectable.** The result is ordinary DI registration code, emitted deterministically rather than hidden behind runtime reflection. * **Refactoring follows structure.** Moving a type between modules changes ownership through namespace containment; deleting a type deletes its registration on the next build. * **AOT and startup behavior are predictable.** Compile-time discovery avoids broad runtime scans and keeps the dependency graph visible to the compiler and linker. Explicit registration still has a place when explicitness is the point: database contexts, external clients, provider-specific decorators, authentication, telemetry, and concrete capability providers should be wired by the platform. The bias is **auto-detect application patterns, explicitly wire platform capabilities**. Developers coming from Spring Boot will find the model familiar — components under a namespace boundary, annotations that declare their role, defaults for the common path — implemented with .NET source generation rather than runtime classpath scanning. ## The trade-off [#the-trade-off] You accept conventions. Handler names, the `IHandler<,>` request/response shape, module namespace containment, and pipeline attributes matter because generators use them. In exchange you get less host boilerplate, inherent modularity, fewer runtime scans, and a clear separation between application policy and host mechanics. The full comparison with idiomatic ASP.NET Core is in [How Elarion differs](/docs/why-elarion#how-elarion-differs-from-aspnet-core). ## The concepts [#the-concepts] The pages in this section cover each building block: How generators turn attributes and conventions into inspectable registration code. The primary use-case unit. `Result` and transport-agnostic `AppError` . Application boundaries and their lifecycle. `[Service]` registration and hosted services. Two-tier: DataAnnotations exported to every schema, business rules in the handler. Ordered cross-cutting behavior around handlers. Declarative, transport-neutral handler authorization. Per-resource point checks and data-level list filtering. Gate handlers with `[FeatureGate]` over any OpenFeature provider. One bootstrap snapshot of modules, flags, and grants for UX-only frontend adaptation. Typed extension points and capability-gated contributions for the web app. Exactly-once command replay with `[Idempotent]` and a single-transaction, unique-constrained key store. Who did what: `[Auditable]` records with field-level change capture, committed with the transaction. Runtime-changeable, DB-backed key/value settings. How handlers, decorators, and events share the DbContext transaction. One expression per domain rule: composed into queries with `Invoke` and `Expand()` , compiled for memory. Notes and files on records of many kinds: exclusive arcs, a table per kind, or a shared identity, instead of a `(kind, id)` pair. Spring-style `${key:-default}` placeholders, change-observable. Published `[ModuleContract]` surfaces between modules. In-memory state machines with mailbox-serialized, source-generated typed facades. Declarative handler result caching and invalidation. Transport-neutral access to the authenticated user. How application, infrastructure, and host projects fit together. # Modules (/docs/concepts/modules) A module is an application boundary: a static partial class marked with `[AppModule]`, sitting at the root of a namespace that contains the module's handlers, services, scheduled jobs, and event consumers. The module decides what it exposes; the host only composes modules. You do **not** wire a module's own building blocks by hand. Everything a module declares is discovered by namespace and registered for you, gated as a single unit by the module's feature flag. A module's optional `ConfigureServices` is reserved for the few registrations that source generation can't see — options binding, third-party libraries, manual decorators. ```csharp title="ClientsModule.cs" using System.Text.Json.Serialization.Metadata; using Elarion.Abstractions.Modules; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace MyApp.Application.Modules.Clients; [AppModule("Clients")] public static partial class ClientsModule { // Optional: only for registrations the generators can't discover. public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) { services.Configure(configuration.GetSection("Clients")); } public static IJsonTypeInfoResolver GetJsonTypeInfoResolver() => ClientsJsonContext.Default; } ``` ## Generated default services [#generated-default-services] For every `[AppModule]`, the generators emit a sibling partial class named by appending `ElarionModuleServices` to the module's type name — for `ClientsModule` that is `ClientsModuleElarionModuleServices` — with a single `ConfigureDefaultServices(IServiceCollection)` method. Its fully-qualified name is exactly the module's type name plus that suffix, so the host bootstrapper can always find and call it without any extra manifest metadata. `ConfigureDefaultServices` aggregates the module's discovered building blocks through a `static partial void` hook per category, invoked in a deterministic order: | Hook | Registers | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `AddHandlers` | The module's [handlers](/docs/concepts/handlers) (and their decorator pipeline). | | `AddStreamHandlers` | The module's [request-driven stream handlers](/docs/capabilities/transports/server-streaming). | | `AddServices` | The module's `[Service]` registrations — see [services](/docs/concepts/services). | | `AddVariantServices` | The module's `[FeatureVariant]`/`[ConfigurationVariant]` implementations — see [variant service injection](/docs/concepts/feature-flags#variant-service-injection). | | `AddValidators` | The module's generated [request-validation](/docs/concepts/validation) resolver — the DataAnnotations metadata for its handlers' request types. | | `AddScheduledJobs` | The module's [scheduled jobs](/docs/capabilities/scheduling). | | `AddEventConsumers` | The module's [event consumers](/docs/capabilities/events/consuming-events). | | `AddAuthorizationPolicies` | The module's `[AuthorizationPolicy]` classes — see [named policies](/docs/concepts/authorization#named-policies). | | `AddPermissions` | The module's slice of the runtime [permission catalog](/docs/concepts/authorization#permission-catalog). | | `AddModuleApi` | The module's generated [module API](/docs/concepts/cross-module-communication) facades. | | `AddActors` | The module's [actors](/docs/concepts/actors). | | `AddClientEvents` | The module's [client-event](/docs/capabilities/events/client-events) topics. | | `AddJsonTypeInfoResolver` | The module's `GetJsonTypeInfoResolver()` context, contributed through `ConfigureElarionJson` — see [serialization](/docs/capabilities/serialization). | The JSON hook is what makes module composition **self-contained**: registering a module brings its `System.Text.Json` metadata along, so a test host that cannot reference the host assembly's generated `ElarionBootstrapper` still gets it. `GetJsonTypeInfoResolver()` must be **pure and return a stable instance** — a generated context's `.Default` singleton, or a `static readonly` field you build once. It is now invoked up to twice per host startup (once by the module's own registration, once by the bootstrapper's aggregate), and duplicate contributions are collapsed by **reference** equality. A body that mints a new resolver per call — `JsonTypeInfoResolver.Combine(A.Default, B.Default)` is the usual one — returns a different instance each time, so both land in the chain. Hoist the combination into a `static readonly` field and return that. Each category generator contributes the filler partial that implements its hook (calling the existing per-module `Add{Module}…` registration method). A hook for a category the module doesn't use elides to a no-op, so a module that declares, say, only handlers and services costs nothing for the rest. The skeleton is emitted unconditionally for every module, so the host call always compiles. There is no hand-written `ConfigureServices` that calls `AddClientsHandlers()` / `AddClientsServices()` anymore. Those per-module methods still exist, but the generated `ConfigureDefaultServices` is what calls them — you should not. **Looking at an older example?** Pre-generator Elarion codebases (including external examples that vendor a pre-generator copy of the framework) wired each module by hand-calling `services.AddXHandlers()` / `AddXServices()` inside the module's `ConfigureServices`. Copying that pattern onto current packages **duplicates registrations**, because `ConfigureDefaultServices` already calls those methods. On current Elarion a module class is minimal — just `[AppModule]` (plus an optional `GetJsonTypeInfoResolver` and a `ConfigureServices` reserved for non-generated registrations). For an up-to-date end-to-end reference, see the compiled sample under [`samples/`](https://github.com/swimmesberger/Elarion/tree/main/samples). ### How the host invokes it [#how-the-host-invokes-it] When the host opts into `[GenerateModuleBootstrapper]`, the generated bootstrapper's `AddElarion` calls each module's `ConfigureDefaultServices(services)` — gated by the module's feature flag — and then, only if the module declares one, its hand-written `ConfigureServices(services, configuration)`. The generated defaults always run **before** your custom registrations. See [Hosting](/docs/capabilities/hosting) for the host-side wiring. ## Feature gating [#feature-gating] Feature modules are **enabled by default** and disabled with configuration: ```json title="appsettings.json" { "Modules": { "Clients": { "Enabled": false } } } ``` The generated bootstrapper resolves this through a single `IsModuleEnabled(configuration, name)` predicate that reads `Modules:{Name}:Enabled`, defaulting to `true`. Every surface is gated by that one predicate, so a disabled feature module disappears completely and consistently: * its generated default services (handlers, `[Service]` registrations, validation metadata, scheduled jobs, event consumers, module API, actors, client-event topics) are never registered; * its hand-written `ConfigureServices` is never called; * its `MapEndpoints` routes and its generated `[HttpEndpoint]` routes are never mapped; * its `[Handler]` JSON-RPC operations are never registered; * its `[Handler]` MCP tools (and their metadata) are never registered; * its `GetJsonTypeInfoResolver()` contribution is left out. This is the canonical statement of the gating contract: a module is enabled or disabled **as one unit**, across services, endpoints, and every transport. Handlers whose namespace falls under no module are reported with a diagnostic and mapped ungated so they are never silently dropped — see [Module-aware transport gating](/docs/reference/conventions) for the per-surface diagnostic ids. ## Core modules [#core-modules] A core module is an ordinary module in every way **except two**: it is always enabled (it ignores `Modules:{Name}:Enabled`) and it initializes before feature modules. Declare it with `Kind = AppModuleKind.Core`: ```csharp title="CoreModule.cs" [AppModule("Core", Kind = AppModuleKind.Core)] public static partial class CoreModule { } ``` A host that conceptually has "no modules" still declares one core `[AppModule]`, since `[GenerateModuleBootstrapper]` is the single transport-wiring path and core modules map unconditionally. ### What belongs in a core module [#what-belongs-in-a-core-module] A core module is for a **foundation capability with behavior that other modules assume is present** — an always-on domain service such as audit recording or current-user context enrichment. Its only reason to exist is that *can't-be-disabled + initializes-first* guarantee; otherwise it is the same kind of thing as a feature module. It is **not** "where shared code lives." A core module is not a junk drawer for everything cross-cutting. Apply the [active-vs-passive test](/docs/concepts/solution-structure#active-modules-vs-passive-building-blocks): cross-cutting **data** belongs in the shared kernel, a cross-cutting **mechanism** belongs in a port, and only cross-cutting **behavior that must always be present** belongs in a core module — kept as small as possible. ### Core module vs. the platform [#core-module-vs-the-platform] Both a core module and the *platform* (the host/runtime) are "always there," so they are easy to conflate. The difference is **domain-awareness**: * The **platform** provides domain-**blind** *mechanisms* — the DI container, the transports, the database *connection*, and the adapters behind intent-only ports (SMTP for `IEmailSender`). It never knows your domain, and the same platform serves any application. It is the ground your application stands on. * A **core module** is domain-**aware** application *behavior* you wrote — your application's load-bearing foundation. A core module *consumes* platform capabilities (audit injects `ICurrentUser`); application always builds on the platform, never the reverse. So a domain-blind mechanism is a *platform capability* (a port); domain-aware always-on behavior is a *foundation capability* (a core module) — never call the latter a "platform capability." ## Ordering with DependsOn [#ordering-with-dependson] `[AppModule]` accepts an optional comma-separated `DependsOn` list of module names. The generated bootstrapper calls the modules' `ConfigureServices` and maps their endpoints in one order: a module comes after every module it depends on, and among modules that are free to go next, Core modules come first, then the module names in ordinal order. Name a module's dependency when it injects that module's [contract](/docs/concepts/cross-module-communication#what-a-contracts-consumer-must-know) (`ELMOD008` asks for it) or relies on that module's registrations. ```csharp [AppModule("Billing", DependsOn = "Catalog,Pricing")] public static partial class BillingModule { } ``` Do not add `DependsOn = "Core"` just to make a feature module see core services — core availability is implicit from the module kind. Use `DependsOn` only for explicit ordering between feature modules or between multiple core modules. ### Modules that depend on each other [#modules-that-depend-on-each-other] Two modules may each need the other, for example when each injects a contract of the other: then each names the other in `DependsOn`, and that is the honest declaration, which `ELMOD008` accepts. No dependency can order such a cycle, so the bootstrapper places its modules as one unit, after everything any of them depends on and before everything that depends on any of them, and orders them among themselves by the same rule (Core first, then by name). It reports the cycle as `ELMOD009` (Info), naming the modules and the order it chose. * **Allowed** when each module really needs the other. Neither module may rely on the other having initialized first: contracts resolve lazily from the container, so injecting each other works, but a `ConfigureServices` that reads or replaces the other module's registrations does not have a defined order. * **Better broken** when one direction only reacts to what the other did (publish an event instead of calling a contract), or when both use one piece that can move into a third module, or into a Core module, that both name. * To keep cycles out of an application, raise the diagnostic in `.editorconfig`: `dotnet_diagnostic.ELMOD009.severity = warning`. A `DependsOn` name that no module of the application carries orders nothing and is reported as `ELMOD010`. ## Endpoints in modules [#endpoints-in-modules] A module's handlers expose themselves over a transport with `[Handler]` ([JSON-RPC](/docs/capabilities/transports/json-rpc) and [MCP](/docs/capabilities/transports/mcp)) or `[HttpEndpoint]` ([HTTP](/docs/capabilities/transports/http-endpoints)). A single `[Handler]` covers every name-routed transport; choose which ones with `[Handler(Transports = ...)]` (default: `HandlerTransports.All` — JSON-RPC, MCP, and [bidirectional connections](/docs/capabilities/connections)). The generated bootstrapper associates each handler with a module by namespace and maps its operation/tool only when the module is enabled — the same feature gate that governs the module's services. ### Hand-written endpoints [#hand-written-endpoints] A module can also declare Minimal API endpoints directly with the real ASP.NET Core abstractions, as an escape hatch when it needs full control — custom authorization, conventions, or a hand-written route: ```csharp [AppModule("Chat")] public static partial class ChatModule { public static void MapEndpoints(IEndpointRouteBuilder endpoints) { endpoints .MapPost("/chat/stream", ChatEndpoint.HandleAsync) .RequireAuthorization(); } } ``` Use real endpoint conventions, filters, typed results, and route handler source generation — Elarion does not introduce a reduced endpoint facade. Keep host lifecycle concerns out of modules: a module should never call `builder.Build()`, `app.UseAuthentication()`, `app.MapElarionJsonRpc()`, or configure concrete infrastructure providers. Those belong to the host. ### Owning the route group [#owning-the-route-group] A module can own the route group, authorization policy, and conventions for **all** of its mapped endpoints — both its generated `[HttpEndpoint]` routes and its hand-written `MapEndpoints` routes — by declaring an optional `ConfigureEndpointGroup` hook: ```csharp [AppModule("Billing")] public static partial class BillingModule { public static IEndpointRouteBuilder ConfigureEndpointGroup(IEndpointRouteBuilder endpoints) => endpoints.MapGroup("/billing").RequireAuthorization("billing"); } ``` When present, the bootstrapper maps the module's endpoints onto the builder it returns; absent the hook, they map onto the root builder. There are no per-module URL prefixes by default — each `[HttpEndpoint]` carries its full route template and modules share a flat URL space. A conventions-only group (`MapGroup("")`) adds policy without a prefix, while `MapGroup("/billing")` opts the whole module into a prefix. The generator never reads `[Authorize]`/`[AllowAnonymous]` from handlers; per-endpoint authorization is the host's or the module's job. ### Declaring the hooks outside the module: `[ModuleEndpoints]` [#declaring-the-hooks-outside-the-module-moduleendpoints] Both endpoint hooks take `IEndpointRouteBuilder`, a shared-framework type — which a deliberately **web-free** module assembly (no `Microsoft.AspNetCore.App` reference) cannot declare. Instead of re-importing the framework or hand-mapping routes in the host (and hand-duplicating the module's feature gate), declare the hooks **on behalf of the module** with `[ModuleEndpoints]` from `Elarion.AspNetCore`, typically in the host: ```csharp [ModuleEndpoints("ImportExport")] internal static class ImportExportEndpoints { public static IEndpointRouteBuilder ConfigureEndpointGroup(IEndpointRouteBuilder endpoints) => endpoints.MapGroup("").RequireAuthorization(); public static void MapEndpoints(IEndpointRouteBuilder endpoints) { // hand-written routes for the ImportExport module } } ``` The class declares the same convention hooks a module type may declare (either or both — a class with neither warns `ELMOD005`). The bootstrapper calls them **inside the named module's feature gate**, composed with the module's own hooks: group hooks chain (the module's first, then contributors in stable type-name order), then every `MapEndpoints`, then the module's generated `[HttpEndpoint]` routes — all onto the builder the group chain returns. Disabling the module drops the contributed endpoints with it, with no hand-written `IsModuleEnabled` re-check. A contributor naming a module no discovery produced warns `ELMOD004` and is skipped. Contributors are discovered in the host compilation and — through the per-assembly Elarion manifest — in referenced assemblies, so a web companion assembly beside a web-free module assembly works the same way. See [ADR-0040](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0040-host-declared-module-endpoints.md). ## Convention-based hooks [#convention-based-hooks] Every module hook is optional and discovered structurally by signature: | Hook | Purpose | | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `ConfigureServices(IServiceCollection, IConfiguration)` | Register **additional, non-generated** services (options, third-party libraries, manual decorators). Runs after the generated defaults. | | `MapEndpoints(IEndpointRouteBuilder)` | Declare module-owned Minimal API endpoints. | | `ConfigureEndpointGroup(IEndpointRouteBuilder) → IEndpointRouteBuilder` | Return a route group (prefix, policy, conventions) onto which the module's endpoints are mapped. | | `GetJsonTypeInfoResolver() → IJsonTypeInfoResolver` | Contribute the module's source-generated `System.Text.Json` metadata. Must be **pure** and return a **stable instance** (a context's `.Default`, or a `static readonly` field): it is invoked up to twice per startup and duplicates are collapsed by reference, so a per-call `JsonTypeInfoResolver.Combine(…)` lands in the chain twice. | The two endpoint hooks may also be declared outside the module type on a [`[ModuleEndpoints]`](#declaring-the-hooks-outside-the-module-moduleendpoints) contributor class, for module assemblies that stay web-free. ## What stays in the host [#what-stays-in-the-host] Concrete infrastructure is a **platform capability**, not a second module system. Feature flags decide which module handlers, endpoints, JSON metadata, scheduled jobs, and event consumers are exposed; the platform registers capability providers up front, and unused providers stay dormant until a feature resolves the corresponding application port. How the host composes modules and calls the generated bootstrapper. Naming, discovery, and gating convention tables and diagnostic ids. The full dependency rules between modules, host, and infrastructure. How discovery and the per-module registration methods are emitted. # Persistence & transactions (/docs/concepts/persistence-and-transactions) Elarion's data stores are designed to **compose with your unit of work**. A handler can open a transaction on its `DbContext`, call one or more framework stores, and have their writes commit — or roll back — atomically with its own business data. Nothing opens a side connection that escapes your transaction. Every EF Core store acts on the **`DbContext` you inject**, so it rides that context's current transaction. You do not pass a transaction around; you share the `DbContext`. See [ADR-0015](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0015-ef-core-transaction-participation.md). ## The contract [#the-contract] Wrap framework writes in your own transaction and they are part of it: ```csharp [Handler("billing.archive")] public sealed class ArchiveInvoice( BillingDbContext db, ISettingsManager settings, IBlobStore blobs) : IHandler> { public async ValueTask> HandleAsync(Command command, CancellationToken ct) { await using var tx = await db.Database.BeginTransactionAsync(ct); db.Invoices.Remove(await db.Invoices.FindAsync([command.Id], ct)); await db.SaveChangesAsync(ct); // Both of these run on the SAME connection + transaction as the delete above. await settings.SetAsync(BillingSettings.LastArchivedInvoice, command.Id, cancellationToken: ct); await blobs.SaveAsync(ArchiveRequest(command.Id), command.Pdf, ct); await tx.CommitAsync(ct); // all three commit together return Result.Success(); // a throw / RollbackAsync would discard all three } } ``` ## Let the framework own the boundary [#let-the-framework-own-the-boundary] Opening the transaction by hand is optional. `TransactionDecorator` wraps a handler in a single unit-of-work transaction that commits on a successful `Result` and rolls back otherwise — so the handler body writes as if the boundary were free: ```csharp [Handler("billing.archive")] public sealed class ArchiveInvoice( BillingDbContext db, ISettingsManager settings, IBlobStore blobs) : IHandler> { // No BeginTransactionAsync / CommitAsync — the decorator owns the boundary. public async ValueTask> HandleAsync(Command command, CancellationToken ct) { db.Invoices.Remove(await db.Invoices.FindAsync([command.Id], ct)); await db.SaveChangesAsync(ct); await settings.SetAsync(BillingSettings.LastArchivedInvoice, command.Id, cancellationToken: ct); await blobs.SaveAsync(ArchiveRequest(command.Id), command.Pdf, ct); return Result.Success(); // commit; a failed Result or throw rolls all three back } } ``` The decorator attaches only where a new unit of work belongs — its compile-time `AppliesTo` predicate matches **commands and integration-event handlers** and skips queries, domain-event handlers (they run inline inside the publisher's transaction), commands marked `[NoTransaction]` (see below), `[Idempotent]` handlers, and integration-event consumers under the default-on inbox (both own the boundary themselves, so a handler is never wrapped in two nested transactions — only an `[AllowDuplicates]` consumer gets the plain transaction). Under the hood it composes the EF-free `IUnitOfWork`/`IUnitOfWorkScope` seam (`Elarion.Abstractions.Pipeline`). `EfUnitOfWork` implements it over `DbContext.Database.BeginTransactionAsync`, with savepoint support and — on PostgreSQL — a `SET LOCAL lock_timeout` derived from `UnitOfWorkOptions.LockTimeout` (a blocked statement fast-fails instead of waiting; other providers ignore it). Two behaviors make the boundary forgiving: * **Commit flushes the change tracker** — the scope calls `SaveChangesAsync` before committing, so a handler that mutated the `DbContext` but forgot to save still persists its writes atomically with the transaction (a no-op when it already saved). * **A nested transactional handler joins with a savepoint** — when a transactional command invokes another transactional command through `IHandlerSender` on the same scope, the inner `BeginAsync` sees the ambient transaction and creates a savepoint instead of opening a second physical transaction (which the provider would reject). The inner commit releases the savepoint, the inner rollback discards only the inner writes, and the outer scope still owns the real commit. Wire it with `AddElarionUnitOfWork()`, which replaces the default in-memory unit of work: ```csharp services.AddElarionUnitOfWork(); ``` [Idempotency](/docs/concepts/idempotency) composes this same `IUnitOfWork` boundary — the `[Idempotent]` handler claims its key inside the transaction it owns, which is why `TransactionDecorator` steps aside for it. A [previewable command](/docs/concepts/previewable-commands) uses it to run the command and roll it back; it relies on the rollback, so it checks `IUnitOfWork.SupportsRollback` (true for the EF Core and SQL-tier units of work, false for the in-memory default) and refuses to preview without it. ### Constraint violations as results [#constraint-violations-as-results] A violated constraint is an exception, so by default the caller gets the framework's [unexpected-error answer](/docs/concepts/results-and-errors#unexpected-errors). When the caller can act on it — the name is taken, the period overlaps another — register an `IUnitOfWorkFailureTranslator` that maps it to an `AppError`: ```csharp public sealed class ConstraintTranslator : IUnitOfWorkFailureTranslator { public AppError? Translate(UnitOfWorkFailureContext context) => (context.Exception as PostgresException ?? context.Exception.InnerException as PostgresException) switch { { SqlState: PostgresErrorCodes.ExclusionViolation, ConstraintName: "ex_periods_overlap" } => AppError.Conflict("The period overlaps another one.", "schedule.overlap"), { SqlState: PostgresErrorCodes.UniqueViolation, ConstraintName: "ux_projects_name" } => AppError.Conflict("A project with this name exists.", "projects.name_taken"), _ => null // everything else stays an unexpected error }; } builder.Services.AddSingleton(); ``` `TransactionDecorator` offers every exception that ends its unit of work to the translators, in registration order: one from the handler (a `SaveChanges` that hit a unique index, wrapped in a `DbUpdateException`) and one from the commit itself. The commit matters for a `DEFERRABLE INITIALLY DEFERRED` constraint — an exclusion constraint over rows that one `SaveChanges` writes in an order EF Core does not promise — which PostgreSQL checks only at `COMMIT`, outside every `SaveChangesInterceptor`. The first error a translator returns becomes the command's failed `Result`, and the unit of work rolls back; a cancellation is never translated, and an exception no translator answers propagates unchanged. Put no exception text in the message: it names tables, columns and values. Declare the codes on the handlers that can return them with `[ProducesError]`. The context also carries `Handler`, the `HandlerMetadata` of the handler whose unit of work failed. A translator meant for one module's handlers checks it and returns `null` for every other handler, which keeps the default answer: ```csharp [AttributeUsage(AttributeTargets.Class)] public sealed class SettlementCommandAttribute : Attribute; public sealed class SettlementConflictTranslator : IUnitOfWorkFailureTranslator { public AppError? Translate(UnitOfWorkFailureContext context) { if (context.Handler.GetAttribute() is null) return null; return context.Exception switch { DbUpdateConcurrencyException => Changed(), { InnerException: PostgresException { SqlState: PostgresErrorCodes.SerializationFailure or PostgresErrorCodes.DeadlockDetected } } => Changed(), _ => null }; static AppError Changed() => AppError.Conflict("The settlement changed concurrently; reload and try again."); } } ``` `Handler` is the outermost handler of the unit of work: a nested handler joins it, and its exception surfaces there. A translator sees only what reaches `TransactionDecorator`. A decorator further in, or the handler itself, that catches an exception and returns a failure owns that exception, and no translator is asked. ### Commands without a transaction [#commands-without-a-transaction] A command whose work is mostly outside the database — sending a test mail, calling a slow external service — would hold a pooled connection and an open transaction for the whole call. Mark it `[NoTransaction]` and `TransactionDecorator` stays off: ```csharp [Handler("settings.smtp.test"), NoTransaction] public sealed class TestSmtp(ISmtpClient smtp) : IHandler> { … } ``` The request stays an `ICommand`, so everything else the request kind decides is unchanged. Each `SaveChanges` then commits on its own; open a transaction in the handler around writes that must commit together. `[Idempotent]` commands and inboxed integration-event consumers own their transaction regardless. Queries get no transaction, and nothing stops a query handler from writing: the request kind is a declaration the framework trusts. A test that scans the query handlers for `SaveChanges`, or a code review rule, is the guard. ### Work after the commit [#work-after-the-commit] Some work must run only once the command's writes are durable — rendering a document that shows the number the commit allocated, calling an external system that must not see an id that may still roll back. Enqueue it on `IAfterCommit` from the handler, or from any scoped service the handler calls, and stay in the default pipeline: ```csharp [Handler("invoices.finalise")] public sealed class FinaliseInvoice(AppDbContext db, InvoiceNumbers numbers, IAfterCommit afterCommit, InvoiceDocuments documents) : IHandler> { public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var invoice = await db.Invoices.SingleAsync(i => i.Id == command.InvoiceId, ct); invoice.Finalise(await numbers.NextAsync(invoice.Series, ct)); afterCommit.Enqueue(async stopping => { db.ChangeTracker.Clear(); // render from what is committed await documents.RenderAsync(invoice.Id, stopping); }); return InvoiceDocument.From(invoice); // the decorator commits, then the work runs } } ``` An auto-attached `AfterCommitDecorator` sits outside every decorator that owns a unit of work (the transaction, [idempotency](/docs/concepts/idempotency) and [preview](/docs/concepts/previewable-commands) decorators) and runs the work when the **outermost** handler of the scope returns a successful `Result`: | Situation | The work | | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | Command, commit succeeds | runs after the commit, in enqueue order, before the response returns | | Query, `[NoTransaction]` command, a handler that commits by hand | runs after the handler succeeds — the code that enqueues need not know which case it is in | | Failed `Result`, an exception, a commit that fails, a response that is not a `Result` | discarded | | Nested handler (`IHandlerSender`, a domain-event handler) | joins the outermost handler's queue; runs only after the outermost commit | | Nested handler that fails | only the work it enqueued is discarded, like its writes roll back to their savepoint | | Preview of a [previewable command](/docs/concepts/previewable-commands) | discarded (the preview rolls back) | | Idempotent replay | nothing runs — the replay does not run the handler | * **The token is the host's stopping token, not the request's.** What is committed stays committed, so a client that hangs up does not abandon the follow-up halfway. When the host stops, the remaining items are skipped and logged. * **An exception in the work is logged and never changes the answer.** The next item still runs. * **The work runs in the request's scope, after the queue is closed.** The `DbContext` still tracks what the handler loaded; the commit flushed it, so every entry is `Unchanged`, and a `SaveChanges` in the work commits on its own, outside any transaction. Call `ChangeTracker.Clear()` first when the work reads data afresh or writes, or dispatch a handler from the work: it is the outermost handler of its own run, with its own transaction and its own after-commit work. * **`Enqueue` outside a running handler throws**, and so does enqueueing from inside after-commit work. * Two messages dispatched concurrently on one reused connection scope keep separate queues, and a handler dispatched into another scope has its own. When the work writes, give it a transaction by sending a handler instead of opening one by hand. The request's transaction has committed, so the handler you send is the outermost one of its run: the default pipeline opens a new transaction on the same `DbContext`, commits it on success, and rolls back only its own writes on failure. The request's current user and tenant stay in place, because it runs in the same scope. ```csharp afterCommit.Enqueue(async stopping => { // A failure rolls back the render's writes and nothing else; the answer has already been decided. await sender.SendAsync(new RenderInvoiceDocuments.Command(invoice.Id), stopping); }); // No transport attribute: an in-process handler, reachable only through IHandlerSender. public sealed class RenderInvoiceDocuments(AppDbContext db, InvoiceDocuments documents) : IHandler> { public sealed record Command(Guid InvoiceId) : ICommand; public async ValueTask> HandleAsync(Command command, CancellationToken ct) { … } } ``` After-commit work is **best-effort and in-process**. It runs once, on the node that handled the request, and is lost if the process stops between the commit and the work. Anything that must happen — a mail that must go out, a document that must exist — is written in the transaction as durable work: an [integration event through the outbox](/docs/capabilities/events/backends) or a [leased-work](/docs/capabilities/scheduling) item. The two combine: write the durable record in the transaction and enqueue an after-commit attempt that does it at once; the durable worker finds it done, or does it after a crash. The generated `AddElarion` registers `IAfterCommit` (`AddElarionAfterCommit()` for a hand-built container); the decorator attaches to every scoped handler once it is registered. Singleton handlers get none. See [ADR-0123](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0123-after-commit-work.md). ### One transaction per item [#one-transaction-per-item] A [scheduled job](/docs/capabilities/scheduling) has no pipeline transaction, and a job that walks a list of rows usually wants each row to stand alone: one that fails must not undo or stop the others. `RunEachInTransactionAsync` (`Elarion.EntityFrameworkCore.UnitOfWork`) is that loop: ```csharp [ScheduledJob("tasks.dueNotices", FixedRate = "1h")] public async ValueTask RunAsync(CancellationToken ct) { var due = await db.Tasks.Where(t => t.DueOn <= today && t.NotifiedOn == null).Select(t => t.Id).ToListAsync(ct); var result = await db.RunEachInTransactionAsync(due, async (id, ct) => { if (!await db.LockRowAsync(id, RowLockMode.NoKeyUpdate, ct)) return false; var task = await db.Tasks.SingleAsync(t => t.Id == id, ct); if (task.NotifiedOn is not null) return false; // told meanwhile: skip task.NotifiedOn = today; db.Notices.Add(Notice.TaskDue(task)); return true; // saved and committed together }, logger, ct); logger.LogInformation("Due notices: {Committed} sent, {Failed} failed", result.Committed, result.Failed); } ``` * **Per item:** a transaction opens, the work runs, and `true` saves the context's changes and commits. `false` rolls back and counts the item as skipped; an exception (from the work or the commit) rolls back, is logged as an error with the item, and counts it as failed. The run goes on, and the result carries the three counts. * **Cancellation is not a failure.** It rolls the current item back and is rethrown; committed items stay committed. * **The change tracker is cleared after every item**, also a failed one, so nothing one item loaded or added reaches the next item's save. Pass ids and load what the work changes inside it; check the row again under its [lock](/docs/capabilities/coordination#row-and-advisory-locks), because the list was read before the item's transaction began. * **It refuses a context that already has a transaction or unsaved changes.** Inside a command handler the items would share the command's transaction; dispatch one command per item through `IHandlerSender` instead. * Each item runs through the context's execution strategy, so a provider configured to retry transient failures retries the item's whole transaction. ### Isolation level [#isolation-level] `TransactionDecorator` opens the provider's default isolation level (`READ COMMITTED` on PostgreSQL). A command that must read one coherent snapshot declares its level: ```csharp [Handler("settlements.close"), TransactionIsolation(IsolationLevel.Serializable)] public sealed class CloseSettlement(AppDbContext db) : IHandler> { … } ``` The EF Core and SQL-tier units of work open the transaction at that level; the in-memory unit of work ignores it. A nested handler joins the outer transaction with a savepoint and cannot change its level, so a nested unit of work that asks for a different level throws instead of running weaker than declared — declare the level on the outermost handler. Answer the serialization failure (SQLSTATE `40001`) with an `IUnitOfWorkFailureTranslator` (see [constraint violations as results](#constraint-violations-as-results)), or retry the whole unit of work with [`[Resilient]`](/docs/capabilities/resilience), which sits outside the transaction decorator. ## What enlists, and how [#what-enlists-and-how] | Store / bus | Technique | Participates in your transaction | | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | **Framework command boundary** (`TransactionDecorator` over `IUnitOfWork`) | `EfUnitOfWork` opens the transaction; commits on success, rolls back otherwise | Yes — it *is* your transaction (commands & integration events) | | **Settings** (`EfCoreSettingsStore`) | `ExecuteUpdate`/`ExecuteDelete` + raw `INSERT` on the injected context | Yes | | **Resource grants** (`EfCoreResourceGrantStore`) | change tracker + `ExecuteDelete` | Yes | | **Outbox capture** (`EfCoreOutboxStore.Append`) | change tracker, committed with your data | Yes | | **Blob store** (`PostgreSqlBlobStore`) | metadata via change tracker; `bytea` content via raw Npgsql **explicitly enlisted** in `Database.CurrentTransaction` | Yes — metadata + content together | | **Domain events** (`IDomainEventBus`) | dispatched inline in your scope | Yes — runs inside your transaction | | **Integration events** (in-memory) | buffered, flushed by EF interceptors **after commit**, discarded on rollback | Commit-gated (see below) | | **Outbox delivery** (`OutboxDeliveryService`) | runs on its own scope **after** commit | No — by design, post-commit | | **Row and advisory locks** (`LockRowAsync`, `AdvisoryLockAsync`) | `FOR UPDATE`/`pg_advisory_xact_lock` on the injected context; refused outside a transaction | Yes — held until your transaction ends ([Coordination](/docs/capabilities/coordination#row-and-advisory-locks)) | The blob store opens its *own* transaction only when you have not started one, so a standalone `SaveAsync` is still atomic. Deleting a blob removes its content row in the same transaction via an `ON DELETE CASCADE` foreign key. ## After-commit delivery is deliberate [#after-commit-delivery-is-deliberate] Two things intentionally run **after** your transaction commits rather than inside it (see [ADR-0001](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0001-event-transaction-phase.md)): * **Integration events** (`IIntegrationEventBus`) are recorded in your unit of work and delivered after commit — never on rollback. This is the cross-boundary notification plane. * **Outbox delivery** polls and dispatches durable messages on isolated scopes, so a delivery failure never fails your command. The **in-memory** integration tier is commit-gated by EF Core interceptors that `AddElarionInMemoryEventBus()` attaches to your context automatically — so a plain `AddDbContext()` is all you write: ```csharp services.AddElarionInMemoryEventBus(); services.AddDbContext(o => o.UseNpgsql(connectionString)); ``` The durable [outbox](/docs/capabilities/events/backends) tier commit-gates through its own `SaveChanges` interceptor instead. ## Data that attaches to many kinds of records [#data-that-attaches-to-many-kinds-of-records] Notes, files and comments on records of many kinds are the one place where a foreign key seems impossible, so a `(kind, id)` pair creeps in, and with it orphans and unchecked inserts. It is a known anti-pattern with database-level answers (exclusive arcs, a table per kind, a shared identity table), all within one shared schema. See [Polymorphic references](/docs/concepts/polymorphic-references) for which to use and what each guarantees. ## Testing persistence [#testing-persistence] Test persistence against a **real PostgreSQL** — a disposable [Testcontainers](https://testcontainers.com/) instance — not the EF Core **InMemory** provider. InMemory is LINQ over dictionaries, not a relational database: it silently diverges from Postgres in exactly the places a persistence test exists to cover, so a green InMemory test is false confidence. It does **not**: * enforce `SaveChanges`' affected-rows check — an `UPDATE` that matches zero rows *passes* on InMemory but throws `DbUpdateConcurrencyException` on Postgres. This is the trap behind [client-assigned keys](/docs/capabilities/entity-framework#entity-identity) (SQLite skips the check too); * run real transactions, savepoints, `lock_timeout`, or concurrency tokens; * execute provider SQL — keyset paging's row-value seek, `COLLATE "C"` ordering, `ExecuteUpdate`, raw SQL, `ON CONFLICT`, or unique-index violations; * apply your migrations or database constraints. Use a Docker-gated fixture that **skips** (never fails) when Docker is absent, so the suite still runs on a machine without it: ```csharp public sealed class PostgresFixture : IAsyncLifetime { private PostgreSqlContainer? _container; public bool IsAvailable { get; private set; } public string SkipReason { get; private set; } = ""; public string ConnectionString { get; private set; } = ""; public async ValueTask InitializeAsync() { try { var container = new PostgreSqlBuilder("postgres:17-alpine").Build(); await container.StartAsync(); // validates the Docker endpoint _container = container; ConnectionString = container.GetConnectionString(); await using var db = CreateContext(); await db.Database.EnsureCreatedAsync(); // or MigrateAsync() to exercise migrations IsAvailable = true; } catch (Exception ex) { SkipReason = $"Docker required: {ex.Message}"; // skip, don't fail } } public AppDbContext CreateContext() => new(new DbContextOptionsBuilder().UseNpgsql(ConnectionString).Options); public async ValueTask DisposeAsync() { if (_container is not null) await _container.DisposeAsync(); } } ``` ```csharp public sealed class InvoiceTests(PostgresFixture fixture) : IClassFixture { [Fact] public async Task ReplacingLineItems_Persists() { Assert.SkipUnless(fixture.IsAvailable, fixture.SkipReason); await using var db = fixture.CreateContext(); // each test owns its own context // … exercise the handler against real Postgres, then assert on a fresh context … } } ``` A test that only inspects the **model** (mappings, keys, indexes) needs no container: build the context with `UseNpgsql(...)` and a throwaway connection string and read `context.Model` — the provider shapes the model without opening a connection. It is still the real provider, not InMemory. The one legitimate use of InMemory is a **demo that must run without Docker** — the [quickstart](/docs/getting-started/quickstart) uses it so you can try Elarion in five minutes. Anything that asserts database *behavior* uses a real database; the framework's own persistence tests are all Testcontainers-backed. ### One database per test, and Npgsql's pool registry [#one-database-per-test-and-npgsqls-pool-registry] Giving every test (or every test host) its own database — a fresh `CREATE DATABASE … TEMPLATE …` per test is the fast way to isolate them, see [Speed up integration tests with Postgres](https://blog.wimmesberger.dev/posts/speed-up-integration-tests-with-postgres/) — runs into an Npgsql detail that is invisible in production: * **`new NpgsqlConnection(connectionString)` registers a data source for that exact string in Npgsql's static pool manager, for the life of the process.** The constructor does it, before `Open`. There is no public API to remove the entry again. `Pooling=false` does not opt out: the unpooled source is registered too. * **`NpgsqlConnection.ClearPool(new NpgsqlConnection(cs))` creates a pool just to clear it.** It reaches only the registry's own source for that string, never the data source your application actually uses, and leaves a new entry behind. * **Every data source keeps a metrics reporter in a static list until it is disposed**, so an undisposed `NpgsqlDataSource.Create(…)` is never collected either. With one connection string per process none of this matters. With one database per test, every distinct connection string adds entries that are never freed, and a long suite grows without bound (one suite measured over 1,500 retained data sources four minutes in). For the work that genuinely needs its own server session — the admin connection that runs `CREATE`/`DROP DATABASE`, a session-level `pg_advisory_lock`, `LISTEN`, a setup statement that must run first and alone — use `UnpooledNpgsqlSession` from `Elarion.Sql.PostgreSql`. It builds a private, unpooled data source, opens one connection, and disposes both together, so the registry is never touched and disposal really ends the server session (its locks, listeners, and temporary tables go with it): ```csharp await using (var admin = await UnpooledNpgsqlSession.OpenAsync(adminConnectionString, ct)) { await using var create = new NpgsqlCommand($"CREATE DATABASE \"{name}\" TEMPLATE app_template", admin.Connection); await create.ExecuteNonQueryAsync(ct); } ``` The rest of the test's traffic goes through the data source the host registers (`AddElarionPostgreSql`, `AddNpgsqlDataSource`, `UseNpgsql`), and the host disposes it with its service provider. If idle pooled connections keep a test database from being dropped, clear **that** data source — `dataSource.Clear()` on the instance the host resolved — not a pool looked up by connection string. Opening an unpooled session costs a full connection handshake each time, so it is the wrong tool for the application's normal queries. The migration runner's connection-string constructor (`new PostgreSqlMigrationRunner(connectionString, …)`) already opens its dedicated session this way, so migrating one fresh database per test leaves nothing behind. # Polymorphic references (/docs/concepts/polymorphic-references) Some data attaches to records of many kinds: notes on properties, contacts and invoices; files on any record; comments, tags, mentions. The tempting model is one table with an owner pair, `(OwnerKind, OwnerId)`. That pair is the **polymorphic association**, a well-known relational anti-pattern ([Karwin, *SQL Antipatterns*](https://pragprog.com/titles/bksap1/sql-antipatterns-volume-1/)). A foreign key points at exactly one table, so the database cannot check the pair. That costs three things: * **No integrity on insert.** A note can point at a record that does not exist, or never did. * **No integrity on delete.** Deleting the owner leaves its notes behind, and nothing in the database removes them. * **No protection from races or raw SQL.** Any cleanup lives in application code. A concurrent insert, an `ExecuteDelete`, or a SQL script slips past it. GitLab's database guide puts it bluntly, "always use separate tables instead of polymorphic associations" ([GitLab](https://docs.gitlab.com/development/database/polymorphic_associations/)). Comparisons of the alternatives find that the pair's only advantage is how easy an ORM makes it ([Hashrocket](https://hashrocket.com/blog/posts/modeling-polymorphic-associations-in-a-relational-database)). Rails (`dependent: :destroy`) and Django (`GenericRelation`) ship exactly that convenience: a cascade in application code, which a bulk delete or raw SQL bypasses. **Module independence is not a reason to avoid a foreign key.** Within one context, Elarion's modules share one `DbContext` and one schema by design ([ADR-0007](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0007-data-is-platform-module-as-plugin.md)). Module boundaries are enforced in code (handlers, services, published contracts), not by keeping tables unaware of each other. A notes table with a foreign key to properties breaks no boundary. ## Choose by the shape of the relationship [#choose-by-the-shape-of-the-relationship] | The attached data belongs to… | Use | The database guarantees | It costs | | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------- | | one kind of record | **a foreign key** with `ON DELETE CASCADE` (or `RESTRICT`) | everything: existence on insert, cleanup on delete, no races | nothing | | one of a few known kinds | **an exclusive arc**: one nullable foreign key per kind, plus a CHECK that exactly one is set | everything | a column and a constraint change per new kind | | many kinds, each with its own columns or volume | **a table per kind**, unified in EF Core with TPC | everything; one query over all kinds with `UNION ALL` | a class and a table per kind | | many or growing kinds, attached data uniform | **a shared identity table** every owner registers in | everything | owners take part; deletes go through the identity | | kinds you cannot change: another context's records, a framework table | **an integration event** from the owner's delete, or an orphan sweep | nothing; cleanup is eventual | idempotent consumers | | an existing `(kind, id)` table you cannot migrate yet | **a delete trigger per owner table** | cleanup on delete, cascades and raw SQL included | SQL in migrations; inserts still unchecked | The rest of this page shows each pattern with its EF Core configuration, then covers races, side effects outside the database, and why Elarion ships no application-level cascade. ## One kind: a plain foreign key [#one-kind-a-plain-foreign-key] If a note only ever belongs to a property, there is nothing polymorphic about it: ```csharp note.HasOne().WithMany().HasForeignKey(n => n.PropertyId).OnDelete(DeleteBehavior.Cascade); ``` Pick `Restrict` instead when the owner must not disappear while attached data exists. The delete then fails with a foreign-key violation (`23503`). Catch it in the handler, or in a constraint-mapping decorator of your pipeline, and answer `AppError.Conflict`. ## A few kinds: the exclusive arc [#a-few-kinds-the-exclusive-arc] One nullable foreign key per owner kind, each cascading, and a CHECK that exactly one is set. This is the usual recommendation for a small, known set of kinds: ```csharp public sealed class Note { public required Guid Id { get; init; } public Guid? PropertyId { get; init; } public Guid? ContactId { get; init; } public Guid? InvoiceId { get; init; } public required string Text { get; set; } } [EntityConfiguration] public sealed class NoteConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder note) { note.HasOne().WithMany().HasForeignKey(n => n.PropertyId).OnDelete(DeleteBehavior.Cascade); note.HasOne().WithMany().HasForeignKey(n => n.ContactId).OnDelete(DeleteBehavior.Cascade); note.HasOne().WithMany().HasForeignKey(n => n.InvoiceId).OnDelete(DeleteBehavior.Cascade); // Exactly one owner. Use the column names your naming convention produces. note.ToTable(t => t.HasCheckConstraint("ck_notes_one_owner", "num_nonnulls(property_id, contact_id, invoice_id) = 1")); } } ``` EF Core indexes each foreign key by convention, so "the notes of contact X" is an index lookup on its own column. Most of each column is null, so a partial index keeps those indexes small: `note.HasIndex(n => n.ContactId).HasFilter("contact_id IS NOT NULL")` configures the convention's index rather than adding a second one. With more than a handful of kinds, keep the list in one place and derive the foreign keys, the indexes and the CHECK from it, so a new kind is one line: ```csharp private static readonly (Type Owner, string Property, string Column)[] Owners = [ (typeof(Property), nameof(Note.PropertyId), "property_id"), (typeof(Contact), nameof(Note.ContactId), "contact_id"), (typeof(Invoice), nameof(Note.InvoiceId), "invoice_id"), ]; public void Configure(EntityTypeBuilder note) { foreach (var (owner, property, column) in Owners) { note.HasOne(owner).WithMany().HasForeignKey(property).OnDelete(DeleteBehavior.Cascade); note.HasIndex(property).HasFilter($"{column} IS NOT NULL"); } note.ToTable(t => t.HasCheckConstraint("ck_notes_one_owner", $"num_nonnulls({string.Join(", ", Owners.Select(o => o.Column))}) = 1")); } ``` `num_nonnulls` is PostgreSQL's; another provider spells the CHECK as a sum of `CASE WHEN column IS NULL THEN 0 ELSE 1 END`. Querying needs no helper — "the notes of contact X" is `db.Notes.Where(n => n.ContactId == id)` — and a `(kind, id)` value the API exposes maps to one of those predicates in the application, which owns that vocabulary. The nullable pointer works directly with [`WhereAuthorizedVia`](/docs/concepts/resource-authorization#data-that-belongs-to-a-resource): `db.Notes.WhereAuthorizedVia(n => n.ContactId, db.Contacts, c => (Guid?)c.Id, contactAccess, user)`. **Trade-offs.** * The notes table names every owner kind, and a new kind is a migration that adds a column, a foreign key, and the new CHECK. In practice the new owner kind arrives with a migration anyway. * A wide row of mostly-null columns is cheap in PostgreSQL, since nulls take no space beyond the null bitmap. * Nothing forces an owner to have notes. That is rarely wanted, and no pattern here enforces it either. ## Many kinds with their own shape: a table per kind (TPC) [#many-kinds-with-their-own-shape-a-table-per-kind-tpc] When the attached data differs per kind, or one kind has far more rows than the others, give each kind its own table. EF Core's table-per-concrete-type mapping keeps one query surface over all of them: ```csharp public abstract class Note { public required Guid Id { get; init; } public required string Text { get; set; } } public sealed class PropertyNote : Note { public required Guid PropertyId { get; init; } } public sealed class ContactNote : Note { public required Guid ContactId { get; init; } } modelBuilder.Entity().UseTpcMappingStrategy(); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(n => n.PropertyId) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(n => n.ContactId) .OnDelete(DeleteBehavior.Cascade); ``` `db.Set()` reads one table, and `db.Set()` reads all of them with a `UNION ALL`. Client-assigned `Guid` keys, the Elarion convention, keep ids unique across the tables, which TPC needs. **Trade-offs.** You get a class and a table per kind. The cross-kind query is a union, which is fine for a timeline and wasteful for hot lookups that already know the kind. ## Many kinds, uniform data: a shared identity table [#many-kinds-uniform-data-a-shared-identity-table] Every owner registers its id in one table, and the attached data references that table: ```sql create table record_identities (id uuid primary key, kind text not null); create table properties (id uuid primary key references record_identities (id) on delete cascade, ...); create table notes (id uuid primary key, record_id uuid not null references record_identities (id) on delete cascade, ...); ``` The notes table knows no owner kind, and adding a kind changes nothing in it. **Trade-offs.** * Every owner insert writes an identity row too. * **The delete must go through the identity.** Deleting the identity row removes the owner and its notes, while deleting only the property row leaves both behind. Either delete the identity, or give each owner table a delete trigger that removes its identity row. * In EF Core, a TPT mapping with an abstract `Record` base produces this shape and deletes both rows itself. But it forces one base class on every owner and adds a join to every owner query, the reason EF Core's own guidance steers away from TPT. ## An existing `(kind, id)` table: a delete trigger [#an-existing-kind-id-table-a-delete-trigger] To fix cleanup before migrating to one of the patterns above, give each owner table a row trigger. PostgreSQL fires row triggers for rows that a foreign-key cascade or raw SQL deletes too: ```sql create function delete_notes_of() returns trigger language plpgsql as $$ begin delete from notes where owner_kind = tg_argv[0] and owner_id = old.id; return old; end $$; create trigger properties_delete_notes after delete on properties for each row execute function delete_notes_of('property'); ``` Ship it as a SQL step of the [migration plan](/docs/capabilities/migrations). It makes deletes complete. Inserts are still unchecked: a note can still point at nothing. ## Inserts and races without a foreign key [#inserts-and-races-without-a-foreign-key] A foreign-key check locks the referenced row (`FOR KEY SHARE`) until the inserting transaction ends, so the owner cannot be deleted under a new note. Without a foreign key, take the same locks yourself with [`LockRowAsync`](/docs/capabilities/coordination#row-and-advisory-locks): ```csharp // Attaching a note: hold the owner the way a foreign-key check would. False means it is gone (or not visible). if (!await db.LockRowAsync(command.PropertyId, RowLockMode.KeyShare, ct)) return AppError.NotFound("No such property."); // Deleting the owner: lock it first, so attaches wait and cleanup sees everything committed before. await db.LockRowAsync(command.Id, RowLockMode.Update, ct); ``` With a foreign key, none of this is needed: the database already does it on every insert. ## Side effects outside the database [#side-effects-outside-the-database] A cascade removes rows, not what they point at elsewhere. Pick the place by whether the other side is transactional: * **Blobs in the PostgreSQL blob store** live in the same database. Delete them in the same transaction, from the handler or from a delete trigger on the files table, so a cascaded file row takes its content with it. * **An external object store, a search index, another system** is not part of the transaction. Record the work and do it after commit: an [integration event](/docs/capabilities/events), or a row in a cleanup table that a trigger writes and a [leased-work](/docs/capabilities/coordination#leased-work-rows) worker drains. Never call the external system before the deletion commits, because a rollback would leave the row without its content. ## Across contexts [#across-contexts] A record in another bounded context, or another database, cannot be referenced by a foreign key. Its owner publishes an integration event when it is deleted (`PropertyDeleted`, after commit, at least once), and the context that keeps attached data removes it idempotently. The data is eventually consistent, so a reader can briefly see a note whose owner is gone, and must tolerate that. ## Why Elarion has no application-level cascade [#why-elarion-has-no-application-level-cascade] Rails (`dependent: :destroy`) and Django (`GenericRelation`) delete the attached rows in application code, and Elarion 0.3.0 did too, with `EntitiesDeleted`. It was removed in the next release ([ADR-0090](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0090-references-between-records-stay-in-the-database.md)). It covered deletes only, and a foreign key covers deletes too and more: * it checks inserts; * it doesn't race; * raw SQL can't bypass it; * it adds no interceptor rules. Every case it served has a pattern above: the exclusive arc for a few kinds, the shared identity table for many, the trigger while migrating an existing table, and an integration event across contexts. What remained was convenience, paid for with an interceptor built on EF Core internals. **Migrating from it:** add the foreign keys (or the identity table), backfill them from `(OwnerKind, OwnerId)` in the same migration, drop the pair, and delete the `EntitiesDeleted` consumers. # Previewable commands (/docs/concepts/previewable-commands) Imports, bulk changes and anything else a person should look at before it happens are usually built as two operations: `*.importPreview` computes what would happen, `*.import` does it. The two share their decision only by discipline, and between the two calls the database can change, so the commit can act on something the person never saw — a bank-statement row shown as *new* in the preview is silently held back at commit because it became a possible duplicate in the meantime. A **previewable command** is one handler that is both. Its request implements `IPreviewableRequest`; the framework runs a preview as the real command and rolls it back, and a commit carries the fingerprint of the outcome the person confirmed, so it commits only that outcome ([ADR-0104](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0104-previewable-commands.md)). ## Writing one [#writing-one] The request carries two members, the outcome type stamps a fingerprint, and the handler is an ordinary command that makes its decision inside the transaction: ```csharp using Elarion.Abstractions; using Elarion.Abstractions.Previews; [Handler("banking.imports.commit")] public sealed class ImportStatement(BankingDbContext db) : IHandler> { // Defaults make both members optional on the wire: an ordinary call sends neither. public sealed record Command(Guid StatementId, bool Preview = false, string? PreviewFingerprint = null) : IPreviewableRequest; public sealed record Outcome(IReadOnlyList Rows, int NewCount, int HeldBackCount) : IPreviewOutcome { public string? PreviewFingerprint { get; init; } public Outcome WithPreviewFingerprint(string? fingerprint) => this with { PreviewFingerprint = fingerprint }; } public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var rows = await db.StatementRows.Where(r => r.StatementId == command.StatementId) .OrderBy(r => r.Position).ToListAsync(ct); var decisions = new List(); foreach (var row in rows) { var duplicate = await db.Bookings.AnyAsync(b => b.Reference == row.Reference, ct); if (!duplicate) db.Bookings.Add(Booking.From(row)); // the real write, previewed or not decisions.Add(new RowDecision(row.Position, duplicate ? "heldBack" : "new")); } return new Outcome(decisions, decisions.Count(d => d.Kind == "new"), decisions.Count(d => d.Kind == "heldBack")); } } ``` There is no `if (command.Preview)` around the database writes: the preview *is* the commit, rolled back. The generator attaches the preview decorator to every handler whose request implements `IPreviewableRequest`; a response that is not `Result` with `T : IPreviewOutcome` is `ELPREV001`. ## The round trip [#the-round-trip] 1. **Preview.** The client sends `preview: true`. The command runs fully, the decorator stamps the outcome with its fingerprint, and every database write is rolled back. The response is the outcome, `previewFingerprint` included. 2. **Confirm.** The client sends the same command with `previewFingerprint` set to the value it showed. The command runs again; if its outcome has the same fingerprint, the decorator commits and answers the outcome. 3. **Changed.** If the outcome differs, nothing is committed and the call fails with `409`/`Conflict`, code `preview.changed`. The error's data is the **new outcome**, with its own fingerprint, so the client can show what changed and let the person confirm again without another preview call. ```ts const preview = await rpc.banking.imports.commit({ statementId, preview: true }) // …show preview.rows, then on confirm: try { await rpc.banking.imports.commit({ statementId, previewFingerprint: preview.previewFingerprint }) } catch (error) { if (isRpcMethodError('banking.imports.commit', error) && error.code === 'preview.changed') return showChangedPreview(error.data) // the new outcome, typed; confirm it with error.data.previewFingerprint throw error } ``` A call with neither member is an ordinary command: the decorator passes it straight through (no extra unit of work, no hashing), so existing callers and in-process senders are unaffected. A call with `preview: true` is a preview even when it also carries a fingerprint. Both `preview.changed` (with the outcome as payload) and `preview.unsupported` are declared on the operation's error contract, so the schema export and the generated client type them. ## The outcome must be deterministic [#the-outcome-must-be-deterministic] The fingerprint is the SHA-256 (base64url) of the outcome's canonical JSON, serialized with `previewFingerprint` cleared through the source-generated metadata of the canonical JSON options. It changes exactly when the outcome changes, so the outcome must describe the **decision** and nothing else: * no freshly minted ids, timestamps, random values or row versions that differ between two runs of the same decision; * collections in a stable order (sort them; avoid sets whose order is unspecified); * nothing that depends on `Preview` itself. What belongs in it is what the person decides on: which rows are new, which are held back and why, the totals. A change in any of those refuses the commit; a change elsewhere in the database does not. The fingerprint is a consistency check, not a security token: a client that sends a forged fingerprint only skips its own check. Authorization, feature gates and validation run on every call as usual. When the outcome has [members visible by permission](/docs/concepts/authorization#members-only-some-callers-see), the fingerprint covers the outcome as the caller sees it, so it never encodes a member the caller may not see — and a change only in such a member does not refuse that caller's commit. ## What a rollback does not undo [#what-a-rollback-does-not-undo] The preview rolls back the **database transaction**. Everything enlisted in it goes: the handler's writes, [domain events](/docs/concepts/persistence-and-transactions#what-enlists-and-how) and their consumers' writes, integration events recorded in the outbox (or buffered by the in-memory tier), PostgreSQL blob commits, settings writes and the [audit](/docs/concepts/auditing) success record. Anything outside it stays done: * **Client events** are broadcast when they are published. They are re-query hints, so a preview's event only makes clients re-read unchanged data; harmless, but publish them as integration events or skip them when `Preview` is set if the noise matters. * **Cache invalidation** (`[CacheInvalidate]`) runs after a successful result, preview or not. It only costs a re-computation. * **External calls** — a payment provider, an e-mail, an Azure blob commit, an HTTP request — happen for real. Check `command.Preview` and skip them, or better, move them behind an integration event, which the outbox rolls back with the preview. ## Requirements and composition [#requirements-and-composition] A preview needs a unit of work whose rollback really discards writes. `IUnitOfWork.SupportsRollback` says so; it is fail-closed (`false` by default), and the EF Core (`AddElarionUnitOfWork()`) and SQL-tier units of work set it. Without one — no unit of work registered, or only the in-memory no-op default — a preview or a fingerprinted commit answers `500`/`Internal`, code `preview.unsupported`, and the handler never runs. A preview can never commit. The preview decorator sits just inside [idempotency](/docs/concepts/idempotency) and outside your `[DecoratorList]` ([order](/docs/concepts/decorator-pipelines#order-matters)), so it owns the unit of work of a preview or a fingerprinted commit: * The handler runs in a nested scope that is committed on success, so the EF unit of work flushes the change tracker (`SaveChanges`) inside the preview too: a constraint violation surfaces in the preview exactly as it would on commit, instead of a preview that says yes to a commit that fails. * Your transaction decorator still attaches (a previewable request is an `ICommand`); its scope nests with a savepoint. * Under `[Idempotent]` the idempotency decorator owns the transaction; the preview's scope is a savepoint in it and rolls back, while the key and the preview response commit. A retry of the same preview replays it. The preview and the commit are two calls, so each carries its own idempotency key (the generated client creates one per call). Reused for the commit, the preview's key would replay the preview instead of committing; the default request fingerprint of `[Idempotent]` rejects that as `idempotency.key_reused`. A previewable command can also [ask the caller to decide](/docs/concepts/results-and-errors#asking-the-caller-to-decide): a preview that reaches an unanswered decision fails with `DecisionRequired` like the commit would, and the generated client's `withDecisions` answers it and previews again with the answers in `decisions`. The commit then sends the same answers and the preview's fingerprint. If the handler should show pending questions inside the preview instead, it reports them in the outcome when `Preview` is set and asks only on commit. The handler span carries `elarion.preview.outcome` (`previewed`, `committed`, `changed`, `failed` or `unsupported`) for calls that are not ordinary. # Resource authorization (/docs/concepts/resource-authorization) [Handler authorization](/docs/concepts/authorization) decides on the *whole operation* ("may this user call this handler?"). **Resource authorization** decides on *specific resources* ("may this user read *this* contact?", "*which* contacts may they list?"). These are two different problems, and Elarion solves them with two complementary, opt-in legs driven from one declarative source — never by filtering rows in memory after the query (which breaks pagination and leaks data). Resource authorization is transport-neutral and depends only on `ICurrentUser` (user id + roles). The database is the only external system — there is no relationship/policy-engine dependency. ## Two questions, two legs [#two-questions-two-legs] | Question | Leg | Mechanism | | --------------------------------------------------- | --------------- | ---------------------------------------------------------------------------------------- | | "Which resources may I read?" (lists/search) | **List filter** | `[ResourceFilter]` → a predicate pushed into SQL **before** paging | | "May I read/write *this* resource?" (get-one/write) | **Point check** | `[RequireResource(...)]` → the `IResourceAuthorizer` seam, answered from the same filter | Both legs read **one rule per entity**: the registered `IQueryAuthorizer`. The list composes it into the query, the point check asks whether one row is in it, and [the complement](#rows-hidden-from-the-caller) negates it. ## Leg B — list filtering (push the rule into SQL) [#leg-b--list-filtering-push-the-rule-into-sql] Declare a filter for an entity on a dedicated partial class (the entity stays clean, like `[Keyset]`): ```csharp [ResourceFilter( OwnerProperty = nameof(Contact.OwnerId), // a grant: the row's owner TenantProperty = nameof(Contact.TenantId), // a scope: must match the caller's tenant claim Shared = true, ResourceTypeName = "Contact")] // a grant: shared via the grants table (user or role) public sealed partial class ContactAccess; ``` The generator completes the class as an `IQueryAuthorizer` and auto-registers it. The class (and the entity) may be `internal`: a filter in a module assembly that the host cannot name is registered through a public `ContactAccessElarionRegistration` class the module's own generator emits next to it. Inject it into the handler and compose it into the query **before** paging: ```csharp public sealed class ListContacts(AppDbContext db, ICurrentUser user, IQueryAuthorizer access) : IHandler>> { public async ValueTask>> HandleAsync(Query request, CancellationToken ct) => await db.Contacts .WhereAuthorized(access, user) // owner OR shared-with-user OR shared-with-role .Where(c => c.Category == request.Category) // your business filters .ToKeysetPageAsync(request, RecentContacts.Definition, c => new ContactDto(c.Id), cancellationToken: ct); } ``` The predicate is part of the single SQL statement, so the database filters the rows — pagination and total counts are correct, and unauthorized rows are never returned. The rules compose as **`AND(scopes) AND OR(grants)`**: a row is visible when it satisfies every scope (tenant) and at least one grant (owner, or a share). In plain terms, the `Shared` flag decides **how wide the list is**: * **`Shared = false`** (owner/tenant rules only) — the caller sees **only the rows they own**, within their tenant. * **`Shared = true`** — the caller *also* sees **rows explicitly shared with them**, either directly or with a role they belong to, recorded in the [grants table](#sharing-with-users-and-roles). Either way, a row the caller neither owns nor was granted is never returned — and never counted. **Inject the authorizer; the static `Specification` is a shortcut for field-only filters.** A filter that uses `Shared` consults the grants table, so it is a **scoped service** — you must inject `IQueryAuthorizer` (as above), and there is no static accessor. A filter with only field rules (`OwnerProperty`/`TenantProperty`) is stateless, so the generator *also* exposes a static `ContactAccess.Specification` singleton you can hand to `WhereAuthorized` without DI. Both forms are auto-registered as `IQueryAuthorizer` by the host bootstrapper (module-feature-gated), so injection works for either. Never filter a list in memory after the query (the `@PostFilter` shape). It returns short pages, wrong counts, and leaks how many rows exist. `WhereAuthorized` exists precisely so you don't. **`WhereAuthorized` is convention-only — nothing attaches it for you.** Unlike `[RequirePermission]` or `[RequireResource]`, which the generator auto-attaches as decorators, the list filter runs only where a handler composes it into the query. A list handler that forgets `WhereAuthorized` (or applies it after a `.Select()` projection that discards the entity) returns **every** row — the classic BOLA/IDOR shape. Treat "every list query over an access-controlled entity starts with `WhereAuthorized`" as a review checklist item, and cover each list handler with a test asserting an unshared row is absent. This is the right trade for *sharing*, where the decision is per feature. It is the wrong trade for *tenancy*, where a forgotten call is a cross-tenant leak rather than a widened list — so tenancy gets its own unconditional mechanism. See [multi-tenancy](/docs/capabilities/multi-tenancy). ### Administrators: a bypass permission [#administrators-a-bypass-permission] "Holds `contacts.manage`, sees every contact" is one property: `BypassPermission`. For a caller with that permission claim the owner and sharing rules are lifted; everyone else gets the declared rules. **The scope stays:** with a `TenantProperty`, the holder sees every contact of their own tenant, never another tenant's, and a caller without a tenant claim still sees nothing. Only a filter with no scope rule becomes unrestricted. ```csharp [ResourceFilter(OwnerProperty = nameof(Contact.OwnerId), Shared = true, ResourceTypeName = "Contact", BypassPermission = "contacts.manage")] public sealed partial class ContactAccess; ``` The permission is read from the `permission` claim, the default of `AuthorizationOptions.PermissionClaimType`; set `PermissionClaimType` on the attribute when the host changes it. Where the administrators are a **role** rather than a permission, `BypassRole = "Admin"` does the same; with both set, either one bypasses. The bypass is part of the filter, so the point check sees it too once the entity's [filter check](#one-rule-for-the-list-and-the-point-check) is registered. The grants-only point check knows neither the owner column nor the bypass. ### Data that belongs to a resource [#data-that-belongs-to-a-resource] Notes, files and comments point at a resource by id and are visible exactly when that resource is. Filter them by their **owner's** visibility instead of re-implementing it for each table — `WhereAuthorizedVia` runs the owner's filter as a subquery of the same statement (`WHERE contact_id IN (SELECT id FROM contacts WHERE …)`): ```csharp var notes = await db.Notes .Where(n => n.OwnerKind == RecordKind.Contact) .WhereAuthorizedVia(n => n.OwnerId, db.Contacts, c => c.Id, contactAccess, currentUser) .ToOffsetPageAsync(request, n => new NoteRow(n.Id, n.Text), NoteSort, ct: ct); ``` **Narrow a shared pointer to one owner kind first.** When `OwnerId` points at contacts, properties and invoices alike, the `OwnerKind` filter above is mandatory, not an optimization: without it, a note on an invoice whose id equals a visible contact's id passes. For data whose owners are of several kinds, filter each kind's rows by its own owner and combine the queries (`Concat`) before paging. A nullable pointer works with an owner key of the same type (`c => (Guid?)c.Id`); rows pointing at no owner are then excluded. #### Visible through an owner, as part of a rule [#visible-through-an-owner-as-part-of-a-rule] `WhereAuthorizedVia` filters one query. When "readable through an owner" is one **alternative** of a type's rule — an e-mail is visible to its sender, and to whoever may read a record it is assigned to — state it with `QueryAuthorizers.Via`, so it composes with the other alternatives and the [inverse](#who-may-see-a-record) can read it. The owner type's own rule, composed or generated, is used as it stands: ```csharp // Owners reached by a navigation, or a join through a link table: a static rule. public static readonly IQueryAuthorizer Visibility = QueryAuthorizers.AnyOf( QueryAuthorizers.ForUser((email, userId) => email.SenderId == userId), QueryAuthorizers.Via( email => email.Links.Select(link => link.Contact), ContactVisibility.Authorizer)); // One owner behind a reference: a static rule. public static readonly IQueryAuthorizer TaskVisibility = QueryAuthorizers.Via(task => task.Contact, ContactVisibility.Authorizer); // Owners behind an id column or a (kind, id) pointer, which has no navigation: one EXISTS per owner kind, over the // queried store's set of that kind. QuerySets.Of() names the set without holding a DbContext, so this is a // static rule too. public static readonly IQueryAuthorizer VisibilityByPointer = QueryAuthorizers.AnyOf( QueryAuthorizers.ForUser((email, userId) => email.SenderId == userId), QueryAuthorizers.Via( QuerySets.Of(), (email, contact) => email.Links.Any(l => l.Kind == RecordKind.Contact && l.RecordId == contact.Id), ContactVisibility.Authorizer), QueryAuthorizers.Via( QuerySets.Of(), (email, property) => email.Links.Any(l => l.Kind == RecordKind.Property && l.RecordId == property.Id), PropertyVisibility.Authorizer)); ``` * **A row needs an owner.** A row with none is not visible through `Via`, also to a caller the owner's rule does not restrict — unlike `WhereAuthorizedVia`, which keeps every row for such a caller. Give unassigned rows an alternative of their own. * **Narrow a shared pointer to the owner's kind** in the join, as above, for the reason given for `WhereAuthorizedVia`. * **Name the set with a placeholder.** `QuerySets.Of()` stands for the queried store's set of `T`, and `QuerySets.Unfiltered()` for the same set without the store's query filters (archived or soft-deleted owners included; EF Core then lifts the filters of the whole query). Entity Framework Core puts the querying context's set in its place when the context options call `UseElarionQuerySets()`: ```csharp builder.Services.AddDbContext(options => options .UseNpgsql(connectionString) .UseElarionQuerySets()); ``` The same placeholder works inside any rule expression that reads another set (`QueryAuthorizers.Rows(email => QuerySets.Of().Any(l => l.EmailId == email.Id))`). A query that reaches a placeholder nothing resolves fails and names it. LINQ to Objects resolves none, so a unit test over in-memory rows passes the rows as the set, or resolves the query with `QuerySets.Resolve`. * **A set passed directly belongs to a scope.** `db.Contacts` becomes part of every query the rule filters, so a rule composed over it lives where the context lives (a scoped registration), not in a static field. * **The owner is asked about the row's operation.** Pass `ownerOperation: ResourceOperation.Read` to let whoever may read the record also change what is assigned to it. ### Composing filters: membership tables and computed rules [#composing-filters-membership-tables-and-computed-rules] A rule the attribute cannot express — sharing through an application-owned membership table (contact groups), rows every holder of a permission may see — is **added to** the generated filter, not written instead of it. `QueryAuthorizers` has the building blocks; the result is still a single predicate the database evaluates: ```csharp // The owner rule, as a building block: generated, but not registered. [ResourceFilter(OwnerProperty = nameof(Contact.OwnerId), Register = false)] public sealed partial class ContactOwnerFilter; public static class ContactVisibility { public static readonly IQueryAuthorizer Authorizer = QueryAuthorizers.AnyOf( // administrators see every contact QueryAuthorizers.WhenRole("Admin", QueryAuthorizers.Unrestricted()), // whoever may read contacts sees the ones nobody restricted QueryAuthorizers.WhenPermission("contacts.read", QueryAuthorizers.Rows(c => !c.IsRestricted)), // the owner ContactOwnerFilter.Specification, // members of a group the contact is shared with QueryAuthorizers.ForUser((c, userId) => c.Shares.Any(share => share.Group.Members.Any(member => member.UserId == userId)))); } // A module's ConfigureServices, or the host: this is the IQueryAuthorizer. services.AddSingleton(ContactVisibility.Authorizer); ``` | Building block | Grants | | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | | `Rows(predicate)` | the rows matching the predicate | | `Unrestricted()` | every row (a `null` filter) | | `ForUser((row, userId) => …)` | the rows related to the caller's id — ownership, membership, an assignment | | `RequireUserId()` | every row, to a caller whose id parses as `TKey` — the precondition `AllOf(RequireUserId<…>(), AnyOf(…))` | | `When(condition, then)` / `WhenPermission(permission, then)` / `WhenRole(role, then)` | `then`, to callers passing the gate | | `UnlessClaim(claimType, then)` / `UnlessClaim(claimType, value, then)` | `then`, to callers **without** the claim ([withdrawing an alternative](#withdrawing-an-alternative-for-a-session)) | | `ForOperations(authorizer, operations…)` | `authorizer`, for the listed operations only | | `Via(owners, ownerRule)` / `Via(reference, ownerRule)` / `Via(ownerSet, joins, ownerRule)` | the rows with an owner `ownerRule` grants ([through an owner](#visible-through-an-owner-as-part-of-a-rule)) | | `AnyOf(…)` / `AllOf(…)` | the union / the intersection | | `From((user, operation) => …)` | whatever the delegate returns — **unchecked** | **Permissions are read from the claims.** `WhenPermission` asks the permission claim, not `IPermissionChecker`: the filter is SQL, and its [inverse](#who-may-see-a-record) reads the stored claims. A host whose checker grants more than the claims (administrators hold everything) grants those permissions as claims too, or adds the rule as its own alternative (`WhenRole("Admin", …)`), so the gate, the filter and the inverse agree — see [one place for "administrators hold everything"](/docs/concepts/authorization#one-place-for-administrators-hold-everything). **They fail closed.** Every building block denies a caller who is not authenticated before the rule is consulted, and `ForUser` also denies a caller whose id does not parse as `TKey`, so no alternative repeats that preamble. An unrestricted alternative (`WhenRole("Admin", Unrestricted())`) does not parse the id, so a service account whose id is not a `Guid` passes it; when every caller of the rule must have an id of the rows' key type, put `RequireUserId()` in front: `AllOf(RequireUserId(), AnyOf(…))`. **Test doubles must be authenticated.** The generated `[ResourceFilter]` and every building block check `ICurrentUser.IsAuthenticated` before anything else, so a test `ICurrentUser` stub that sets a `UserId` but leaves `IsAuthenticated` `false` sees no rows at all — set both. `From` is the exception: its delegate is the whole rule, including the authentication check. `ForUser` takes the rule as one expression over the row and the caller's id; the id reaches the database as a parameter. **Register the composition, not its parts.** `Register = false` keeps a building block out of the container. The generated registration is a `TryAdd` in any case, so an `IQueryAuthorizer` you register yourself — in a module's `ConfigureServices`, or in the host before or after `AddElarion` — is the one an injected authorizer and the point check resolve. Two registered `[ResourceFilter]` classes for one entity are reported as [`ELMOD007`](/docs/reference/diagnostics). A filter with `Shared` is a scoped service, so compose it in a factory: `services.AddScoped>(sp => QueryAuthorizers.AnyOf(new ContactAccess(sp.GetRequiredService()), …))`. **A scope does not survive an OR.** `AnyOf(tenantScopedFilter, groupRule)` lets `groupRule` reach rows of every tenant, and an `Unrestricted()` alternative lifts the scope for its callers. Keep the scope outside the alternatives — `QueryAuthorizers.AllOf(scope, QueryAuthorizers.AnyOf(…))`, where an unrestricted alternative is neutral — or leave tenancy to [ambient tenant scoping](/docs/capabilities/multi-tenancy), which no composition can lift. #### Wider for reading than for writing [#wider-for-reading-than-for-writing] `ForOperations` states which operations an alternative grants; every other operation is denied for it: ```csharp QueryAuthorizers.AnyOf( QueryAuthorizers.ForOperations( // reading only QueryAuthorizers.WhenPermission("contacts.read", QueryAuthorizers.Rows(c => !c.IsRestricted)), ResourceOperation.Read), ContactOwnerFilter.Specification) // every operation ``` `WhereAuthorized` asks about **`Read` unless told otherwise**. With a rule like this one, a write handler must pass its operation (`WhereAuthorized(access, user, ResourceOperation.Update)`) or declare it on `[RequireResource]`, which passes it for you. #### Withdrawing an alternative for a session [#withdrawing-an-alternative-for-a-session] `UnlessClaim` is a negated gate: its alternative applies to callers who do **not** hold a claim. It lets one rule drop an alternative for sessions the host marks — while an administrator views the application as another user, an `act` claim on the session withdraws the administrator's bypass, and the rest of the rule answers as for that user: ```csharp QueryAuthorizers.AnyOf( QueryAuthorizers.UnlessClaim("act", QueryAuthorizers.WhenRole("Admin", QueryAuthorizers.Unrestricted())), ContactOwnerFilter.Specification) ``` A negated gate grants when the claim is missing, so use it only to withdraw an alternative from a claim the host adds on purpose, never as the only thing between a caller and rows. The [inverse](#who-may-see-a-record) reads the claim from the principal directory; a session marker is held by no stored principal, so "who may see this record" answers for ordinary sessions. ### Rows hidden from the caller [#rows-hidden-from-the-caller] A document registry that subtracts the hidden rows of several record kinds needs the **complement** of a filter. `WhereNotAuthorized` is that, as a query — nothing for an unrestricted caller, everything for a caller the rule denies entirely: ```csharp var hiddenContactIds = db.Contacts.WhereNotAuthorized(ContactVisibility.Authorizer, currentUser).Select(c => c.Id); var files = db.Files.Where(f => f.ContactId == null || !hiddenContactIds.Contains(f.ContactId.Value)); ``` The two sets partition the source under Entity Framework Core's default null semantics; with `UseRelationalNulls` a predicate that evaluates to SQL `NULL` puts its row in neither. ## Sharing with users and roles [#sharing-with-users-and-roles] Shares live in a DB-native grants table. Map it on your context — either with the attribute (emits the `DbSet` and the table mapping, like `[GenerateElarionIdentity]`): ```csharp [GenerateDbSets] [GenerateElarionResourceGrants] public sealed partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder); } ``` …or by hand: `modelBuilder.ApplyElarionResourceGrants()`. Both forms take the same overrides — the attribute accepts optional `TableName` and `Schema` properties alongside `SnakeCase`, and `ApplyElarionResourceGrants(tableName, schema, snakeCase)` mirrors them (defaults `elarion_resource_grants`, or `ElarionResourceGrants` with `snakeCase: false`; the principal index name is derived from the table name — `ix_{table}_principal` / `IX_{table}_Principal`). Then register the backend and manage shares: ```csharp services.AddElarionResourceAuthorization(); // grants source, store, and the point-check authorizer ``` Shares are managed through the injected `IResourceGrantStore`: ```csharp [Handler] public sealed class ShareContact(IResourceGrantStore grants) { public async ValueTask HandleAsync(ShareContactCommand command, CancellationToken ct) { // Share one contact with the "Hausmeister" role for read — every user in that role can now see it. await grants.GrantAsync( new ResourceGrant("Contact", command.ContactId.ToString(), ResourcePrincipal.Role("Hausmeister"), ResourceOperation.Read), ct); return Result.Success(); } } ``` The `Shared` filter turns this into an indexed correlated `EXISTS` over the caller's user id **or any of their roles** — a small, bounded lookup that scales. Granting the same `(resource, principal, operation)` twice is **idempotent** — the EF Core backend claims a grant with an `INSERT … ON CONFLICT DO NOTHING`, so a concurrent duplicate never raises a unique violation (which would otherwise abort, and poison, the caller's ambient transaction). The resource-type discriminator, resource id, user ids, and role names are matched **case-sensitively** (`StringComparison.Ordinal`): a casing mismatch between a stored grant and the caller's `ICurrentUser` fails closed (denies) — it never grants access. Store principal ids and role names in a consistent casing. Grants are **operation-scoped**, and the `Shared` rule only matches grants for the operation `WhereAuthorized` asks about — which **defaults to `Read`**. To list the rows a caller may *edit*, pass the operation explicitly: ```csharp db.Contacts.WhereAuthorized(access, user, ResourceOperation.Update) // EXISTS matches "update" grants ``` The operation narrows only the **grant** (`Shared`) lookup; the `OwnerProperty`/`TenantProperty` rules are operation-independent, so an owner still sees their own rows under any operation. ## Leg A — the per-resource point check [#leg-a--the-per-resource-point-check] For a get-one or write handler, declare which request property names the resource. The id is a **compile-checked path** (per [ADR-0012](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0012-dynamic-variable-references.md)), not a string expression — the generator validates it against the request and emits a zero-reflection accessor: ```csharp [RequireResource(typeof(Contact), Operation = "read", Id = nameof(GetContact.Query.Id))] public sealed class GetContact : IHandler> { public sealed record Query : IQuery { public Guid Id { get; init; } } // ... } ``` The decorator resolves the id and asks `IResourceAuthorizer`. ### One rule for the list and the point check [#one-rule-for-the-list-and-the-point-check] Register a **filter check** for the entity, and its point check asks the same `IQueryAuthorizer` the list uses — one `EXISTS` for the row with that key, among the rows the rule lets the caller access for the declared operation: ```csharp services.AddElarionResourceFilterCheck(c => c.Id); [RequireResource(typeof(Contact), Operation = "update", Id = nameof(Command.Id), DenyAs = ResourceDenial.NotFound)] public sealed class UpdateContact : IHandler { /* ... */ } ``` Owner, sharing, bypass and every composed alternative apply, because it is the registered authorizer that is asked — an administrator who sees a contact in the list passes its get-one, and a caller who may read but not change a record is denied the update. It needs `Elarion.Authorization.EntityFrameworkCore`, but not the grants table. * **A row that does not exist is denied**, also for an unrestricted caller. With `DenyAs = ResourceDenial.NotFound` a hidden record and a missing one get the same answer. * **The set's query filters apply**: a soft-deleted row is denied, and ambient tenant scoping holds. To keep a hidden record authorized for the accounts that could see it (a restore command), shape the set: `AddElarionResourceFilterCheck(c => c.Id, rows => rows.IgnoreQueryFilters(["SoftDelete"]))`. Name the filter you drop — a bare `IgnoreQueryFilters()` drops the tenant filter with it. * **The request's id** may be the key type or, for `Guid`/`int`/`long` keys, its text. An id that cannot be the entity's key is denied. * The check is for an **existing** record. Guard a create with `[RequirePermission]`. A resource type **without** a filter check is authorized from the grants table (a share with the caller's user or roles) once `AddElarionResourceAuthorization` is called; with no backend registered the check **fails closed** (a logged 403). The filter check is registered per entity: a `[RequireResource]` on a type that has a filter but no check is answered by the grants alone — it denies more, never less. A hand-written check for one type is a keyed service: `services.AddKeyedScoped(typeof(Invoice))`. ### Hidden, not forbidden [#hidden-not-forbidden] A `403` tells the caller the record exists. When a list filter hides records, their point check should answer like a missing record instead — otherwise ids can be probed one by one: ```csharp [RequireResource(typeof(Contact), Id = nameof(GetContact.Query.Id), DenyAs = ResourceDenial.NotFound)] public sealed class GetContact : IHandler> { /* ... */ } ``` A denial now answers `404` with the code `not_found` and `AuthorizationOptions.ResourceNotFoundMessage` (default "The requested resource was not found."); make the handler's own missing-record answer use the same message, or the two stay distinguishable. `not_found` joins the operation's declared error contract. With several `[RequireResource]` on one handler, they are checked in declaration order and the first denial answers with its own `DenyAs`, so declare the hidden resource first when a later, forbidden one would confirm it exists. ### The resource-type discriminator [#the-resource-type-discriminator] A grant identifies its resource by a **discriminator string**, stored in the `resource_type` column. The point check derives that discriminator from `typeof(Contact)` — by default the type's **`FullName`** (e.g. `MyApp.Crm.Contact`), so two entities named `Contact` in different modules never share authorization. Every path that produces or compares the discriminator agrees on it via `Elarion.Abstractions.Authorization.ResourceTypeDiscriminator`: * what `IResourceGrantStore.GrantAsync` **writes** (the `ResourceGrant.ResourceType` string you pass), * the point check in the grants-backed `IResourceAuthorizer`, and * the `EXISTS` subquery the `[ResourceFilter(Shared = true)]` generator emits. When you want a **stable, namespace-independent** discriminator (e.g. the short `"Contact"`), set the same override on all three: `[RequireResource(typeof(Contact), ResourceTypeName = "Contact")]`, `[ResourceFilter(Shared = true, ResourceTypeName = "Contact")]`, and the `ResourceType` string on every `ResourceGrant` you write. If they disagree, the grant simply never matches (fail-closed). ## The escape hatch — validate before a write [#the-escape-hatch--validate-before-a-write] A handler that loads the record anyway can authorize and load in **one statement**, by the same rule — the deliberate alternative to a hidden write interceptor, and one round trip less than `[RequireResource]`: ```csharp var contact = await db.Contacts .WhereAuthorized(access, currentUser, ResourceOperation.Update) .FirstOrDefaultAsync(c => c.Id == request.Id, ct); if (contact is null) return AppError.NotFound("The requested resource was not found."); // hidden and missing answer alike ``` Or inject `IResourceAuthorizer` for a check by id without loading; it routes like `[RequireResource]` does (the entity's filter check, else the grants): ```csharp if (!await resourceAuth.AuthorizeResourceAsync( new ResourceAuthorizationContext(currentUser, typeof(Contact), "Contact", ResourceOperation.Update, request.Id), ct)) return Result.Failure(AppError.Forbidden("Not allowed to update this contact.")); ``` `IQueryAuthorizer.Matches(entity, user)` evaluates the predicate in memory against a loaded entity. Use it only for rules that read the entity's own scalar fields (owner, tenant): a navigation the entity was loaded without is empty there, which denies a positive rule and **allows** a negated one. `[ResourceFilter]` predicates are a **read** filter; they do not stop a wrong-owner *write*. Enforce writes with `[RequireResource]` or the escape hatch above. Raw SQL (`FromSqlRaw`) and `IgnoreQueryFilters` bypass the in-app predicate — there is no Postgres RLS backstop, so keep enforcement in your handlers. ## Who may see a record? [#who-may-see-a-record] Mentions, notifications and an access overview ask the inverse question: *which* principals may access record X. `WhereAuthorizedFor` answers it from the same rule the list filter applies, in one statement: ```csharp // The active staff accounts that may read this contact. var readers = await users.ActiveStaff(now) // the candidates: your eligibility rule .WhereAuthorizedFor(db.Contacts.Where(c => c.Id == contactId), contactAccess, directory) .ToListAsync(ct); ``` * **The candidates are yours.** The result is a subset of the principal ids you pass, so you decide who is eligible at all (the accounts that can still sign in, the staff of one department) and the rule decides who among them may access the rows. With several rows, a principal is returned when it may access at least one. * **Every row of a selection: `WhereAuthorizedForAll`.** A selection action — "whom may these 12 e-mails be put in charge of" — needs the principals who may access **all** of them. It reads the same rule, in one statement, and returns nobody for an empty selection: ```csharp var assignees = await users.ActiveStaff(now) .WhereAuthorizedForAll(db.Emails.Where(e => selectedIds.Contains(e.Id)), emailAccess, directory) .ToListAsync(ct); ``` The rows are used as given, so a selected id that no longer names a row (deleted, or hidden by a query filter) is not asked about. Like the complement, "all" is exact under EF Core's default null semantics; with `UseRelationalNulls` a relation that evaluates to SQL `NULL` does not exclude a principal. * **The rule is read as a relation** between a row and a principal id. `ForUser` already is one; `Rows`, `Unrestricted`, `WhenPermission`, `WhenRole`, `UnlessClaim`, `ForOperations`, `Via`, `AnyOf`, `AllOf` and the generated `[ResourceFilter]` (owner, bypass permission and role, user and role grants) translate to one. Pass the operation to ask who may *change* the record. * **Complete or refused.** A rule that contains `QueryAuthorizers.From`, `QueryAuthorizers.When`, a hand-written authorizer or a generated filter with a `TenantProperty` throws `NotSupportedException` naming that part — it never answers for the rest and leaves an alternative out. Restate the part with the building blocks, or implement `IPrincipalQueryAuthorizer` on your authorizer. ### The principal directory [#the-principal-directory] A gate such as "holds `contacts.read`" is read from the live `ICurrentUser` when a caller lists contacts. For the inverse there is no caller, so the same fact comes from an `IPrincipalDirectory`: two queries, the roles and the **effective** claims (a role's claims listed for each member) of every principal. ```csharp // ASP.NET Core Identity tables: user_roles, user_claims and the role_claims of a principal's roles. services.AddElarionIdentityPrincipalDirectory(); ``` **The directory must agree with the principal your host builds.** The Identity-backed directory mirrors Identity's default claims factory. If the host adds a role or a claim at sign-in or per request — an instance owner who is made an administrator on every request — register your own directory that adds the same fact, or those principals are missing from the answer: ```csharp public sealed class AppPrincipalDirectory(AppDbContext db) : IPrincipalDirectory { private readonly IdentityPrincipalDirectory _stored = new(db); public IQueryable> Roles => _stored.Roles.Concat( db.Users.Where(u => u.IsOwner).Select(u => new PrincipalRole { PrincipalId = u.Id, Role = "Admin" })); public IQueryable> Claims => _stored.Claims; } services.AddScoped, AppPrincipalDirectory>(); // kept: the default is a TryAdd ``` Pin the agreement with a test that builds a principal the way the host does and compares its roles and claims with the directory. The forward filter stays the authority: a principal the inverse lists is still checked when it reads the record. ### Who holds a permission [#who-holds-a-permission] Mention candidates, assignees and the readers of a notification often need no record at all, only the accounts that hold a permission or a role. Ask the directory, so the answer is derived the same way as the principal: ```csharp var handlers = await users.ActiveStaff(now) .Where(u => directory.HoldersOf("requests.handle").Contains(u.Id)) // user claims and role claims, each once .ToListAsync(ct); var admins = directory.MembersOf("Admin"); ``` `HoldersOf(permission, claimType?)` and `MembersOf(role)` return composable queries of principal ids; pass the host's permission claim type when it is not `permission`. For shares alone, `IResourceGrantStore.GetGrantsAsync(resourceType, resourceId)` still lists the users and roles a record is shared with. ## See also [#see-also] * [ADR-0013: Resource-based and data-level authorization](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0013-resource-and-data-level-authorization.md) * [ADR-0095: One resource rule for the list, the point check and the complement](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0095-one-resource-rule-for-list-point-check-and-complement.md) * [ADR-0012: Referencing dynamic variables in attributes](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0012-dynamic-variable-references.md) * [Authorization](/docs/concepts/authorization) — the operation-level gate this builds on. # Results & errors (/docs/concepts/results-and-errors) Handlers return outcomes as values, not exceptions. `Result` carries either a success value or an `AppError`, and the host maps that error to whatever the transport requires. ## `Result` [#resultt] `Result` is a `readonly struct` with a success value or an `AppError`: ```csharp public readonly struct Result { public bool IsSuccess { get; } public T Value { get; } public AppError Error { get; } public static Result Success(T value); public static Result Failure(AppError error); } ``` Implicit conversions let a handler return either a response or an error directly — no wrapping ceremony: ```csharp return new Response(project.Id); // implicit Success return AppError.Validation("Name is required."); // implicit Failure return AppError.Conflict("Invoice number is already reserved."); AppError.Conflict("The seat is taken.", code: "seat.taken", data: new SeatTaken(4)); // specific code + payload ``` Because it is a struct with `ValueTask`-friendly ergonomics, the success path stays allocation-light. ## `AppError` [#apperror] `AppError` is a transport-agnostic record describing *what kind* of failure occurred, not *how* a particular protocol should report it: ```csharp public sealed record AppError { public required ErrorKind Kind { get; init; } public required string Message { get; init; } public string Code { get; init; } // always present: a stable, machine-readable identifier public object? Data { get; init; } // typed payload for that code } ``` `Message` is prose; clients branch on `Code`. Each kind has a default code (`not_found`, `conflict`, `validation`, ...) and any factory takes a specific one: `AppError.Conflict("Seat taken.", code: "seat.taken", data: new SeatTaken(4))`. A handler **declares** the failures it can produce with `[ProducesError("seat.taken", ErrorKind.Conflict, typeof(SeatTaken))]`; the declaration flows into the JSON-RPC schema and the generated TypeScript client, which types `error.code` and `error.data` per method. See the [reference](/docs/reference/result-and-errors#produceserror--the-declared-error-contract). Failures that many handlers share are declared once: on the assembly or the `[AppModule]` class for kind-default codes such as `not_found`, or on the decorator that adds them (see [Declaring errors for many operations](/docs/reference/result-and-errors#declaring-errors-for-many-operations)). ### Error kinds [#error-kinds] | `ErrorKind` | Meaning | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Validation` | Invalid input or constraint violation. | | `NotFound` | The requested resource does not exist. | | `Conflict` | The operation conflicts with existing state (duplicate, concurrent modification). | | `Unauthorized` | The caller is not authenticated (missing or invalid credentials). Maps to HTTP 401. | | `Forbidden` | The caller is authenticated but not authorized to perform this operation. | | `BusinessRule` | A domain business rule was violated. | | `DecisionRequired` | The request is valid but needs the caller's decision before it runs. Maps to HTTP 409. See [Asking the caller to decide](#asking-the-caller-to-decide). | | `Internal` | An unexpected internal error occurred. | ### Factory methods [#factory-methods] Each kind has a factory; validation supports an optional structured payload: ```csharp AppError.Validation("Name is required."); AppError.Validation("Invalid command.", new[] { "Name is required.", "Email is invalid." }); AppError.Validation("Invalid command.", new Dictionary { // field-keyed: renders as ["name"] = ["Name is required."], // RFC 7807 `errors` over HTTP }); AppError.NotFound($"Client {id} was not found."); AppError.Conflict("Invoice number is already reserved."); AppError.Unauthorized("Authentication required."); AppError.Forbidden("You cannot modify this resource."); AppError.BusinessRule("Credit limit exceeded.", data: limitInfo); AppError.DecisionRequired("banking.possible_duplicate", "Import these lines anyway?", duplicates); AppError.Internal("Failed to render the document."); ``` `AppError.InternalError` is a shared instance for the generic internal-failure case. ## Mapping to a transport [#mapping-to-a-transport] `Kind` is the seam between application semantics and protocol codes. Each host owns the mapping, so different deployments can translate the same domain failure differently: ```csharp // The framework default: AppError → JSON-RPC error code (Elarion.JsonRpc.AppErrorMapper) var code = error.Kind switch { ErrorKind.Validation => -32602, // spec "Invalid params" ErrorKind.NotFound => -32001, // server range ErrorKind.Conflict => -32002, // server range ErrorKind.Forbidden => -32003, // server range ErrorKind.BusinessRule => -32004, // server range ErrorKind.Unauthorized => -32005, // server range ErrorKind.DecisionRequired => -32006, // server range _ => -32603, // spec "Internal error" }; ``` This keeps handlers free of transport details: the same `AppError.NotFound(...)` becomes a JSON-RPC error in one host and an HTTP `404` in another. For the complete, authoritative tables — both the JSON-RPC codes and the HTTP status mapping — see the [Result & error model reference](/docs/reference/result-and-errors). ## Asking the caller to decide [#asking-the-caller-to-decide] Some commands are valid but need the caller's decision first: "this line looks like a booking you already have — import it anyway?", or a choice such as changing an exported invoice "only here" or "as a correction". Instead of a `Conflict` with a code of its own plus a `ConfirmX` flag per flow, a handler declares the decision and asks with `ErrorKind.DecisionRequired`; every flow then shares one shape on the server, on the wire and in the generated client ([ADR-0101](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0101-a-decision-required-answer.md)). ```csharp public enum DuplicateChoice { Import, Skip } [Handler] [RequirePermission("banking", Verbs.Write)] [RequiresDecision(Codes.PossibleDuplicate, Options = typeof(DuplicateChoice), PerItem = true, DataType = typeof(PossibleDuplicates))] [RequiresDecision(Codes.ClosedPeriod)] // no Options: a confirmation public sealed class CommitImport(AppDbContext db) : IHandler> { public sealed record Command : ICommand, IDecidingRequest { public required UploadedFile Statement { get; init; } public IReadOnlyList? Decisions { get; init; } } public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var lines = await ReadLinesAsync(command.Statement, ct); if (lines.Any(l => l.InClosedPeriod) && !command.IsConfirmed(Codes.ClosedPeriod)) return AppError.DecisionRequired(Codes.ClosedPeriod, "Some lines fall into a closed period. Import them?"); // Per item: refuse while any line the server finds has no declared option, then act on each answer. var duplicates = await FindPossibleDuplicatesAsync(lines, ct); var unanswered = command.Unanswered(Codes.PossibleDuplicate, duplicates.Select(d => d.Key)); if (unanswered.Count > 0) return AppError.DecisionRequired(Codes.PossibleDuplicate, "Some lines look like existing bookings.", new PossibleDuplicates([.. duplicates.Where(d => unanswered.Contains(d.Key))])); foreach (var line in lines) if (command.Decision(Codes.PossibleDuplicate, line.Key) != DuplicateChoice.Skip) db.Bookings.Add(line.ToBooking()); … } } ``` * **The declaration** (`[RequiresDecision(code, Options = typeof(TEnum), PerItem = …, DataType = …)]`) joins the operation's error contract like `[ProducesError]`: the schema exports the code with kind `decision_required`, its options (the enum members in camel case, here `import`/`skip`; a confirmation's one option is `confirm`) and `perItem`. Options that are not an enum are a build error (`ELERR003`). * **The answers travel in one member.** The request implements `IDecidingRequest`; its `Decisions` is a list of `{ code, item?, option }`. `IsConfirmed(code)`, `Decision(code)` and their per-item overloads read it (the last answer for a code and item wins); `Unanswered(code, keys)` lists the items of a choice still to ask, and `Unanswered(code, keys)` those of a per-item confirmation. An option the enum does not declare counts as no answer everywhere, so the handler asks again: an item `Unanswered` leaves out always has a `Decision`, and one answered with an undeclared option is asked about, never skipped silently. * **The schema states the answers the request takes.** Its `decisions` member is exported narrowed to the declared decisions: each answer names one of the declared codes and one of that decision's options (which a confirmation may leave out), and a per-item answer names its item. The generated client types `decisions` per method from it, so the request's description need not list its decision codes. * **Answering from C#** — a test, or an in-process caller — takes one line per answer, with the option spelled as `Decision` reads it: ```csharp var command = new CommitImport.Command { Statement = statement, Decisions = [ DecisionAnswer.Confirming(Codes.ClosedPeriod), // { code } DecisionAnswer.Choosing(Codes.PossibleDuplicate, "line-3", DuplicateChoice.Skip) // { code, item, option: "skip" } ] }; ``` `Confirming(code, item)` confirms one item of a per-item decision, and `Choosing(code, option)` answers a choice for the whole request. * **Ask inside the transaction**, only when the state that needs the decision is there. A resend after the state changed simply runs — or asks about what is new: a line that became a possible duplicate since the caller last answered is unanswered, so the command refuses instead of silently holding it back. * **Per item, the data lists the items.** The client answers by item key, so the payload names each item's key (and whatever the dialog shows). The kind is on the wire (JSON-RPC `-32006`, HTTP `409`, gRPC `FailedPrecondition`), so a generic client recognizes every decision without knowing its code. The generated TypeScript client's [`withDecisions`](/docs/capabilities/transports/typescript-client#answering-decisions) asks the application's dialog and resends; the dialog stays the application's. ## Unexpected errors [#unexpected-errors] An exception is not a `Result`: it is a bug or an outage, and the caller gets one framework-owned answer for it. Every transport — JSON-RPC, MCP, and generated `[HttpEndpoint]` routes — catches an exception that escaped the handler pipeline **outside every decorator**, so a throw from the authorization, validation, audit or observability decorator is answered exactly like a throw from the handler. The answer carries the stable code `internal`, a message, and a **reference** the user can quote to support: | Transport | Wire shape | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | JSON-RPC | `{"code": -32603, "message": "Internal error", "data": {"code": "internal", "reference": "4bf92f3577b34da6a3ce929d0e0e4736"}}` | | MCP | an error tool result with the message, and `{"code": "internal", "reference": "…"}` as structured content (with `IncludeErrorDetails`, the default) | | HTTP | `500` ProblemDetails with the message as `detail`, `"code": "internal"` and `"reference": "…"` | The reference is never part of the message, and the transport logs the exception at error level together with it, so support finds the log line (and the trace) from what the user reports. By default the message is `Internal error` and the reference is the current trace id; configure both once for every transport: ```csharp builder.Services.ConfigureElarionUnexpectedErrors(o => { // Shown to the user; never the exception text unless you choose to expose it. o.Message = context => "Something went wrong. Please contact support and quote the reference."; // The default is Activity.Current's trace id (a fresh id when no trace is active); return null to send none. o.Reference = context => Activity.Current?.TraceId.ToHexString(); }); ``` Each hook receives an `UnexpectedErrorContext` — the `Exception`, the `Transport` (`jsonrpc`, `mcp`, `http`), the `Operation` being served, and the call's scoped `Services`, so a hook can resolve a localizer. A hook that throws falls back to the default for its part: the error path always answers. No application decorator, exception handler or pipeline-order test is needed for this. Clients branch on `code: "internal"` and show `reference`; the generated TypeScript `RpcError` exposes it as `error.reference`. Generated HTTP routes can hand an exception to the host instead — the developer exception page in Development, or an `IExceptionHandler` that maps an exception type to its own status: ```csharp builder.Services.ConfigureElarionUnexpectedErrors(o => o.LeaveToHost = context => builder.Environment.IsDevelopment() || context.Exception is DbUpdateConcurrencyException); ``` JSON-RPC and MCP always answer: a batch entry or a tool call has no host handler to fall back to. ## Results in pipelines [#results-in-pipelines] Decorators can inspect a `Result` through the non-generic `IResultLike` interface — for example a transaction decorator that commits on success and rolls back on failure. In generic code, go through `ResultInspection` rather than an inline `response is IResultLike { … }` pattern: the helpers never box a struct result, while the inline pattern does inside a method compiled with .NET 11 runtime async: ```csharp if (ResultInspection.IsSuccess(response)) { await transaction.CommitAsync(ct); } else { await transaction.RollbackAsync(ct); } ``` See [Decorator pipelines](/docs/concepts/decorator-pipelines) for the full pattern, including how a validation decorator turns failures into `Result.Failure(...)`. # Rules (/docs/concepts/rules) A rich domain defines rules — "the open amount of an invoice", "is it settled", "is it overdue" — and needs each of them twice: inside a query, translated to SQL, and in memory, on an entity that is already loaded. A **rule** holds the one expression both use. It lives in `Elarion.Expressions` in the core `Elarion` package, is plain `System.Linq.Expressions`, and depends on no ORM; EF Core is where it is most often translated. Why the API is shaped this way, and what was rejected (LINQKit, an EF-only helper, views and computed columns), is in [ADR-0102](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0102-rules-are-expressions-composed-once.md). ## Define a rule [#define-a-rule] `Rule.Create` takes a lambda and infers the types from it. A rule may invoke other rules: ```csharp using Elarion.Expressions; public static class InvoiceRules { public static readonly Rule Paid = Rule.Create((Invoice invoice) => invoice.Payments.Sum(p => p.Amount)); public static readonly Rule OpenAmount = Rule.Create((Invoice invoice) => invoice.Gross - Paid.Invoke(invoice)); public static readonly Rule IsSettled = Rule.Create((Invoice invoice) => OpenAmount.Invoke(invoice) <= 0); } ``` `rule.Expression` is the definition, an `Expression>`. ## Run it in memory [#run-it-in-memory] `rule.Invoke(invoice)` runs the rule on a loaded object. The expression is compiled on first use and the delegate is cached (`rule.Compiled`); concurrent first calls are safe. Without dynamic code (NativeAOT) the delegate runs on the expression interpreter. ```csharp var invoice = await db.Invoices.Include(i => i.Payments).SingleAsync(i => i.Id == id, ct); if (InvoiceRules.IsSettled.Invoke(invoice)) return AppError.Conflict("The invoice is already settled."); ``` In memory, a rule sees only what is loaded: `OpenAmount` over an invoice whose `Payments` were not included sums an empty list, where SQL would have joined the payments. ## Compose rules into queries [#compose-rules-into-queries] Inside another expression, `rule.Invoke(x)` is a **marker**: a query provider cannot translate it. `Expand()` replaces every marker with the rule's body, its parameter substituted by the call's argument, and does so recursively for rules that invoke rules. Call it on the query, after the last operator that invokes a rule: ```csharp var rows = await db.Invoices .Where(invoice => !InvoiceRules.IsSettled.Invoke(invoice)) .OrderByDescending(invoice => InvoiceRules.OpenAmount.Invoke(invoice)) .Select(invoice => new OpenInvoiceRow(invoice.Id, invoice.Number, InvoiceRules.OpenAmount.Invoke(invoice))) .Expand() .ToListAsync(ct); ``` EF Core receives the inlined bodies, so the filter, the ordering and the projection are all SQL: a projection is a normal lambda with a constructor, not an `Expression.New` built by hand. `query.Expand()` returns a new query from the same provider; operators appended to it afterwards are not expanded, so expand last (or again). A rule can also go into an operator directly, `db.Invoices.Where(InvoiceRules.IsSettled.Expression)`; when it invokes other rules, call `Expand()` on the query as well. `Expand()` also works on any `Expression` or `Expression`. ### When `Expand()` is forgotten [#when-expand-is-forgotten] | Where the marker is | What EF Core does | | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | A filter, an ordering, a join key | Fails: "The LINQ expression … could not be translated", naming `Invoke`. | | The final projection, rule in a static field or property | Fails: "The client projection contains a reference to a constant expression of 'Elarion.Expressions.Rule…' through the instance method 'Invoke'". | | The final projection, rule in a captured local | **Runs the rule on the client**, on an entity whose navigations were not loaded: the result is silently wrong. | Keep rules in static fields, as above, and turn on the rule check, so no row can pass silently: ```csharp builder.Services.AddDbContext(options => options .UseNpgsql(connectionString) .UseElarionRuleCheck()); // Elarion.EntityFrameworkCore ``` `UseElarionRuleCheck()` adds an EF Core query interceptor that refuses every query still invoking a rule, with the expression and the fix in the message. It runs when EF Core compiles a query shape, not on every execution. A projection that should run a rule in memory on purpose ends the query first (`ToListAsync()`) and invokes the rule on the loaded entities. ### Where a rule can live [#where-a-rule-can-live] `Expand()` reads the rule instance out of the expression tree without compiling code. It follows constants and field or property accesses: a static field or property, a local the lambda captures, a field of a captured object. A rule obtained from a method call (`GetRule().Invoke(x)`) or from a lambda parameter throws a `NotSupportedException` that names the expression. A rule that invokes itself, directly or through another rule, has no finite expansion and throws an `InvalidOperationException`; in memory it runs. ## Rules with more inputs [#rules-with-more-inputs] A rule takes up to four inputs, the result last as in `Func`: next to `Rule` there are `Rule`, `Rule` and `Rule`. The inputs after the first carry values the rule cannot reach from the entity: today's date, a threshold, a joined aggregate. A local passed as an argument is a parameter in SQL. ```csharp public static readonly Rule IsOverdue = Rule.Create((Invoice invoice, DateOnly today) => invoice.DueOn < today && InvoiceRules.OpenAmount.Invoke(invoice) > 0); var today = DateOnly.FromDateTime(timeProvider.GetUtcNow().UtcDateTime); var overdue = await db.Invoices.Where(invoice => IsOverdue.Invoke(invoice, today)).Expand().ToListAsync(ct); ``` Three and four inputs fit a rule over several aggregates, each [joined once](#an-aggregate-used-several-times-join-it-once) and passed in, or over an aggregate and the values a query supplies: ```csharp public static readonly Rule OpenGiven = Rule.Create((Invoice invoice, decimal paid, decimal credited) => invoice.Gross - paid - credited); public static readonly Rule IsDunnable = Rule.Create((Invoice invoice, decimal paid, decimal credited, DateOnly today) => invoice.DueOn < today && OpenGiven.Invoke(invoice, paid, credited) > 0); ``` C# expression trees cannot contain tuple literals, so a rule over a tuple could not be invoked inside a query; give it more inputs instead. Values that come from outside the query and belong together, such as a date window, can also travel as one record input, as the booking window [below](#predicates-built-at-run-time) does. ## A rule that reads another set [#a-rule-that-reads-another-set] A rule whose condition lives in another table, with no navigation to it, needs that table's set. Capturing `db.Payments` would make the rule a function of the `DbContext`: built per call, passed along by every caller, and no longer a static field. Name the set with a placeholder instead. `QuerySets.Of()` (`Elarion.Abstractions.Authorization`) stands for the querying context's set of `T`, and `QuerySets.Unfiltered()` for the same set without the context's query filters: ```csharp public static readonly Rule HasPaymentAbove = Rule.Create((Invoice invoice, decimal minimum) => QuerySets.Of() .Any(payment => payment.InvoiceId == invoice.Id && payment.Amount > minimum)); var flagged = await db.Invoices.Where(invoice => HasPaymentAbove.Invoke(invoice, 10_000m)).Expand().ToListAsync(ct); ``` EF Core puts the context's set in the placeholder's place when the context options call `UseElarionQuerySets()` (`Elarion.EntityFrameworkCore`), once per query shape. A context without that call fails the query and names the fix. Such a rule translates only: run in memory, the placeholder throws, because a loaded object has no store to ask. The same placeholders serve [row rules](/docs/concepts/resource-authorization#visible-through-an-owner-as-part-of-a-rule), where they were introduced. ## Expressions without a rule [#expressions-without-a-rule] `Invoke` is also an extension on `Expression>` with one to four inputs. Inside a query it is a marker `Expand()` inlines the same way; outside one it compiles the expression once per instance and runs it. ```csharp Expression> isLarge = invoice => invoice.Gross > 10_000m; var large = await db.Invoices.Where(invoice => isLarge.Invoke(invoice) && invoice.Payments.Count == 0).Expand().ToListAsync(ct); ``` ## Helpers that return a composed expression [#helpers-that-return-a-composed-expression] A lambda has no type of its own, so `Expand()` cannot be called on one where it is written: a helper that returns a composed filter would need a typed local first. `Expr.Expand` takes the lambda directly and infers the types from its parameters, for one to four inputs: ```csharp public static Expression> OverdueOn(DateOnly today) => Expr.Expand((Invoice invoice) => IsOverdue.Invoke(invoice, today)); var overdue = await db.Invoices.Where(InvoiceFilters.OverdueOn(today)).ToListAsync(ct); ``` The returned expression is already expanded, so the query needs no `Expand()` of its own unless another operator invokes a rule. It expands like `Expand()` and throws the same exceptions. ## Predicates built at run time [#predicates-built-at-run-time] `Expr` combines predicates over one row, each rebound to one shared parameter: * `Expr.AnyOf(predicates)` joins them with OR. No predicates give a predicate that is always false: no alternatives match no row. * `Expr.AllOf(predicates)` joins them with AND. No predicates give a predicate that is always true: no conditions restrict nothing. * `Expr.Not(predicate)` negates one. Both joins take `params` or any sequence. A typical use is one window per bank account, each with its own dates: ```csharp public sealed record BookingWindow(Guid AccountId, DateOnly From, DateOnly To); static readonly Rule InWindow = Rule.Create((Booking booking, BookingWindow window) => booking.AccountId == window.AccountId && booking.BookedOn >= window.From && booking.BookedOn <= window.To); var inAnyWindow = Expr.AnyOf(windows.Select(window => (Expression>)(booking => InWindow.Invoke(booking, window)))); var bookings = await db.Bookings.Where(inAnyWindow).Expand().ToListAsync(ct); ``` Each window is a captured local, so every account and date is a parameter, and the query keeps one cached plan per number of windows: ```sql WHERE (b."AccountId" = @window_AccountId AND b."BookedOn" >= @window_From AND b."BookedOn" <= @window_To) OR (b."AccountId" = @window_AccountId3 AND b."BookedOn" >= @window_From4 AND b."BookedOn" <= @window_To5) ``` For a tree assembled from `Expression` factories, two more helpers keep the same properties: * `Expr.Captured(value)` returns the value as a member access on a closure object, the shape the compiler emits for a captured local, so the provider sends it as a parameter. `Expression.Constant(value)` would put the literal into the SQL text and give every value a plan of its own. * `Expr.Inline(lambda, arguments)` returns a lambda's body with its parameters replaced by the given expressions. ```csharp var invoice = Expression.Parameter(typeof(Invoice), "invoice"); var body = Expr.Inline(IsOverdue.Expression, invoice, Expr.Captured(today)); var predicate = Expression.Lambda>(body, invoice); ``` ## An aggregate used several times: join it once [#an-aggregate-used-several-times-join-it-once] Expansion inlines a rule at every use. When the rule is a correlated subquery, every use is one more subquery: this filter and projection make PostgreSQL sum each invoice's payments three times. ```csharp var partiallyPaid = db.Invoices .Where(invoice => OpenAmount.Invoke(invoice) > 0 && OpenAmount.Invoke(invoice) < invoice.Gross) .Select(invoice => new OpenInvoiceRow(invoice.Id, invoice.Number, OpenAmount.Invoke(invoice))) .Expand(); ``` Compute the aggregate once per row instead: project it in a grouped subquery, left-join that subquery once, and apply rules that take the joined value as their second input. ```csharp public static readonly Rule OpenGiven = Rule.Create((Invoice invoice, decimal paid) => invoice.Gross - paid); public static readonly Rule IsPartiallyPaid = Rule.Create((Invoice invoice, decimal paid) => OpenGiven.Invoke(invoice, paid) > 0 && OpenGiven.Invoke(invoice, paid) < invoice.Gross); var paidByInvoice = db.Payments .GroupBy(payment => payment.InvoiceId) .Select(group => new { InvoiceId = group.Key, Paid = group.Sum(payment => payment.Amount) }); var partiallyPaid = await db.Invoices .LeftJoin(paidByInvoice, invoice => invoice.Id, paid => paid.InvoiceId, (invoice, paid) => new { Invoice = invoice, Paid = (decimal?)paid!.Paid ?? 0m }) .Where(row => IsPartiallyPaid.Invoke(row.Invoice, row.Paid)) .Select(row => new OpenInvoiceRow(row.Invoice.Id, row.Invoice.Number, OpenGiven.Invoke(row.Invoice, row.Paid))) .Expand() .ToListAsync(ct); ``` ```sql SELECT i."Id", i."Number", i."Gross" - COALESCE(p."Paid", 0.0) FROM invoices AS i LEFT JOIN ( SELECT p0."InvoiceId", COALESCE(sum(p0."Amount"), 0.0) AS "Paid" FROM payments AS p0 GROUP BY p0."InvoiceId" ) AS p ON i."Id" = p."InvoiceId" WHERE i."Gross" - COALESCE(p."Paid", 0.0) > 0.0 AND i."Gross" - COALESCE(p."Paid", 0.0) < i."Gross" ``` The rule stays one definition; only its input changed. In memory, pass the aggregate the same way: `IsPartiallyPaid.Invoke(invoice, Paid.Invoke(invoice))`. Write `(decimal?)paid!.Paid ?? 0m` for the joined value: EF Core translates it to `COALESCE`, while a `paid == null` test on the anonymous type does not translate. A rule over several aggregates (the paid and the credited sum) takes each as an input of its own: join one grouped subquery per aggregate and pass the joined values to a rule with three or four inputs, such as `OpenGiven` in [Rules with more inputs](#rules-with-more-inputs). The same holds for a subquery that is not a sum. A predicate that asks one correlated set three questions ("is there a seen entry", "is one newer than the mark", and the first again in the other branch) sends three subqueries, whether the set is named by a rule, by an expression invoked with `Invoke`, or by a [set placeholder](#a-rule-that-reads-another-set). Fold the questions into the aggregates that answer them (`Any` becomes a count or a `Max` that is null when there is none, "one newer than" becomes the `Max` of the time), join that grouped subquery once, and pass the values to the rule as inputs. There is no way to bind a sub-expression once inside a predicate, and Elarion adds no `LATERAL` or CTE construct for it. `Expand()` substitutes text, which is what lets the provider translate a rule at all; SQL has no `let` inside a `WHERE`; and EF Core inlines a projected value again wherever a later operator reads it, so a `Select` before the `Where` repeats the subquery too. Only the query's shape gives every provider one evaluation per row, and a predicate (`Expression>`) cannot change the shape of the query it is applied to. Repeating a cheap indexed `EXISTS` is often fine: read the plan before reshaping a query. # Services (/docs/concepts/services) A service is any module-owned class you want in DI that is not a [handler](/docs/concepts/handlers) or scheduled job. `[Service]` is an auto-detected application pattern: annotate the class and Elarion emits its registration and wires it into the owning module automatically — you never hand-write an `Add…()` call or touch a service collection. ```csharp title="ClientNumberGenerator.cs" using Elarion.Abstractions; namespace MyApp.Application.Modules.Clients.Services; public interface IClientNumberGenerator { string Next(); } [Service] public sealed class ClientNumberGenerator : IClientNumberGenerator { public string Next() => "C-001"; } ``` That is the whole opt-in. The class implements one interface, so it registers against `IClientNumberGenerator` with the default `Scoped` lifetime, and any handler or other service in the module can inject `IClientNumberGenerator`. ## How registration is wired [#how-registration-is-wired] `ModuleServiceRegistrationGenerator` runs when `[assembly: UseElarion]` or `[assembly: GenerateModuleServices]` is present. It emits a per-service registration helper and an aggregating `Add{Module}Services()` per module (longest-prefix namespace match places each service in its module). You never call these directly: the generator also contributes the `AddServices` filler to the module's generated `ConfigureDefaultServices(IServiceCollection)`, which the host bootstrapper invokes — gated by `IsModuleEnabled` — for every `[AppModule]`. So a `[Service]` in a disabled feature module disappears alongside its handlers, jobs, and consumers. `ConfigureDefaultServices` aggregates all of a module's discovered registrations (handlers, services, validation metadata, scheduled jobs, event consumers, module API); a module's hand-written `ConfigureServices` is reserved for the non-generated registrations only. See [Modules](/docs/concepts/modules) and [Source generation](/docs/concepts/source-generation). A service whose namespace falls under no `[AppModule]` is not picked up by any module aggregation, so it never reaches DI. Keep `[Service]` classes inside a module's namespace. ## Contract resolution [#contract-resolution] The generator decides which contract(s) to register the implementation against, in order: **Explicit contracts.** If `[Service(typeof(...))]` lists service types, those are used. Each must be assignable from the implementation, or the generator reports [`ELSG002`](/docs/reference/diagnostics) . **Directly implemented interfaces.** Otherwise every interface the class implements directly becomes a contract (base-class interfaces are not treated as explicit contracts). **Self.** Otherwise the implementation type registers as itself. When more than one contract is registered, the first is the concrete anchor and the rest resolve to the same instance, so all contracts share one object per scope. Pin the contracts explicitly when a class implements several interfaces but should only be injectable through some of them: ```csharp title="SystemClock.cs" [Service(typeof(IClock), Scope = ServiceScope.Singleton)] public sealed class SystemClock : IClock, IDisposable { public DateTimeOffset UtcNow => DateTimeOffset.UtcNow; public void Dispose() { } } ``` ### Injecting the class itself [#injecting-the-class-itself] The class itself is a contract only by the last rule. So a class that gains an interface stops being resolvable as itself, and every constructor that injects the class fails when the container resolves it. The build warns about such a constructor ([`ELSG020`](/docs/reference/diagnostics)) in any class the container creates (a `[Service]` or a handler). Either inject the interface, or set `AsSelf` to register the class too: ```csharp title="ApprovalWorkflow.cs" [Service(AsSelf = true)] public sealed class ApprovalWorkflow : IApprovalWorkflow { … } ``` With `AsSelf` the class is the anchor and every contract forwards to it, so the class and `IApprovalWorkflow` resolve to the same instance per scope (per application for a singleton). It is opt-in, because registering every class as itself would make each one injectable past the interface it was given. A `[FeatureVariant]` or `[ConfigurationVariant]` class ignores it: it is resolved through its contracts only. ## Lifetime [#lifetime] The default scope is `Scoped`. Override it with the `Scope` property; `ServiceScope` has `Scoped`, `Singleton`, and `Transient`: ```csharp [Service(typeof(IClock), Scope = ServiceScope.Singleton)] public sealed class SystemClock : IClock { /* ... */ } ``` Use `Singleton` only when the service and its dependencies are thread-safe and hold no scoped state such as a `DbContext`. For the full contract and lifetime rules, see [Conventions](/docs/reference/conventions). Generic service implementations are rejected ([`ELSG003`](/docs/reference/diagnostics)) until open-generic aliasing semantics are defined. Register open generics manually for now. ## Hosted services [#hosted-services] A class that implements `IHostedService` or derives from `BackgroundService` is auto-detected as a hosted service. **Hosted services must be singletons** — a scoped or transient hosted service is an error ([`ELSG001`](/docs/reference/diagnostics)). The generator registers the concrete service (and any non-`IHostedService` contracts) and adds a singleton `IHostedService` forwarder that resolves the same instance, so the host runs its `StartAsync`/`StopAsync` while ordinary consumers inject the typed contract: ```csharp title="MailboxPollingService.cs" public interface IMailboxPollingService { Task PollNowAsync(CancellationToken cancellationToken); } [Service(typeof(IMailboxPollingService), Scope = ServiceScope.Singleton)] public sealed class MailboxPollingService : IMailboxPollingService, IHostedService { Task IHostedService.StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; Task IHostedService.StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; public Task PollNowAsync(CancellationToken cancellationToken) => Task.CompletedTask; } ``` Implementing `IHostedService` explicitly (as above) keeps the lifecycle methods off the public contract, so callers see only `PollNowAsync`. `IHostedService` is never registered as an injectable contract itself — only as the lifecycle forwarder. For recurring or delayed background work, prefer [scheduled jobs](/docs/capabilities/scheduling) over a hand-rolled `BackgroundService` loop. Scheduled jobs share one scheduler with explicit overlap, misfire, and resilience policies plus telemetry. ## Module services vs. contract sets [#module-services-vs-contract-sets] `[Service]` is deliberately **module-shaped**: registrations are aggregated per `[AppModule]` and invoked gated on `Modules:{Name}:Enabled`, so a feature module's services disappear with the module. Both properties are wrong for a class of registrations module-less host assemblies have: **infrastructure seams** — N implementations of one contract composed into a routing or dispatch table at boot (protocol packet bindings, codec catalogs, pipeline stages). There is no module to own them, and a config gate that silently empties a transport's dispatch table while the listener stays up produces a server that boots deaf. For these, declare a **contract set**: author the composition method you already call — a `static partial` extension method — and let the generator fill in the body: ```csharp title="PacketBindingRegistrations.cs" public static partial class PacketBindingRegistrations { [GenerateContractSetRegistration(typeof(IPacketBinding))] public static partial IServiceCollection AddPacketBindings(this IServiceCollection services); } ``` You name and place the method, so go-to-definition works and no naming convention is involved; the generator finds every non-abstract, non-generic class in the declaring assembly that is assignable to the contract and implements the method, registering each implementation with `TryAddEnumerable` (calling it twice never duplicates the set) at `Singleton` scope by default (`Scope` overrides). Discovery is compilation-local by design: the assembly that declares the seam owns its implementations; a host wanting external ones registers them explicitly. When do you use which? * **`[Service]`** — feature-gated module services, *pushed* by the gated module bootstrapper. The registration lives and dies with the module. * **Contract sets** — unconditional infrastructure seams, *pulled* by the host from its composition root, exactly once. Nothing gates the composition; the registry consuming `IEnumerable` validates the set at startup and is free to fail loudly on an invalid one. An empty set is a warning at compile time ([`ELSG015`](/docs/reference/diagnostics)) — almost always a typo'd contract or refactor casualty. A type must pick one mechanism per contract: an implementation that also carries `[Service]` resolving to the same contract would register twice — once gated, once not — and reports [`ELSG018`](/docs/reference/diagnostics). See [`[GenerateContractSetRegistration]`](/docs/reference/attributes#generatecontractsetregistration) for the full parameter and diagnostic reference. ## Reacting to events from a service [#reacting-to-events-from-a-service] A `[Service]` can host a lightweight **event consumer** for a small side effect: an instance method annotated with `[ConsumeEvent]`. The marker interface on the event selects the plane (`IDomainEvent` → inline; `IIntegrationEvent` → after commit), and the method is always a **fan-out subscriber** returning `void`/`Task`/`ValueTask` — the event bus is pub/sub-only. Optional `IEventContext` and `CancellationToken` parameters are supplied by the runtime: ```csharp title="ClientNotifier.cs" [Service] public sealed class ClientNotifier { [ConsumeEvent] public Task OnClientCreated(ClientCreated @event, CancellationToken cancellationToken) => Task.CompletedTask; } ``` `[ConsumeEvent]` is only valid on a `[Service]` class for the method form — a consumer method elsewhere reports [`ELEVT001`](/docs/reference/diagnostics). Unlike the handler form, the method form runs **no decorator pipeline**: reach for a handler-based consumer when the consumer is first-class business logic that needs tracing, validation, resilience, or cache invalidation. See [Consuming events](/docs/capabilities/events/consuming-events). Full contract and lifetime resolution rules for `[Service]` . How `ConfigureDefaultServices` gates and aggregates a module's registrations. # Settings (/docs/concepts/settings) Elarion's settings subsystem gives applications **runtime-changeable configuration**. Settings are **declared once** as typed definitions; one **effective-value resolver** layers a default, a value stored at runtime and an optional deployment-configuration pin; everything that reads settings — your code, the admin describe call, the `IConfiguration` projection — goes through it. See [ADR-0078](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0078-settings-definitions-and-effective-value-resolver.md) (and [ADR-0011](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0011-runtime-settings-subsystem.md) for the store/change-source split). Two backends ship: an **in-process** store (the zero-dependency default) and an **EF Core database** store (`Elarion.Settings.EntityFrameworkCore`). Change notification is in-process by default; add `Elarion.Settings.PostgreSql` (PostgreSQL `LISTEN/NOTIFY`) to propagate changes across all nodes. The EF Core store writes on your injected `DbContext`, so a `SetAsync`/`ResetAsync` made inside a transaction commits or rolls back with it — see [persistence & transactions](/docs/concepts/persistence-and-transactions). ## Declaring settings [#declaring-settings] A `static partial` class marked `[SettingDefinitions]` holds one `static partial SettingDefinition` property per setting. The attribute carries the key and metadata; a generator implements the property and verifies the declarations at build time. ```csharp [SettingDefinitions] public static partial class AppSettings { [Setting("app:title", Default = "Untitled", Pinnable = true, Description = "The application title.")] public static partial SettingDefinition Title { get; } [Setting("app:smtp", DefaultFactory = nameof(DefaultSmtp), Pinnable = true)] public static partial SettingDefinition Smtp { get; } [Setting("app:smtp:password", Secret = true)] public static partial SettingDefinition SmtpPassword { get; } [Setting("ui:theme", Scopes = ["global", "user"], Default = "light")] public static partial SettingDefinition Theme { get; } private static SmtpSettings DefaultSmtp() => new() { Host = "localhost" }; } ``` | `[Setting]` option | Meaning | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `key` | Hierarchical key with `:` separators; unique case-insensitively (it doubles as the `IConfiguration` key). | | `Scopes` | Scope kinds the setting may be used in. Default: global only. | | `Secret` | Protected at rest, never described, never projected into `IConfiguration`. No default allowed. | | `Pinnable` | Deployment configuration may pin the value (global scope only). | | `FallbackConfigurationKey` | A deployment-configuration key read **below** the stored value (global scope only): stored, else configured there, else the default. Never refuses a write. | | `Default` / `DefaultFactory` | A constant for scalars, or a static factory (lazy, once) for records. | | `Description` | Text for admin tooling. | Build-time diagnostics: `ELSDEF001` invalid container (must be a top-level `static partial` class), `ELSDEF002` invalid member, `ELSDEF003` invalid key, `ELSDEF004` duplicate key, `ELSDEF005` secret with a default, `ELSDEF006` pinnable without the global scope, `ELSDEF007` invalid default, `ELSDEF008` blank or malformed `FallbackConfigurationKey`, or one on a setting without the global scope. Register the definitions on the host. `[assembly: UseElarion]` (or `[assembly: GenerateSettingDefinitionCatalog]`) emits `ElarionSettingDefinitions.All`, aggregating this assembly and the public containers of referenced module assemblies: ```csharp builder.Services.ConfigureElarionJson(o => o.TypeInfoResolvers.Add(AppSettingsJsonContext.Default)); builder.Services.AddElarionSettings(o => o.AddDefinitions(ElarionSettingDefinitions.All)); [JsonSerializable(typeof(SmtpSettings))] [JsonSerializable(typeof(string))] internal sealed partial class AppSettingsJsonContext : JsonSerializerContext; ``` Values serialize through the canonical [`IElarionJsonSerialization`](/docs/capabilities/serialization) options — source-generated `JsonTypeInfo`, no reflection — so the value types must be in a JSON context. An undeclared setting cannot be named: the manager takes definitions, not strings. A definition that is not registered, or used in a scope it does not allow, throws `InvalidOperationException` (a programming error). ## Scopes [#scopes] A setting belongs to a `SettingsScope`: `Global` (system-wide), `User(userId)`, or the `CurrentUser` placeholder resolved against the ambient `ICurrentUser`. A scope is an open `(Kind, Owner)` value, so more kinds can be added without changing the contracts or the store schema; a definition lists the kinds it allows. User-scoped access **fails closed**: outside an authenticated context, `CurrentUser` throws rather than reading global data. ## Reading and writing [#reading-and-writing] ```csharp public sealed class SendEmailHandler(ISettingsManager settings) : IHandler> { public async ValueTask> HandleAsync(SendEmail request, CancellationToken ct) { var smtp = await settings.GetAsync(AppSettings.Smtp, cancellationToken: ct); var password = await settings.GetAsync(AppSettings.SmtpPassword, cancellationToken: ct); var theme = await settings.GetAsync(AppSettings.Theme, SettingsScope.CurrentUser, ct); // ... return Result.Success(); } } var write = await settings.SetAsync(AppSettings.Title, "Inbox", cancellationToken: ct); if (!write.IsSuccess && write.Error.Code == SettingErrorCodes.Pinned) // deployment configuration pins the title; the UI should show it read-only ``` `GetAsync` returns the **effective** value. `GetResolvedAsync` returns it together with its `SettingSource` and store `Version` (`SettingValue`), so "unset" is distinguishable from "explicitly stored the default" without a nullable value type or a `DescribeAsync` call. Two shorthands read `Source`: * `IsSet` is `Source != SettingSource.Default`: `true` for a stored value, a pin, **and** a deployment value at the `FallbackConfigurationKey`. It answers "does anything override the default?". * `IsStored` is `Source == SettingSource.Store`: `true` only while the effective value is the stored one. It answers "has someone saved a value?", for example to show a "Reset" button. A pinned setting reports `false` even when a stored value exists underneath the pin, because that value is ignored. `SetAsync` returns `Result` (the new version); `ResetAsync` removes the stored value so the setting reverts to its default. Failures are `AppError`s with a stable code ([ADR-0080](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0080-errors-are-a-declared-contract-with-a-stable-code.md)) and a `SettingWriteFailure(Key)` payload: `settings.pinned` (`SettingErrorCodes.Pinned`, a `BusinessRule` — the stored value would be ignored) and `settings.concurrency_conflict` (`SettingErrorCodes.ConcurrencyConflict`, a `Conflict`). A handler that returns them declares them, so the schema and the generated client type them: `[ProducesError(SettingErrorCodes.Pinned, ErrorKind.BusinessRule, typeof(SettingWriteFailure))]`. Concurrency is opt-in: an unconditional write is last-write-wins; pass `expectedVersion` for optimistic concurrency. ## The effective-value resolver [#the-effective-value-resolver] `ISettingResolver` layers, lowest to highest: 1. the definition's **default** (`default(T)` when it declares none), 2. a **configuration fallback** — only for a definition that declares a `FallbackConfigurationKey`, in the global scope: the deployment's value at that key, used while nothing is stored (`SettingSource.ConfigurationFallback`), 3. the **store** value, 4. a **configuration** value — only for `Pinnable` definitions in the global scope. A configuration value *pins* the definition: it wins, and writes are refused. The fallback answers "the administrator's value, else the deployment's, else the built-in one" — an SMTP host an administrator may change, which a deployment presets in `Email:Smtp:Host`: ```csharp [Setting("app:smtp:host", Default = "localhost", FallbackConfigurationKey = "Email:Smtp:Host")] public static partial SettingDefinition SmtpHost { get; } ``` `GetAsync` then returns the stored host, else the configured one, else `localhost`; a stored value replaces the configured one, and resetting it brings the configured one back. Its configuration text is read as a pin's is, and a blank value means "not set". `Watch` fires when the deployment configuration reloads, as for a pinnable definition. A configuration value pins only when it is present and neither empty nor whitespace, so a blank environment variable or an unfilled template placeholder does not freeze a setting. Set `o.EmptyConfigurationValuesPin = true` when an empty string is a legitimate pinned value. The configuration text of a string setting is the string itself; any other type uses its JSON form (`2525`, `true`, a JSON document such as `{"host":"mail"}` for a record), and bare words work for enums and string-like types. A malformed pinned value fails loudly on read. Only non-projection configuration providers are consulted (see below), so the projection cannot pin. The pin check itself is `ISettingPins` — `IsPinned(definition, scope)`, `GetPinnedText(definition)` — a **singleton** that needs only the catalog and `IConfiguration`, never the store. Inject it where the scoped resolver is not available (a singleton, middleware, options setup). The resolver stack (`ISettingResolver`, `ISettingPins`, `ISettingsManager`, `ISettingNormalizer`, `ISettingReprotector`, `ISettingDefinitionCatalog`) is exposed as interfaces only; the implementations are internal so their names never collide with application types. Replace one by registering your own implementation of the interface before `AddElarionSettings()`. ### Unreadable and legacy rows [#unreadable-and-legacy-rows] A stored row that cannot be read — a secret that cannot be decrypted, or a value that is not valid for the definition's type — never takes the other settings down. Bulk resolution (`ResolveAllAsync`, `DescribeAsync`, the configuration projection) flags it (`IsUnreadable` plus an `UnreadableReason` that never contains the value) and carries on; a single `GetAsync` of that setting still throws. The configuration projection skips the row and the refresher logs its key and reason once. Rows written before a definition existed typically hold the raw text (`smtp.example.com`, `30`, `True`, `Red`) instead of its JSON form. Reads do not guess — `42` is a legal string and a legal number — so convert them once with `ISettingNormalizer.NormalizeAsync(scope, options?)`. For every definition it keeps a value that already is valid JSON for the type and otherwise attempts one well-defined coercion of the raw text: | Definition type | Raw text accepted | | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `string` | anything, verbatim | | `bool` | `true` / `false`, any case, trimmed | | integer types, `decimal`, `double`, `float` | invariant-culture number, trimmed (`" 30 "`, `030`); out-of-range is not coerced | | enum | a member name, case-insensitive (or the number of a defined member) | | `Guid`, `TimeSpan`, `DateTimeOffset`, `Uri`, other string-serialized scalars | the trimmed text, when the type accepts it | | records, collections | never coerced — only text that already is valid JSON for the type | The report lists one entry per examined key — `Rewritten`, `AlreadyCanonical`, `Unreadable` (with a reason that never contains the value), `Removed` or `Skipped` (changed concurrently) — so an application can log exactly which keys were changed or need attention. `SettingNormalizationOptions.KeyPrefix` limits the run to a subtree; `RemoveUnrecoverable = true` deletes rows whose readable text cannot be coerced, so the default applies again (the default is to leave them `Unreadable`). The run is idempotent and every write is guarded by the entry's version. A **secret** row is normalized in place of its plaintext representation and keeps its protection state: a protected row is protected again with the same scheme, a legacy plaintext row stays plaintext until `ISettingReprotector` protects it. Normalization never changes a row's scheme behind the application's back, and a row whose protection cannot be undone (other scheme, lost key, no protector) is reported `Unreadable` and never removed. **Upgrading a store written before 0.2.8.** Releases before 0.2.8 accepted raw text on read; from 0.2.8 on, such a row reads as `Unreadable` (`GetAsync` throws, the projection skips it and the refresher logs it). Nothing runs the normalizer for you — a write behind the application's back on every start would be the wrong default — so run it once, after the schema migrations and before the host starts. With the [migration plan](/docs/capabilities/migrations), make it a code step so it runs exactly once per database: ```csharp public sealed class NormalizeLegacySettings(ILogger logger) : ICodeMigration { public string Version => "20261007120000"; // after the migration that created the settings table public string Description => "normalize legacy settings rows"; public bool UseTransaction => false; // the store writes on its own connection; the run is idempotent public async Task ExecuteAsync(MigrationStepContext context, CancellationToken ct) { var normalizer = context.Services.GetRequiredService(); var report = await normalizer.NormalizeAsync(SettingsScope.Global, cancellationToken: ct); foreach (var entry in report.Where(SettingNormalizationOutcome.Unreadable)) logger.LogWarning("Setting {Key} was left unchanged: {Reason}", entry.Key, entry.Reason); } } ``` A host that migrates by other means calls the same `NormalizeAsync` from its startup code between the migration and `app.RunAsync()`; it is idempotent, so running it on every start is harmless. Per-user rows need one run per user scope. ## Secrets [#secrets] Definitions with `Secret = true` are protected at rest through an `ISettingValueProtector`. Add the Data Protection implementation: ```csharp builder.Services.AddElarionSettingsDataProtection(); // Elarion.Settings.DataProtection ``` * The payload is bound to scope kind, owner and key (renaming a secret key requires writing it again). * The protection **scheme** is store metadata — `SettingEntry.Protection`, the nullable `protection` column on the EF row — not a prefix inside the value. Add the column to an existing table with a migration. * **Fail closed:** a secret definition with no `ISettingValueProtector` registered fails host startup. There is no unprotected fallback; development hosts use Data Protection's default key ring. * `DescribeAsync` never returns a secret's value, and secrets are never projected into `IConfiguration` (it is routinely bound, logged and dumped). Read secrets through `ISettingsManager`, or bind one onto options (below). * `ISettingReprotector.ReprotectAsync(scope, prefix?)` converges legacy plaintext, rotated keys and older schemes; it is idempotent and version-guarded. `AddElarionSettingsDataProtection` also runs it once at start for the global scope (`ReprotectOnStartup`). * Persist and share the Data Protection key ring in production; a lost key ring makes protected settings unrecoverable. ### Secrets on options [#secrets-on-options] An adapter whose options are bound from configuration (an SMTP client reading `Email:Smtp`) cannot receive a secret through `IConfiguration`. `BindSecretSetting` (in `Elarion.Settings.Configuration`) sets just the secret member from the stored value and leaves the rest of the section bound from configuration: ```csharp builder.AddElarionSettingsConfiguration(); builder.Services.AddOptions() .BindConfiguration("Email:Smtp") // host, port, user .BindSecretSetting(AppSettings.SmtpPassword, static (o, password) => o.Password = password); ``` The value comes from the resolution the projection refresher already performs (so `AddElarionSettingsConfiguration` is required), only the bound definitions are kept in memory, and `IOptionsMonitor`/`IOptionsSnapshot` reload when the secret changes. The callback is skipped while the secret is unset or unreadable, so the member keeps its configured or default value. Read the options through `IOptionsMonitor` or `IOptionsSnapshot`: the refresher loads at host start, after which an `IOptions` value built earlier would stay stale. A non-secret definition is rejected — it is already in `IConfiguration`. ## Reading your own write [#reading-your-own-write] `ISettingsManager` reads through the resolver on the request's own scope, so a handler that writes a setting reads the new value back at once — inside its transaction, before the commit, with the EF Core store. Read settings that a request may have just changed through the manager (with a `FallbackConfigurationKey` for the deployment's preset), not through options bound from the [`IConfiguration` projection](#iconfiguration-projection). The projection follows the store **after** the commit, on the refresher's background loop, so `IOptionsSnapshot` and `IOptionsMonitor` see a change a moment later — a request that runs right after the saving one can still bind the old value. Code that must not continue before the projection has caught up awaits `SettingsConfigurationRefresher.RefreshAsync(ct)` after the commit (it reprojects on a fresh scope, so it cannot see uncommitted writes). There is no per-request overlay of the projection: `IConfiguration` is shared by the whole process, and the manager already is the per-request read. ## Describing settings for an admin UI [#describing-settings-for-an-admin-ui] ```csharp IReadOnlyList all = await settings.DescribeAsync(cancellationToken: ct); ``` Each entry has `Key`, `ValueType`, `Scope`, `AllowedScopes`, `IsSecret`, `IsPinnable`, `IsPinned`, `HasValue`, `Source` (`Default`, `ConfigurationFallback`, `Store` or `Configuration`), `ValueJson` (never for secrets), `Version` (usable as `expectedVersion`), `IsUnreadable` / `UnreadableReason` (a stored entry that cannot be decrypted or is not a valid value of its type) and `Description`. Elarion ships no handlers for it; map it to whatever your host exposes. ## Watching for changes [#watching-for-changes] `ISettingsManager.Watch(definition)` and `Watch(prefix)` return an `IChangeToken` that fires when the effective value may have changed: a store change, or — for pinnable global definitions — a deployment-configuration reload. Tokens are one-shot; re-watch or use `ChangeToken.OnChange`. ```csharp ChangeToken.OnChange( () => settings.Watch(AppSettings.Smtp), () => _logger.LogInformation("SMTP settings changed; reloading.")); ``` ## Using the EF Core database store [#using-the-ef-core-database-store] `Elarion.Settings.EntityFrameworkCore` persists settings to a relational database via your `DbContext`: ```csharp // In your DbContext's OnModelCreating: modelBuilder.UseElarionSettings(); // maps the elarion_settings table // In Program.cs (replaces the in-process store): builder.Services.AddElarionSettingsEntityFrameworkCore(); ``` Writes are change-tracker-free and immediate (they never flush the caller's unrelated tracked changes), with a `version` column backing optimistic concurrency. Generate and apply an EF migration for the `elarion_settings` table; the framework ships no migrations. **Database providers.** The store is provider-neutral EF Core: table and column names are resolved from your model, and the two raw statements it issues (the create-path `INSERT` and the last-write-wins `UPDATE … RETURNING`) are built from that model rather than hard-coded for one dialect. **PostgreSQL and SQLite are both exercised by the test suite**; any relational provider whose SQL supports `RETURNING` should behave the same (SQLite has supported it since 3.35 — every bundled `Microsoft.Data.Sqlite` native build is far newer). On SQLite, pair the store with the default in-process change source: a SQLite database file implies a single application node, and in-process notification already reaches every watcher in that process. The multi-node change source below is deliberately PostgreSQL-only — with SQLite there is no second node to notify. **Change notification and transactions.** A store write enlists in the context's ambient transaction when one is open, and the default in-process notifier is **commit-gated** to match: a write made *outside* a transaction is announced immediately (it is already durable), while a write made *inside* a caller-owned transaction is deferred and announced only when that transaction commits — and dropped on rollback, so a watcher never reloads a value a rollback discards. This works out of the box — `AddElarionSettingsEntityFrameworkCore` auto-attaches an EF Core transaction interceptor to `TContext` — so single-node live reload of `IConfiguration`/`IOptionsMonitor` and the scheduler applies as soon as the command that changed the setting commits (a setting changed from a command handler no longer needs a restart to take effect). The one thing the in-process notifier cannot do is cross process boundaries; the PostgreSQL change source below extends the same commit-gated delivery to **every** node. **Single-instance notification.** With only the shipped in-process source, a settings change on one node is not observed by another node's watchers or scheduler until that node restarts. When the EF Core store is paired with the in-process source, `AddElarionSettingsEntityFrameworkCore` registers a startup service that logs a **Warning** making this limitation visible at runtime; registering the PostgreSQL source below silences it. In a deliberately single-node deployment — a SQLite-backed host, say — the warning is informational and safe to ignore: there is no other node whose watchers could go stale. ## Multi-node change notification (PostgreSQL LISTEN/NOTIFY) [#multi-node-change-notification-postgresql-listennotify] `Elarion.Settings.PostgreSql` makes change notification cross-instance over the database the settings already live in — no extra infrastructure: ```csharp // In Program.cs, next to the EF Core store (either order): builder.Services.AddElarionSettingsEntityFrameworkCore(); builder.Services.AddElarionPostgreSqlSettingsChanges(connectionString); // or, if the host already manages an NpgsqlDataSource: builder.Services.AddElarionPostgreSqlSettingsChanges(dataSource); ``` A write on any node now fires `IChangeToken` watchers on **every** node — `ISettingsManager.Watch`, the settings `IConfiguration` projection, `IOptionsMonitor`, and the scheduler's `${...}` live rescheduling all follow. How it works: * A hosted listener holds one dedicated `LISTEN` connection per node and fires the matching watch tokens for each received notification, reconnecting with exponential backoff if the connection drops. PostgreSQL does not queue notifications for absent listeners, so after a reconnect the listener fires **all** watches — a spurious re-read is cheap and always converges. * Watch tokens fire **only** from the notification loop: a local write loops back through the database like a remote one, so every node — including the writer — observes changes in commit order through one path. * The EF Core store's writes are announced with `pg_notify` **on the store's own connection**, which PostgreSQL makes transactional: a write inside a caller-owned transaction is announced only when that transaction commits, and never on rollback. Transactional writes are therefore fully notified with this backend. * The channel (`elarion_settings_changed` by default) and the reconnect backoff are configurable via `PostgreSqlSettingsChangeOptions`; two applications sharing one database should use distinct channels. The store's `DbContext` must target the same PostgreSQL database as the connection string / data source given to `AddElarionPostgreSqlSettingsChanges`. See [ADR-0024](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0024-postgres-listen-notify-settings-changes.md) for the design and alternatives. `UseElarionSettings` (which also maps the nullable `protection` column) takes optional `tableName` and `schema` parameters to rename the table or place it in a non-default schema, plus a `snakeCase` toggle (default `true`; `false` switches to PascalCase names — the default table becomes `ElarionSettings`): `modelBuilder.UseElarionSettings("app_settings", "app")`. On a `[GenerateDbSets]` context you can skip the hand-written call: annotate the context with `[GenerateElarionSettings]` (optionally with `SnakeCase`/`TableName`/`Schema`) and the bundled generator emits the `DbSet` and applies the same model configuration through the EF generator's model-config seam (`ELSET001` if `[GenerateDbSets]` is missing). ## IConfiguration projection [#iconfiguration-projection] `Elarion.Settings.Configuration` projects the resolver's effective **global** values into `IConfiguration` with live reload, for `IOptionsMonitor` and the scheduler's `${...}` variable substitution: ```csharp builder.AddElarionSettingsConfiguration(); // after the other configuration sources ``` It is a **projection, not a second source of truth**: it is derived from the resolver and the resolver never reads it back, so it cannot pin a definition and there is no store-versus-configuration precedence switch. Scalar definitions become one key; object values are flattened to `key:property` (and `key:0`, `key:1` for arrays) so a section binds to your options type. Secrets are never projected, values pinned by configuration are skipped (they are already there), and only the global scope is surfaced. A **stored** value is always projected; a declared **default** only when it is a scalar — a structured (record or collection) default would add a key per property that nobody set, and the options type already carries its own defaults. An unreadable row is skipped and reported, never fatal (see above). Register it after your other sources so a later provider does not mask the projected effective value. A declared default never masks deployment configuration: when appsettings or the environment already supply a non-blank value at a definition's key, the default is not projected, so `IConfiguration` keeps the deployment value until an administrator stores one (a stored value is projected and wins). This makes "appsettings is the fallback, the settings store overrides it" work for options bound from configuration, with or without a declared default. Only the projection behaves this way — the resolver reads deployment configuration for `Pinnable` definitions only, so `ISettingsManager` returns the declared default for such a key. Declare the definition `Pinnable` when the deployment value should be authoritative for every reader (and freeze writes). Because `IConfiguration` is built before the DI container, the background refresher performs the initial load in its `StartAsync`, before later-registered hosted services (notably the scheduler) start. The load is time-bounded so a slow store cannot hang startup. The refresher reprojects on store changes and when the rest of the configuration reloads (a pin may have appeared); the provider reloads only when its data actually changed. ### Before the host is built [#before-the-host-is-built] Configuration consumed while the builder is still being assembled (server endpoints, authentication options) cannot wait for the refresher. `SettingsConfigurationSnapshot.LoadAsync(definitions, store, serialization, deploymentConfiguration)` runs the same resolver and projection against a store you construct yourself and returns a `SettingsProjection` (`Data`, `Problems`); `SettingsConfigurationProjection.Flatten` is the public decode helper. Pass the snapshot to `builder.AddElarionSettingsConfiguration(snapshot)` so the live provider starts with it (one provider, so a value that is later reset cannot linger), or add it to a plain `IConfigurationBuilder` with `AddElarionSettingsSnapshot(snapshot)`. Secret definitions are skipped. ## Scheduler integration [#scheduler-integration] Settings flow into the scheduler through [variable substitution](/docs/concepts/variable-substitution): a job's `${...}` schedule variables resolve from the (config-backed) variable source, and the settings `IConfiguration` adapter is observable, so changing a setting **reschedules affected recurring jobs live** (not just on their next fire). No scheduler-specific wiring is needed. ## Roadmap [#roadmap] The foundation, the EF Core database store, the `IConfiguration`/`IOptionsMonitor` adapter, the scheduler integration, and the cross-instance PostgreSQL `LISTEN/NOTIFY` change source ship today. A Redis pub/sub change source is a possible future provider over the same contracts. See [ADR-0011](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0011-runtime-settings-subsystem.md) for the full design and phasing and [ADR-0024](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0024-postgres-listen-notify-settings-changes.md) for the multi-node backend. # Solution structure (/docs/concepts/solution-structure) [Project structure](/docs/getting-started/project-structure) covers the mechanical layout the generators rely on. This page is the **decision behind that layout**: given that Elarion's module-boundary analyzer ([`ELMOD002`](/docs/concepts/cross-module-communication)) treats everything inside an `[AppModule]` as module-internal, where do shared things like entities go? ## The rule that drives everything [#the-rule-that-drives-everything] The boundary analyzer treats every type declared inside a module as **module-internal** — reachable from another module only through a [`[ModuleContract]`](/docs/concepts/cross-module-communication) interface. Declaring `DependsOn` does **not** grant access to another module's internals; it only orders initialization. Concretely, the rule is **location-based**: any type declared *inside* module A — an entity, DTO, `[Service]`, handler, or `[EntityConfiguration]` — cannot be referenced from module B except through a `[ModuleContract]`. Types declared under **no** `[AppModule]` (the shared kernel and platform ports) are shareable, so every module may depend on them freely. **Entities live in that shared kernel** — that is what makes them shareable; an entity placed inside a module would become module-owned and flagged like any other internal type. That distinction — code is module-internal, data is shared — decides where entities go. Said as a model: **a feature is a *plugin* over the application's shared data layer.** A feature composes the data layer (the entities + their configuration) and the host's platform capabilities into behavior; it may touch *any* entity, but it never depends on another feature except through a [`[ModuleContract]`](/docs/concepts/cross-module-communication). The dependency arrow points **feature → data layer**, never the reverse and never feature → feature. Touching many *entities* is using the data layer; depending on another *feature* is the thing to avoid. [Why Elarion](/docs/why-elarion) develops this model — including what "platform" means (the host) versus the data layer — and what it implies for where the database and configuration belong. ## Active modules vs. passive building blocks [#active-modules-vs-passive-building-blocks] Everything in an Elarion application is one of two kinds, and this — **not** "core-ness" — is the axis that decides where it lives: * **A module is *active*.** It is a self-registering unit of *behavior*: the generators discover its handlers, services, validation metadata, scheduled jobs, and event consumers and wire them as a gated unit, and it can expose transports (JSON-RPC / HTTP / MCP). It contributes DI registrations. * **A shared building block is *passive*.** It is referenced or *composed by* modules and the host; it never self-registers behavior. Entities, value objects, `[EntityConfiguration]`, the `DbContext`, and intent-only ports are all passive. The test is one question: **does it contribute behavior the framework should discover and wire as a gated unit?** Yes → a module. No (it is referenced, applied to something, or wired by the host) → a shared building block. They are not two flavors of "core," and they cannot be merged: entities **must** live *outside* modules precisely *because* modules are boundaries. `ELMOD002` makes everything in a module module-internal, and shared data must not be boundaried (modules are *feature* separation, not *data* separation) — so it lives outside every module. The shared kernel exists **because** modules are boundaries; they are opposites. ### Where does it go? [#where-does-it-go] | If it is… | …it lives in | Example | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------- | | Pure data or a value — no behavior, no DI | the **shared kernel** (`Domain`) | a `Money` value type, the `Client` entity, an enum | | How the database is shaped or accessed | the **persistence** layer (`Persistence`) | `[EntityConfiguration]`, the `DbContext`, migrations | | An intent-only **mechanism** — you care only *what*, the impl is swappable, no domain data you query | a **port** (in the application) + adapter (`Infrastructure`), wired by the host | `IEmailSender`, `IBlobStore` | | **Behavior** — logic, a DI participant, perhaps endpoints | a **module** | a feature; the audit capability | | …used by one area and switchable | a **feature module** | `Invoicing` | | …a foundation every module assumes is present, always on | the **Core module** | recording an audit event | A single capability often **spans** these — and that is the model working, not a smell. The audit trail is the worked example: the `AuditEntry` record is shared-kernel data, its `[EntityConfiguration]` is in `Persistence`, and the recording capability (a `[ModuleContract]` plus its implementation) is in the Core module. ### Port or module? (the email-vs-audit line) [#port-or-module-the-email-vs-audit-line] Both a platform-capability **port** and a module **capability** are shared and injected, so they are easy to confuse. The split is the same *intent-vs-specifics* line that decides the data layer: * **A port** wraps a domain-blind **mechanism** you only invoke ("send this email") and could swap (SMTP ↔ SES) without changing your application's meaning. It is *platform* — provided by the host, never aware of your domain. * **A module capability** is domain-aware **behavior** — it has business meaning, owns or queries domain data, and may expose endpoints. Recording an audit event and reading its history is domain behavior, so audit is a module capability (published cross-module as a `[ModuleContract]`), not a port. ## Entities are shared kernel, not module-internal [#entities-are-shared-kernel-not-module-internal] **Do not put entities inside a module.** Domain entities cross-reference each other through foreign-key navigation properties, and handlers routinely query across aggregates — so a single module cannot own them, and a `[ModuleContract]` interface cannot model an EF relationship. Modules are *feature* separation, not *data* separation: every module reaches the whole database through the shared concrete `DbContext` by design (real data isolation would be a separate `DbContext`). The boundary analyzer is purely **location-based** — it flags any type placed *inside* a module, so keeping entities in the shared kernel (under no `[AppModule]`) is what keeps a cross-aggregate reference unflagged. (Reference other aggregates by id rather than by navigation property; see [the delete-the-module test](#the-delete-the-module-test) for why.) Keeping entities in one shared-kernel namespace gives shared data an obvious home; placing an entity inside a module instead deliberately makes it module-owned — the first step toward a bounded context. Keep entities and their enums in a **shared-kernel namespace under no `[AppModule]`** — for example `MyApp.Application.Domain` — that every module may depend on and that depends on no module. ```text src/ MyApp.Application/ Domain/ ← shared kernel: entities + enums (NOT in any [AppModule]) Client.cs (plain entity — no marker) Invoice.cs (plain entity; references Client by id, not a navigation) InvoiceStatus.cs (enum) Persistence/ ← the database is application logic (under no [AppModule]) ClientConfiguration.cs [EntityConfiguration] : IEntityTypeConfiguration InvoiceConfiguration.cs [EntityConfiguration] : IEntityTypeConfiguration AppDbContext.cs the concrete DbContext (+ design-time factory) Migrations/ … EF Core migrations Modules/ Clients/ ← vertical slice: handlers, services — behavior only ClientsModule.cs [AppModule("Clients")] Handlers/ … Invoicing/ InvoicingModule.cs [AppModule("Invoicing")] Handlers/ … MyApp.Infrastructure/ ← intent-only mechanism adapters: IEmailSender (SMTP), external clients MyApp.Api/ ← host: [GenerateModuleBootstrapper], middleware, transport, UseNpgsql + connection ``` ## The persistence layer is application logic [#the-persistence-layer-is-application-logic] The application depends on the database's *specifics* — constraints are invariants, indexes serve specific queries, raw SQL and provider functions encode rules — so the database is application logic, not an infrastructure detail ([Why Elarion](/docs/why-elarion)). The whole persistence concern therefore lives in **one `Persistence` layer in the application**: the `[EntityConfiguration]` classes, the concrete `DbContext`, and the migrations. The only genuinely host concern is provider *registration* — `UseNpgsql(...)` and the connection string. `[EntityConfiguration]` is the single source of truth for an entity's participation: it drives both the generated `DbSet` and the configuration application. The generator emits direct `ApplyConfiguration` calls into a generated `ConfigureEntities(ModelBuilder)` on the context — no `ApplyConfigurationsFromAssembly` reflection. Because the configurations and the `DbContext` share an assembly, that emission is in-place and needs no cross-assembly manifest. Keep the layer flat while there is one `DbContext`; use one folder per `DbContext` once you [scope](#graduating-to-a-bounded-context). A configuration never crosses the module boundary, for two reasons: 1. It references only the shared-kernel entity (`Client`), never another module's internals. 2. `ELMOD002` inspects only the **dependency surface** — constructor parameters, fields, and properties — never a method body like `Configure`. `Infrastructure` is **not** where the database lives. It holds only intent-only mechanism adapters — the SMTP `IEmailSender`, external API clients — the things you depend on by intent ("send an email") and could swap without changing your application's meaning. The database, which you depend on by specifics, is application logic and stays in `Persistence`. ## A separate `Domain` project is usually unnecessary [#a-separate-domain-project-is-usually-unnecessary] For **one bounded context / one `DbContext`**, a shared-kernel *namespace* inside the application project is enough. A separate assembly only earns its keep when **multiple host projects share the code**. Until then, `MyApp.Application.Domain` (a namespace, not an assembly) avoids a project boundary you would only have to wire and reference. Whatever assembly declares `[EntityConfiguration]`/`[GenerateDbSets]` types must reference **`Elarion.EntityFrameworkCore`** (whose bundled generator emits that assembly's configuration manifest), not merely depend on a project that does. NuGet analyzer assets are not transitive. If you *do* split entities and their configurations into their own project, that project needs the reference directly — otherwise no manifest is emitted, the context resolves zero configurations, and no `DbSet`s are generated, with no error. See [Entity Framework Core → Setup](/docs/capabilities/entity-framework). ## The delete-the-module test [#the-delete-the-module-test] A module is meant to be a plugin: **delete its folder and every other module still compiles, untouched.** That holds because cross-module *code* goes through `[ModuleContract]`s (`ELMOD002` keeps it honest) and `[EntityConfiguration]` is discovered structurally, never referenced by name — so removing a feature removes its behavior cleanly. Two disciplines keep the test green: * **Reference other aggregates by ID, not by navigation property.** `Invoice.ClientId` (a `Guid`) leaves the model untangled, so removing the `Clients` feature does not ripple into `Invoicing`. A cross-module navigation creates an EF relationship that couples the two. * **Treat new data as shared.** A feature that adds an entity, index, or column *extends the shared data layer*; that data lives in the shared persistence layer and does **not** vanish when the feature folder is deleted — its removal is a deliberate migration step, because data is durable and shared. (How a plugin should own new typed data while staying cleanly removable is an open design question.) ## Graduating to a bounded context [#graduating-to-a-bounded-context] The shared-kernel default is right until an aggregate cluster becomes a **genuinely separate bounded context with its own `DbContext` and schema** — real *data* separation, not just feature separation. At that point its entities become context-private (correctly, since nothing outside the context references them). The graduation is incremental, not a rewrite: | Stage | Layout | | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | One bounded context, one `DbContext` | Shared-kernel **namespace** + a shared `Persistence` layer in the application project | | Partition into separate `DbContext`s without splitting assemblies | **Scopes** — `[GenerateDbSets("ctx")]` / `[EntityConfiguration("ctx")]`, one `Persistence` folder per scope | | An aggregate becomes its own bounded context | A self-contained **`Context.Application` / `.Infrastructure` / `.Contract`** assembly group owning its entities, configs, and migrations | The by-ID reference discipline above is what keeps each promotion cheap. A bounded context collaborates with the rest of the system only through a [`[ModuleContract]`](/docs/concepts/cross-module-communication) and integration events (the outbox) — exactly as modules already do — so promoting one is mostly moving files and splitting the schema, not a rewrite. The boundary it adds is enforced by the compiler (separate assemblies) rather than the analyzer, which is the heavier guarantee real data separation deserves. ## See also [#see-also] * [Why Elarion](/docs/why-elarion) — the principles behind this layout: features as plugins over the shared data layer, and the database as application logic. * [Project structure](/docs/getting-started/project-structure) — the mechanical layout and the conventions the generators rely on. * [Cross-module communication](/docs/concepts/cross-module-communication) — `[ModuleContract]` and the `ELMOD002` analyzer in full. * [Entity Framework Core](/docs/capabilities/entity-framework) — `[EntityConfiguration]`, `[GenerateDbSets]`, and configuration discovery. * The runnable [`samples/Billing`](https://github.com/swimmesberger/Elarion/tree/main/samples/Billing) app follows this layout — entities in `Billing.Application.Domain`, the persistence layer (configuration and `BillingDbContext`; the sample uses `EnsureCreated` instead of migrations) in `Billing.Application.Persistence`, and the SMTP adapter in `Billing.Infrastructure`. # Source generation (/docs/concepts/source-generation) Source generation is the mechanism behind everything in Elarion. Instead of scanning assemblies with reflection at startup, the generators read your attributes and conventions at compile time and emit ordinary DI registration code. Startup is deterministic, AOT-friendly, and the generated code can be inspected like any other source. ## Turning generators on [#turning-generators-on] An application project references the runtime package — the source generator ships inside it: ```xml ``` (When building inside this repository, reference the generator project with `OutputItemType="Analyzer" ReferenceOutputAssembly="false"` instead — a `ProjectReference` to the runtime project does not pull in the bundled analyzer.) Then add the full framework opt-in once in the assembly: ```csharp using Elarion.Abstractions; using MyApp.Application.Pipeline; [assembly: DefaultPipeline] [assembly: UseElarion] ``` `[assembly: UseElarion]` enables the framework-owned assembly-level generators for module handlers, services, scheduled jobs, event consumers, resilience policies, actor facades, authorization policies, client-event topics, permissions, and variants. It intentionally does **not** replace application-owned policy attributes such as `[DefaultPipeline]`, nor the dedicated triggers `[assembly: GenerateModuleBootstrapper]` (the host) or `[GenerateDbSets]` (the application's `DbContext`). ## Narrow triggers [#narrow-triggers] Use the narrower triggers when an assembly intentionally wants only a subset of the generators: ```csharp [assembly: GenerateModuleHandlers] [assembly: GenerateModuleServices] [assembly: GenerateScheduledJobs] [assembly: GenerateEventConsumers] [assembly: GenerateResiliencePolicies] [assembly: GenerateActors] [assembly: GenerateModuleAuthorizationPolicies] [assembly: GenerateClientEventTopics] [assembly: GeneratePermissionCatalog] [assembly: GenerateVariantCatalog] ``` ## Generator reference [#generator-reference] | Generator | Trigger | Generated API | | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `HandlerRegistrationGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateModuleHandlers]` | `Add{HandlerName}()` and `Add{ModuleName}Handlers()` extension methods. | | `ModuleServiceRegistrationGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateModuleServices]` | `Add{ServiceName}Service()` and `Add{ModuleName}Services()` extension methods. | | `ContractSetRegistrationGenerator` | `[GenerateContractSetRegistration(typeof(TContract))]` on a host-authored `static partial IServiceCollection` extension method (each declaration is its own opt-in; not subsumed by `[UseElarion]`) | The method's implementation, composing every implementation of the contract in the declaring assembly via `TryAddEnumerable` — pulled unconditionally by the host, never module-gated. See [Services](/docs/concepts/services#module-services-vs-contract-sets). | | `ValidationResolverGenerator` | Handler discovery (`[assembly: UseElarion]` or `[assembly: GenerateModuleHandlers]`) when the compilation references `Elarion.Validation` | A per-module `IValidatableInfoResolver` for the module handlers' annotated request types (constant-constructed attribute arrays — no runtime attribute reflection), registered through the module's gated `ConfigureDefaultServices`. See [Validation](/docs/concepts/validation). | | `SchedulerRegistrationGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateScheduledJobs]` | Per-module `Add{Module}ScheduledJobs()` registering descriptors and job types. | | `EventConsumerRegistrationGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateEventConsumers]` | Per-module `Add{Module}EventConsumers()` registering each `[ConsumeEvent]` consumer (handler or `[Service]` method) plus its `EventSubscriptionDescriptor`. See [Events](/docs/capabilities/events). | | `ResiliencePolicyRegistrationGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateResiliencePolicies]` | Policy name, typed `Reference`, per-policy and aggregate registration methods. | | `ActorRegistrationGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateActors]` | Typed actor facades and each module's `Add{Module}Actors()` registration hook. See [Actors](/docs/concepts/actors). | | `AuthorizationPolicyRegistrationGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateModuleAuthorizationPolicies]` | Per-module registration for named `[AuthorizationPolicy]` implementations. See [Authorization](/docs/concepts/authorization). | | `ClientEventRegistrationGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateClientEventTopics]` | Per-module topic catalog/registration from `IClientEvent` contracts and their subscribe-time requirements. See [Client events](/docs/capabilities/events/client-events). | | `PermissionCatalogGenerator` | `[assembly: UseElarion]` or `[assembly: GeneratePermissionCatalog]` | The typed `ElarionPermissions` catalog harvested from handler permission and role requirements. | | `VariantCatalogGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateVariantCatalog]` | The typed `ElarionVariants` catalog, grouped by module and switch. See [Feature flags](/docs/concepts/feature-flags). | | `FeatureFlagGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateFeatureFlags]` | The typed `ElarionFeatureFlags` registry and per-module flag registration. See [Feature flags](/docs/concepts/feature-flags). | | `SettingDefinitionGenerator` | `[assembly: UseElarion]` or `[assembly: GenerateSettingDefinitionCatalog]` | The `[SettingDefinitions]` property implementations and the aggregated `ElarionSettingDefinitions.All`. See [Settings](/docs/concepts/settings). | | `ElarionManifestGenerator` | Any project containing `[AppModule]`, `[ModuleEndpoints]`, `[HttpEndpoint]`, `[Handler]`, `[ResourceFilter]`, `[RequirePermission]`, `[RequireRole]`, `[FeatureVariant]`, `[ConfigurationVariant]`, `[FeatureFlag]`, `[BackendFeatureFlag]`, or `[SettingDefinitions]` | Internal assembly metadata manifests consumed by host-side generators for referenced modules and transport handlers. | | `AppModuleDiscoveryGenerator` | `[assembly: GenerateModuleBootstrapper]` on the host → the fixed-name `ElarionBootstrapper` static | Extension methods on their natural receivers — `services.AddElarion(configuration)`, `endpoints.MapElarionEndpoints(configuration)`, `dispatcher.RegisterHandlers(configuration)`, `configuration.GetMcpMetadata()`, `configuration.GetAllJsonTypeInfoResolvers()`, `configuration.IsModuleEnabled(name)` — plus the parameterless `GetAllModuleNames`, the per-module transport extension methods `Map{Module}Http` / `Add{Module}Handlers`, and the parameterless `Get{Module}McpMetadata`. The single transport-wiring path for `[HttpEndpoint]`, JSON-RPC, and MCP. See [Hosting](/docs/capabilities/hosting) and [HTTP endpoints](/docs/capabilities/transports/http-endpoints). | | EF Core `DbSet` generator | `[GenerateDbSets]` on the concrete partial `DbContext` class (entities supplied by `[EntityConfiguration]` classes) | `DbSet` members and entity configuration application via direct `ApplyConfiguration` calls. See [Entity Framework Core](/docs/capabilities/entity-framework). | Generated code intentionally uses explicit type names and DI factory registrations. Startup behavior remains deterministic and AOT-friendly. Projects that contain modules or transport handlers emit compact compile-time manifests as assembly metadata. Host-side map/bootstrapper generators read those manifests from referenced assemblies instead of recursively scanning referenced symbols. This makes the manifest the compile-time contract for cross-assembly discovery: generators that create `[AppModule]`, `[HttpEndpoint]`, or `[Handler]` types must also emit matching Elarion manifest metadata for those generated types. Hosts still read `[AppModule]` declarations in their own compilation directly because source generators cannot consume another generator's same-compilation output. A host wires every transport through `[GenerateModuleBootstrapper]`, which emits **module-scoped, feature-flag-gated** mapping: `MapElarionEndpoints` and `RegisterHandlers` map each enabled module's generated `[HttpEndpoint]` routes and its `[Handler]` operations into the dispatcher bus respectively (core modules always; feature modules gated by `Modules:{Name}:Enabled`). `RegisterHandlers` builds the one operation registry that both the JSON-RPC and MCP adapters resolve, each serving only the operations flagged for its surface. A handler picks its dispatcher surfaces with `[Handler(Transports = ...)]`. Modules are the only path — a host with no modules declares a single core `[AppModule]` (which maps unconditionally). See [Hosting](/docs/capabilities/hosting), [MCP server](/docs/capabilities/transports/mcp), and [HTTP endpoints](/docs/capabilities/transports/http-endpoints). ## Diagnostics over surprises [#diagnostics-over-surprises] Because discovery is compile-time, mistakes surface as build diagnostics rather than runtime failures: a missing trigger attribute, an invalid service contract, a scoped hosted service, an unsupported generic service, or a handler outside its module namespace each produce an actionable message. The common cases and their fixes are listed in [Troubleshooting](/docs/reference/troubleshooting). The generators ship analyzer release notes (`AnalyzerReleases.Shipped.md` / `AnalyzerReleases.Unshipped.md`) so diagnostic IDs are tracked across versions — a small but real signal that diagnostics are treated as a stable contract. # Writing a transport (/docs/concepts/transports) Custom transport authoring now lives alongside HTTP, JSON-RPC, MCP, schema generation, and client generation in [Transport capabilities: writing a custom transport](/docs/capabilities/transports/custom-transports). This URL remains available so existing bookmarks and external links continue to work. The guide covers the transport-neutral `HandlerDispatcher`, the per-call dispatch scope, off-HTTP identity, typed and name-based invocation, `AppError` mapping, imperative exposure, packaging, and a complete console-host example. ## Exposing a handler you do not own [#exposing-a-handler-you-do-not-own] This section's former deep link is retained here for compatibility. Continue with [imperative handler exposure](/docs/capabilities/transports/custom-transports#exposing-a-handler-you-do-not-own). # Validation (/docs/concepts/validation) Validation in Elarion is **two-tier**, and the dividing line is not "simple vs. complex" but **what a wire contract can express**. JSON Schema — and therefore the JSON-RPC schema, the OpenAPI document, MCP tool schemas, and the Zod client generated from them — can carry exactly one category of rule: static, single-property shape constraints (lengths, ranges, patterns, formats, requiredness). Everything else is server-side by nature. * **Tier 1 — shape constraints** are declared on the request DTO as standard `System.ComponentModel.DataAnnotations` attributes. One declaration feeds **four surfaces**: the runtime validator, `rpc-schema.json` (and MCP tool schemas), the OpenAPI document, and the generated Zod client. * **Tier 2 — business rules** — cross-field comparisons, conditional rules, and every async or database-backed check — live in the handler (or a domain [`[Service]`](/docs/concepts/services) it calls), returning `AppError.Validation`/`AppError.Conflict` through the normal `Result` channel, **inside the transaction** where those checks are actually sound. There is no standalone validator class layer: an exportable rule has exactly one legal home (the DTO), so what the client pre-validates is by construction what the server enforces. ## Tier 1 — declare shape constraints on the request [#tier-1--declare-shape-constraints-on-the-request] Annotate the request's properties. Requiredness needs no attribute at all — it comes from nullability ([ADR-0082](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0082-requiredness-comes-from-nullability-in-both-directions.md)): a non-nullable property is required, a nullable one is optional, and a request property with a default value is optional to send. The `required` modifier is still useful — the compiler enforces it at construction sites — but it no longer changes the exported schema: ```csharp title="src/Billing.Application/Modules/Clients/Handlers/CreateClient.cs" using System.ComponentModel.DataAnnotations; [Handler("clients.create")] public sealed class CreateClient(BillingDbContext db, ICurrentUser user) : IHandler> { public sealed record Command : ICommand { [Required, StringLength(200)] // not blank: rejects "" and whitespace-only names public required string Name { get; init; } [EmailAddress, MaxLength(320)] public required string Email { get; init; } [Range(0, 365)] public int PaymentTermDays { get; init; } = 30; } // ... } ``` The validator walks the whole request graph, so constraints on nested objects and collection elements are enforced (and reported) too: a record in a request list is checked at its indexed path (`rows[1].code`). The supported vocabulary is the set every schema surface can carry: | Attribute | Enforced as | Exported as (JSON Schema) | | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | non-nullable (no default) | member must be present (the canonical serializer rejects `null` and a missing constructor parameter) | `required` | | nullable, or a request member with a default | member may be omitted | optional | | `[Range(min, max)]` | numeric bounds | `minimum` / `maximum` (`exclusiveMinimum`/`exclusiveMaximum` for exclusive bounds) | | `[MinLength]` / `[MaxLength]` / `[Length]` / `[StringLength]` | string/collection length | `minLength` / `maxLength` (`minItems`/`maxItems` on arrays) | | `[RegularExpression]` | the **whole** value matches | `pattern`, anchored as `^(?:…)$` unless already anchored | | `[Required]` on a string | not empty and not whitespace-only | a not-blank lookahead on `pattern` | | `[EmailAddress]` | email shape | `format: "email"` | | `[Url]` | absolute URL | `format: "uri"` | | `[Base64String]` | base64 content | `format: "byte"` | | `[AllowedValues(...)]` | value ∈ the declared set; `null` passes on a nullable member | `enum` (with `null` on a nullable member) | | `[DecimalRange(typeof(T), nameof(T.Min), nameof(T.Max))]` (Elarion) | decimal bounds read from decimal members of `T`; `null` passes | `minimum` / `maximum` (exclusive variants as `[Range]`) | | `[MaxDecimalPlaces(n)]` (Elarion) | at most `n` decimal places, trailing zeros not counted; `null` passes | `multipleOf: 10^-n` | `[AllowedValues]` pairs naturally with the generated variant registry: declare a switch's vocabulary once (`[AllowedValues(ElarionVariants.EmailBackend.Smtp, ElarionVariants.EmailBackend.Office365)]`) and the 400, the schema `enum`, the OpenAPI document, and the TypeScript client's `z.enum(...)` all follow — see [Feature flags](/docs/concepts/feature-flags#the-variant-registry). A single-value rule on a nullable member applies to a value that is present. `[Range]` already lets `null` pass; the BCL's `AllowedValuesAttribute` would look `null` up as one more value, so `[AllowedValues(30, 90, 365)] int? Days` would refuse every request that leaves `days` out. The generated metadata therefore adds `null` to the allowed values of a nullable member (`int?`, or a reference type annotated `?`), and the exported `enum` lists `null` too — JSON Schema applies `enum` to `null` as well, so an MCP client validating against it would otherwise refuse the same request. Listing `null` yourself (`[AllowedValues(null, 30, 90, 365)]`) means the same and compiles in a nullable-enabled project. Only the attribute itself is adjusted, not a subclass of it, and code that calls `Validator.TryValidateObject` directly runs the BCL attribute unchanged. ### Decimal bounds and decimal places [#decimal-bounds-and-decimal-places] C# admits no `decimal` attribute argument, so the BCL `[Range]` takes a decimal bound only as text (`[Range(typeof(decimal), "1", "999.9")]`) or as a `double`, which cannot hold every decimal (`9_999_999_999_999_999.99` rounds up). Either way the bound is a copy beside the decimal constant the rest of the code reads. And DataAnnotations has no attribute for "at most two decimal places", the scale of a `numeric(p, s)` column, which a database rounds silently on write. Elarion ships two attributes for these, both in `Elarion.Abstractions.Validation` ([ADR-0128](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0128-decimal-bounds-and-scale-are-declared-from-decimals.md)): ```csharp public static class CylinderLength { public const decimal MinMm = 1m; public const decimal MaxMm = 999.9m; public const int Scale = 1; public const string RangeMessage = "The length must be between 1 and 999.9 mm."; } public sealed record Command( Guid Id, [property: DecimalRange(typeof(CylinderLength), nameof(CylinderLength.MinMm), nameof(CylinderLength.MaxMm), ErrorMessage = CylinderLength.RangeMessage)] [property: MaxDecimalPlaces(CylinderLength.Scale, ErrorMessage = "At most one decimal place.")] decimal? LengthMm) : ICommand; ``` * `[DecimalRange]` **is** a `RangeAttribute`: it names two static `decimal` members of a type (a `const`, a `static readonly` field or a static property, public or not) and reads their values, so the bound is declared once. `null` passes, `MinimumIsExclusive`/`MaximumIsExclusive` apply, values compare as decimals. A name that is no such member fails when the attribute is created — at the first validation, and when the schema is exported at build time; `nameof` makes a typo a compile error. Every surface that reads `[Range]` reads it, the OpenAPI document included. * `[MaxDecimalPlaces(n)]` refuses a value with more than `n` decimal places (`1.50` has one); integers always pass. It is exported as `multipleOf` (`0.1` for one place), which the generated Zod client checks with `.multipleOf(0.1)` — Zod compares with a float-safe remainder, so `30.3` passes and `30.25` fails — and which `rpcLimits` lists, for a number input's `step`. Both report their explicit `ErrorMessage` on the server and in the client, like every other attribute. ### Not blank, and whole-value patterns [#not-blank-and-whole-value-patterns] `[StringLength(200, MinimumLength = 1)]` admits `" "`. The DataAnnotations rule for "not blank" is `[Required]`: on a string it rejects `""` and whitespace-only values. Elarion does not use it for requiredness (nullability is the source), but it exports it as what it enforces — a not-blank `pattern`: ```json "name": { "type": "string", "maxLength": 200, "pattern": "^(?=[\\s\\S]*\\S)(?:[\\s\\S]*)$" } ``` `[Required(AllowEmptyStrings = true)]` and `[Required]` on a non-string add nothing to the schema. The server's `RegularExpressionAttribute` requires the **whole** value to match, while JSON Schema — and every client validator built on it, the generated Zod `.regex(...)` included — only searches for a match. A pattern is therefore exported anchored: `[RegularExpression("[a-z]+")]` becomes `"pattern": "^(?:[a-z]+)$"`, so the client rejects `"abc1"` just as the server does. A pattern that already anchors both ends (`^…$` without a top-level `|`) is exported unchanged. A member with both `[Required]` and `[RegularExpression]` exports one combined pattern (`^(?=[\s\S]*\S)(?:…)$`); the regular expression's explicit message wins the shared keyword. The [OpenAPI document](/docs/capabilities/transports/openapi) keeps ASP.NET's own mapping: the pattern as declared and `[Required]` as a required member. Both rewrites apply to **request** schemas, which describe what the server validates. Result and event schemas keep the pattern as declared and get no not-blank lookahead: the server never validates what it sends, but the generated client parses it, and a stored value from before a constraint must not fail a read. Two edges differ between the anchored pattern and the server: `RegularExpressionAttribute` accepts an empty string (the client rejects it), and it checks only the first match, so `a|ab` rejects `"ab"` on the server while `^(?:a|ab)$` accepts it. ### Custom constraints [#custom-constraints] A reusable rule subclasses one of the mapped attributes, so it gets runtime enforcement *and* every schema surface for free — no registration, no exporter extension: ```csharp title="src/Billing.Application/Validation/SlugAttribute.cs" using System.ComponentModel.DataAnnotations; /// Lowercase words separated by single hyphens, e.g. "spring-sale". public sealed class SlugAttribute() : RegularExpressionAttribute("^[a-z0-9]+(-[a-z0-9]+)*$"); ``` ```csharp public sealed record Command : ICommand { [Slug, MaxLength(64)] public required string Slug { get; init; } } ``` Because `[Slug]` *is* a `RegularExpressionAttribute`, the runtime validator enforces it and every schema exports it as a `pattern` — the subclass changes nothing about the plumbing. ### Error messages [#error-messages] An attribute's **explicit** message travels with its constraint. `ErrorMessage` (or a resource message via `ErrorMessageResourceType`/`ErrorMessageResourceName`) is exported under the vendor keyword `x-elarion-error-messages`, keyed by the JSON Schema keyword the attribute produced: ```csharp public sealed record Command : ICommand { [RegularExpression("^[A-Z]{3}$", ErrorMessage = "Code must be three capital letters.")] [StringLength(20, ErrorMessage = "{0} must be at most {1} characters.")] public required string Code { get; init; } } ``` ```json "code": { "type": "string", "maxLength": 20, "pattern": "^[A-Z]{3}$", "x-elarion-error-messages": { "pattern": "Code must be three capital letters.", "maxLength": "Code must be at most 20 characters." } } ``` The exporter formats the message exactly as the server's validator does (`FormatErrorMessage` with the `[Display(Name)]` or the member name, so `{0}`/`{1}`/`{2}` placeholders are filled in), so the generated client reports the same text before the round trip that the server would after it. An attribute that produces two keywords (`[StringLength]` with a minimum, `[Length]`, `[Range]`) carries its message on both. Keywords stay last-wins: a later attribute without a message for the same keyword drops the earlier message. * **Only explicit messages are exported.** An attribute relying on the framework's default text adds nothing; the client then shows its own validation library's wording. * **Resource messages are resolved at export time**, in the exporting process's UI culture, so the schema carries one language. When the server localizes per request, the client's pre-flight text is that one language; the server's response still follows the request culture. ## Enforcement [#enforcement] Reference the opt-in **`Elarion.Validation`** package and register it once in the host: ```csharp title="src/Billing.Api/Program.cs" builder.Services.AddElarionValidation(); ``` `AddElarionValidation([configure])` wires the `Microsoft.Extensions.Validation`-backed default behind the Elarion-owned `IRequestValidator` seam (`Elarion.Abstractions.Validation`) and also calls `AddElarionJson()`. Everything else is generated: a per-module resolver contributes each request type's validation metadata as **constant-constructed attribute arrays** (no runtime attribute reflection), registered through the module's gated `ConfigureDefaultServices` — a [disabled module](/docs/concepts/modules) contributes no validation metadata. The framework-owned `ValidationDecorator` (`Elarion.Pipeline`) is auto-attached by the handler generator **just inside the feature gate** — the pipeline runs observability → audit → authorization → feature gate → **validation** → cache invalidation → resilience → idempotency → your `[DefaultPipeline]` decorators → handler (the full order is in [Decorator pipelines](/docs/concepts/decorator-pipelines#order-matters)) — for any handler whose request type graph carries validation attributes. Two consequences: * **Validation runs pre-transaction.** A bad request is rejected before caching, your pipeline, or a unit of work is ever touched. * **Unannotated requests cost nothing.** No decorator is attached, no resolver entry exists, no lookup happens. Attaching is opt-in by construction, exactly like [authorization](/docs/concepts/authorization) and [feature gates](/docs/concepts/feature-flags): the attributes on your DTO are the switch. There is nothing to add to a `[DecoratorList]`. ### On .NET 11 [#on-net-11] Behavior is the same on both target frameworks; the plumbing differs. `Microsoft.Extensions.Validation` 11 no longer exposes the walker that runs the attributes (its own generator compiles that walker into each application), so the `net11.0` build of `Elarion.Validation` carries the same walker, and the generated resolvers bind to it. The .NET 11 walker also runs `AsyncValidationAttribute`s (after every synchronous attribute of the member passed) and `IAsyncValidatableObject`. Both still run in the validation decorator, **before the transaction** — see the next section for what that rules out. A property typed as a C# 15 union is validated as its active case: the attributes of the case type apply, and errors use the property's path (`result.name`, not `result.value.name`), matching the JSON, where a union is written as its active case. ### Validating outside a handler request [#validating-outside-a-handler-request] A type that reaches the validator without a handler, such as a row read from a file, is marked `[ValidationRoot]` (`Elarion.Abstractions.Validation`). It joins the generated metadata of the module whose namespace contains it, exactly like a handler request, and is validated through the same seam with the same messages: ```csharp [ValidationRoot] public sealed record ProductRow { [StringLength(40, MinimumLength = 1)] public required string Sku { get; init; } } if (!validator.HasMetadata(typeof(ProductRow))) throw new InvalidOperationException("No validation metadata is registered for ProductRow."); var errors = await validator.ValidateAsync(typeof(ProductRow), row, cancellationToken); ``` A package that defines its own kind of validated type marks its attribute class instead: a type that carries an attribute whose class is marked `[ValidationRoot]` is a root too. `[SpreadsheetRecord]` is marked this way, so every spreadsheet record with validation attributes gets its module's metadata without a marker of its own. `ValidateAsync` answers "valid" for a type it holds no metadata for, and metadata exists only while the module is enabled, so code that validates outside the pipeline asks `IRequestValidator.HasMetadata(type)` first and fails when the answer is no. A root outside every module is `ELVAL004`; without `Elarion.Validation` it is `ELVAL002`. ## Field-keyed errors [#field-keyed-errors] A violation fails with `AppError.Validation` carrying `FieldErrors` — messages keyed by **wire-named field path** using the [canonical JSON naming policy](/docs/capabilities/serialization), so error keys match the property names the client actually sent: `"address.street"`, with collection indexers preserved as `"deliveries[1].street"`. The empty-string key carries messages not specific to a single field. Over HTTP the mapper surfaces them as the standard RFC 7807 `errors` extension (the `HttpValidationProblemDetails` shape): ```json { "title": "One or more validation errors occurred.", "status": 400, "detail": "Name is required", "errors": { "name": ["The Name field is required."], "deliveries[1].street": ["The Street field is required."] } } ``` Over JSON-RPC the same structure rides in `error.data.data` under the stable code `validation` (numeric code `-32602`, the spec's "Invalid params"): ```json { "error": { "code": -32602, "message": "The Name field is required.", "data": { "code": "validation", "data": { "errors": ["The Name field is required.", "The Street field is required."], "fieldErrors": { "name": ["The Name field is required."], "deliveries[1].street": ["The Street field is required."] } } } } } ``` Because a client-side Zod pre-flight failure and a server 400 key violations by the same wire paths, a form binds either one to the same input field: the generated client's `RpcParamsValidationError` exposes `fieldErrors` in exactly this notation (see [Params validation](/docs/capabilities/transports/typescript-client#params-validation)). ## One attribute, four surfaces [#one-attribute-four-surfaces] The point of tier 1 is that a constraint **cannot drift from the contract** — every surface reads the same declaration: | Surface | How the constraint gets there | | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Runtime enforcement | The generated per-module resolver + the auto-attached `ValidationDecorator`. | | [JSON-RPC schema](/docs/capabilities/transports/schema-generation) & [MCP tools](/docs/capabilities/transports/mcp) | `JsonRpcSchemaExporter` injects the JSON Schema keywords and explicit messages (`x-elarion-error-messages`); MCP tool input schemas share the same builder. | | [OpenAPI document](/docs/capabilities/transports/openapi) | `Microsoft.AspNetCore.OpenApi` maps DataAnnotations natively (reflection-off); `Elarion.AspNetCore.OpenApi` adds `format: "email"` parity. | | [Generated Zod client](/docs/capabilities/transports/typescript-client) | The Zod emitter maps the keywords (`.min()`, `.max()`, `.regex()`, `.gte()`, `.email()`, …) with their explicit messages, and the client pre-validates params before the wire. | ## Tier 2 — business rules in the handler [#tier-2--business-rules-in-the-handler] Cross-field comparisons, conditional rules, and anything that touches the database belong in the handler, where they run **inside the transaction**. An async pre-handler check would be unsound anyway: the validation decorator runs before the transaction opens, so a pre-flight uniqueness query is a time-of-check/time-of-use race — the database constraint is the real fence, and the handler must handle the conflict regardless. .NET 11 adds `AsyncValidationAttribute` and `IAsyncValidatableObject`, and Microsoft's documentation shows a uniqueness check as the example. On an Elarion request DTO they run in the validation decorator, before the transaction — the race described above, which `ELVAL003` reports at build time. Keep database and service lookups in the handler. ```csharp public async ValueTask> HandleAsync(Command command, CancellationToken ct) { // Cross-field rule: field-keyed so the client can bind it to the input. if (command.ValidFrom > command.ValidTo) { return AppError.Validation("Invalid validity range.", new Dictionary { ["validTo"] = ["Must be on or after validFrom."], }); } // Database-backed rule: checked inside the transaction, backed by a unique constraint. var exists = await db.Clients.AnyAsync(c => c.OwnerId == user.UserId && c.Email == command.Email, ct); if (exists) { return AppError.Conflict($"A client with email {command.Email} already exists."); } // ... } ``` The `AppError.Validation(message, fieldErrors)` overload produces the same field-keyed error shape as tier 1, so tier-2 failures render identically on every transport. A rule shared by several handlers moves to a domain [`[Service]`](/docs/concepts/services) those handlers call — not to a validator layer. ### What stays server-only [#what-stays-server-only] Be honest about the boundary: the client pre-validates *shape*, never *truth*. These never reach a schema, by design: * **Uniqueness and existence checks** — only the database knows, and only inside the transaction. * **Cross-field rules** — the schema subset the surfaces share cannot express "ValidTo ≥ ValidFrom"; the client discovers them as field-keyed 400s. * **Conditional requiredness** — "B is required when A is set" is a tier-2 branch. * **Anything reading `ICurrentUser`, settings, or feature flags** — ambient state is not contract. Nothing pretends a uniqueness check can run in a browser; the contract simply guarantees that what *can* be expressed is expressed everywhere. ## Diagnostics [#diagnostics] | Id | Severity | Meaning | | ---------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ELVAL001` | Error | A handler's request carries validation attributes but the response type cannot represent failure (no `IResultFailureFactory`, i.e. not `Result`/`Result`) — the decorator could not short-circuit and would be silently skipped. Mirrors `ELAUTH001`. | | `ELVAL002` | Warning | A request or a `[ValidationRoot]` type carries validation attributes but the compilation does not reference `Elarion.Validation` — the constraints are documented in every schema but **unenforced** at runtime. Reference the package and call `AddElarionValidation()`, or remove the attributes; the gap must be a visible choice, never a silent one. | | `ELVAL003` | Warning | (.NET 11) The request graph has an `AsyncValidationAttribute` or an `IAsyncValidatableObject`. It is enforced, but it runs in the validation decorator **before the transaction**, so a database or service lookup there is a time-of-check/time-of-use race. Move the check into the handler and return `AppError.Validation`/`AppError.Conflict`, or suppress the warning when the check reads no shared state. | | `ELVAL004` | Error | A `[ValidationRoot]` type carries validation attributes but lies outside the namespace of every module, so no module registers its metadata. Move it into the namespace of the module that validates it. | ## Coming from FluentValidation [#coming-from-fluentvalidation] Elarion's earlier FluentValidation integration (`[GenerateModuleValidators]` and per-module `IValidator` registration) is removed: imperative rule lambdas are invisible to every contract surface, which guaranteed exportable rules hiding in unexportable places. Migrate shape rules to attributes and business rules into the handler. If you want FluentValidation for its combinator style, wire it as an app-owned [decorator](/docs/concepts/decorator-pipelines) — which is all it ever was. ## See also [#see-also] * [ADR-0027: Declarative request validation](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0027-declarative-request-validation.md) — the full rationale, including why Microsoft's bundled validation generator is not used. * [Results & errors](/docs/concepts/results-and-errors) — the `Result`/`AppError` channel tier-2 rules report through. * [Decorator pipelines](/docs/concepts/decorator-pipelines) — where the validation gate sits and how decorators compose. * [TypeScript client](/docs/capabilities/transports/typescript-client) — constraint-aware Zod schemas and params pre-validation. * [OpenAPI](/docs/capabilities/transports/openapi) — the same constraints in the REST contract. # Variable substitution (/docs/concepts/variable-substitution) Variable substitution is a small, reusable building block: resolve `${key}` placeholders (with optional `${key:-default}` fallbacks) from a pluggable source. It is **not tied to any one subsystem** — the scheduler uses it for `${...}` variables in cron/interval expressions, and you can use it anywhere you want configurable, runtime-changeable string values. ## The pieces [#the-pieces] * **`IVariableSource`** — the pluggable backend: `bool TryGetValue(string key, out string? value)`. The shipped adapter is `ConfigurationVariableSource` (over `IConfiguration`); other sources (a dictionary, environment, a custom store) implement the same seam. * **`VariableSubstitution`** — the resolver. A missing, empty, or whitespace value is treated as unset so an inline `:-` default can recover. Both live in `Elarion.Abstractions.Substitution`. ## Two models [#two-models] **Whole-value** — a string is either a literal or a single placeholder. Useful for optional, settable attributes; an unresolved placeholder yields `null`. ```csharp IVariableSource source = new ConfigurationVariableSource(configuration); VariableSubstitution.Resolve("plain", source); // "plain" (literal) VariableSubstitution.Resolve("${Jobs:Interval:-15s}", source); // configured value, else "15s" VariableSubstitution.Resolve("${Jobs:Interval}", source); // null when unset (no default) VariableSubstitution.ResolveRequired("${Jobs:Interval}", source); // throws when unset ``` **Embedded** — replace every `${...}` inside a larger template (a connection string, a path, a message): ```csharp VariableSubstitution.Substitute("postgres://${db:host}:${db:port:-5432}/app", source); // → "postgres://db.local:5432/app" ``` Embedded substitution throws when a placeholder is unset and has no default; nesting (`${a:${b}}`) is not supported. ## Dependency injection [#dependency-injection] Register a default source so any subsystem can inject one: ```csharp builder.Services.AddElarionVariableSubstitution(); // IVariableSource → ConfigurationVariableSource ``` Because it reads `IConfiguration`, it transparently sees appsettings, environment variables, and — if you add the [settings](/docs/concepts/settings) `IConfiguration` adapter — database-backed settings, with **runtime changes** as those providers reload. Register a different `IVariableSource` first to override the source. ### Observable sources [#observable-sources] A source that can signal change implements `IObservableVariableSource` (`IChangeToken Watch()`). `ConfigurationVariableSource` is observable — `Watch()` bridges to the configuration reload token, so a provider reload (appsettings change, or a settings-backed provider reload) propagates to consumers. A static source (a dictionary) simply doesn't implement it. ## How the scheduler uses it [#how-the-scheduler-uses-it] Scheduled jobs resolve `${...}` variables in their schedule (interval, cron, time zone, enabled flag) on **every occurrence**, so changing a variable changes the schedule on its next fire. The scheduler injects an `IVariableSource` (config-backed by default), so pointing it at a settings-backed `IConfiguration` makes job schedules runtime-changeable with no scheduler-specific wiring — the substitution concept is shared, not duplicated. Because the default source is **observable**, the scheduler goes further than next-fire pickup: when a watched variable changes it **reschedules affected recurring jobs immediately**, re-resolving each job whose variables changed and replacing its queued occurrence (a job with a literal schedule, or one whose variables didn't change, is left untouched; a fixed-delay job mid-run reschedules itself on completion). So shortening a job's interval, changing its cron, or enabling a `${...}`-disabled job takes effect at once rather than after the (possibly long) current interval. A reschedule only replaces the *queued successor* — it never injects an extra run alongside one already executing: when a fixed-rate or cron job has a run in flight, its recomputed successor lands on the new grid strictly after now, so the new schedule applies without a duplicate immediate execution. # Getting started (/docs/getting-started) This section takes you from an empty solution to a working, source-generated endpoint. Follow the three pages in order — each builds on the last. Add the runtime packages and source generators to an application project and an ASP.NET Core host. Build your first module and handler and call it over a JSON-RPC endpoint — a few minutes, no database server. The solution layout and naming conventions the generators rely on, and the dependency direction that keeps your application independent of the host. ## Where to go next [#where-to-go-next] A full end-to-end tutorial: a modular billing backend with a typed React frontend. Handlers, results, modules, and the source generation that wires them — the mental model behind everything else. **Don't learn from pre-generator examples.** Older Elarion codebases predate the current generator model: they vendor an older copy of Elarion and hand-write the per-module `services.AddXHandlers()` / `AddXServices()` registrations that `[GenerateModuleBootstrapper]` and the generated `ConfigureDefaultServices` now emit for you — copying that pattern onto current packages duplicates registrations the generator already emits (see [Modules](/docs/concepts/modules)). Use the [tutorial](/docs/tutorial) and its compiled billing sample under [`samples/Billing`](https://github.com/swimmesberger/Elarion/tree/main/samples/Billing) as the current reference instead. One gap to know about: the billing sample authenticates with JWT bearer tokens, so the ASP.NET [Identity](/docs/capabilities/identity) path has no sample of its own yet. # Installation (/docs/getting-started/installation) Elarion is distributed as a set of focused NuGet packages plus npm packages for TypeScript client generation and frontend contributions. You only install the pieces you use. ## Prerequisites [#prerequisites] * **.NET 10 SDK** or later. Every runtime package ships `net10.0` and `net11.0` builds, so a .NET 10 application keeps a supported line while a .NET 11 application gets assets built against .NET 11 (in-box `Microsoft.Extensions` abstractions, .NET 11 package majors, and runtime async instead of compiler-generated state machines, so live stack traces show the real handler and decorator chain). The source generators target `netstandard2.0` so they load in the Roslyn analyzer host of either SDK. The Entity Framework Core packages depend on EF Core 10 for both frameworks until the Npgsql EF Core 11 provider is released. * An **ASP.NET Core** host project if you want the JSON-RPC HTTP transport (`Elarion.AspNetCore`). * **Node.js 20.11+** only if you use the npm packages (the TypeScript JSON-RPC client generator or frontend contributions). ## Packages [#packages] | Package | Install in | Purpose | | ------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.Abstractions` | Contract-only assemblies (comes transitively with `Elarion`) | Attributes and contracts: `[AppModule]`, `[Service]`, `[ScheduledJob]`, `IHandler<,>`, `Result`, `AppError`. | | `Elarion` | Application / host | Runtime primitives: decorators, the in-memory scheduler, current-user abstraction, and the default authorizer. Depends only on `Microsoft.Extensions.*` abstractions (ADR-0017). **Bundles the Elarion source generator** (handlers, services, modules, RPC/HTTP/MCP maps, validation resolvers, resilience policies, scheduled jobs, event consumers). | | `Elarion.Caching` | Application / host | `HybridCache`-backed default `IHandlerCache` for handler result caching — `services.AddElarionHandlerCaching()`. **Required by `[Cacheable]`/`[CacheInvalidate]`** (extracted from core, ADR-0017). | | `Elarion.Resilience` | Application / host | Microsoft/Polly-backed default `IResiliencePipelineRunner` — `services.AddElarionResilience()`. **Required by `[Resilient]` handlers and deferred scheduler retries** (extracted from core, ADR-0017). | | `Elarion.Validation` | Application (+ `services.AddElarionValidation()` in the host) | `Microsoft.Extensions.Validation`-backed default `IRequestValidator` — **required to enforce the DataAnnotations validation attributes on request DTOs** (otherwise they are schema-documented but unenforced, `ELVAL002`). See [Validation](/docs/concepts/validation). | | `Elarion.FeatureFlags.OpenFeature` | Application / host | The `IBackendFeatureFlagEvaluator` over OpenFeature for `[BackendFeatureFlag]`s — `services.AddElarionOpenFeature()`. Bring your own OpenFeature provider. | | `Elarion.FeatureFlags.FeatureManagement` | Application / host | Batteries-included config-driven flags via the Microsoft.FeatureManagement OpenFeature provider — `services.AddElarionFeatureManagement(configuration)`. | | `Elarion.Blobs` | Application | Provider-neutral blob storage contracts and DTOs. | | `Elarion.Blobs.PostgreSql` | Infrastructure / host | PostgreSQL-backed blob storage using EF Core model configuration and Npgsql content I/O. | | `Elarion.Typst` | Infrastructure / host | PDF rendering with Typst — `services.AddElarionTypst()`. Its build targets bundle the pinned, checksum-verified Typst binary into every executable that references it. See [PDF documents](/docs/capabilities/pdf-documents). | | `Elarion.JsonRpc` | Host | Transport-neutral JSON-RPC dispatcher, envelopes, telemetry, and schema export. | | `Elarion.Grpc` | Custom gRPC host | Host-neutral unary and request-driven server-streaming invocation, configurable principal capture, and stable startup `AppError` → `RpcException` translation. Bring your own host and generated protobuf contracts. | | `Elarion.Grpc.AspNetCore` | ASP.NET Core gRPC host | Recommended grpc-dotnet conventions: `AddGrpc().AddElarion()`, automatic `HttpContext.User`/`RequestServices` adoption, and delegate-free `ServerCallContext.InvokeElarionAsync(request)`/`InvokeElarionStreamAsync(request)` dispatch. | | `Elarion.AspNetCore` | Host | ASP.NET Core JSON-RPC endpoint mapping, batch execution, and current-user middleware. | | `Elarion.AspNetCore.SchemaGeneration` | Host (build tooling) | MSBuild target that exports `rpc-schema.json` during `dotnet build`. | | `Elarion.EntityFrameworkCore` | Application | Marker attributes for generated `DbSet`s and entity inclusion. **Bundles the EF Core source generator** (`DbSet` properties, entity configuration, keyset pagination). | | `@swimmesberger/elarion-jsonrpc-client-generator` | Frontend (npm) | Generates TypeScript method contracts, constraint-aware Zod params/result schemas, and a params-pre-validating fetch client from a schema export. | | `@swimmesberger/elarion-contributions` | Frontend (npm) | The frontend contribution model: typed extension points, declarative module manifests, and capability-gated resolution; optional bindings under `/react`, `/angular`, and `/tanstack-router`. See [Frontend modules](/docs/concepts/frontend-modules). | The source generators ship **inside** their runtime packages — the Elarion generator in `Elarion` and the EF Core generator in `Elarion.EntityFrameworkCore`. There are no separate analyzer packages to install. Because NuGet analyzer assets are not transitive, every assembly that needs a generator must reference its package **directly**: `Elarion` for handlers/modules/transports, and `Elarion.EntityFrameworkCore` for any assembly that declares `[EntityConfiguration]`/`[GenerateDbSets]` types or holds the concrete `DbContext` (a pure domain/entity project declares neither — entities are plain classes — so it needs no reference). **Caching and resilience are now opt-in packages (ADR-0017, breaking).** The `HybridCache`-backed handler cache moved to `Elarion.Caching` and the Polly-backed resilience runner to `Elarion.Resilience` — neither ships in `Elarion` core anymore. If you use `[Cacheable]`/`[CacheInvalidate]`, add `Elarion.Caching` and call `services.AddElarionHandlerCaching()`. If you use `[Resilient]` handlers **or deferred scheduler retries**, add `Elarion.Resilience` and call `services.AddElarionResilience()` — `AddElarionScheduler` no longer auto-wires the resilience runner, so a copy-paste upgrade that drops these references silently loses caching and resilience. ## Application project [#application-project] An application (class library) holds your modules, handlers, and services. Add the runtime package — the source generator ships inside it: ```xml ``` Then enable the framework generators once, anywhere in the assembly (commonly in a `Usings.cs` or `AssemblyInfo.cs`): ```csharp using Elarion.Abstractions; [assembly: UseElarion] ``` `[assembly: UseElarion]` turns on the framework-owned application generators, including handlers, services, jobs, event consumers, actor facades, policy registration, and typed catalogs. If you want only a subset, use the narrower triggers instead — see [Source generation](/docs/concepts/source-generation). ## Host project [#host-project] The ASP.NET Core host references your application and the JSON-RPC packages. It also needs the Elarion generator (for the RPC map and module bootstrapper it emits in the host assembly), which lives in the `Elarion` package — and since analyzer assets are not transitive, the host references `Elarion` **directly** (it already depends on it transitively via `Elarion.AspNetCore`): ```xml ``` The [Quickstart](/docs/getting-started/quickstart) wires these together into a working JSON-RPC endpoint. ## Optional: build-time schema export [#optional-build-time-schema-export] To export `rpc-schema.json` automatically during `dotnet build`, add the schema generation package as private build tooling in the host: ```xml true ``` See [JSON-RPC schema generation](/docs/capabilities/transports/schema-generation) for the full set of properties. ## Optional: TypeScript client generator [#optional-typescript-client-generator] Install the generator in your frontend app and run it against an exported schema: ```bash npm install --save-dev @swimmesberger/elarion-jsonrpc-client-generator npx elarion-jsonrpc-client-generator --schema rpc-schema.json --out src/generated ``` The generated client imports `zod`, so install it as a runtime dependency. See [TypeScript client](/docs/capabilities/transports/typescript-client) for usage. ## Building from source [#building-from-source] To build the framework itself rather than consume the published packages: ```bash git clone https://github.com/swimmesberger/Elarion.git cd Elarion dotnet restore Elarion.slnx dotnet build Elarion.slnx --configuration Release dotnet test --project tests/Elarion.Tests/Elarion.Tests.csproj --configuration Release ``` When building from source, reference the generator projects with `OutputItemType="Analyzer" ReferenceOutputAssembly="false"` instead of a `PackageReference`. # Project structure (/docs/getting-started/project-structure) Elarion discovers application code by **namespace containment** and **type conventions**. Getting the layout right is what lets the generators emit registration code without a central list. ## A typical solution [#a-typical-solution] ```text MyApp.sln ├─ src/ │ ├─ MyApp.Domain/ # entities (plain classes) + value objects + enums — no marker, no Elarion ref │ ├─ MyApp.Application/ # modules (behavior); Persistence (config + DbContext + migrations); [GenerateDbSets] ← Elarion, Elarion.EntityFrameworkCore │ ├─ MyApp.Infrastructure/ # intent-only mechanism adapters: mail, blob storage, external services │ └─ MyApp.Api/ # ASP.NET Core host (UseNpgsql + connection) ← Elarion, Elarion.JsonRpc, Elarion.AspNetCore └─ tests/ ``` The boundary that matters: **the application project declares intent; the host wires platform capabilities.** See [Dependency rules](#dependency-rules) below for where each kind of code belongs. The whole layout can also collapse into a **single project** — the bootstrapper discovers handlers in the host compilation too, so `Program`, the modules, and the trigger can share one csproj (`samples/LiveQuotes` is that shape); the split above is simply the layout that grows well. `MyApp.Domain` above is shown as a separate project, but for a **single bounded context** a shared-kernel *namespace* inside `MyApp.Application` (e.g. `MyApp.Application.Domain`) is usually enough — a separate assembly only earns its keep when multiple host projects share the code. Either way, entities belong to the **shared kernel, not inside a module**. [Solution structure](/docs/concepts/solution-structure) explains why and when to graduate to a separate assembly. The source generators ship **inside** their runtime packages, and NuGet analyzer assets are not transitive — so every assembly that declares generator-driven types must reference the package directly. For EF Core that is the **application** project: it holds the persistence layer (the `[EntityConfiguration]` configurations, the `[GenerateDbSets]` concrete `DbContext`, and migrations — the database is application logic, not an infrastructure detail), so its generator emits the `DbSet`s and `ConfigureEntities` in place. Reference **`Elarion.EntityFrameworkCore`** there. Entities themselves stay plain classes with no marker, so a pure domain/entity project needs no reference. (If you split the entities/configurations into a *separate* assembly from the `DbContext`, each needs the reference, and the context reads the configurations from the other assembly's emitted manifest.) Without the reference, the context resolves zero configurations and generates no `DbSet`s. ## Module layout [#module-layout] A module is a namespace plus an `[AppModule]` marker. Everything under that namespace belongs to the module. A common per-module layout: ```text MyApp.Application/Modules/Clients/ ├─ ClientsModule.cs # [AppModule("Clients")] + ConfigureServices / JSON resolver ├─ ClientsJsonContext.cs # [JsonSerializable(...)] per request/response type ├─ Handlers/ │ ├─ GetClient.cs # [Handler] IHandler> │ └─ CreateClient.cs # handler; its Command carries the DataAnnotations constraints └─ Services/ └─ ClientNumberGenerator.cs # [Service] implementation ``` For each `[AppModule]`, the generators emit a `{Module}ElarionModuleServices.ConfigureDefaultServices(IServiceCollection)` method that auto-wires the module's handlers, services, validation metadata, scheduled jobs, and event consumers. The host bootstrapper calls it for every enabled module — you do not hand-write any `Add{Module}…()` calls. The optional `ConfigureServices` method on the module is reserved for non-generated registrations. See [Modules](/docs/concepts/modules) for the full model. ## Conventions the generators rely on [#conventions-the-generators-rely-on] Because Elarion prefers convention over configuration, a handful of naming and placement rules are load-bearing: | Convention | Why it matters | | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | Types live **under a module namespace** | Namespace containment decides which module owns a type and whose generated `ConfigureDefaultServices` registers it. | | Handlers implement `IHandler` | The handler generator matches on this interface, and reads the request/response shape from it — the types may be nested in the handler or top-level. | | Services are annotated with `[Service]` | Marks the type for registration and contract resolution. | | Request DTOs carry `DataAnnotations` attributes | The generators attach the validation decorator and emit the module's validation metadata from them — see [Validation](/docs/concepts/validation). | | Hosted services use singleton scope | The generator rejects scoped/transient `IHostedService` with a diagnostic. | If a type is in the wrong namespace or breaks a convention, the result is a **build-time diagnostic or a missing generated method** — not a silent runtime failure. See [Conventions](/docs/reference/conventions) for the full convention tables and diagnostic ids, and [Troubleshooting](/docs/reference/troubleshooting) for the common cases. ## Core vs. feature modules [#core-vs-feature-modules] * **Feature modules** are enabled by default and can be switched off with `Modules:{Name}:Enabled=false` in configuration. * **Core modules** declare `Kind = AppModuleKind.Core`, are always enabled, ignore the `Enabled` flag, and initialize before feature modules. ```csharp [AppModule("Core", Kind = AppModuleKind.Core)] public static partial class CoreModule { /* ... */ } ``` Do not add `DependsOn = "Core"` just to see core services — core availability is implicit. Use `DependsOn` only for explicit ordering between feature modules. See [Modules](/docs/concepts/modules) for the full lifecycle. ## Dependency rules [#dependency-rules] Use this table when deciding where code belongs: | Code | Location | | ------------------------------------------------------------------ | --------------------------------------------------------------- | | Generic handler / result / module / pipeline / RPC primitives | `Elarion` (the framework) | | Feature module composition and business handlers | Application project | | Concrete database / blob / mail / external service implementations | Infrastructure, registered by the host as a platform capability | | Middleware, authentication, telemetry exporters, app lifetime | API host | | Application-specific domain types | Domain / application projects | Application modules may depend on abstractions — DI, configuration, `IEndpointRouteBuilder`, and `System.Text.Json` metadata. They should **not** depend on the API host, `WebApplicationBuilder`, concrete infrastructure classes, or deployment-specific packages. ## Creating a new module [#creating-a-new-module] 1. Create a module namespace, e.g. `MyApp.Application.Modules.Billing`. 2. Add `[AppModule("Billing")]` to a static partial `BillingModule` class. 3. Add a source-generated `BillingJsonContext`. 4. Add services under the namespace and annotate them with `[Service]`. 5. Add handlers implementing `IHandler>`, with DataAnnotations constraints on their request DTOs where the input has a shape to enforce. 6. Mark handlers for a transport, e.g. `[Handler("billing.someAction")]` or `[HttpEndpoint("billing")]`. 7. Build. The generators emit the module's `ConfigureDefaultServices`, which the host bootstrapper calls automatically — there is no registration list to maintain. # Quickstart (/docs/getting-started/quickstart) This walkthrough builds a minimal but complete Elarion application: one module, one handler exposed over JSON-RPC, and a host that wires it together. By the end you can call the handler with a JSON-RPC request over HTTP. It assumes you have followed [Installation](/docs/getting-started/installation) and have two projects: an application library (`MyApp.Application`) and an ASP.NET Core host (`MyApp.Api`). The data-model step uses two packages beyond the base installation: the application project needs the EF Core integration/generator, and the host needs the demo-only in-memory provider. ```bash dotnet add MyApp.Application package Elarion.EntityFrameworkCore --version 0.5.0 dotnet add MyApp.Api package Microsoft.EntityFrameworkCore.InMemory --version 10.0.12 ``` ### Turn on the generators [#turn-on-the-generators] In the application project, opt in once. This enables the framework-owned application generators across the assembly; the narrower trigger list is in [Source generation](/docs/concepts/source-generation). ```csharp title="MyApp.Application/ElarionAssembly.cs" using Elarion.Abstractions; [assembly: UseElarion] ``` ### Define a module [#define-a-module] A module is a static partial class marked with `[AppModule]`, placed at the root of a namespace that will contain your handlers and services. Modules are enabled by default. ```csharp title="MyApp.Application/Modules/Clients/ClientsModule.cs" using System.Text.Json.Serialization.Metadata; using Elarion.Abstractions.Modules; namespace MyApp.Application.Modules.Clients; [AppModule("Clients")] public static partial class ClientsModule { public static IJsonTypeInfoResolver GetJsonTypeInfoResolver() => ClientsJsonContext.Default; } ``` That is the whole module declaration. You don't register its handlers or services by hand — under `[GenerateModuleBootstrapper]` (added below) the generators emit a `ConfigureDefaultServices` that the host bootstrapper calls for you, gated by `Modules:Clients:Enabled`. The optional `ConfigureServices` hook is reserved for additional, non-generated wiring (options binding, third-party libraries): ```csharp [AppModule("Clients")] public static partial class ClientsModule { public static IJsonTypeInfoResolver GetJsonTypeInfoResolver() => ClientsJsonContext.Default; // Optional hook — only for wiring the generators can't emit (options, third-party services): public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) { services.Configure(configuration.GetSection("Clients")); } } ``` See [Conventions](/docs/reference/conventions). ### Define the data model [#define-the-data-model] Handlers access data through the concrete `AppDbContext` directly — there is no repository layer and no context interface. Write an `IEntityTypeConfiguration` for the entity and mark it with `[EntityConfiguration]`, annotate the concrete partial `AppDbContext` with `[GenerateDbSets]`, and let the [EF Core generator](/docs/capabilities/entity-framework) emit the `DbSet`s. The entity itself is a plain class — `[EntityConfiguration]` on its configuration is the single source of truth that drives both the generated `DbSet` and the `Configure(...)` application. ```csharp title="MyApp.Application/Data/Client.cs" namespace MyApp.Application.Data; public sealed class Client { public Guid Id { get; set; } public required string Name { get; set; } } ``` ```csharp title="MyApp.Application/Data/ClientConfiguration.cs" using Elarion.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace MyApp.Application.Data; [EntityConfiguration] public sealed class ClientConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { builder.HasKey(c => c.Id); } } ``` ```csharp title="MyApp.Application/Data/AppDbContext.cs" using Microsoft.EntityFrameworkCore; using Elarion.EntityFrameworkCore; namespace MyApp.Application; [GenerateDbSets] public sealed partial class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); ConfigureEntities(modelBuilder); // generated } } ``` This step needs `Elarion.EntityFrameworkCore` (which bundles the EF Core source generator) in any assembly that declares `[EntityConfiguration]`/`[GenerateDbSets]` types, and an EF Core provider — the quickstart uses `Microsoft.EntityFrameworkCore.InMemory`. In a real application the concrete `AppDbContext` lives in the application's persistence layer (the database is application logic, not an infrastructure detail); the quickstart keeps everything in one project for brevity. ### Write a handler [#write-a-handler] Handlers are the unit of work. This one is exposed over JSON-RPC with `[Handler]`, injects `AppDbContext`, and returns a `Result`. ```csharp title="MyApp.Application/Modules/Clients/Handlers/GetClient.cs" using Elarion.Abstractions; using Microsoft.EntityFrameworkCore; using MyApp.Application; namespace MyApp.Application.Modules.Clients.Handlers; [Handler("clients.get")] public sealed class GetClient(AppDbContext db) : IHandler> { public sealed record Query(Guid Id); public sealed record Response(Guid Id, string Name); public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var client = await db.Clients .Where(c => c.Id == query.Id) .Select(c => new Response(c.Id, c.Name)) .FirstOrDefaultAsync(ct); return client is null ? AppError.NotFound($"Client {query.Id} was not found.") : client; } } ``` The handler generator reads the request and response straight from the `IHandler>` interface — here the nested `Query` and `Response` types, though they could equally be top-level; nesting carries no semantic weight. The handler queries the generated `db.Clients` `DbSet` directly with EF Core async LINQ. ### Add a JSON context [#add-a-json-context] Each module contributes source-generated JSON metadata for its request/response types. This keeps serialization AOT-friendly and scoped to the module. ```csharp title="MyApp.Application/Modules/Clients/ClientsJsonContext.cs" using System.Text.Json.Serialization; using MyApp.Application.Modules.Clients.Handlers; namespace MyApp.Application.Modules.Clients; [JsonSerializable(typeof(GetClient.Query))] [JsonSerializable(typeof(GetClient.Response))] public sealed partial class ClientsJsonContext : JsonSerializerContext; ``` ### Add the host bootstrapper [#add-the-host-bootstrapper] In the host, one small partial class tells the generator to emit the cross-module wiring — including the gated handler registration, so disabling a module also removes its `[Handler]` operations. ```csharp title="MyApp.Api/ElarionAssembly.cs" using Elarion.AspNetCore; [assembly: GenerateModuleBootstrapper] ``` ### Wire the host [#wire-the-host] The host composes modules, configures serialization, and publishes the JSON-RPC endpoint. The host owns infrastructure (here, the database provider); modules own application logic. The concrete `AppDbContext` is registered once and injected into handlers directly. ```csharp title="MyApp.Api/Program.cs" using Elarion.AspNetCore; using Microsoft.EntityFrameworkCore; using MyApp.Api; // the generated ElarionBootstrapper lives in the host's root namespace using MyApp.Application; using MyApp.Application.Data; var builder = WebApplication.CreateSlimBuilder(args); builder.Services.AddDbContext(o => o.UseInMemoryDatabase("quickstart")); // Registers modules and contributes every enabled module's source-generated JSON context to the // canonical serializer every subsystem reads — no hand-built JsonSerializerOptions needed. builder.Services.AddElarion(builder.Configuration); // Gated dispatcher: only enabled modules' [Handler] operations are registered. builder.Services.AddElarionJsonRpc(ElarionBootstrapper.RegisterHandlers); var app = builder.Build(); // Seed one client so the call below returns data. using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.Clients.Add(new Client { Id = Guid.Parse("00000000-0000-0000-0000-000000000001"), Name = "Acme Inc.", }); db.SaveChanges(); } app.MapElarionEndpoints(app.Configuration); app.MapElarionJsonRpc(); app.Run(); ``` `UseInMemoryDatabase` is a **demo shortcut** so this quickstart runs without Docker — it is not a real database, and its behavior diverges from one. A real application uses PostgreSQL (`UseNpgsql`). Do **not** test database behavior on it either: a green InMemory test is false confidence (it skips constraints, real transactions, and provider SQL). [Test against a real database](/docs/concepts/persistence-and-transactions#testing-persistence) with Testcontainers instead. ### Build and call it [#build-and-call-it] ```bash dotnet run --project MyApp.Api ``` Then send a JSON-RPC request: ```bash curl -s http://localhost:5000/rpc \ -H 'content-type: application/json' \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "clients.get", "params": { "id": "00000000-0000-0000-0000-000000000001" } }' ``` A registered client returns a result envelope; a missing one returns the JSON-RPC error your host mapped from `AppError.NotFound`. ## What you just built [#what-you-just-built] * A **module** that publishes its own handlers and services with no host-side registration list. * A **handler** that is simultaneously a use case, a DI registration, and a JSON-RPC method. * A host that **composes** modules and **maps** the transport — and owns nothing about `clients` except the database provider. ## Where to go next [#where-to-go-next] The conventions generators rely on, and how to lay out a real application. Handlers, results, modules, services, validation, and pipelines in depth. Export a schema and generate a typed frontend client for `clients.get`. Add recurring and one-off background work to your module. # Introduction (/docs) Elarion is a .NET application framework for **module-based handler pipelines and deterministic, compile-time wiring**. Its focused packages add HTTP, JSON-RPC and MCP transports; background work; events and realtime delivery; PostgreSQL-backed coordination and persistence; device connections; and optional EF Core or NativeAOT-friendly SQL data access. The central idea is simple: your application assemblies define modules and handlers; your host assembly only wires infrastructure, transport, and deployment concerns. Everything that can be discovered from your code — handler pipelines, module registrations, transport maps, serializers, jobs, event consumers, policy catalogs, actor facades, and data-access metadata — is emitted by source generators at compile time instead of scanned by reflection at startup. ```csharp [Handler("clients.get")] public sealed class GetClient(AppDbContext db) : IHandler> { public sealed record Query(Guid Id); public sealed record Response(Guid Id, string Name); public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var client = await db.Clients .Where(c => c.Id == query.Id) .Select(c => new Response(c.Id, c.Name)) .FirstOrDefaultAsync(ct); return client is null ? AppError.NotFound($"Client {query.Id} was not found.") : client; } } ``` That single class is a use case, a registered service, a JSON-RPC method, an MCP tool for AI agents, and (optionally) a schema-exported TypeScript contract — with no entry added to any `Program.cs` registration list. ## Why Elarion [#why-elarion] Handlers, services, modules, RPC maps, validation metadata, and scheduled jobs are generated as ordinary DI code. Startup is deterministic and AOT-friendly; missing wiring is a build error, not a runtime surprise. A module is a namespace plus an `[AppModule]` marker. Add a handler under it and the module publishes it automatically through its generated `ConfigureDefaultServices`. Handlers return `Result` with a transport-agnostic `AppError`. The host maps failures to JSON-RPC, HTTP, or any other protocol. Mark a handler with `[Handler]`, export a schema at build time, and generate a typed TypeScript + Zod client — without hand-writing DTOs. Expose the same `[Handler]` handlers to AI agents as an MCP server. Tool names, descriptions, and input schemas are generated from your handlers and `[Description]` attributes at compile time — no separate tool layer, no duplicated schemas. Source-generated scheduled jobs share one scheduler with explicit overlap, misfire, and resilience policies — and full OpenTelemetry instrumentation. Gate any handler behind a flag with `[FeatureGate]` — runtime rollouts, kill switches, and per-variant service injection over OpenFeature. Transport-neutral and provider-agnostic, a closed gate returns 404 so the feature name never leaks. Gate any handler with `[RequirePermission]`/`[RequireRole]`/`[RequireClaim]`/`[RequirePolicy]` — the generator auto-attaches the decorator, so the same rules apply under JSON-RPC, MCP, and HTTP. Opt-in deny-by-default, and no ASP.NET coupling. Point-check a resource with `[RequireResource]`, or filter whole result sets at the database with `[ResourceFilter]` + `WhereAuthorized(authorizer, user)` — owner/tenant/role sharing compiled into EF Core predicates, no in-memory post-filter. Depend on provider-neutral blob contracts in application code and choose PostgreSQL- or Azure-backed storage in the host. JSON-RPC, scheduling, caching, and resilience emit OpenTelemetry-compatible traces and metrics through `System.Diagnostics` — no SDK dependency forced on you. ## Choose the right runtime shape [#choose-the-right-runtime-shape] The framework now covers several kinds of work, but they are not interchangeable. Start with the simplest shape whose correctness contract fits: Use a handler for bounded request/reply work. It is the transport-facing gate for authorization, validation, transactions, idempotency, resilience, caching, and audit policy. Use a cold stream when one request returns lazy output such as an export, token output, or tail query. Publish a client event when a lost message merely leaves the UI stale and re-querying converges. Use an ordered stream when a missing item makes the consumer wrong and one live producer owns the key, sequence, replay window, and resume behavior. Use a connection for interactive-rate client input, device links, or server-to-client request/reply. Default to the database. Reach for an actor only when a live resource, ephemeral hot state, or a decide-once coordinator is genuinely the consistency unit. Use a PostgreSQL role lease for a handful of coarse leader roles—not as a per-record distributed lock. Choose EF Core for the full application data platform, or generated SQL mapping and migrations for EF-free NativeAOT hosts. Batch loss-tolerant writes and conflate latest-wins values before adding a reactive or streaming stack. ## The philosophy in one line [#the-philosophy-in-one-line] > Auto-detect application patterns, explicitly wire platform capabilities. Repeating what your code already states — "I handle this request", "this is what a valid command looks like", "this is a module service" — in a separate registration list creates a parallel model that drifts. Elarion declares intent *next to the type* and generates the wiring. The host stays a thin composition and transport shell that owns authentication, middleware, database providers, telemetry exporters, and deployment. This is the same broad approach used by mature annotation-driven frameworks such as Spring Boot — components live below a namespace boundary, attributes declare their role, sensible defaults cover the common path — implemented with .NET source generation instead of runtime classpath scanning. For the full reasoning behind each design decision — compile-time generation, handlers as the use-case boundary, result-based errors, JSON-RPC for internal APIs, and a thin host — see [Design & philosophy](/docs/why-elarion). ## When Elarion is a good fit [#when-elarion-is-a-good-fit] * You are building a modular application or service and want feature modules to be self-contained. * You value deterministic startup, AOT compatibility, and inspectable generated code over runtime reflection. * You want a typed RPC contract shared between a .NET backend and a TypeScript frontend. * You want to expose your application to AI agents as MCP tools without hand-writing a separate tool layer. * You want in-process recurring/background work without standing up external job infrastructure. * You need realtime, device, or coordination building blocks sized for roughly 1–10 nodes on the PostgreSQL your application already runs. It is intentionally **not** a thin wrapper around default ASP.NET Core. You trade some convention freedom for less host boilerplate, inherent modularity, and a clear line between application policy and host mechanics. See [How Elarion differs from ASP.NET Core](/docs/why-elarion#how-elarion-differs-from-aspnet-core) for the full trade-off table. ## Next steps [#next-steps] Add the packages and generators to an application and host project. Build your first module, handler, and JSON-RPC endpoint end to end. Handlers, results, modules, services, validation, pipelines, and caching. What each Elarion package contains and when you need it. Elarion is pre-1.0. The public surface described here is stable enough to build on, but minor releases may introduce breaking changes until 1.0. See the [changelog](https://github.com/swimmesberger/Elarion/blob/main/CHANGELOG.md) for details. # Attributes (/docs/reference/attributes) A lookup-only catalog of every Elarion attribute, grouped by area. Each entry lists the package, what it applies to, a one-line "triggers", and a parameter table (type, default, meaning). For the behavior behind each attribute see the linked capability or concept page. Parameters are listed as constructor arguments and `init` properties. Defaults are the literal defaults baked into the attribute. Enum value tables follow the group they belong to. ## Modules & DI [#modules--di] ### `[AppModule]` [#appmodule] * **Package:** `Elarion.Abstractions` · **Applies to:** class * **Triggers:** groups handlers/services/jobs/consumers under a module boundary and emits the `{ModuleType}ElarionModuleServices.ConfigureDefaultServices` sibling plus host bootstrapping; feature modules are gated by `Modules:{Name}:Enabled`. | Parameter | Type | Default | Meaning | | ----------- | ---------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` (ctor) | required | Unique module name; used for the feature-flag key `Modules:{Name}:Enabled` and logging. | | `Kind` | `AppModuleKind` (init) | `Feature` | `Feature` (optional, can be disabled) or `Core` (always enabled, ignores feature flags). | | `DependsOn` | `string?` (init) | `null` | Comma-separated module names this module depends on; the generator orders modules so dependencies initialize first. Modules that depend on each other initialize together (`ELMOD009`), an unknown name is `ELMOD010`. See [Ordering with DependsOn](/docs/concepts/modules#ordering-with-dependson). | The class may optionally implement convention-based statics: `ConfigureServices(IServiceCollection, IConfiguration)`, `MapEndpoints(IEndpointRouteBuilder)`, `GetJsonTypeInfoResolver()`, and `ConfigureEndpointGroup(IEndpointRouteBuilder)`. **`AppModuleKind`:** `Feature` (= 0), `Core` (= 1). See [Modules](/docs/concepts/modules). ### `[Service]` [#service] * **Package:** `Elarion.Abstractions` · **Applies to:** class * **Triggers:** source-generated DI registration. Without explicit service types, directly implemented interfaces are used as contracts; with none, the implementation type registers as itself. Base-class interfaces are not treated as explicit contracts. | Parameter | Type | Default | Meaning | | -------------- | ----------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `serviceTypes` | `params Type[]` (ctor) → `IReadOnlyList ServiceTypes` | empty | Explicit contract types to register; when empty, contracts are inferred from directly implemented interfaces. | | `Scope` | `ServiceScope` (init) | `Scoped` | DI lifetime. | | `AsSelf` | `bool` (init) | `false` | Also register the implementation type itself; it becomes the one registration that creates the instance, and every contract forwards to it. Ignored on a variant. A constructor that injects a `[Service]` class not registered as itself is `ELSG020`. | **`ServiceScope`:** `Scoped`, `Singleton`, `Transient`. See [Services](/docs/concepts/services). ### `[GenerateContractSetRegistration]` [#generatecontractsetregistration] * **Package:** `Elarion.Abstractions` · **Applies to:** method (a `static partial` extension method the generator implements) * **Triggers:** runs the `ContractSetRegistrationGenerator` to compose **every implementation of one contract, unconditionally** — the module-less counterpart to `[Service]` for infrastructure seams (protocol packet bindings, codec catalogs, pipeline stages) that live in host assemblies with no `[AppModule]`. The host authors, names, and places the composition method; the generator fills in the body. Discovery is compilation-local: every non-abstract, non-generic class in the declaring assembly assignable to the contract is registered via `TryAddEnumerable` (calling the method twice never duplicates the set). The method is **pulled** by the host's composition root, exactly once, unconditionally; no bootstrapper invokes it and no configuration gates it, so a transport's routing table cannot be silently emptied by a module switch. The method shape is fixed (`ELSG019` otherwise): `static partial IServiceCollection Name(this IServiceCollection services)` on a non-generic static partial class, without a hand-written implementation. | Parameter | Type | Default | Meaning | | -------------- | ------------------------------ | ----------- | --------------------------------------------------------------------------------------- | | `contractType` | `Type` (ctor) → `ContractType` | — | The composed contract; must be an interface or abstract class (open generics rejected). | | `Scope` | `ServiceScope` (init) | `Singleton` | DI lifetime for every implementation — infrastructure seams are boot-composed. | ```csharp public static partial class PacketBindingRegistrations { [GenerateContractSetRegistration(typeof(IPacketBinding))] public static partial IServiceCollection AddPacketBindings(this IServiceCollection services); } // host composition root: services.AddPacketBindings(); ``` Diagnostics `ELSG014` (contract not an interface/abstract class) / `ELSG015` (empty set) / `ELSG016` (same contract declared twice) / `ELSG017` (generic implementation) / `ELSG018` (implementation also a `[Service]` under the same contract) / `ELSG019` (invalid method shape). See [Services — module services vs. contract sets](/docs/concepts/services#module-services-vs-contract-sets). ### `[DecoratorList]` [#decoratorlist] * **Package:** `Elarion.Abstractions` (Pipeline) · **Applies to:** class * **Triggers:** declares the decorator types for an application-owned pipeline profile attribute so the generator can read the list at compile time. (Pipeline profile attributes themselves, e.g. `DefaultPipelineAttribute`, are application-defined, not framework-shipped.) | Parameter | Type | Default | Meaning | | ------------ | ------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------ | | `decorators` | `params Type[]` (ctor) → `Decorators` | empty | Ordered decorator types (open generics), applied outermost-first: the first type is the outermost decorator. | See [Decorator pipelines](/docs/concepts/decorator-pipelines). ## Transports [#transports] ### `[Handler]` [#handler] * **Package:** `Elarion.Abstractions` · **Applies to:** class * **Triggers:** marks a handler as a named operation on the transport-neutral request/reply bus (the handler must implement `IHandler`). The operation name is declared once and shared by every dispatcher transport; `Transports` selects JSON-RPC, MCP, or both. JSON-RPC and MCP are thin adapters over the one bus, so a handler is "define once, choose surfaces via the `Transports` flag". REST is a separate opt-in via `[HttpEndpoint]`. The operation name is **optional**: `[Handler]` alone is valid. When omitted, the name is inferred by convention as `{module}.{operation}`, where `operation` is the handler type name minus a `Handler`/`Command`/`Query`/`Request` suffix, camelCased (e.g. module `Clients` + `CreateClient` → `clients.createClient`). Supply an explicit name for stable public/wire contracts. | Parameter | Type | Default | Meaning | | ------------ | ------------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string?` (ctor) → `Name` | optional | The operation name, e.g. `"clients.create"`. When omitted, inferred by convention as `{module}.{operation}`. | | `Transports` | `HandlerTransports` (init, `[Flags]`) | `All` (`JsonRpc \| Mcp \| Connection`) | Which dispatcher transports expose the handler. | | `Scope` | `ServiceScope` (init) | `Scoped` | The handler's registration lifetime — the same vocabulary and semantics as `[Service(Scope = …)]`. `Singleton` removes scope participation from dispatch (the low-allocation choice, ADR-0066) and is compile-time verified: every constructor dependency must be provably singleton (`ELSG011`/`ELSG012`) and the pipeline must not attach scope-dependent features (`ELSG013`). | **`HandlerTransports`:** `JsonRpc` (= 1), `Mcp` (= 2), `Connection` (= 4, bidirectional connection dispatch), `All` (= `JsonRpc \| Mcp \| Connection`). See [JSON-RPC](/docs/capabilities/transports/json-rpc) and [MCP](/docs/capabilities/transports/mcp). ### `[HandlerTelemetry]` [#handlertelemetry] * **Package:** `Elarion.Abstractions` · **Applies to:** class (handler or module), assembly * **Triggers:** declares how much always-on observability the generated pipeline gives handlers. Leveled, nearest declaration wins: handler class → module class → assembly → `Full`. With the effective mode `None`, the registration generator does not emit the observability decorator at all — no span, no execution metric, no context enrichment, no log scope, no decorator object on the hot path (ADR-0066). Failures are unaffected: they remain `Result` values and exceptions still propagate to the transport. The typical use is a hot module opting down once while one cold handler inside it re-enables by declaring `Full` on itself. | Parameter | Type | Default | Meaning | | --------- | -------------------------------------- | -------- | ----------------------------------------------------------------------- | | `mode` | `HandlerTelemetryMode` (ctor) → `Mode` | required | `Full` (= 0, the default when the attribute is absent) or `None` (= 1). | See [Telemetry](/docs/capabilities/telemetry) and [Connections — the low-allocation dispatch profile](/docs/capabilities/connections/low-allocation). ### `[ProducesError]` [#produceserror] * **Package:** `Elarion.Abstractions` · **Applies to:** class, assembly (repeatable) * **Triggers:** declares a failure the handler can produce — a stable error code, its `ErrorKind`, and an optional typed payload. The generator publishes the declarations (plus the validation, authorization, feature-gate and idempotency failures the framework adds) with the operation; the schema export lists them under the method's `errors`, and the TypeScript client types `error.code`/`error.data` per method. On a pipeline decorator it declares the failure for every operation the decorator wraps, on an `[AppModule]` class for every operation in the module, and on the assembly for every operation declared in it; the declaration closest to the handler wins. Constructors: `(ErrorKind)`, `(ErrorKind, Type)`, `(string code, ErrorKind)`, `(string code, ErrorKind, Type)`. See [Result & error model](/docs/reference/result-and-errors#produceserror--the-declared-error-contract). ### `[ClientTag]` [#clienttag] * **Package:** `Elarion.Abstractions` · **Applies to:** class (repeatable, inherited) * **Triggers:** a client hint for a `[Handler]` operation, exported under the method's `tags` in `rpc-schema.json` and in the generated client's `rpcMethodInfo` — e.g. `[ClientTag("timeout", "180s")]` for a slow operation, or a marker the UI honours. Never enforcement: the pipeline does not read it. One value per key; a derived handler's tag overrides its base's, and a key repeated on one class keeps its last declaration. See [TypeScript client › Method requirements](/docs/capabilities/transports/typescript-client#method-requirements-and-ui-gating). | Parameter | Type | Meaning | | --------- | -------- | -------------- | | `key` | `string` | The tag key. | | `value` | `string` | The tag value. | ### `[Reads]` / `[Writes]` [#reads--writes] * **Package:** `Elarion.Abstractions` · **Applies to:** class (single, not inherited) * **Triggers:** the resources a query reads (`[Reads]`) or a command writes (`[Writes]`), in addition to the operation name's prefix up to the last dot, which every operation has by default (ADR-0124). The schema export writes the resolved list under the method's `resources`; the generated client invalidates, after a command succeeded, every query that reads a resource it writes (`queriesInvalidatedBy`, `invalidationKeys`). `IncludeNameResource = false` replaces the name's resource. `[Reads]` on a command or `[Writes]` on a query is `ELRPC015` and ignored; a written resource no query reads is `ELRPC014`. See [TypeScript client › Invalidating queries after a command](/docs/capabilities/transports/typescript-client#invalidating-queries-after-a-command). | Parameter | Type | Default | Meaning | | --------------------- | ----------------- | ------- | -------------------------------------------------------- | | `resources` | `params string[]` | — | The resources read or written, plain lower-case strings. | | `IncludeNameResource` | `bool` (init) | `true` | Whether the name's prefix counts too. | ### `[RequestPreset]` [#requestpreset] * **Package:** `Elarion.Abstractions` · **Applies to:** field * **Triggers:** a named request preset: a `static readonly` field of a `[Handler]` class holding a value of its request type — a list's quick filter. The schema export writes it under the method's `presets` (the required members and every member that differs from the request's defaults, in the wire form) and the generated client exposes it as `rpcPresets['{method}'].{name}`, typed as the method's params. The server counts with the same field, so a chip opens exactly what it counted. The handler must be on JSON-RPC; anything else is `ELRPC006`–`ELRPC008`. See [TypeScript client › Limits, presets, sort keys and constants](/docs/capabilities/transports/typescript-client#limits-presets-sort-keys-and-constants). | Parameter | Type | Meaning | | --------- | -------- | -------------------------------------------------------------- | | `name` | `string` | The preset's name, as the client reads it. Unique per handler. | ```csharp [Handler] public sealed class ListInvoices(AppDbContext db) : IHandler>> { [RequestPreset("toTransfer")] public static readonly Query ToTransfer = new() { ToTransfer = true }; // … } ``` ### `[ClientConstants]` [#clientconstants] * **Package:** `Elarion.Abstractions` · **Applies to:** class * **Triggers:** exports the public `const` fields, `static readonly` fields and static get-only properties of a static class (not private) under a module's namespace — numbers, strings, booleans, enums, and arrays, `IReadOnlyList`, `IReadOnlyCollection` or `ImmutableArray` of them — as `constants.{module}.{name}` in the schema and `rpcConstants.{module}.{name}` (a literal type) in the generated client, module and member camel-cased. The module's generated services register them, so they exist exactly when the module is enabled; non-public members are not exported. An unexportable or mutable public member, a class its module cannot register, or a duplicate name is `ELRPC009`–`ELRPC011`. ```csharp [ClientConstants] public static class BillingLimits { public const decimal MaxTransferAmount = 999_999.99m; // rpcConstants.billing.maxTransferAmount public static readonly IReadOnlyList Currencies = ["EUR", "CHF"]; } ``` ### `[PresenceRequired]` [#presencerequired] * **Package:** `Elarion.Abstractions` · **Applies to:** class, struct, property, field, parameter * **Triggers:** a nullable request member that System.Text.Json requires (a constructor parameter without a default, a `required` or `[JsonRequired]` member) must be sent, as a value or an explicit `null`; on a type, for every such member. Leaving it out fails with invalid params instead of binding `null` (ADR-0129), which protects an update command from a caller that predates a new member. The schema lists it as required, admitting `null`, and the generated client types it `T | null`. A member with a default stays optional. See [Nullable members that must be sent](/docs/capabilities/transports/schema-generation#nullable-members-that-must-be-sent). No parameters. ### `[UploadLimits]` [#uploadlimits] * **Package:** `Elarion.Abstractions` · **Applies to:** property, parameter (positional record) * **Triggers:** declares the size, content-type and file-extension limits of an `UploadedFile` request member (or a collection of them). The pipeline declares them for the request's files before the handler runs, and `IUploadedFiles` checks them on every open and commit of those files, on top of any constraints the call passes; the handler's error contract gains `upload.not_found` and the code of each declared limit with the limit as typed data; the schema exports them as `x-elarion-max-bytes` / `x-elarion-content-types` / `x-elarion-file-extensions`, and the generated client rejects a file that breaks them before uploading it. Needs `AddElarionUploadedFiles`; a declaration the pipeline would not enforce is `ELUPL001`/`ELUPL002`. See [Declaring the limits on the member](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member). | Parameter | Type | Default | Meaning | | ---------------- | ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `MaxBytes` | `long` | `0` | The largest accepted size in bytes; `0` for no limit (`upload.too_large`, `UploadTooLargeData`). | | `ContentTypes` | `string[]?` | `null` | The accepted media types, compared case-insensitively with parameters ignored; empty for any (`upload.content_type`, `UploadContentTypeData`). | | `FileExtensions` | `string[]?` | `null` | The accepted file-name extensions with their leading dot (`".xlsx"`), compared case-insensitively against the end of the stored file name; empty for any (`upload.file_extension`, `UploadFileExtensionData`). For formats whose declared type varies between systems. | ### `[McpHandler]` [#mcphandler] * **Package:** `Elarion.Abstractions` · **Applies to:** class * **Triggers:** optional MCP tool-name customization for a handler already on the MCP surface (its `[Handler]` `Transports` includes `Mcp`). Purely additive — carries no enable/disable flag. Tool/parameter descriptions come from `System.ComponentModel.DescriptionAttribute`, not this attribute. | Parameter | Type | Default | Meaning | | ---------- | ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ToolName` | `string?` (init) | `null` | Overrides the MCP tool name; when null/empty the name is derived from the handler's operation name via the host's transform (e.g. `"clients.create"` → `"clients_create"`). | See [MCP](/docs/capabilities/transports/mcp). ### `[HttpEndpoint]` [#httpendpoint] * **Package:** `Elarion.Abstractions` · **Applies to:** class * **Triggers:** marks a handler as an HTTP/REST endpoint; `AppModuleDiscoveryGenerator` emits the matching `MapGet`/`MapPost`/… registration as an AOT-safe `RequestDelegate` with generator-owned binding (ADR-0071). The handler must implement `IHandler>`. With no explicit verb the verb is inferred from the request's CQRS marker (`ICommand` → POST, `IQuery` → GET); a request with neither marker requires an explicit verb (else `ELHTTP004`). Carries no ASP.NET Core dependency; a handler may carry both this and `[Handler]`. The attribute has two constructors: | Constructor | Parameters | Effect | | ---------------------------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------- | | `HttpEndpointAttribute(string route)` | `route` (required) | Maps at `route`, inferring the verb from the request's `ICommand`/`IQuery` marker. | | `HttpEndpointAttribute(HttpVerb verb, string route)` | `verb`, `route` (both required) | Maps at `route` with the explicit `verb`; sets `HasVerb = true`. | Read-only properties: | Property | Type | Default | Meaning | | --------- | ---------- | --------------------------- | ------------------------------------------------------------------------------------------ | | `Route` | `string` | required | The route pattern, e.g. `"clients/{id}"`. | | `Verb` | `HttpVerb` | `default(HttpVerb)` = `Get` | The explicit HTTP method, or the default when `HasVerb` is `false`. | | `HasVerb` | `bool` | `false` | Whether `Verb` was set explicitly; when `false` the verb is inferred from the CQRS marker. | **`HttpVerb`:** `Get`, `Post`, `Put`, `Patch`, `Delete`. A handler responding with `Result` (the in-memory small-file payload — content bytes + content type + file name, in `Elarion.Abstractions`) is mapped as a **file download** instead of JSON; the same handler may also carry `[Handler]`, where the payload rides the canonical base64 envelope over JSON-RPC/MCP (and the generated TypeScript client maps it to a native `File`). Large files use the staged-blob tier instead (ADR-0039). See [Files](/docs/capabilities/transports/http-endpoints#files-downloads-and-uploads) and [File payloads](/docs/capabilities/transports/json-rpc#file-payloads). See [HTTP endpoints](/docs/capabilities/transports/http-endpoints). ### `[GenerateModuleBootstrapper]` [#generatemodulebootstrapper] * **Package:** `Elarion.AspNetCore` · **Applies to:** assembly * **Triggers:** marks the host assembly to have the fixed-name `ElarionBootstrapper` static generated by `AppModuleDiscoveryGenerator` (in the host's root namespace; see [ADR-0018](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0018-generated-infrastructure-is-framework-named.md)) — the single transport-wiring path; emits per-module and aggregate `Map`/`Add` methods for HTTP, JSON-RPC, and MCP, all module-scoped and feature-flag gated. Marker only — no parameters. See [Hosting](/docs/capabilities/hosting). ### `[ModuleEndpoints]` [#moduleendpoints] * **Package:** `Elarion.AspNetCore` · **Applies to:** class (static) * **Triggers:** declares endpoint hooks for a module **from outside its assembly** (typically the host, on behalf of a web-free module assembly). The class declares the same convention hooks a module type may declare — `static MapEndpoints(IEndpointRouteBuilder)` and/or `static ConfigureEndpointGroup(IEndpointRouteBuilder)` — and `AppModuleDiscoveryGenerator` calls them inside the named module's feature gate in `MapElarionEndpoints`, composed with the module's own hooks (module first, contributors in stable type-name order, group hooks chained). Discovered in the host compilation and via referenced assemblies' Elarion manifests. An unknown module name warns `ELMOD004` (hooks skipped); a class with no recognized hook warns `ELMOD005`. | Parameter | Type | Default | Meaning | | ------------ | ------------------------------ | -------- | ----------------------------------------------- | | `moduleName` | `string` (ctor) → `ModuleName` | required | The `[AppModule]` name the hooks contribute to. | See [Modules](/docs/concepts/modules#declaring-the-hooks-outside-the-module-moduleendpoints) and [ADR-0040](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0040-host-declared-module-endpoints.md). ## Scheduling [#scheduling] ### `[ScheduledJob]` [#scheduledjob] * **Package:** `Elarion.Abstractions` · **Applies to:** method | class * **Triggers:** marks a method as a compile-time scheduled job or a class as a runtime-schedulable job type. Methods must declare exactly one of `FixedRate`, `FixedDelay`, or `Cron`; runtime-schedulable classes may declare at most one. String values accept `${Config:Key}` and `${Config:Key:-default}` placeholders re-resolved per occurrence. | Parameter | Type | Default | Meaning | | ------------------- | ---------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` (ctor) → `Name` | required | Stable unique job name used in logs, telemetry, and runtime scheduling. | | `FixedRate` | `string?` (init) | `null` | Grid-aligned interval between due times regardless of run duration. Accepts `TimeSpan` text or suffixes (`50ms`, `30s`, `15m`, `6h`, `1d`). | | `FixedDelay` | `string?` (init) | `null` | Delay between completion of one run and start of the next (polling-loop style). Same duration format; misfire policy does not apply. | | `Cron` | `string?` (init) | `null` | Cron expression with 5 (minute-level) or 6 (second-level) fields, evaluated in `TimeZone`. `"-"` disables the schedule. | | `TimeZone` | `string?` (init) | `null` (UTC) | Time-zone id used to evaluate `Cron`; passed to `TimeZoneInfo.FindSystemTimeZoneById` after placeholder resolution (prefer IANA ids). | | `InitialDelay` | `string?` (init) | `null` | Optional delay before the first execution (same format as `FixedRate`). Not valid with `Cron`. | | `RunOnStart` | `bool` (init) | `true` | Whether interval jobs run once immediately at host start. Not valid with `Cron`. | | `Group` | `string?` (init) | `null` | Optional key serializing jobs that must not run concurrently; jobs sharing a non-empty group share a serialization gate. | | `Overlap` | `ScheduledJobOverlap` (init) | `Skip` | How occurrences behave when another is already active. | | `MisfirePolicy` | `ScheduledJobMisfirePolicy` (init) | `FireOnce` | How fixed-rate/cron schedules handle missed in-process occurrences. | | `MaxConcurrentRuns` | `int` (init) | `0` | Max concurrently executing occurrences when `Overlap = AllowConcurrent`. `0` means no job-local cap (global scheduler limit still applies); negative is rejected by the generator. | | `Enabled` | `string?` (init) | `null` (always enabled) | `"true"`, `"false"`, or a placeholder, evaluated per occurrence. An unconfigured placeholder without inline default means enabled; an unparseable value means disabled. | | `Placement` | `JobPlacement` (init) | `Cluster` | Multi-node execution: `Cluster` = exactly one node per occurrence when a cross-instance coordinator is registered; `EveryNode` = every node runs every occurrence (for jobs maintaining process-local in-memory state). Identical on a single node. | **`ScheduledJobOverlap`:** `Skip`, `Queue`, `AllowConcurrent`. **`ScheduledJobMisfirePolicy`:** `FireOnce` (one overdue, skip intermediate), `Skip`, `CatchUp`. See [Scheduling](/docs/capabilities/scheduling), [Schedules](/docs/capabilities/scheduling/schedules), and [Overlap and misfire](/docs/capabilities/scheduling/overlap-and-misfire). ## Events [#events] ### `[ConsumeEvent]` [#consumeevent] * **Package:** `Elarion.Abstractions` · **Applies to:** method | class * **Triggers:** marks an event consumer, discovered by the event-consumer generator and registered as an `EventSubscriptionDescriptor`. * **Handler form (preferred):** on a class implementing `IHandler` (sugar over `IHandler>`) whose request type *is* the event; runs through the full decorator pipeline. Always a fan-out subscriber — the event bus is pub/sub-only. A non-`Unit` `Result` return is rejected (`ELEVT005`). * **Method form:** on a method of a `[Service]` class (no pipeline); plane taken from the message type marker (`IDomainEvent`/`IIntegrationEvent`). Always a fan-out subscriber, returning `void`/`Task`/`ValueTask` or the non-generic `Result`/`Task`/`ValueTask` (a failed `Result` → `EventConsumerFailedException`). A `Result` with a value is request/reply and is rejected. | Parameter | Type | Default | Meaning | | --------- | ------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `Order` | `int` (init) | `0` | Relative invocation order among fan-out subscribers of the same event, ascending. Equal orders run in a stable generator-determined sequence. | See [Consuming events](/docs/capabilities/events/consuming-events) and [Backends](/docs/capabilities/events/backends). ## Actors [#actors] ### `[Actor]` [#actor] * **Package:** `Elarion.Actors` · **Applies to:** class * **Triggers:** marks a plain class as an in-memory actor: its public async methods (`Task`/`Task`/`ValueTask`/`ValueTask`) become request/reply methods on a source-generated typed facade (`I{Name}`, class name minus the `Actor` suffix), while methods returning `IAsyncEnumerable` become facade streams with a generated trailing cancellation token. Calls attach through the activation's mailbox; stream enumeration continues off-mailbox. Keyed when the constructor takes an `IActorContext` (one activation per key, activated on first message, passivated when idle) or `KeyType` is set; otherwise a process singleton. Registered per module via the generated `Add{Module}Actors`; requires the assembly opt-in `[assembly: GenerateActors]` (or `[UseElarion]`). | Parameter | Type | Default | Meaning | | -------------------- | ----------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Name` | `string?` (init) | class name minus `Actor` | Logical actor name used in telemetry, logging, and the registration. | | `KeyType` | `Type?` (init) | `null` | Explicit key type for a keyed actor whose constructor does not take an `IActorContext`; must match the context parameter when both are present (`ELACT004`). | | `MailboxCapacity` | `int` (init) | `0` (unbounded) | Bounded mailbox capacity. | | `MailboxFullMode` | `ActorMailboxFullMode` (init) | `Wait` | Full-mailbox behaviour: `Wait` (async backpressure) or `Fail` (`ActorMailboxFullException`). No drop modes — facade calls are request/reply. | | `IdleTimeoutSeconds` | `double` (init) | `0` (5 min) | Inactivity window before passivation; `-1` disables passivation. | | `CallTimeoutSeconds` | `double` (init) | `0` (30 s) | End-to-end facade call timeout (queue wait + execution) failing with `TimeoutException` — the deadlock backstop for actor→actor call cycles; `-1` disables it. | | `Placement` | `ActorPlacementMode` (init) | `Local` | `SingleHome` runs only on the actor-home holder; `VirtualShards` assigns a keyed actor to a fixed virtual-shard role lease. Register the corresponding PostgreSQL placement recipe; calls elsewhere fail with `ActorNotHomedException` and are never forwarded. | **`ActorPlacementMode`:** `Local` (default), `SingleHome`, `VirtualShards`. **`ActorMailboxFullMode`:** `Wait` (default), `Fail`. ### `[Reentrant]` [#reentrant] * **Package:** `Elarion.Actors` · **Applies to:** class (alongside `[Actor]`) * **Triggers:** opts the actor into Orleans-style turn-based interleaving: while one message awaits, the mailbox may start another, but turns never run in parallel (an exclusive scheduler serializes every continuation). State observed across an `await` may have been changed by an interleaved message; `ConfigureAwait(false)` in the actor's own code escapes the scheduler and forfeits the guarantee (flagged by `ELACT006`; libraries the actor calls may use it internally without harm). ### `[ActorKey]` [#actorkey] * **Package:** `Elarion.Actors` · **Applies to:** method (alongside `[ConsumeEvent]` on a keyed actor) * **Triggers:** names the consumed event's property that supplies the actor key when the generator cannot infer it (the event has zero or more than one property assignable to the actor's key type). Constructor arg `propertyName` (use `nameof`); the property's type must be assignable to the key type, else `ELACT008`. Not needed when inference is unambiguous or the actor is a singleton. `[ConsumeEvent]` itself stays an actor-agnostic contract in `Elarion.Abstractions` — the key selector is an actor concern, so it lives here (ADR-0046). See [Actors](/docs/concepts/actors). ## Caching [#caching] ### `[Cacheable]` [#cacheable] * **Package:** `Elarion.Abstractions` · **Applies to:** class * **Triggers:** marks a handler as cacheable and supplies compile-time metadata to the handler-registration generator. Only successful `Result` responses are cached; failed results are returned but not stored. | Parameter | Type | Default | Meaning | | ----------------- | --------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `tags` | `params string[]` (ctor) → `Tags` | empty | Logical cache tags for grouping and invalidation. | | `DurationSeconds` | `int` (init) | `60` | Entry lifetime in seconds for both distributed and local cache layers. | | `Scope` | `HandlerCacheScope` (init) | `CurrentUser` | Whether generated keys/tags are scoped to the current user or shared globally. | | `KeyProperties` | `string[]` (init) | `[]` | Request property names included in the generated key; when empty, all public request properties are used. Invalid names are reported at build time. | **`HandlerCacheScope`:** `CurrentUser` (= 0), `Global` (= 1). Under tenant scoping both sit inside the tenant in scope ([tenant isolation](/docs/capabilities/caching#tenant-isolation)). ### `[CacheInvalidate]` [#cacheinvalidate] * **Package:** `Elarion.Abstractions` · **Applies to:** class * **Triggers:** marks a mutating handler as invalidating cached entries for the given tags. Invalidation runs only after the inner handler returns a successful `Result`; failed validation or business results do not evict cached reads. | Parameter | Type | Default | Meaning | | --------- | --------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tags` | `params string[]` (ctor) → `Tags` | empty | Logical cache tags to invalidate after a successful handler result. | | `Scope` | `HandlerCacheScope` (init) | `Global` | `Global` evicts the globally shared entries **and** every user's `CurrentUser`-scoped entries for the tags (safe over-invalidation — the mutating caller is usually not the user whose cached read must be evicted); `CurrentUser` clears only the invoking user's entries. | **Runtime:** the cache itself was extracted out of Elarion core ([ADR-0017](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0017-dependency-light-core.md)). `[Cacheable]`/`[CacheInvalidate]` now **require** the `Elarion.Caching` package — the host wires the `HybridCache`-backed `IHandlerCache` with `services.AddElarionHandlerCaching()`. Without it the attributes are inert. See [Caching](/docs/capabilities/caching). ## Resilience [#resilience] ### `[ResiliencePolicy]` [#resiliencepolicy] * **Package:** `Elarion.Abstractions` · **Applies to:** class * **Triggers:** marks a static partial type as a source-generated resilience policy (a named execution behavior applied to handlers and scheduled jobs). Retry options create additional attempts after a handled exception; `Timeout` limits each individual attempt (not a total deadline across retries). | Parameter | Type | Default | Meaning | | ------------------ | ------------------------------ | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` (ctor) → `Name` | required | Stable policy name used by `[Resilient]` and `ScheduledJobOptions.ResiliencePolicy`. | | `MaxRetryAttempts` | `int` (init) | `3` | Maximum retry attempts after the original attempt (`0` = no retries; `3` = up to four total). Supplying this or another retry property enables retry generation. | | `Delay` | `string` (init) | `"2s"` | Base delay before a retry, e.g. `200ms`, `2s`, `5m`, or `TimeSpan` text. May be changed by `Backoff`, capped by `MaxDelay`, randomized by `UseJitter`. | | `Backoff` | `ResilienceBackoffType` (init) | `Constant` | How retry delays grow between attempts. | | `MaxDelay` | `string?` (init) | `null` | Optional maximum retry delay after applying `Backoff`; used with linear/exponential backoff to cap waits. | | `UseJitter` | `bool` (init) | `false` | Whether retry delays include jitter so many failures do not retry at the same instant. | | `Timeout` | `string?` (init) | `null` | Optional per-attempt timeout, e.g. `30s` or `TimeSpan` text. Not a total deadline across retries; cancels the attempt token. | **`ResilienceBackoffType`:** `Constant`, `Linear`, `Exponential`. ### `[Resilient]` [#resilient] * **Package:** `Elarion.Abstractions` · **Applies to:** class | method * **Triggers:** applies a named resilience policy to a generated handler or scheduled-job invocation. On handlers and compile-time jobs the policy executes inline around the current invocation; runtime scheduled jobs can alternatively use `ScheduledJobOptions` for scheduler-deferred retry. | Parameter | Type | Default | Meaning | | ------------ | ------------------------------ | -------- | ---------------------------------------------------------------------------------------------------------- | | `policyName` | `string` (ctor) → `PolicyName` | required | Stable policy name registered by a `[ResiliencePolicy]` type or a manual resilience pipeline registration. | **Runtime:** the resilience runner was extracted out of Elarion core ([ADR-0017](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0017-dependency-light-core.md)). `[Resilient]` handlers and scheduler-deferred retries now **require** the `Elarion.Resilience` package — the host wires the Microsoft/Polly-backed `IResiliencePipelineRunner` with `services.AddElarionResilience()`. **Breaking:** `AddElarionScheduler` no longer auto-wires the runner, so deferred scheduler retries opt in through this package too. See [Resilience](/docs/capabilities/resilience). ## Feature flags [#feature-flags] ### `[FeatureFlag]` [#featureflag] * **Package:** `Elarion.Abstractions` (Features) · **Applies to:** class (not inherited) * **Triggers:** declares a **code-defined** flag and makes the class its owner. The class must be a concrete, non-generic `IFeatureFlagResolver` (`ELFLAG003` otherwise) under an `[AppModule]` namespace of its assembly (`ELFLAG004`). The generator registers it into the module's default services, so the flag exists exactly when the module is enabled, and publishes it in the manifest so duplicates across assemblies are rejected (`ELFLAG002`). | Parameter | Type | Default | Meaning | | ---------------- | ------------------------ | -------- | ---------------------------------------------------------------------------- | | `name` | `string` (ctor) → `Name` | required | The flag name; blank is `ELFLAG005`. | | `Description` | `string?` (init) | `null` | What the flag controls. | | `ExposeToClient` | `bool` (init) | `false` | Whether the session snapshot evaluates and returns the flag to the frontend. | ### `[BackendFeatureFlag]` [#backendfeatureflag] * **Package:** `Elarion.Abstractions` (Features) · **Applies to:** class (`AllowMultiple`, not inherited) * **Triggers:** declares a **backend-evaluated** flag owned by the host's `IBackendFeatureFlagEvaluator` (`Elarion.FeatureFlags.FeatureManagement`/`.OpenFeature`). Same parameters and declaration rules as `[FeatureFlag]`; place it on the module type or any class under the module's namespace. A host that declares backend flags without registering a backend fails at startup. ### `[assembly: GenerateFeatureFlags]` [#assembly-generatefeatureflags] * **Package:** `Elarion.Abstractions` · **Applies to:** assembly (included in `[assembly: UseElarion]`) * **Triggers:** emits the `ElarionFeatureFlags` registry: typed `FeatureFlagKey` members, a `Names` class of constants and `All` descriptors, aggregated across referenced assemblies. ### `[FeatureGate]` [#featuregate] * **Package:** `Elarion.Abstractions` (Features) · **Applies to:** class (`AllowMultiple`, inherited) * **Triggers:** gates a handler behind one or more feature flags. The handler-registration generator auto-attaches the `FeatureGateDecorator` **just inside the authorization gate** so the flag is evaluated *before* the handler runs (before caching and the rest of the pipeline). When the gate is not satisfied the call short-circuits to `AppError.NotFound` (404) — a disabled feature is indistinguishable from a missing one, so the feature name is **never leaked** (MS-MVC-style "hide the roadmap"). Transport-neutral: identical under JSON-RPC, MCP, and HTTP. Stacking multiple `[FeatureGate]` attributes ANDs them. Every name must be a declared flag (`ELFLAG001`); it is evaluated through `IFeatureFlagService` by the flag's single owner. The attribute has two constructors: | Constructor | Parameters | Effect | | -------------------------------------------------------------------------------- | ------------------------- | ---------------------------------------------------------------- | | `FeatureGateAttribute(params string[] features)` | `features` | Gates on `features` with `Requirement = FeatureRequirement.All`. | | `FeatureGateAttribute(FeatureRequirement requirement, params string[] features)` | `requirement`, `features` | Gates on `features` with the explicit `requirement`. | Read-only / settable properties: | Property | Type | Default | Meaning | | ------------- | ----------------------- | ------------------------ | --------------------------------------------------------------------------------------------------- | | `Features` | `IReadOnlyList` | required (≥ 1 non-blank) | The feature names this gate evaluates. A blank/empty set has no effect (`ELFEAT002`). | | `Requirement` | `FeatureRequirement` | `All` | `All` = every feature must be on (AND); `Any` = at least one must be on (OR). | | `Negate` | `bool` (init) | `false` | When `true`, the gate is satisfied when the feature(s) are **off** (an inverse / kill-switch gate). | **`FeatureRequirement`:** `All`, `Any`. The gated handler's response must be able to represent failure (`Result` / `Result`); otherwise the gate cannot short-circuit and `ELFEAT001` is reported. A `[FeatureGate]` with no non-blank feature name reports `ELFEAT002`. Module flags (`Modules:{Name}:Enabled`) are *compose-time* (the module disappears); feature gates are *runtime* (gradual rollouts, targeting, kill switches without a redeploy). See [Feature flags](/docs/capabilities/feature-flags). ### `[FeatureVariant]` [#featurevariant] * **Package:** `Elarion.Abstractions` (Features) · **Applies to:** class (single, not inherited) * **Triggers:** a **modifier on a `[Service]` registration** that binds multiple implementations of one contract; a named feature flag's allocated variant picks which implementation resolves per request. The implementation class **must also carry `[Service]`** (which declares the contract(s) and lifetime) — otherwise `ELVAR007`. The contract is not repeated here: it is whatever `[Service]` registers under, and each registered contract becomes variant-resolved. Consumers inject the plain contract transparently — a handler injecting it directly is registered behind an async-resolving proxy that awaits the right variant for the current user; outside a handler constructor, inject `IVariantServiceProvider`. Runtime seams: `IFeatureVariantService` + `IVariantServiceProvider`; the `VariantServiceRegistrationGenerator` emits the wiring ([ADR-0019](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0019-variant-service-injection.md)). | Parameter | Type | Default | Meaning | | ----------- | --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `feature` | `string` (ctor) → `Feature` | required | The single feature whose allocated variant selects the implementation. All variants of one contract must name the same feature (`ELVAR004`). | | `Variant` | `string?` (init) | `null` | The variant key this implementation serves. Omit it on exactly **one** implementation to mark it the default (used when no variant is allocated); a contract without a default warns `ELVAR003`, and a duplicate variant key reports `ELVAR001`. | | `IsDefault` | `bool` (init) | `false` | Marks this implementation as a **named default**: it serves its `Variant` name *and* every unallocated/unknown allocation. More than one default per contract reports `ELVAR001`. | Diagnostics: `ELVAR001` (duplicate variant key), `ELVAR003` (no default implementation — warning), `ELVAR004` (contract bound to more than one selector), `ELVAR005` (blank feature name — warning), `ELVAR006` (generic implementation unsupported), `ELVAR007` (missing `[Service]`), `ELVAR008` (contract also bound by `[ConfigurationVariant]` — one selection axis per contract). `ELVAR002` is intentionally unused. See [Feature flags](/docs/capabilities/feature-flags). ### `[ConfigurationVariant]` [#configurationvariant] * **Package:** `Elarion.Abstractions` (Features) · **Applies to:** class (single, not inherited) * **Triggers:** the **configuration-selected sibling of `[FeatureVariant]`** — a modifier on a `[Service]` registration that binds multiple implementations of one contract, with a plain `IConfiguration` value picking which implementation resolves. Selection is a **synchronous** configuration read, so there is no async-resolving proxy and no per-scope warm-up: any consumer (handler, service, any assembly) injects the contract directly, each new DI scope observes the current value, and an open scope keeps the implementation it started with. Any configuration provider drives the switch — `appsettings.json` (with `reloadOnChange`), environment variables, or the [settings bridge](/docs/concepts/settings) (`AddElarionSettingsConfiguration`) for admin-writable, cluster-propagated runtime switching with no flag provider. The implementation class **must also carry `[Service]`** (otherwise `ELVAR007`); the contract is whatever `[Service]` registers under. Runtime seam: `IVariantServiceProvider` (completes synchronously); the `VariantServiceRegistrationGenerator` emits the wiring ([ADR-0028](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0028-configuration-selected-service-variants.md)). | Parameter | Type | Default | Meaning | | ----------- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `key` | `string` (ctor) → `Key` | required | The configuration key whose value selects the implementation (e.g. `"Email:Backend"`). All variants of one contract must name the same key (`ELVAR004`), and a contract cannot mix `[ConfigurationVariant]` with `[FeatureVariant]` (`ELVAR008`). A blank key warns `ELVAR009`. | | `Value` | `string?` (init) | `null` | The configured value this implementation is selected for, matched **case-insensitively**. Omit it on exactly **one** implementation to mark it the default (used when the key is absent or its value matches no variant); a contract without a default warns `ELVAR003`, and a duplicate value — including case-only differences — reports `ELVAR001`. | | `IsDefault` | `bool` (init) | `false` | Marks this implementation as a **named default**: selectable by its `Value` *and* the fallback when the key is absent or unknown — so the default state stays writable by name (an admin switches back with `"smtp"` rather than by removing the key). Recommended for admin-facing switches; more than one default per contract reports `ELVAR001`. | Diagnostics: `ELVAR001` (duplicate value), `ELVAR003` (no default implementation — warning), `ELVAR004` (contract bound to more than one selector), `ELVAR006` (generic implementation unsupported), `ELVAR007` (missing `[Service]`), `ELVAR008` (contract also bound by `[FeatureVariant]`), `ELVAR009` (blank configuration key — warning). See [Feature flags](/docs/capabilities/feature-flags). ## Idempotency [#idempotency] ### `[Idempotent]` [#idempotent] * **Package:** `Elarion.Abstractions` (Idempotency) · **Applies to:** class (single, not inherited) * **Triggers:** marks a command handler as idempotent — a retried or duplicated request carrying the same idempotency key executes at most once and replays the first result. The handler-registration generator auto-attaches the `IdempotencyDecorator`, which owns the unit-of-work transaction: it writes the key row atomically with the handler's business writes, lets a database unique constraint reject a duplicate, and replays the stored result. Applies only to `ICommand` handlers whose response can represent failure (`Result`/`Result`). Declarative, transport-neutral, and provider-agnostic — the same shape as `[Cacheable]`/`[FeatureGate]`. | Parameter | Type | Default | Meaning | | ------------------ | ------------------------------------ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `RetentionHours` | `int` (init) | `24` | How long a completed key is retained and replayable, in hours: 1 to `MaxRetentionHours` (1 000 000), or `IdempotentAttribute.Permanent` (`-1`) for a key that is never purged. | | `KeyRequired` | `bool` (init) | `true` | Whether a request without an idempotency key is rejected with a 400. Set `false` to run without idempotency when no key is supplied. | | `Scope` | `IdempotencyScope` (init) | `CurrentUser` | Whether the key is scoped per authenticated user or shared globally. | | `Fingerprint` | `bool` (init) | `true` | Whether a request fingerprint is stored so reusing the key with a *different* request body is rejected (422). | | `ConflictBehavior` | `IdempotencyConflictBehavior` (init) | `Conflict` | Behavior for a concurrent in-flight duplicate (default 409). | | `StoreFailures` | `IdempotencyFailureStorage` (init) | `None` | Whether definitive failures are stored and replayed (default success-only). | | `Operation` | `string?` (init) | `null` | The key space shared with every handler that names the same operation (ADR-0126); `null` gives the handler its own. Handlers of one operation need the same success type, `Scope` and `Fingerprint` (`ELIDEM006`). See [Idempotency › One operation, two commands](/docs/concepts/idempotency#one-operation-two-commands). | **`IdempotencyScope`:** `CurrentUser` (= 0, isolated per authenticated user), `Global` (= 1, single shared namespace), `Consumer` (= 2, isolated per event consumer — the inbox; owner is the consuming handler's identity, key is the message id). **`IdempotencyConflictBehavior`:** `Conflict` (= 0, fail fast with 409 then replay — the IETF/Stripe standard), `WaitThenReplay` (= 1, block on the key's lock until the first request commits, then replay). **`IdempotencyFailureStorage`:** `None` (= 0, success-only — a failed result rolls back and stays retryable), `Definitive` (= 1, also store and replay definitive failures via a savepoint; transient failures stay retryable). The `[Idempotent]` attribute, seams, decorator, and in-memory default store live in `Elarion.Abstractions`/`Elarion`; the durable PostgreSQL key store ships in `Elarion.Idempotency.EntityFrameworkCore` (`AddElarionIdempotencyEntityFrameworkCore` + `[GenerateElarionIdempotencyKeys]`, below), atop the EF unit of work in `Elarion.EntityFrameworkCore.UnitOfWork`. See [Idempotency](/docs/concepts/idempotency). ### `[AllowDuplicates]` [#allowduplicates] * **Package:** `Elarion.Abstractions` (Messaging) · **Applies to:** class (single, not inherited) * **Triggers:** declares that **duplicate deliveries are harmless** to this handler-form integration-event consumer, opting it out of the default-on **inbox** (ADR-0022). The inbox attaches automatically to every handler whose request is an `IIntegrationEvent` — a `Consumer`-scoped `IdempotencyDecorator` claiming *(consumer, message id)* inside the consumer's own transaction, so a redelivered message is acknowledged instead of re-run (claims expire after 24 h, well above the outbox retry window). Declare `[AllowDuplicates]` when re-running is safe by construction — the effect is naturally idempotent (a conditional transition/upsert), or the only effect is a call to a downstream keyed on `IEventContext.MessageId` — and the plain transaction decorator returns. The consumer-side mirror of `[AllowAnonymous]`: a positive property declaration switching off a default guard. Inert on non-integration-event handlers (`ELINBX001`); domain-event consumers never have an inbox (exactly-once by atomicity); method-form consumers have no pipeline to attach to. See [Handling duplicates](/docs/capabilities/events/consuming-events#handling-duplicates). ## Transactions [#transactions] ### `[NoTransaction]` [#notransaction] * **Package:** `Elarion.Abstractions` (Pipeline) · **Applies to:** class (single, not inherited) * **Triggers:** keeps `TransactionDecorator` off a command handler, so the handler runs without a framework-owned unit of work and nothing holds a connection or a transaction for the whole call — for a command whose work is mostly outside the database (a test mail, a slow external call). The request stays an `ICommand`. Each `SaveChanges` commits on its own; the handler opens a transaction itself around writes that must commit together. No effect on `[Idempotent]` commands or inboxed integration-event consumers, which own their transaction. See [Persistence & transactions](/docs/concepts/persistence-and-transactions#commands-without-a-transaction). ### `[TransactionIsolation]` [#transactionisolation] * **Package:** `Elarion.Abstractions` (Pipeline) · **Applies to:** class (single, not inherited) * **Triggers:** makes `TransactionDecorator` open the handler's unit of work at the given `System.Data.IsolationLevel` instead of the provider's default (ADR-0123). The EF Core and SQL-tier units of work honor it; the in-memory one ignores it. A nested unit of work that asks for a level other than the ambient transaction's throws. No effect where `TransactionDecorator` does not attach (queries, `[NoTransaction]`, `[Idempotent]`). See [Persistence & transactions](/docs/concepts/persistence-and-transactions#isolation-level). ## Auditing [#auditing] ### `[Auditable]` [#auditable] * **Package:** `Elarion.Abstractions` (Auditing) · **Applies to:** class (single, not inherited) * **Triggers:** marks a handler for audit recording (ADR-0045) — every invocation produces one structured `AuditRecord` (actor, action, resource, outcome, correlation, field-level changes). The handler-registration generator auto-attaches two decorators: the outer observer (just outside authorization, recording denials/failures on a detached path that survives the rollback) and the inner success recorder (inside the transaction, so the success record commits atomically with the business writes). Attachment is soft — no registered `IAuditTrail`, no change to the pipeline. Declarative, transport-neutral, and provider-agnostic — the same shape as `[Idempotent]`/`[FeatureGate]`. | Parameter | Type | Default | Meaning | | ---------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Enabled` | `bool` (init) | `true` | Set `false` to opt a handler out under `[ElarionAuditDefaults]`. | | `Resource` | `string?` (init) | `null` | Fallback resource **type** only (the record's `ResourceType`) — used when the handler does not call `IAuditScope.SetResource`. It never sets the resource *id*; `SetResource(type, id)` supplies both and its type wins, so don't set `Resource` when the handler calls `SetResource`. Use the **same string as the handler's `[RequirePermission(resource, …)]`** (the plural, K8s-RBAC resource name — `clients`, `invoices`) so authorization and audit share one vocabulary. | See [Audit trail](/docs/concepts/auditing). ### `[ElarionAuditDefaults]` [#elarionauditdefaults] * **Package:** `Elarion.Abstractions` (Auditing) · **Applies to:** assembly or module class (single, not inherited) * **Triggers:** opts the scope into audit-by-default: every **command** handler is audited as if it carried `[Auditable]`, unless it opts out with `[Auditable(Enabled = false)]`. Queries and event consumers are never audited by defaults (read auditing is per-handler; a delivery scope has no caller). Mirrors `[ElarionAuthorizationDefaults]`. See [Audit trail](/docs/concepts/auditing). ### `[Audited]` [#audited] * **Package:** `Elarion.Abstractions` (Auditing) · **Applies to:** entity class (single, not inherited) * **Triggers:** opts an entity into automatic change capture: while an audited handler runs, the EF change-capture interceptor records field-level `{property, oldValue, newValue}` diffs for this entity on every flush, attached to the invocation's record. Opt-in on purpose (fail-closed PII stance; keeps framework tables out of capture). `ExecuteUpdate`/raw-SQL writes bypass the change tracker — the handler records those via `IAuditScope.AddChange`. See [Audit trail](/docs/concepts/auditing). ### `[AuditIgnore]` [#auditignore] * **Package:** `Elarion.Abstractions` (Auditing) · **Applies to:** property (single, not inherited) * **Triggers:** excludes a property of an `[Audited]` entity from automatic change capture — its values never appear in a record. For sensitive columns (password hashes, tokens, personal data) and noisy technical columns. See [Audit trail](/docs/concepts/auditing). ## Validation [#validation] Request validation is declared with the standard `System.ComponentModel.DataAnnotations` attributes on the handler's request DTO — `[Range]`, `[MinLength]`/`[MaxLength]`/`[Length]`/`[StringLength]`, `[RegularExpression]`, `[EmailAddress]`, `[Url]`, `[Base64String]`, `[AllowedValues]` — with requiredness from nullability (ADR-0082; no `[Required]` needed). Elarion adds only the two decimal rules DataAnnotations cannot express, `[DecimalRange]` and `[MaxDecimalPlaces]` (ADR-0128), both ordinary `ValidationAttribute`s. The handler-registration generator auto-attaches the framework `ValidationDecorator` (just inside the feature gate) for any handler whose request type graph carries validation attributes, and the same attributes are exported to the JSON-RPC schema, MCP tool schemas, the OpenAPI document, and the generated Zod client. Reusable custom constraints subclass a mapped attribute (e.g. `[Slug] : RegularExpressionAttribute`). Enforcement requires the opt-in `Elarion.Validation` package (`AddElarionValidation()`); diagnostics `ELVAL001`/`ELVAL002`/`ELVAL003`. See [Validation](/docs/concepts/validation). ### `[DecimalRange]` [#decimalrange] * **Package:** `Elarion.Abstractions` (`Elarion.Abstractions.Validation`) · **Applies to:** property, field, parameter * **Triggers:** a `RangeAttribute` whose bounds are two static `decimal` members of a type, named instead of copied (C# has no `decimal` attribute argument). Enforced and exported like `[Range]` (`minimum`/`maximum`, the exact decimal); `null` passes. A name that is no static decimal field or property fails when the attribute is created. See [Decimal bounds and decimal places](/docs/concepts/validation#decimal-bounds-and-decimal-places). | Parameter | Type | Meaning | | --------------------- | -------- | ---------------------------------------------------------------------- | | `declaringType` | `Type` | The type that declares the bounds. | | `minimum` / `maximum` | `string` | The names (`nameof`) of the static decimal members holding the bounds. | Inherits `ErrorMessage`, `MinimumIsExclusive` and `MaximumIsExclusive` from `RangeAttribute`. ```csharp [property: DecimalRange(typeof(MoneyBounds), nameof(MoneyBounds.Zero), nameof(MoneyBounds.Max))] decimal Amount ``` ### `[MaxDecimalPlaces]` [#maxdecimalplaces] * **Package:** `Elarion.Abstractions` (`Elarion.Abstractions.Validation`) · **Applies to:** property, field, parameter * **Triggers:** refuses a number with more than `places` decimal places (trailing zeros do not count; integers pass; `null` passes). Exported as `multipleOf: 10^-places`, checked by the generated Zod client (`.multipleOf`) and listed in `rpcLimits`. | Parameter | Type | Meaning | | --------- | ----- | --------------------------------------------- | | `places` | `int` | The decimal places a value may have, 0 to 28. | ### `[ValidationRoot]` [#validationroot] * **Package:** `Elarion.Abstractions` · **Applies to:** class, struct (records included) * **Triggers:** makes a type that is validated outside a handler request a validation root of the module whose namespace contains it, so the validation generator emits the same constant-constructed metadata for it as for a handler request and `IRequestValidator.HasMetadata` answers `true` for it while the module is enabled. A marked type with validation attributes outside every module is `ELVAL004`; one in a compilation without `Elarion.Validation` is `ELVAL002`. A generic type is not a root. On an attribute class, it makes every type that carries that attribute a root, as `[SpreadsheetRecord]` does for spreadsheet records. See [Validating outside a handler request](/docs/concepts/validation#validating-outside-a-handler-request). No parameters. ## Authorization [#authorization] Handler requirements are class attributes the handler-registration generator reads to auto-attach the `AuthorizationDecorator` (the outermost functional gate, just inside the observability decorator's handler span). Different attribute *kinds* AND together; multiple of one kind AND; OR lives inside a single `[RequireClaim]`. All are transport-neutral (identical under JSON-RPC, MCP, and HTTP) and evaluate against `ICurrentUser` — an unauthenticated caller yields `AppError.Unauthorized` (401), authenticated-but-denied yields `AppError.Forbidden` (403). The gated handler's response must be able to represent failure (`Result`/`Result`) or `ELAUTH001` is reported. ### `[RequirePermission]` [#requirepermission] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** class (`AllowMultiple`, inherited) * **Triggers:** requires the principal to hold a permission to perform a verb on a resource — the Kubernetes-RBAC `(resource, verb)` shape, sugar for `[RequireClaim(PermissionClaimType, "{resource}.{verb}")]`. Surfaced into the generated permission catalog (see `[GeneratePermissionCatalog]`). | Parameter | Type | Default | Meaning | | ------------ | ---------------------------- | -------- | ------------------------------------------------------------------------------- | | `resource` | `string` (ctor) → `Resource` | required | The resource the permission applies to, e.g. `"properties"`. | | `verb` | `string` (ctor) → `Verb` | required | The action on the resource; a `Verbs` constant or any string (open vocabulary). | | `Permission` | `string` (read-only) | derived | The composed claim value enforced — `{Resource}.{Verb}` (separator `"."`). | **`Verbs`** (constants, open vocabulary): `Read` (`"read"`), `List` (`"list"`), `Create` (`"create"`), `Update` (`"update"`), `Write` (`"write"`), `Delete` (`"delete"`), `Manage` (`"manage"`). ### `[RequirePermissionFor]` [#requirepermissionfor] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** handler class (`AllowMultiple`, inherited) * **Triggers:** a member-scoped permission: the caller needs `{resource}.{verb}` for the resource the request member's enum value names (`[PermissionResource]` on the enum member), or any one of `AnyOf`. Enforced by the authorization decorator (unary and stream) through `IPermissionChecker`; a null member or an undeclared value is satisfied only by `AnyOf`. Exported as `requires.memberPermissions` in `rpc-schema.json` and decided by `canCall` from a call's params. Build errors `ELAUTH007`–`ELAUTH010`. See [Permissions that depend on a request member](/docs/concepts/authorization#permissions-that-depend-on-a-request-member). | Parameter | Type | Default | Meaning | | --------- | -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `member` | `string` (ctor) → `Member` | required | The request member whose value names the resource, as a compile-checked path: `nameof(Query.Kind)` or a dotted path. Its type is an enum or a nullable enum. | | `verb` | `string` (ctor) → `Verb` | required | The verb the permission grants on that resource; see `Verbs`. | | `AnyOf` | `string[]?` (init) | `null` | Permissions any one of which satisfies the requirement instead (`ElarionPermissions.Settings.Read`, or a string). | ### `[PermissionResource]` [#permissionresource] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** enum member (single) * **Triggers:** names the permission resource an enum member stands for, so a `[RequirePermissionFor]` reading the enum composes `{resource}.{verb}`. Every member of such an enum needs one (`ELAUTH009`); an alias of an earlier member's value needs none. | Parameter | Type | Default | Meaning | | ---------- | ---------------------------- | -------- | --------------------------------------------- | | `resource` | `string` (ctor) → `Resource` | required | The permission resource, e.g. `"properties"`. | ### `[DeclarePermission]` [#declarepermission] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** class or record (`AllowMultiple`, not inherited) * **Triggers:** adds `{resource}.{verb}` to the generated permission catalog (`ElarionPermissions`, `IPermissionCatalog`) of the module whose namespace contains the type, **without** requiring it anywhere. For a permission a row-level rule checks on top of a coarser `[RequirePermission]`, so role policy derived from the catalog can grant it. No runtime effect. Same parameters as `[RequirePermission]`. ### `[RequiresDecision]` [#requiresdecision] * **Package:** `Elarion.Abstractions` · **Applies to:** handler class (`AllowMultiple`, inherited) * **Triggers:** declares a decision the handler may ask its caller with `AppError.DecisionRequired(code, …)`: it joins the operation's error contract (kind `DecisionRequired`), and the schema exports its options and whether it is answered per item, which the generated client's `withDecisions`, `decisionQuestion` and `answerDecision` use. The request implements `IDecidingRequest`; its `decisions` member is exported narrowed to the declared codes and options. Options that are not an enum report `ELERR003`. See [Asking the caller to decide](/docs/concepts/results-and-errors#asking-the-caller-to-decide). | Parameter | Type | Default | Meaning | | ---------- | ------------------------ | -------- | --------------------------------------------------------------------------------------------- | | `code` | `string` (ctor) → `Code` | required | The decision's stable code. | | `Options` | `Type?` (init) | `null` | An enum whose members (in camel case) are the choices; `null` for a confirmation (`confirm`). | | `PerItem` | `bool` (init) | `false` | Answered per item key rather than once for the request. | | `DataType` | `Type?` (init) | `null` | The payload the question carries as `AppError.Data`. | ### `[VisibleWith]` [#visiblewith] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** property or constructor parameter of a response type * **Triggers:** shows the member only to callers who hold the permission, or any one of the permissions it names; for everyone else the generated `VisibilityDecorator` (just inside authorization) answers it as `null`. The decision is `IPermissionChecker.Holds`, the same as the `[RequirePermission]` gate. Exported as `x-elarion-visible-with` in `rpc-schema.json` (a string, or an array for several permissions). Build errors `ELAUTH003` (member not nullable), `ELAUTH004` (a shape the pipeline cannot copy) and `ELAUTH005` (no permission, or one the generator cannot read). See [Members only some callers see](/docs/concepts/authorization#members-only-some-callers-see). | Parameter | Type | Default | Meaning | | ------------------ | ------------------------------ | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `permission` | `string` (ctor) → `Permission` | required (one form) | The composed permission, e.g. `ElarionPermissions.Banking.Read`. | | `resource`, `verb` | `string` (ctor) | required (other form) | Composed to `{resource}.{verb}`, as `[RequirePermission]` composes it. | | `AnyOf` | `string[]?` (init) | `null` | Further permissions, any one of which shows the member too; alone (`[VisibleWith(AnyOf = [...])]`) it names them all. `Permissions` lists the constructor's permission, then these. | ### `[RequireRole]` [#requirerole] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** class (`AllowMultiple`, inherited) * **Triggers:** requires the principal to be in the named role. Also surfaced into the permission catalog. | Parameter | Type | Default | Meaning | | --------- | ------------------------ | -------- | ----------------------- | | `role` | `string` (ctor) → `Role` | required | The required role name. | ### `[RequireClaim]` [#requireclaim] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** class (`AllowMultiple`, inherited) * **Triggers:** requires the principal to carry a claim of the given type; with values supplied the principal must match at least one (OR). The general primitive `[RequirePermission]`/`[RequireRole]` build on. | Parameter | Type | Default | Meaning | | --------------- | -------------------------------------------------------------------- | -------- | ------------------------------------------------ | | `claimType` | `string` (ctor) → `ClaimType` | required | The claim type the principal must carry. | | `allowedValues` | `params string[]` (ctor) → `AllowedValues` (`IReadOnlyList`) | empty | Accepted values (OR); empty means presence-only. | ### `[RequirePolicy]` [#requirepolicy] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** class (`AllowMultiple`, inherited) * **Triggers:** requires a named `IAuthorizationPolicy` (an Elarion-native policy evaluated against `ICurrentUser` + the request, **not** the ASP.NET policy engine) to pass. | Parameter | Type | Default | Meaning | | --------- | -------------------------- | -------- | ----------------------------------------------------------------------------------------------- | | `policy` | `string` (ctor) → `Policy` | required | The policy name, matched against `IAuthorizationPolicy.Name` / `[AuthorizationPolicy("name")]`. | ### `[AllowAnonymous]` [#allowanonymous] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** class (single, inherited) * **Triggers:** marks a handler as public; authorization is skipped entirely and wins over any `Require*` attribute and over an `[ElarionAuthorizationDefaults]` deny-by-default scope. Marker only — no parameters. ### `[AuthorizationPolicy]` [#authorizationpolicy] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** class (single, not inherited) * **Triggers:** marks an `IAuthorizationPolicy` implementation as a named, auto-registered policy (per module, like `[Service]`), referenced by `[RequirePolicy("name")]`. Diagnostics `ELPOL001`/`ELPOL002`. | Parameter | Type | Default | Meaning | | --------- | ------------------------ | -------- | ------------------------------------------- | | `name` | `string` (ctor) → `Name` | required | The policy name `[RequirePolicy]` resolves. | ### `[ElarionAuthorizationDefaults]` [#elarionauthorizationdefaults] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** assembly | class (single, not inherited) * **Triggers:** flips the in-scope handlers to **deny-by-default** — every handler requires authentication unless `[AllowAnonymous]`. Resolved most-specific-wins (a `[AppModule]`-class scope overrides the assembly scope), like `[DefaultPipeline]`. | Parameter | Type | Default | Meaning | | ---------------------- | ------------- | ------- | ------------------------------------------------------------- | | `RequireAuthenticated` | `bool` (init) | `true` | Whether in-scope handlers require an authenticated principal. | ### `[RequireResource]` [#requireresource] * **Package:** `Elarion.Abstractions` (Authorization) · **Applies to:** class (`AllowMultiple`, inherited) * **Triggers:** the per-resource point check (the BOLA-class "may I touch *this* one?" gate). The decorator reads the resource id from the request by a **compile-checked path** (no reflection) and calls the `IResourceAuthorizer` seam. A resource type with a registered filter check (`AddElarionResourceFilterCheck`) is checked through its `IQueryAuthorizer` — the same rule as the list filter, for the declared `Operation`; every other type is authorized from the grants table, and the check **fails closed** when no backend is registered. An unresolvable `Id` path is `ELAUTH002`. | Parameter | Type | Default | Meaning | | ------------------ | ------------------------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `resourceType` | `Type` (ctor) → `ResourceType` | required | The resource type being accessed, e.g. `typeof(Contact)`. | | `Operation` | `string` (init) | `"read"` | The operation name (an open `ResourceOperation` value). | | `ResourceTypeName` | `string?` (init) | `null` | Explicit grants-table discriminator overriding the default (`ResourceType.FullName`). Set the same string on the matching `[ResourceFilter].ResourceTypeName` and on every stored grant; compared ordinally. | | `Id` | `string` (init) | `"Id"` | Request property path naming the resource id, e.g. `nameof(Query.Id)` or a dotted path of existing properties. | | `DenyAs` | `ResourceDenial` (init) | `Forbidden` | How a denial is answered: `Forbidden` (`403`), or `NotFound` (`404`, `not_found`, `AuthorizationOptions.ResourceNotFoundMessage`) so a hidden record is indistinguishable from a missing one. `NotFound` adds `not_found` to the operation's error contract. | ### `[ResourceFilter]` [#resourcefiltertentity] * **Package:** `Elarion.Abstractions` · **Applies to:** class (generic attribute, `where TEntity : class`) * **Triggers:** the data-level **list filter** (Leg B). Declared on a dedicated partial class (the entity stays clean, like `[Keyset]`); the EF Core generator completes it as an `IQueryAuthorizer` whose predicate composes the rules as `AND(scope rules) AND OR(grant rules)` and pushes it into SQL via `source.WhereAuthorized(authorizer, currentUser)` **before** paging. Diagnostics `ELRES001`–`ELRES005`. | Parameter | Type | Default | Meaning | | --------------------- | ---------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TEntity` | type parameter (`where TEntity : class`) | required | The entity being authorized. | | `OwnerProperty` | `string?` (init) | `null` | A **grant** (OR): the row is visible when this column equals the caller's `UserId`. Type Guid/string/int/long. | | `TenantProperty` | `string?` (init) | `null` | A **scope** (AND): every visible row's column must equal the caller's tenant claim. Type Guid/string/int/long. | | `TenantClaimType` | `string` (init) | `"tenant"` | The claim type the tenant value is read from. | | `Shared` | `bool` (init) | `false` | A **grant** (OR): a correlated `EXISTS` over the resource-grants table for the caller's user **or any of their roles**, for the operation `WhereAuthorized` asks (defaults to `Read`). Makes the filter a **scoped service** (no static `Specification`); requires `ResourceTypeName` (else `ELRES005`) and a reference to `Elarion.Authorization.EntityFrameworkCore`. | | `ResourceTypeName` | `string?` (init) | `null` | The resource-type discriminator stored in the grants table (e.g. `"Contact"`), used by the `Shared` `EXISTS`. | | `IdProperty` | `string` (init) | `"Id"` | The entity key property whose stringified value matches the grant's resource id. Type Guid/string/int/long. | | `BypassPermission` | `string?` (init) | `null` | A permission (`"{resource}.{verb}"`) whose holders see every row of their scope: the owner and grant rules are lifted, the `TenantProperty` scope still applies (unrestricted only without one). | | `PermissionClaimType` | `string` (init) | `"permission"` | The claim type `BypassPermission` is read from; match `AuthorizationOptions.PermissionClaimType`. | | `BypassRole` | `string?` (init) | `null` | A role whose members see every row of their scope, with the same rules as `BypassPermission`; with both set, either one bypasses. | | `Register` | `bool` (init) | `true` | Whether the host bootstrapper registers the filter as `IQueryAuthorizer`. Set `false` on a **building block** of a composed rule and register the composition; two registered filters for one entity are `ELMOD007`. | Consume the filter by injecting `IQueryAuthorizer` (the form that works for `Shared`). A field-only filter (`OwnerProperty`/`TenantProperty`, no `Shared`) is stateless, so the generator *also* exposes a static `Specification` singleton. Both are auto-registered as `IQueryAuthorizer`, module-feature-gated — with `TryAdd`, so an `IQueryAuthorizer` the application registers itself (a composed rule) is the one that resolves. See [Authorization](/docs/concepts/authorization) and [Resource authorization](/docs/concepts/resource-authorization). ## EF Core [#ef-core] ### `[EntityConfiguration]` [#entityconfiguration] * **Package:** `Elarion.EntityFrameworkCore` · **Applies to:** class (an `IEntityTypeConfiguration` implementation) * **Triggers:** marks an `IEntityTypeConfiguration` implementation as the single source of truth for an entity's participation; it drives both the generated `DbSet` and the `Configure(...)` application. The entity itself carries no marker (previously `[DbEntity]`) — a configured entity is a discovered entity. A plain `IEntityTypeConfiguration` with no attribute is ignored (no DbSet, no Configure). A single `[EntityConfiguration]` class may implement `IEntityTypeConfiguration` more than once; each implemented entity gets its own `DbSet` and its own `Configure(...)` call. A class implementing no `IEntityTypeConfiguration` is reported (`ELEFC001`). | Parameter | Type | Default | Meaning | | --------- | ------------------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------- | | `scopes` | `params string[]` (ctor) → `Scopes` (`IReadOnlyList`) | empty | Optional context scopes this configuration belongs to. Omit scopes to participate in unscoped/global contexts. | ```csharp // Entities/Invoice.cs — plain class, no attribute public sealed class Invoice { public Guid Id { get; set; } } // Invoicing/InvoiceConfiguration.cs — the single source of truth using Elarion.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; [EntityConfiguration] public sealed class InvoiceConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { /* ... */ } } ``` ### `[GenerateDbSets]` [#generatedbsets] * **Package:** `Elarion.EntityFrameworkCore` · **Applies to:** class * **Triggers:** applied to a partial DbContext class; generates a `DbSet` property for each `[EntityConfiguration]` entity and `ConfigureEntities(ModelBuilder)` directly onto that class (reflection-free, AOT-friendly direct `ApplyConfiguration` calls). | Parameter | Type | Default | Meaning | | --------- | ------------------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `scopes` | `params string[]` (ctor) → `Scopes` (`IReadOnlyList`) | empty | Optional context scopes generated for this class. Omit scopes to include every `[EntityConfiguration]`; a scoped class includes only configurations whose scopes intersect. | ### `[GenerateElarionIdentity]` [#generateelarionidentitytuser-trole-tkey] * **Package:** `Elarion.EntityFrameworkCore.Identity` · **Applies to:** class (generic attribute; `TUser : IdentityUser`, `TRole : IdentityRole`, `TKey : IEquatable`) * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the seven Identity `DbSet`s and applies the self-contained snake\_case Identity model (keys, composite keys, indexes, table/column names) through the EF generator's per-feature model-config seam — **no** `IdentityDbContext` inheritance and **no** `EFCore.NamingConventions` dependency. The web-free Identity *model*; the host wiring is `AddElarionIdentity` in `Elarion.AspNetCore.Identity`. Requires `[GenerateDbSets]` (else `ELIDN001`). | Parameter | Type | Default | Meaning | | ------------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column/index names use snake\_case. | | `Schema` | `string?` (init) | `null` | The schema for all seven Identity tables, or `null` for the provider's default schema. | | `TablePrefix` | `string?` (init) | `null` | Optional prefix prepended verbatim to every Identity table name (e.g. `"auth_"` → `auth_users`). Because Identity spans seven tables, the prefix is the table-name override — there is no per-table name parameter. | ### `[GenerateElarionResourceGrants]` [#generateelarionresourcegrants] * **Package:** `Elarion.Authorization.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet` and applies the grants model configuration — the table backing `[ResourceFilter(Shared = true)]` and the `[RequireResource]` point check. The hand-written equivalent is `modelBuilder.ApplyElarionResourceGrants()`. Requires `[GenerateDbSets]` (else `ELRG001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column/index names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`elarion_resource_grants` / `ElarionResourceGrants` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Resource authorization](/docs/concepts/resource-authorization) and [Identity](/docs/capabilities/identity). ### `[GenerateElarionTenantScoping]` [#generateelariontenantscoping] * **Package:** `Elarion.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator implements the EF model-configuration seam with a call to `ApplyElarionTenantScoping`, which attaches a named query filter to every entity implementing `ITenantScoped`. Takes no parameters — which entities are tenant-scoped is a property of the entities, not of the context. Covers the **read** leg only: register `AddElarionTenantScoping()` and `AddElarionTenantScopingEntityFrameworkCore()` for the tenant value and the insert-time stamp. The hand-written equivalent is `modelBuilder.ApplyElarionTenantScoping(this)` as the last statement of `OnModelCreating`. Requires `[GenerateDbSets]` (else `ELTEN001`). See [Multi-tenancy](/docs/capabilities/multi-tenancy). ### `[GenerateElarionIdempotencyKeys]` [#generateelarionidempotencykeys] * **Package:** `Elarion.Idempotency.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet` and applies the idempotency-keys model configuration through the EF generator's model-config seam — the table backing the durable `[Idempotent]` store. The hand-written equivalent is `modelBuilder.ApplyElarionIdempotencyKeys()`. Mirrors `[GenerateElarionResourceGrants]`. Requires `[GenerateDbSets]` (else `ELIDEMEF001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column/index names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`elarion_idempotency_keys` / `ElarionIdempotencyKeys` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Idempotency](/docs/concepts/idempotency). ### `[GenerateElarionAuditing]` [#generateelarionauditing] * **Package:** `Elarion.Auditing.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet` and applies the audit-log model configuration through the EF generator's model-config seam — the append-only table backing the durable `IAuditTrail`. The hand-written equivalent is `modelBuilder.UseElarionAuditing()`. Mirrors `[GenerateElarionIdempotencyKeys]`. Requires `[GenerateDbSets]` (else `ELAUD001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column/index names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`elarion_audit_log` / `ElarionAuditLog` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Audit trail](/docs/concepts/auditing). ### `[GenerateElarionOutbox]` [#generateelarionoutbox] * **Package:** `Elarion.Messaging.Outbox` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits `DbSet` and applies the transactional-outbox model configuration through the EF generator's model-config seam. The hand-written equivalent is `modelBuilder.UseElarionOutbox()`. Requires `[GenerateDbSets]` (else `ELOBX001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column/index names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`elarion_outbox_messages` / `ElarionOutboxMessages` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Event bus backends](/docs/capabilities/events/backends). ### `[GenerateElarionSchedulerClaims]` [#generateelarionschedulerclaims] * **Package:** `Elarion.Scheduling.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet` and applies the scheduler-claims model configuration through the EF generator's model-config seam — the table that makes each recurring occurrence execute on exactly one node (ADR-0025). The hand-written equivalent is `modelBuilder.UseElarionSchedulerClaims()`. Mirrors `[GenerateElarionIdempotencyKeys]`. Requires `[GenerateDbSets]` (else `ELSCH001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column/index names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`elarion_scheduler_claims` / `ElarionSchedulerClaims` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Scheduling](/docs/capabilities/scheduling). ### `[GenerateElarionSettings]` [#generateelarionsettings] * **Package:** `Elarion.Settings.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet` and applies the settings model configuration through the EF generator's model-config seam — the table backing the EF Core `ISettingsStore`. The hand-written equivalent is `modelBuilder.UseElarionSettings()`. Mirrors `[GenerateElarionIdempotencyKeys]`. Requires `[GenerateDbSets]` (else `ELSET001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------ | | `SnakeCase` | `bool` (init) | `true` | Whether table/column/index names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`elarion_settings` / `ElarionSettings` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Settings](/docs/concepts/settings). ### `[GenerateElarionBlobStorage]` [#generateelarionblobstorage] * **Package:** `Elarion.Blobs.PostgreSql` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet` and applies the blob model configuration — both the metadata table and the content table (the content row type is `internal`: mapped, but no `DbSet`) — through the EF generator's model-config seam. The hand-written equivalent is `modelBuilder.UseElarionBlobStorage()`. Mirrors `[GenerateElarionIdempotencyKeys]`. Requires `[GenerateDbSets]` (else `ELBLB001`). | Parameter | Type | Default | Meaning | | ------------------ | ---------------- | ------- | -------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column/index names use snake\_case. | | `TableName` | `string?` (init) | `null` | The metadata table name, or `null` for the default (`stored_blobs` / `StoredBlobs` depending on `SnakeCase`). | | `ContentTableName` | `string?` (init) | `null` | The content table name, or `null` for the default (`blob_contents` / `BlobContents` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Blob storage](/docs/capabilities/blob-storage). ### `[GenerateElarionStagedUploads]` [#generateelarionstageduploads] * **Package:** `Elarion.Blobs.PostgreSql` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet` and applies the staged-upload model configuration through the EF generator's model-config seam — the table backing the durable `IStagedUploadStore` that resumable transports (tus) stage into. The hand-written equivalent is `modelBuilder.UseElarionStagedUploads()`. Mirrors `[GenerateElarionBlobStorage]`, which maps the blob tables a completed upload is written to. Requires `[GenerateDbSets]` (else `ELBLB002`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | -------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column/index names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`staged_uploads` / `StagedUploads` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Blob uploads](/docs/capabilities/blob-uploads). ### `[GenerateElarionActorSnapshots]` [#generateelarionactorsnapshots] * **Package:** `Elarion.Actors.PostgreSql` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet` and applies the actor snapshot model configuration through the EF generator's model-config seam — the table backing the `IActorSnapshotStore` behind every `IActorState` (ADR-0047). The hand-written equivalent is `modelBuilder.UseElarionActorSnapshots()`. Mirrors `[GenerateElarionSettings]`/`[GenerateElarionIdempotencyKeys]`. Requires `[GenerateDbSets]` (else `ELASN001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`elarion_actor_snapshots` / `ElarionActorSnapshots` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Actor state and placement](/docs/concepts/actors/state-and-placement#durable-state-with-snapshots). ### `[GenerateElarionRoleLeases]` [#generateelarionroleleases] * **Package:** `Elarion.Coordination.PostgreSql` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet` and applies the role-lease model configuration through the EF generator's model-config seam — the leader-election table behind `IRoleLease` (ADR-0049) and therefore behind `[Actor(Placement = ActorPlacementMode.SingleHome)]` (ADR-0048). The hand-written equivalent is `modelBuilder.UseElarionRoleLeases()`. Requires `[GenerateDbSets]` (else `ELROLE001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | ----------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`elarion_role_leases` / `ElarionRoleLeases` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Actors — multiple instances and single-homing](/docs/concepts/actors/state-and-placement#multiple-instances-and-single-homing). ### `[GenerateElarionAppPasswords]` [#generateelarionapppasswords] * **Package:** `Elarion.AppPasswords.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits `DbSet ElarionAppPasswords` and applies the app-password model configuration through the EF generator's model-config seam — the table backing the EF `IAppPasswordStore` (ADR-0111). The hand-written equivalent is `modelBuilder.UseElarionAppPasswords()`. Mirrors `[GenerateElarionDeviceIdentity]`. Requires `[GenerateDbSets]` (else `ELAPW001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column names use snake\_case. | | `TableName` | `string?` (init) | `null` | The table name, or `null` for the default (`elarion_app_passwords` / `ElarionAppPasswords` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [App passwords](/docs/capabilities/app-passwords). ### `[GenerateElarionDavStore]` [#generateelariondavstore] * **Package:** `Elarion.WebDav.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `ElarionDavCollections`, `ElarionDavObjects` and `ElarionDavChanges` sets and applies the store's model configuration through the EF generator's model-config seam — the tables behind the EF `IDavCollectionStore` (ADR-0111). The hand-written equivalent is `modelBuilder.UseElarionDavStore()`. Requires `[GenerateDbSets]` (else `ELDAV001`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | ---------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column names use snake\_case (`elarion_dav_collections`, …) or PascalCase. | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [CalDAV](/docs/capabilities/caldav#the-published-collection-store). ### `[GenerateElarionDeviceIdentity]` [#generateelariondeviceidentity] * **Package:** `Elarion.Devices.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet`/`DbSet` and applies the device identity model configuration through the EF generator's model-config seam — the tables backing `IDeviceKeyStore` and `IPairingCodeStore` (ADR-0054). The hand-written equivalent is `modelBuilder.UseElarionDeviceIdentity()`. Mirrors `[GenerateElarionActorSnapshots]`/`[GenerateElarionRoleLeases]`. Requires `[GenerateDbSets]` (else `ELDEV001`). | Parameter | Type | Default | Meaning | | ---------------------- | ---------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column names use snake\_case. | | `KeyTableName` | `string?` (init) | `null` | The device key table name, or `null` for the default (`elarion_device_keys` / `ElarionDeviceKeys` depending on `SnakeCase`). | | `PairingCodeTableName` | `string?` (init) | `null` | The pairing code table name, or `null` for the default (`elarion_device_pairing_codes` / `ElarionDevicePairingCodes` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Device identity](/docs/capabilities/devices). ### `[GenerateElarionWebPush]` [#generateelarionwebpush] * **Package:** `Elarion.WebPush.EntityFrameworkCore` · **Applies to:** class * **Triggers:** on a `[GenerateDbSets]` partial DbContext; the bundled generator emits the `DbSet`/`DbSet` and applies the Web Push model configuration through the EF generator's model-config seam — the tables backing `IPushSubscriptionStore` and `IVapidKeyStore` (ADR-0076). The hand-written equivalent is `modelBuilder.UseElarionWebPush()`. Mirrors `[GenerateElarionDeviceIdentity]`. Requires `[GenerateDbSets]` (else `ELWP001`). | Parameter | Type | Default | Meaning | | ----------------------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `SnakeCase` | `bool` (init) | `true` | Whether table/column names use snake\_case. | | `SubscriptionTableName` | `string?` (init) | `null` | The push subscription table name, or `null` for the default (`elarion_push_subscriptions` / `ElarionPushSubscriptions` depending on `SnakeCase`). | | `VapidKeyTableName` | `string?` (init) | `null` | The VAPID key table name, or `null` for the default (`elarion_vapid_keys` / `ElarionVapidKeys` depending on `SnakeCase`). | | `Schema` | `string?` (init) | `null` | The schema, or `null` for the provider's default schema. | See [Web Push](/docs/capabilities/web-push). ### `[Keyset]` [#keysettentity] * **Package:** `Elarion.Paging` · **Applies to:** class (generic attribute, `where TEntity : class`) * **Triggers:** declares an ordered keyset (seek) definition for `TEntity` on the annotated partial class. The EF Core generator fills the class with a reflection-free `IKeysetDefinition` implementation (ordering, seek predicate, opaque cursor codec) plus a static `Definition` singleton, so handlers page via `source.ToKeysetPageAsync(request, MyKeyset.Definition, selector)`. Declared on a dedicated partial class (not the entity), so an entity may have any number of orderings. Non-partial or nested keyset classes are reported (`ELKEY005`). | Parameter | Type | Default | Meaning | | --------- | -------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TEntity` | type parameter (`where TEntity : class`) | required | The entity type being paginated. | | `columns` | `params string[]` (ctor) → `Columns` (`IReadOnlyList`) | empty | Ordered keyset column names in precedence order; each names a property on `TEntity`. Ascending by default; a leading `-` marks the column descending (e.g. `"-CreatedAt"`). The final column should be unique (typically the primary key) for determinism. | See [Entity Framework](/docs/capabilities/entity-framework) and [Pagination](/docs/capabilities/pagination). ## SQL row mapping (EF-free tier) [#sql-row-mapping-ef-free-tier] ### `[SqlRecord]` [#sqlrecord] * **Package:** `Elarion.Sql` · **Applies to:** class, struct (records included) * **Triggers:** marks a row type for SQL mapper generation (ADR-0058). The bundled generator emits a sealed `{Type}SqlMapper : ISqlRowMapper` — column ordinals resolved by name once per result set (`Ordinals` struct), synchronous typed `GetFieldValue` row reads, typed `BindParameters` (parameters named like columns), `TableName`/`Columns.*` constants (including `Columns.All` and `Columns.AllParameters`), a static `Instance`, and a per-assembly `AddElarionSqlMappers()` DI registration. Column names default to the snake\_case of the property name; the table name defaults to the snake\_case of the type name (no pluralization). Positional records construct through the primary constructor; nominal records with `required`/`init` members through an object initializer. Derived (get-only) members are skipped. There is no reflection fallback: an unmapped type or unsupported shape is a compile error (`ELSQL001`–`ELSQL007`). | Parameter | Type | Default | Meaning | | ----------- | ---------------- | ------- | --------------------------------------------------------------- | | `tableName` | `string?` (ctor) | `null` | The table name, or `null` for the snake\_case of the type name. | ### `[SqlColumn]` [#sqlcolumn] * **Package:** `Elarion.Sql` · **Applies to:** property * **Triggers:** overrides the column name of a `[SqlRecord]` property (default: snake\_case of the property name). On a non-writable property this is an error (`ELSQL007`). | Parameter | Type | Default | Meaning | | --------- | --------------- | -------- | ------------------------------------- | | `name` | `string` (ctor) | required | The column name as it appears in SQL. | ### `[SqlIgnore]` [#sqlignore] * **Package:** `Elarion.Sql` · **Applies to:** property * **Triggers:** excludes a `[SqlRecord]` property from mapping (neither read nor bound). A `required` property cannot be ignored (`ELSQL003`). ### `[SqlJson]` [#sqljson] * **Package:** `Elarion.Sql` · **Applies to:** property * **Triggers:** maps a `[SqlRecord]` property as a JSON column, (de)serialized through the canonical JSON accessor's `JsonTypeInfo` (`IElarionJsonSerialization`, ADR-0023) — the property type must be in a registered `JsonSerializerContext`. A mapper with JSON columns takes the accessor as a constructor parameter instead of exposing `Instance`; the generated DI registration wires it. Under `[UseElarionSql(Provider = SqlProvider.Npgsql)]`, parameters bind as `NpgsqlDbType.Jsonb`. ### `[UseElarionSql]` [#useelarionsql] * **Package:** `Elarion.Sql` · **Applies to:** assembly * **Triggers:** provider trigger for the SQL mapper generator (precedent: `[UseElarionEntityFrameworkCore]`). `Provider = SqlProvider.Npgsql` emits PostgreSQL-specific parameter typing (`jsonb` for `[SqlJson]` columns); without it, emission stays provider-neutral. | Parameter | Type | Default | Meaning | | ---------- | -------------------- | ---------- | ------------------------------------------------------------------------- | | `Provider` | `SqlProvider` (init) | `Portable` | The provider to emit provider-specific code for (`Portable` or `Npgsql`). | See [SQL mapping](/docs/capabilities/sql-mapping). ## Spreadsheet records [#spreadsheet-records] ### `[SpreadsheetRecord]` [#spreadsheetrecord] * **Package:** `Elarion.Spreadsheets` · **Applies to:** `partial` class (record classes included) * **Triggers:** makes the class a spreadsheet record (ADR-0108). The bundled generator implements `ISpreadsheetRecord` (the mapper `SpreadsheetWorkbook` and `SpreadsheetReader` use) and emits a nested `Columns` class with one `SpreadsheetColumn` per column. Every public instance property with a getter is a column, in declaration order; a get-only property is written and not read. The attribute class is marked `[ValidationRoot]`, so a record's DataAnnotations are validated on every row read. Unsupported shapes are build errors (`ELSHEET001`–`ELSHEET009`). | Parameter | Type | Default | Meaning | | --------------- | ---------------- | ------- | ---------------------------------------------------- | | `worksheetName` | `string?` (ctor) | `null` | The worksheet's name, or `null` for the type's name. | ### `[SpreadsheetColumn]` [#spreadsheetcolumn] * **Package:** `Elarion.Spreadsheets` · **Applies to:** property * **Triggers:** sets how a property of a spreadsheet record is written and read. Without a header, the column's header is the property's `[Display(Name)]`, else its name. | Parameter | Type | Default | Meaning | | ------------------------- | ---------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `header` | `string?` (ctor) | `null` | The header text. | | `Order` | `int` | `-1` (declaration order) | The column's position. | | `Format` | `string?` | `null` | The number format of a number or date column; a date column without one shows in the viewer's notation. | | `Width` | `double` | `0` (measured) | The width in characters; measured from the header and the first 200 values when not set, at most 80. | | `Aliases` | `string[]?` | `null` | Older headers that still read as this column; the column's own header wins when a file has both. | | `TrueLabel`, `FalseLabel` | `string?` | `null` | On a boolean, both together: the texts written, offered as a dropdown and read (`ELSHEET005` otherwise). | | `Choices` | `string?` | `null` | On a `string`: `nameof` a static `IReadOnlyList` field or property of the record whose labels the column offers as a dropdown (`ELSHEET009` otherwise). | | `StrictChoices` | `bool` | `false` | With `Choices`: reading accepts only those labels and reports other text as `invalid_value`. | ### `[SpreadsheetIgnore]` [#spreadsheetignore] * **Package:** `Elarion.Spreadsheets` · **Applies to:** property * **Triggers:** leaves the property out of the worksheet: no column, neither written nor read. ### `[SpreadsheetChoice]` [#spreadsheetchoice] * **Package:** `Elarion.Spreadsheets` · **Applies to:** enum member * **Triggers:** gives the member extra spellings that read as it in an enum column of a spreadsheet record, ignoring case and surrounding white space. An alias is never written and never offered in the dropdown list, which show the member's `[Display(Name)]`, else its name. Labels, names and aliases of two members of one enum must differ ignoring case (`ELSHEET008`); an alias equal to its own member's label or name, or an empty one, is ignored. | Parameter | Type | Default | Meaning | | --------- | ---------- | ------- | --------------------------------------------------------------------- | | `Aliases` | `string[]` | empty | The spellings that read as the member besides its label and its name. | See [Spreadsheets](/docs/capabilities/spreadsheets). ## Cross-module communication [#cross-module-communication] ### `[ModuleContract]` [#modulecontract] * **Package:** `Elarion.Abstractions` (Modules) · **Applies to:** interface | class * **Triggers:** marks a module's published cross-module surface — the stable type other modules may depend on. Use it **sparingly and deliberately**: it is for genuine cross-module *domain* calls, not shared infrastructure (use a port outside the modules) or shared data (use the shared kernel). The owning module keeps the implementation `internal`; other modules inject the contract. `ModuleBoundaryAnalyzer` (`ELMOD002`) is location-based — it allows a `[ModuleContract]` but reports any other cross-module reference to a type placed *inside* another module (an entity, DTO, `[Service]`, handler, or `[EntityConfiguration]`). Types outside every module — the shared kernel and platform ports — are never flagged. Marker only — no parameters. ### `[ModuleApi]` [#moduleapi] * **Package:** `Elarion.Abstractions` (Modules) · **Applies to:** class * **Triggers:** configures how a handler participates in its module's generated typed in-process API (see `[GenerateModuleApi]`). A configurator, never a gate: every handler is in the default facade automatically (opt-out). Apply only to exclude a handler or to tag it into named scopes (additive). Scope vocabulary mirrors `[EntityConfiguration]`/`[GenerateDbSets]`. | Parameter | Type | Default | Meaning | | --------- | ------------------------------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `scopes` | `params string[]` (ctor) → `Scopes` (`IReadOnlyList`) | empty | Named scopes this handler is tagged into so it also appears on matching scoped facades. Empty means the handler participates only in the module's default (unscoped) facade. | | `Exclude` | `bool` (init) | `false` | When `true`, the handler is excluded from every generated facade, scoped or default. | ### `[GenerateModuleApi]` [#generatemoduleapi] * **Package:** `Elarion.Abstractions` (Modules) · **Applies to:** interface * **Triggers:** marks a partial interface to be filled with a typed in-process API over the owning module's handlers — one method per handler, dispatched typed-direct to `IHandler` (full decorator pipeline, no serialization). Not a transport and absent from the JSON-RPC/MCP schema; module-internal (must not cross boundaries). The interface must be partial and at namespace scope. Diagnostics `ELAPI001`–`ELAPI004`. | Parameter | Type | Default | Meaning | | --------- | ------------------------------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `scopes` | `params string[]` (ctor) → `Scopes` (`IReadOnlyList`) | empty | The scopes this facade selects. Empty = default facade (every non-excluded handler in the owning module by longest-prefix namespace match); one or more = only handlers tagged with an intersecting scope via `[ModuleApi]`. | See [Cross-module communication](/docs/concepts/cross-module-communication). ## Assembly opt-ins [#assembly-opt-ins] ### `[UseElarion]` [#useelarion] * **Package:** `Elarion.Abstractions` · **Applies to:** assembly * **Triggers:** enables the framework-owned assembly generators at once — handlers, services, scheduled jobs, event consumers, resilience policies, actor facades/registration, authorization-policy registration, client-event topics, the permission catalog, the variant catalog, the feature-flag registry, and the setting-definition catalog. Application-owned policy attributes such as pipeline defaults remain explicit, as do host/provider triggers such as `[GenerateModuleBootstrapper]`, `[GenerateDbSets]`, and `[UseElarionSql]`. Marker only — no parameters. ### Individual generation triggers [#individual-generation-triggers] All are `Elarion.Abstractions`, applied to the assembly, marker-only (no parameters), and subsumed by `[UseElarion]`. | Attribute | Triggers | | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `[GenerateModuleHandlers]` | Per-module handler registration methods (and, when the compilation references `Elarion.Validation`, the per-module request-validation resolvers). | | `[GenerateModuleServices]` | Per-module service registration methods. | | `[GenerateScheduledJobs]` | Source-generated scheduler descriptor registration. | | `[GenerateEventConsumers]` | Source-generated event-consumer descriptor registration. | | `[GenerateResiliencePolicies]` | Source-generated resilience-policy registration. | | `[GenerateActors]` | Actor typed facades and per-module actor registration. | | `[GenerateModuleAuthorizationPolicies]` | Per-module registration for `[AuthorizationPolicy]` implementations. | | `[GenerateClientEventTopics]` | Per-module client-event topic registration and subscribe-time policy metadata. | | `[GeneratePermissionCatalog]` | The typed permission/role catalog harvested from handler requirements. | | `[GenerateVariantCatalog]` | The typed feature/configuration variant catalog. | | `[GenerateFeatureFlags]` | The typed `ElarionFeatureFlags` registry and per-module flag registration (ADR-0079). | | `[GenerateSettingDefinitionCatalog]` | The aggregated catalog of declared settings (`ElarionSettingDefinitions.All`). | ### `[GeneratePermissionCatalog]` [#generatepermissioncatalog] * **Package:** `Elarion.Abstractions` · **Applies to:** assembly * **Triggers:** runs the `PermissionCatalogGenerator` to harvest every `[RequirePermission]`/`[RequireRole]`/`[DeclarePermission]` (on a class or record) in the assembly into a runtime `IPermissionCatalog` (a K8s-style resource + verb catalog, with `Verbs`, in `Elarion.Abstractions.Authorization`) — so admin UIs, role editors, and audits read straight from the handler attributes with no second source of truth to drift. Marker only — no parameters. Subsumed by `[UseElarion]`, or apply it standalone. Diagnostics `ELPERM001` (handler with requirements outside any `[AppModule]`) / `ELPERM002` (two permissions colliding on the same typed accessor). ```csharp [assembly: GeneratePermissionCatalog] ``` See [Authorization](/docs/concepts/authorization). ### `[GenerateClientEventTopics]` [#generateclienteventtopics] * **Package:** `Elarion.Abstractions` · **Applies to:** assembly * **Triggers:** runs the `ClientEventRegistrationGenerator` to register a topic per `IClientEvent` contract: grouped under its owning `[AppModule]` by longest-prefix namespace match, the topic named `{module}.{name}` (both camel-cased, a trailing `Event` suffix stripped; `[ClientEvent("…")]` overrides the full name), with the contract's `[RequirePermission]`/`[RequireRole]` attributes becoming subscribe-time requirements and `[AllowAnyResource]` declaring the resource segment a routing key. Emits `Add{Module}ClientEvents(IServiceCollection)` wired into the module's `ConfigureDefaultServices`, so a topic exists just by declaring the contract and disappears with the module's feature gate. Marker only — no parameters. Subsumed by `[UseElarion]`, or apply it standalone. Diagnostics `ELCEV001` (contract outside any `[AppModule]`) / `ELCEV002` (duplicate topic name) / `ELCEV003` (contracts declared but `Elarion.ClientEvents` not referenced). ```csharp [assembly: GenerateClientEventTopics] ``` See [Client events](/docs/capabilities/events/client-events). ### `[ClientEvent]` [#clientevent] * **Package:** `Elarion.Abstractions` (ClientEvents) · **Applies to:** class (single, not inherited) * **Triggers:** overrides the topic name the generator infers for an `IClientEvent` contract — the **full** name, like an explicit `[Handler("module.action")]`. Use it to keep a wire name stable across a type rename. | Parameter | Type | Default | Meaning | | --------- | ------------------------ | -------- | ----------------------------------------------------------------------------- | | `name` | `string` (ctor) → `Name` | required | The full topic name clients subscribe to (e.g. `"invoicing.invoiceChanged"`). | ### `[AllowAnyResource]` [#allowanyresource] * **Package:** `Elarion.Abstractions` (ClientEvents) · **Applies to:** class (single, not inherited) * **Triggers:** declares the resource segment of this `IClientEvent` contract's topic a **routing key, not an entitlement**: any caller passing the topic's subscribe-time requirements (authenticated, plus any `[RequirePermission]`/`[RequireRole]` on the contract) may subscribe to any resource of this topic, without consulting the `IClientEventSubscriptionAuthorizer` seam. Without it, resource-scoped subscriptions stay **fail-closed** (denied unless a registered authorizer approves). Deliberately per-topic so a future entitlement-scoped topic is never silently opened by a global "allow everything" authorizer. Imperative form: `AllowAnyResource()` on the topic options in `AddElarionClientEvents`. Marker only — no parameters. ```csharp [AllowAnyResource] // the symbol selects which events to receive; it gates nothing public sealed record QuoteChanged : IClientEvent { /* … */ } ``` See [Client events](/docs/capabilities/events/client-events). ### `[SubscriptionObserver]` [#subscriptionobservertobserver] * **Package:** `Elarion.Abstractions` (ClientEvents) · **Applies to:** class (single, not inherited) * **Triggers:** declares the topic's `IClientEventSubscriptionObserver` — the producer-side subscription lifecycle. `TObserver` is called with a **per-subscriber sink** when a client subscribes (`OnSubscribedAsync` — the producer-controlled initial value: greet the new subscriber with the current value, so the stream is self-converging) and on **debounced interest transitions** (`OnInterestChangedAsync` — `true` on the first watcher of a (topic, scope), `false` only after the last one leaves and the linger elapses, so a browser reload never bounces the producer). Resolved from a fresh DI scope per callback, detached from the subscribe path; the pull sibling is `IClientEventInterest.HasSubscribers`. Imperative form: `ObserveSubscriptions()` (+ `WithInterestLinger(...)`) on the topic options. | Parameter | Type | Default | Meaning | | ----------------------- | --------------- | ------- | ----------------------------------------------------------------------------------------- | | `InterestLingerSeconds` | `double` (init) | `5` | The last-watcher departure debounce before `OnInterestChangedAsync(active: false)` fires. | ```csharp [SubscriptionObserver(InterestLingerSeconds = 30)] public sealed record QuoteChanged : IClientEvent { /* … */ } ``` See [Client events](/docs/capabilities/events/client-events). ### `[GenerateVariantCatalog]` [#generatevariantcatalog] * **Package:** `Elarion.Abstractions` · **Applies to:** assembly * **Triggers:** runs the `VariantCatalogGenerator` to emit the assembly's `ElarionVariants` registry — the compile-time catalog of every `[FeatureVariant]`/`[ConfigurationVariant]` switch, aggregated across referenced assemblies from the Elarion manifest (the variant analog of `ElarionPermissions`). Per switch it emits an accessor class with the selector `Key` and one `const string` per value (usable in `[AllowedValues(...)]`), plus `VariantDescriptor` data surfaced as `All`/`ByKey`/`ByModule`/`Platform` (variants outside every module — the platform-adapter placement — carry `Module = null`). The host seeds runtime consumers explicitly: `services.AddElarionVariantCatalog(ElarionVariants.All)`, optionally with `AddElarionVariantValidation()` for startup + reload validation. Marker only — no parameters. Subsumed by `[UseElarion]`, or apply it standalone. Diagnostic `ELVAR010` (two selectors/values colliding on the same typed accessor). ```csharp [assembly: GenerateVariantCatalog] ``` See [Feature flags](/docs/concepts/feature-flags). ### `[SettingDefinitions]` and `[Setting]` [#settingdefinitions-and-setting] * **Package:** `Elarion.Abstractions` · **Applies to:** `[SettingDefinitions]` on a top-level `static partial` class; `[Setting("key")]` on a `static partial` get-only property of type `SettingDefinition` inside it * **Triggers:** the settings-definition generator implements each property as a `SettingDefinition` built from the attribute and adds a per-class `All` list; the container is published in the Elarion manifest. Diagnostics `ELSDEF001`–`ELSDEF008` (invalid container or member, invalid key, duplicate key, secret with a default, pinnable without the global scope, invalid default, invalid fallback configuration key). | `[Setting]` parameter | Type | Default | Meaning | | -------------------------- | ----------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `key` | `string` (ctor) | — | The hierarchical key; unique case-insensitively (it doubles as the `IConfiguration` key). | | `Scopes` | `string[]` (init) | `["global"]` | Scope kinds the setting may be accessed in. | | `Secret` | `bool` (init) | `false` | Protected at rest, never described, never projected into `IConfiguration`. Cannot declare a default. | | `Pinnable` | `bool` (init) | `false` | Deployment configuration may pin the value. Requires the global scope. | | `FallbackConfigurationKey` | `string?` (init) | `null` | A deployment-configuration key read below the stored value: stored, else configured there, else the default. Never refuses a write. Requires the global scope. | | `Description` | `string?` (init) | `null` | Text for admin tooling. | | `Default` | `object?` (init) | none | A constant default for scalar settings. | | `DefaultFactory` | `string?` (init) | none | `nameof` a static parameterless method returning the value type (lazy, once). Exclusive with `Default`. | See [Settings](/docs/concepts/settings). ### `[GenerateSettingDefinitionCatalog]` [#generatesettingdefinitioncatalog] * **Package:** `Elarion.Abstractions` · **Applies to:** assembly * **Triggers:** emits `ElarionSettingDefinitions.All`, the declared settings of this assembly plus the public `[SettingDefinitions]` containers of referenced assemblies (from the manifest). The host seeds the runtime catalog with `services.AddElarionSettings(o => o.AddDefinitions(ElarionSettingDefinitions.All))`. Marker only. Subsumed by `[UseElarion]`. ### `[UseElarionEntityFrameworkCore]` [#useelarionentityframeworkcore] * **Package:** `Elarion.EntityFrameworkCore` · **Applies to:** assembly * **Triggers:** declares the target database provider so EF Core generators can emit provider-optimized variants (the EF Core analogue of `[assembly: UseElarion]`). When omitted, generators behave as `Portable` and emit provider-neutral code. | Parameter | Type | Default | Meaning | | ---------- | ----------------------- | ---------------- | ------------------------- | | `Provider` | `EfCoreProvider` (init) | `Portable` (= 0) | Target database provider. | **`EfCoreProvider`:** `Portable` (= 0, provider-neutral code), `Npgsql` (= 1, opts generated keyset seek predicates into PostgreSQL row-value comparisons; requires the Npgsql EF Core provider be referenced). See [Entity Framework](/docs/capabilities/entity-framework). ## Related references [#related-references] The complete compiler-diagnostic catalog, grouped by generator and capability. Feature flags ( `Modules:{Name}:Enabled` ) and other settings keys. Module statics, namespace matching, and naming rules. Which package each attribute ships in. # Configuration (/docs/reference/configuration) This page collects the runtime configuration sections and build properties Elarion reads. Most are optional with sensible defaults. ## Modules [#modules] Feature modules are enabled by default. Disable one by name: ```json { "Modules": { "Clients": { "Enabled": false } } } ``` | Key | Default | Effect | | ------------------------ | ------- | ------------------------------------------------------------------------------------------------------------- | | `Modules:{Name}:Enabled` | `true` | Disables a feature module's handlers, endpoints, JSON metadata, and scheduled jobs. Ignored for core modules. | See [Modules](/docs/concepts/modules). ## Scheduler [#scheduler] Read by `AddElarionScheduler(IConfiguration)`: ```json { "Scheduler": { "Enabled": true, "MaxConcurrentExecutions": 8, "MaxRetainedCompletedJobs": 1024, "MaxMisfireCatchUpRuns": 32 } } ``` | Key | Default | Effect | | ------------------------------------ | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Scheduler:Enabled` | `true` | Master switch for the in-memory scheduler. When `false`, descriptor-declared jobs are not enqueued and the runtime `IJobScheduler` enqueue/schedule APIs throw `InvalidOperationException` (a disabled instance never drains its queue). | | `Scheduler:MaxConcurrentExecutions` | `Environment.ProcessorCount` (at least 1) | Global cap on concurrent job executions. | | `Scheduler:MaxRetainedCompletedJobs` | `1024` | How many terminal job states are kept in memory. | | `Scheduler:MaxMisfireCatchUpRuns` | `32` | Upper bound on catch-up runs for the `CatchUp` misfire policy. | See [Scheduling](/docs/capabilities/scheduling). ## Scheduled job placeholders [#scheduled-job-placeholders] `[ScheduledJob]` string properties (`FixedRate`, `FixedDelay`, `Cron`, `Enabled`, …) support Spring-style configuration placeholders, re-resolved per occurrence: | Placeholder | Behavior | | ----------------------- | -------------------------------------------------------- | | `${Jobs:Interval}` | Resolve the key; throw during resolution if missing. | | `${Jobs:Interval:-15m}` | Resolve the key; fall back to `15m` if missing or blank. | See [Schedules](/docs/capabilities/scheduling/schedules). ## Feature flags [#feature-flags] Declared flags are evaluated through `IFeatureFlagService`. Code-defined flags (`[FeatureFlag]`) are answered by their resolver; the values of backend-evaluated flags (`[BackendFeatureFlag]`) come from the provider package the host wires. ### Batteries-included config-driven flags [#batteries-included-config-driven-flags] `AddElarionFeatureManagement(IConfiguration)` (from `Elarion.FeatureFlags.FeatureManagement`) wires the Microsoft.FeatureManagement OpenFeature provider behind the OpenFeature-backed `IBackendFeatureFlagEvaluator`, so declared backend flags read their values out of the conventional `FeatureManagement` configuration section: ```json { "FeatureManagement": { "BetaCheckout": true, "PricingExperiment": { "Variants": [ { "Name": "control", "ConfigurationValue": "control" }, { "Name": "treatment", "ConfigurationValue": "treatment" } ], "Allocation": { "DefaultWhenEnabled": "control", "Percentile": [ { "Variant": "treatment", "From": 0, "To": 50 }, { "Variant": "control", "From": 50, "To": 100 } ] }, "EnabledFor": [ { "Name": "AlwaysOn" } ] } } } ``` `BetaCheckout` is a boolean gate (drives a `[FeatureGate("BetaCheckout")]`); `PricingExperiment` is a variant flag whose allocated variant selects a `[FeatureVariant("PricingExperiment", Variant = "treatment")]` implementation. | Section | Read by | Effect | | ------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `FeatureManagement` | `AddElarionFeatureManagement(configuration)` | Standard Microsoft.FeatureManagement schema (booleans, filters, variants/allocations) surfaced to `[FeatureGate]`/`[FeatureVariant]`. | ### Bring-your-own provider [#bring-your-own-provider] `AddElarionOpenFeature()` (from `Elarion.FeatureFlags.OpenFeature`) registers the OpenFeature-backed `IBackendFeatureFlagEvaluator` and takes its flag values from whatever OpenFeature provider the host registers separately (`services.AddOpenFeature(b => b.AddProvider(...))` — LaunchDarkly, ConfigCat, flagd, Flagsmith, …), not from an Elarion-owned config section. It maps the explicit `FeatureEvaluationContext` into the OpenFeature `EvaluationContext` off-HTTP (targeting key plus the user id / groups / tenant), so per-user targeting works under JSON-RPC, MCP, and HTTP alike. Configure the provider per its own documentation. See [Feature flags](/docs/capabilities/feature-flags). ## JSON-RPC schema generation (MSBuild) [#json-rpc-schema-generation-msbuild] Properties read by `Elarion.AspNetCore.SchemaGeneration` during build: | Property | Default | Purpose | | ------------------------------------------ | ---------------------------------------------- | ---------------------------------------------------- | | `ElarionJsonRpcGenerateSchema` | `false` | Enables the build-time export targets. | | `ElarionJsonRpcGenerateSchemaOnBuild` | same as above | Controls automatic generation during `dotnet build`. | | `ElarionJsonRpcSchemaOutputPath` | `$(BaseIntermediateOutputPath)rpc-schema.json` | Exact output file path. | | `ElarionJsonRpcSchemaOutputDirectory` | `$(BaseIntermediateOutputPath)` | Output directory (with `…FileName`). | | `ElarionJsonRpcSchemaFileName` | `rpc-schema.json` | Output file name. | | `ElarionJsonRpcSchemaEnvironment` | `Development` | Environment used while loading the app. | | `ElarionJsonRpcSchemaApplicationArguments` | empty | Args passed to the app entry point. | | `ElarionJsonRpcSchemaGenerationOptions` | empty | Extra tool arguments. | See [Schema generation](/docs/capabilities/transports/schema-generation). ## Typst PDF rendering (MSBuild and options) [#typst-pdf-rendering-msbuild-and-options] Properties read by the `Elarion.Typst` build targets: `ElarionTypstBundle`, `ElarionTypstAssetsDirectory`, `ElarionTypstVersion`, `ElarionTypstSha256`, `ElarionTypstExecutable`, and `ElarionTypstCacheDirectory`. Runtime settings are `TypstOptions`, set through `AddElarionTypst(options => …)` (options, not config). Both tables, with defaults, are in [PDF documents](/docs/capabilities/pdf-documents#build-integration). ## Calendars [#calendars] `AddElarionCalendars(configuration)` binds `CalendarOptions` (package `Elarion.Calendars`), conventionally from the `Calendars` section (`CalendarOptions.SectionName`). `ReadDefaults` holds the `CalendarReadOptions` a read uses when it passes none, bound by the configuration-binding source generator; `ExpandDefaults` holds the `CalendarExpandOptions` `CalendarReadResult.Expand` uses, its zone given by id. | Key | Default | | -------------------------------------------------- | ----------------------------------- | | `Calendars:ReadDefaults:MaxBytes` | `16777216` (16 MiB) | | `Calendars:ReadDefaults:MaxComponents` | `50000` | | `Calendars:ReadDefaults:MaxLineBytes` | `4194304` (4 MiB) | | `Calendars:ReadDefaults:MaxPropertiesPerComponent` | `1000` | | `Calendars:ReadDefaults:MaxDepth` | `8` | | `Calendars:ReadDefaults:FallbackEncoding` | `windows-1252` | | `Calendars:ReadDefaults:MaxLines` | `1000000` | | `Calendars:ReadDefaults:MaxItems` | `50000` | | `Calendars:ReadDefaults:MaxTimeZoneIdLength` | `128` | | `Calendars:ReadDefaults:Strict` | `false` | | `Calendars:ExpandDefaults:MaxOccurrences` | `10000` | | `Calendars:ExpandDefaults:MaxIterations` | `100000` | | `Calendars:ExpandDefaults:MaxCandidates` | `1000000` | | `Calendars:ExpandDefaults:ResolveOverrideVersions` | `true` | | `Calendars:ExpandDefaults:SkipCancelled` | `false` | | `Calendars:ExpandDefaults:FloatingTimeZone` | — (floating times stay unconverted) | ## Spreadsheets [#spreadsheets] `AddElarionSpreadsheets(configuration)` binds `SpreadsheetOptions` (package `Elarion.Spreadsheets`), conventionally from the `Spreadsheets` section (`SpreadsheetOptions.SectionName`), with the configuration-binding source generator. Its one member, `ReadDefaults`, holds the `SpreadsheetReadOptions` a read uses when it passes none. | Key | Default | | ---------------------------------------------------- | ------------------------------------------------------------- | | `Spreadsheets:ReadDefaults:MaxUnpackedBytes` | `268435456` (256 MiB) | | `Spreadsheets:ReadDefaults:MaxRows` | `100000` | | `Spreadsheets:ReadDefaults:MaxColumns` | `256` | | `Spreadsheets:ReadDefaults:DateFormats` | — (ISO 8601, `d.M.yyyy` and `d.M.yy` are always read) | | `Spreadsheets:ReadDefaults:TrueWords` / `FalseWords` | — (`true`/`yes`/`x`/`1` and `false`/`no`/`0` are always read) | Write options (`SpreadsheetWriteOptions`) are passed per call, not configured. See [Spreadsheets](/docs/capabilities/spreadsheets#limits-and-options). ## Contacts [#contacts] `AddElarionContacts(configuration)` binds `ContactOptions` (package `Elarion.Contacts`), conventionally from the `Contacts` section (`ContactOptions.SectionName`), with the configuration-binding source generator. Its one member, `ReadDefaults`, holds the `ContactReadOptions` a read uses when it passes none. | Key | Default | | ------------------------------------------------ | -------------------------------------------------------------------------------- | | `Contacts:ReadDefaults:MaxBytes` | `33554432` (32 MiB) | | `Contacts:ReadDefaults:MaxContacts` | `10000` | | `Contacts:ReadDefaults:MaxPropertiesPerContact` | `1000` | | `Contacts:ReadDefaults:MaxProperties` | `1000000` (lines of all cards of a file, each parameter value counting one more) | | `Contacts:ReadDefaults:MaxParametersPerProperty` | `100` (parameter values of one line) | | `Contacts:ReadDefaults:MaxErrors` | `10000` | | `Contacts:ReadDefaults:MaxLineBytes` | `1048576` (1 MiB) | | `Contacts:ReadDefaults:MaxPhotoBytes` | `1048576` (1 MiB) | | `Contacts:ReadDefaults:FallbackEncoding` | `windows-1252` (an unknown name throws when the reader is resolved) | Write options (`ContactWriteOptions`) are passed per call, not configured. See [Contacts](/docs/capabilities/contacts#limits-and-options). ## WebDAV [#webdav] `AddElarionWebDav(configuration)` (and `AddElarionWebDavEntityFrameworkCore(configuration)`, and `AddElarionCalDav`, which calls it) binds `WebDavOptions` (package `Elarion.WebDav`), conventionally from the `WebDav` section (`WebDavOptions.SectionName`), with the configuration-binding source generator. The values are validated when the host starts. | Key | Default | | ------------------------------------ | ------------- | | `WebDav:Prefix` | `/dav` | | `WebDav:MaxBodyBytes` | `1048576` | | `WebDav:MaxXmlDepth` | `32` | | `WebDav:MaxXmlElements` | `10000` | | `WebDav:MaxMultigetHrefs` | `1000` | | `WebDav:JournalRetention` | `90.00:00:00` | | `WebDav:MaxJournalRowsPerCollection` | `10000` | | `WebDav:RefuseWhenNoCollections` | `false` | See [CalDAV](/docs/capabilities/caldav#configuration). ## CalDAV [#caldav] `AddElarionCalDav(configuration)` binds `CalDavOptions` (package `Elarion.CalDav`), conventionally from the `CalDav` section (`CalDavOptions.SectionName`). Calendar data uses `Elarion.Calendars`' own option types, not limits of this package. | Key | Default | | ------------------------------------------------------------------------- | ----------------------------------- | | `CalDav:CalendarRead:MaxBytes` (and the other `CalendarReadOptions` keys) | `16777216` | | `CalDav:CalendarExpand:MaxOccurrences` | `10000` | | `CalDav:CalendarExpand:MaxIterations` | `100000` | | `CalDav:CalendarExpand:MaxCandidates` | `1000000` | | `CalDav:CalendarExpand:ResolveOverrideVersions` | `true` | | `CalDav:CalendarExpand:SkipCancelled` | `false` | | `CalDav:FeedsEnabled` | `true` | | `CalDav:ProductId` | `-//Elarion//Elarion.Calendars//EN` | See [CalDAV](/docs/capabilities/caldav#configuration). ## CardDAV [#carddav] `AddElarionCardDav(configuration)` binds `CardDavOptions` (package `Elarion.CardDav`), conventionally from the `CardDav` section (`CardDavOptions.SectionName`). Contact data uses `Elarion.Contacts`' own option type, not limits of this package; the store, journal and request limits are `WebDav`'s. | Key | Default | | ----------------------------------------------------------------------------------------------------------------- | ---------- | | `CardDav:ContactRead:MaxBytes` (and the other `ContactReadOptions` keys) | `33554432` | | `CardDav:ContactRead:MaxPropertiesPerContact` (also the largest card that can be published, so the largest group) | `1000` | See [CardDAV](/docs/capabilities/carddav#configuration). ## App passwords [#app-passwords] `AddElarionAppPasswords(configuration)` (and `AddElarionAppPasswordsEntityFrameworkCore(configuration)`) binds `AppPasswordOptions` (package `Elarion.AppPasswords`), conventionally from the `AppPasswords` section (`AppPasswordOptions.SectionName`), with the configuration-binding source generator. The values are validated when the host starts. | Key | Default | | ------------------------------ | ---------------------------------------------------------------------------- | | `AppPasswords:SecretPrefix` | `elap_` (up to 32 ASCII letters, digits, `-`, `_`; affects new secrets only) | | `AppPasswords:MaxPerUser` | `10` | | `AppPasswords:LastUseInterval` | `00:15:00` | The scheme's options (`AppPasswordAuthenticationOptions`: `Realm`, `FeedTokenReader`, `Events`) are set in code, not configuration. See [App passwords](/docs/capabilities/app-passwords). ## Proxy identity [#proxy-identity] `AddElarionProxyIdentity(configuration, environment)` binds the `ProxyIdentity` section (package `Elarion.AspNetCore.ProxyIdentity`). Outside Development it refuses to start unless `Enabled` is `true` and the section is complete, or `Fixed:Enabled` is `true` with a `Fixed:Subject`. | Key | Default | | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `ProxyIdentity:Enabled` | `false` | | `ProxyIdentity:Issuer` | — (required when enabled) | | `ProxyIdentity:JwksUrl` / `ProxyIdentity:MetadataAddress` | — (neither: `{Issuer}/.well-known/openid-configuration`) | | `ProxyIdentity:RequireHttpsMetadata` | `true` | | `ProxyIdentity:Audiences` | — (required unless `AllowAnyAudience`) | | `ProxyIdentity:AllowAnyAudience` | `false` | | `ProxyIdentity:TokenHeader` / `ProxyIdentity:TokenCookie` | — (at least one) | | `ProxyIdentity:Claims:{Subject,Email,EmailVerified,Name,Groups,Roles}` | `sub`, `email`, `email_verified`, `name`, `groups`, `roles` | | `ProxyIdentity:EmailTrust` | `Claim` | | `ProxyIdentity:LogoutUrl` | — | | `ProxyIdentity:ClockSkew` | `00:01:00` | | `ProxyIdentity:AutomaticRefreshInterval` | `01:00:00` | | `ProxyIdentity:RefreshInterval` | `00:01:00` | | `ProxyIdentity:LastKnownGoodLifetime` | `00:00:00` (off) | | `ProxyIdentity:Development:*` | `developer` / `developer@example.com`, switch header `X-Elarion-Dev-User`, cookie `elarion-dev-user` | | `ProxyIdentity:Development:{RolesHeader,RolesCookie}` | `X-Elarion-Dev-Roles`, `elarion-dev-roles` | | `ProxyIdentity:Development:{GroupsHeader,GroupsCookie}` | `X-Elarion-Dev-Groups`, `elarion-dev-groups` | | `ProxyIdentity:Fixed:Enabled` | `false` (requires `Enabled: false`; allowed in every environment) | | `ProxyIdentity:Fixed:{Subject,Email,Name,Groups,Roles}` | — (`Subject` required when enabled) | The user switch value `-` (`ProxyIdentityDefaults.DevelopmentSignedOutUser`) signs nobody in for the request; it is reserved, so no stand-in user (`Development:Subject`/`Email`, `Development:Users:*:Subject`/`Email`) may use it. See [Proxy identity](/docs/capabilities/proxy-identity). ## Current user (options, not config) [#current-user-options-not-config] `AddElarionCurrentUser(options => …)` configures claim mapping in code rather than `appsettings`: | Option | Default | | ------------------------------- | ----------------- | | `UserIdClaimType` | `"sub"` | | `EmailClaimType` | `"email"` | | `RoleClaimType` | `ClaimTypes.Role` | | `DefaultRolesWhenAuthenticated` | empty | See [Current user](/docs/capabilities/current-user). ## Authorization messages (options, not config) [#authorization-messages-options-not-config] `AddElarionAuthorization(o => …)` registers `AuthorizationOptions` as a plain singleton; configure it in code: ```csharp builder.Services.AddElarionAuthorization(o => o.ResourceNotFoundMessage = "Not found."); ``` | Option | Default | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `PermissionClaimType` | `"permission"` (`AuthorizationOptions.DefaultPermissionClaimType`) — the claim `[RequirePermission]` reads. `[ResourceFilter].BypassPermission` and `QueryAuthorizers.WhenPermission` cannot read the options and take the claim type themselves; pass the same value when you change it | | `ForbiddenMessageFormat` | `"Access denied."` — `{0}` echoes the unmet requirement when included | | `UnauthorizedMessage` | `"Authentication required."` | | `ResourceNotFoundMessage` | `"The requested resource was not found."` — the answer of `[RequireResource(DenyAs = ResourceDenial.NotFound)]`; keep it identical to your handlers' own not-found message | See [Authorization](/docs/concepts/authorization) and [Resource authorization](/docs/concepts/resource-authorization#hidden-not-forbidden). ## Idempotency purge (options, not config) [#idempotency-purge-options-not-config] `AddElarionIdempotencyEntityFrameworkCore(configure => …)` takes an optional `Action` configured in code rather than `appsettings`. It tunes the background `IdempotencyKeyPurgeService` that reclaims expired keys: | Option | Default | | ----------------- | -------- | | `PollingInterval` | `1 hour` | Complementary to the per-handler `[Idempotent(RetentionHours = …)]`, which sets how long a completed key is retained; `PollingInterval` sets how often the worker sweeps out keys past that retention. See [Idempotency](/docs/concepts/idempotency). ## Outbox (options, not config) [#outbox-options-not-config] `AddElarionOutbox(configure => …)` (from `Elarion.Messaging.Outbox`) takes an optional `Action` configured in code rather than `appsettings`. It tunes the durable integration-event tier and its background `OutboxDeliveryService`: | Option | Default | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `RunDeliveryWorker` | `true` (`false` disables claiming only; publishers still require the complete generated consumer catalog for fan-out/role resolution) | | `PollingInterval` | `1 second` | | `BatchSize` | `100` | | `MaxDeliveryAttempts` | `10` | | `LeaseDuration` | `2 minutes` | | `BaseRetryDelay` | `5 seconds` (exponential backoff base; `Zero` retries on the next poll) | | `MaxRetryDelay` | `1 hour` | | `RetentionPeriod` | `7 days` (`null` keeps delivered rows forever) | | `PurgeInterval` | `1 hour` (how often the worker runs the retention purge) | | `SerializerOptions` | `null` (canonical `IElarionJsonSerialization`) | See [Event backends](/docs/capabilities/events/backends). ## JSON serialization (options, not config) [#json-serialization-options-not-config] Every subsystem shares one canonical `JsonSerializerOptions`, configured in code (not `appsettings`) via `ConfigureElarionJson(Action)`. `AddElarion(configuration)` already contributes every enabled module's source-generated context, so most hosts configure nothing: ```csharp builder.Services.ConfigureElarionJson(o => { o.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower; // default: CamelCase o.TypeInfoResolvers.Add(SomeExtraContext.Default); // an extra source-gen context }); ``` | Option | Default | | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `PropertyNamingPolicy` | `JsonNamingPolicy.CamelCase` | | `PropertyNameCaseInsensitive` | `true` | | `DefaultIgnoreCondition` | `WhenWritingNull` | | `EnableReflectionFallback` | `false` (AOT-strict; a type missing from every source-gen context throws) | | `TypeInfoResolvers` | Transport envelope + module contexts, composed first-match-wins | | `OverrideTypeInfoResolvers` | empty (host-priority resolvers composed ahead of every `TypeInfoResolvers` entry — the way to override a type a transport envelope context also registers) | | `PostConfigure` | none (escape hatch for converters/encoder) | See [Serialization](/docs/capabilities/serialization). ## Unexpected errors (options, not config) [#unexpected-errors-options-not-config] `ConfigureElarionUnexpectedErrors(o => …)` (from `Elarion.Abstractions`) sets the answer JSON-RPC, MCP and generated `[HttpEndpoint]` routes give for an exception that escaped the handler pipeline. Calls accumulate; a later call overrides only the hooks it sets. Both hooks receive an `UnexpectedErrorContext` (`Exception`, `Transport`, `Operation`, the call's scoped `Services`); a hook that throws falls back to the default. | Option | Default | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Message` | `"Internal error"` (`UnexpectedErrorOptions.DefaultMessage`) | | `Reference` | the current trace id (`Activity.Current.TraceId`), or a fresh id when no trace is active; return `null` to send none | | `LeaveToHost` | answer every exception. Generated HTTP routes only: `true` lets the exception reach the host's exception handling (the developer exception page, an `IExceptionHandler`); JSON-RPC and MCP always answer | ```csharp builder.Services.ConfigureElarionUnexpectedErrors(o => o.Message = _ => "Something went wrong. Please contact support and quote the reference."); ``` See [Unexpected errors](/docs/concepts/results-and-errors#unexpected-errors). ## Request validation (options, not config) [#request-validation-options-not-config] `AddElarionValidation(configure => …)` (from `Elarion.Validation`) registers the default `IRequestValidator` over `Microsoft.Extensions.Validation` and takes an optional `Action` configured in code rather than `appsettings`. It also calls `AddElarionJson()`; the generated per-module validation resolvers register themselves through each module's `ConfigureDefaultServices`, so most hosts pass nothing: ```csharp builder.Services.AddElarionValidation(); ``` | Option | Default | | ---------- | ------------------------------------------------------------- | | `MaxDepth` | `32` (cycle protection when walking the request object graph) | See [Validation](/docs/concepts/validation). ## Handler context enrichment (options, not config) [#handler-context-enrichment-options-not-config] Every handler is wrapped in a context-enrichment decorator that is **on by default** — it needs no registration. `AddElarionUserContextEnrichment(configure => …)` (from `Elarion`) takes an optional `Action` configured in code rather than `appsettings`; call it only to narrow the payload, opt into email, or disable the built-in user enricher: ```csharp // on by default — nothing to register; call only to change the defaults builder.Services.AddElarionUserContextEnrichment(o => o.IncludeEmail = true); // opt into user.email (PII) builder.Services.AddElarionUserContextEnrichment(o => o.Enabled = false); // disable the built-in user enricher ``` | Option | Default | | -------------------- | ----------------------------------------------------------------------------------- | | `Enabled` | `true` (the built-in user enricher runs; host-registered enrichers are unaffected) | | `IncludeRoles` | `true` (emit `user.roles` / `UserRoles`) | | `IncludePermissions` | `true` (emit `user.permissions` / `UserPermissions` from the permission claim type) | | `IncludeEmail` | `false` (email is PII — opt in to emit `user.email` / `UserEmail`) | | `MaxItems` | `16` (upper bound on roles/permissions joined into a tag) | Contribute your own trace tags / log-scope items by registering an `IHandlerContextEnricher`: ```csharp builder.Services.AddElarionHandlerContextEnricher(); ``` The log-scope keys only surface if the host enables `IncludeScopes` on its logging exporter. See [Telemetry & observability › User & request context](/docs/capabilities/telemetry#user--request-context). ## Connections (options, not config) [#connections-options-not-config] `AddElarionConnections(options => …)` (from `Elarion.Connections`) takes an optional `Action` configured in code rather than `appsettings` — kernel-wide behavior every connection adapter applies identically (per-endpoint and per-connection knobs stay on the adapters): ```csharp builder.Services.AddElarionConnections(o => o.DefaultInvokeTimeout = TimeSpan.FromSeconds(10)); ``` | Option | Default | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `DefaultInvokeTimeout` | `30 seconds` (applied whenever an `InvokeAsync` call carries no per-call `ClientInvokeOptions.Timeout`; `null` = no default — the call is bounded only by its token) | | `MaxIdentityMetadataEntries` | `32` (adapter-owned identity metadata entries accepted at registration or promotion) | | `MaxIdentityMetadataKeyLength` | `128` (UTF-16 chars per metadata key) | | `MaxIdentityMetadataValueLength` | `1024` (UTF-16 chars per metadata value) | | `MaxPrincipalIdentities` | `16` (identities per connection principal) | | `MaxPrincipalClaims` | `256` (claims across the principal and every actor identity) | | `MaxPrincipalActorDepth` | `16` (actor-identity nesting depth) | The layering is per-call `Timeout` > `DefaultInvokeTimeout` > unbounded; pass `Timeout.InfiniteTimeSpan` per call to make a single invoke unbounded without touching the default. See [Connections](/docs/capabilities/connections). ### TCP endpoints (options, not config) [#tcp-endpoints-options-not-config] Each `AddElarionTcpConnectionListener`/`Dialer` call (and each runtime `Apply…`) configures one endpoint in code via `ElarionTcpListenerOptions`/`ElarionTcpDialerOptions`; per-connection overrides come from the session's `Settings` returning `TcpConnectionSettings`: | Option | Default | | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Framer` | required (`LengthPrefixedTcpFramer`, `DelimitedTcpFramer`, or custom) | | `MaxInboundFrameBytes` | `1 MiB` (total unconsumed wire bytes per inbound frame — prefix/header/body/trailer included) | | `MaxOutboundFrameBytes` | `1 MiB` (total framed wire bytes per outbound message) | | `InitialReadBufferBytes` / `InitialSendBufferBytes` | `8 KiB` / `4 KiB` (send buffer is pooled and trimmed after oversized frames) | | `MaxPendingSends` | `256` (bounded outbound admission — queued plus in-progress; at capacity a send throws `TcpSendQueueFullException`) | | `ShutdownGracePeriod` | `5 seconds` (graceful-close drain window before stragglers are force-aborted; shutdown then awaits every connection task) | | `HandshakeTimeout` | `10 seconds` (framed application authentication deadline) | | `Tls` | `null` (`TcpServerTlsOptions` on listeners / `TcpClientTlsOptions` on dialers; own `HandshakeTimeout` default 10 s; TLS always completes before framing) | | `IdleTimeout` | `null` (arms the codec's `OnIdleAsync`) | | `NoDelay` | `true` | | `Transport` | `"tcp"` (bounded telemetry tag) | | `MaxConcurrentConnections` (listener) | `null` (shed excess accepted sockets at the cap) | | `ReconnectMinDelay` / `ReconnectMaxDelay` (dialer) | `1 s` / `30 s` (jittered exponential backoff) | # Conventions & layout (/docs/reference/conventions) Elarion discovers application code by **namespace containment** and **type conventions** — there is no central registration list. Get the layout right and the generators emit DI registration and transport maps for you, gated per module. This page consolidates every convention the generators rely on and the project dependency rules. When a type is in the wrong namespace or breaks a convention, the result is a **build-time diagnostic** or a **missing generated method** — never a silent runtime failure. See [Diagnostics](/docs/reference/diagnostics) for every id, and [Troubleshooting](/docs/reference/troubleshooting) for the common cases. ## Solution layout [#solution-layout] A conventional Elarion solution separates intent (the application) from platform wiring (the host): ```text title="MyApp.sln" src/ ├─ MyApp.Domain/ # entities, value objects — no framework dependency ├─ MyApp.Application/ # modules, handlers, services ← Elarion + generators ├─ MyApp.Infrastructure/ # concrete database/blob/mail/PDF implementations └─ MyApp.Api/ # ASP.NET Core host ← Elarion.AspNetCore (+ .JsonRpc / .Mcp) ``` A module is a namespace plus an `[AppModule]` marker; everything under that namespace belongs to the module. A common per-module layout: ```text title="MyApp.Application/Modules/Clients/" ClientsModule.cs # [AppModule("Clients")] + optional ConfigureServices / JSON resolver ClientsJsonContext.cs # [JsonSerializable(...)] per request/response type Handlers/ ├─ GetClient.cs # [Handler] IHandler> └─ CreateClient.cs # handler; its Command carries the DataAnnotations constraints Services/ └─ ClientNumberGenerator.cs # [Service] implementation ``` ## Naming & namespace conventions [#naming--namespace-conventions] These rules are load-bearing for the generators in `Elarion.Generators`. | Convention | What the generator does | Source | | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | A type lives **under a module namespace** | Decides which `[AppModule]` owns it via longest-prefix containment, and therefore which gated registration runs. | `ModuleScanner` | | Handlers implement `IHandler` | The request type and the `Result`-unwrapped success type are read straight from the interface. | `HandlerShape` | | Services are annotated with `[Service]` | Registered with contracts inferred from implemented interfaces and the `Scope` lifetime. | `ServiceAttribute` | | Request DTOs carry `DataAnnotations` attributes | The handler generator auto-attaches the `ValidationDecorator`, and the resolver generator emits the module's validation metadata (when `Elarion.Validation` is referenced). | `ValidationAttribute` | | `IHostedService`/`BackgroundService` use `ServiceScope.Singleton` | A scoped/transient hosted service is rejected with `ELSG001`. | `[Service]` | ### Framework API naming [#framework-api-naming] Framework registration and wiring methods follow a single prefix convention: **DI registration methods are named `AddElarionX`** (`AddElarionScheduler`, `AddElarionOutbox`, `AddElarionResilience`, `AddElarionInMemoryEventBus`, …), and **EF Core model-wiring methods are `UseElarionX` / `ApplyElarionX`** (`UseElarionOutbox`, `UseElarionSettings`, `UseElarionBlobStorage`, `UseElarionStagedUploads`, `ApplyElarionIdempotencyKeys`, `ApplyElarionResourceGrants`, `ApplyElarionIdentity`). The model-wiring methods share the same override shape — optional `tableName` (plus `contentTableName` for blobs; Identity takes a `tablePrefix` instead) and `schema` parameters and a `snakeCase` toggle (default `true`) — and each has a `[GenerateElarionX]` attribute counterpart for `[GenerateDbSets]` contexts. ### Module namespace containment (longest prefix) [#module-namespace-containment-longest-prefix] Every generator that groups registrations by module assigns each type to the `[AppModule]` whose namespace is the **longest prefix** of the type's namespace. Containment requires either an exact match or a `.`-delimited prefix (so `MyApp.Billing` does **not** swallow `MyApp.BillingArchive`); a module at the global namespace matches everything. ```text MyApp.Application.Modules.Billing ← [AppModule("Billing")] MyApp.Application.Modules.Billing.Invoices → owned by Billing (prefix match) MyApp.Application.Modules.Reporting → not owned by Billing ``` A `[Handler]`/`[HttpEndpoint]` handler whose namespace falls under **no** module is not dropped — it is mapped ungated and a warning is raised (`ELRPC001` for RPC/MCP, `ELHTTP003` for HTTP). Module-scoped runtime registrations that require an owner (scheduled jobs, event consumers) are instead left unregistered with `ELSG010` / `ELEVT003`. ### Handler request/response shape [#handler-requestresponse-shape] The transport generators resolve a handler's request and response **from its `IHandler` interface** — argument 0 is the request, argument 1 is the response, and the success type is unwrapped from `Result`. Request and response types may be **nested or top-level**; nesting and naming carry no semantic weight. (The older convention of scanning for nested `Command`/`Query`/`Response` members no longer applies.) ```csharp title="A handler with top-level request/response types" public sealed record GetClientQuery(Guid Id) : IQuery; public sealed record ClientResponse(Guid Id, string Name); [Handler("clients.get")] public sealed class GetClient : IHandler> { public ValueTask> HandleAsync(GetClientQuery request, CancellationToken ct) => /* ... */; } ``` A handler annotated with `[Handler]`/`[HttpEndpoint]` that does not implement `IHandler<,>` with a `Result` response generates no endpoint and reports `ELRPC002` / `ELHTTP001`. For HTTP, when no explicit verb is given, the verb is inferred from the request's CQRS marker (`ICommand` → POST, `IQuery` → GET); neither marker present without an explicit verb reports `ELHTTP004`. A `Result` response maps as a [file download](/docs/capabilities/transports/http-endpoints#files-downloads-and-uploads) over HTTP and as the canonical [base64 envelope](/docs/capabilities/transports/json-rpc#file-payloads) over JSON-RPC/MCP. The `[Handler]` operation name is **optional**: `[Handler]` alone is valid. When omitted, the name is inferred by convention as `{module}.{operation}`, where `operation` is the handler type name minus a `Handler`/`Command`/`Query`/`Request` suffix, camelCased (e.g. module `Clients` + `CreateClient` → `clients.createClient`). Supply an explicit name for stable public/wire contracts. ### `[Service]` contract & lifetime resolution [#service-contract--lifetime-resolution] `[Service]` registers a class for DI. Contracts and lifetime resolve as follows: | Aspect | Rule | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | Explicit contracts | `[Service(typeof(IFoo), typeof(IBar))]` registers exactly those types; each must be assignable from the implementation or `ELSG002` is reported. | | Inferred contracts | With no explicit types, the **directly implemented interfaces** are the contracts (base-class interfaces are not treated as explicit). | | No interfaces | With no direct interfaces, the implementation registers **as itself**. | | Multiple contracts | The first contract is the concrete registration; the rest forward to it (one shared instance per scope). | | Lifetime | `Scope` selects the lifetime — `ServiceScope.Scoped` (default), `Singleton`, or `Transient`. | | Hosted services | An `IHostedService`/`BackgroundService` is also registered as `IHostedService` (singleton) and **must** use `Singleton` scope (`ELSG001`). | | Generic implementations | Open-generic `[Service]` classes are unsupported (`ELSG003`). | ```csharp title="Inferred contract, scoped lifetime" [Service] public sealed class ClientNumberGenerator : IClientNumberGenerator { /* registered as IClientNumberGenerator */ } [Service(typeof(IClock), Scope = ServiceScope.Singleton)] public sealed class SystemClock : IClock { /* explicit contract, singleton */ } ``` ### Request validation [#request-validation] There is no validator class convention. Shape constraints are `System.ComponentModel.DataAnnotations` attributes **on the handler's request DTO**; a per-module validation resolver is generated from them (when the compilation references `Elarion.Validation`) and the handler generator auto-attaches the framework `ValidationDecorator`. Business rules live in the handler. See [Validation](/docs/concepts/validation). ## Auto-wiring: `ConfigureDefaultServices` [#auto-wiring-configuredefaultservices] Under `[GenerateModuleBootstrapper]`, a module's discovered **handlers (including stream handlers), services, validation metadata, scheduled jobs, event consumers, and other generated module content** are registered automatically — you do **not** hand-write `Add{Module}…()` calls. * `ModuleDefaultServicesGenerator` emits, per `[AppModule]`, a sibling `static partial class {ModuleType}ElarionModuleServices` with `ConfigureDefaultServices(IServiceCollection)` that calls one `static partial void` hook per category (`AddHandlers`, `AddStreamHandlers`, `AddServices`, `AddVariantServices`, `AddValidators`, `AddScheduledJobs`, `AddEventConsumers`, `AddAuthorizationPolicies`, `AddPermissions`, `AddModuleApi`, `AddActors`, `AddClientEvents`, `AddJsonTypeInfoResolver`). * Each category generator contributes a filler partial implementing its hook; unimplemented hooks elide to no-ops, so a module pays nothing for categories it does not use. * The generated host bootstrapper calls `{Module}.ConfigureDefaultServices(services)` gated by `IsModuleEnabled` (which reads `Modules:{Name}:Enabled`, default `true`), **before** the module's optional hand-written `ConfigureServices`. `ConfigureServices` is therefore reserved for **additional, non-generated** registrations (options binding, third-party libraries, manual decorators) — not for re-declaring the module's own handlers/services. ```csharp title="A module needs no manual Add{Module}… calls" [AppModule("Clients")] public static partial class ClientsModule { // Optional: only for extra, non-generated wiring. public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) => services.Configure(configuration.GetSection("Clients")); public static IJsonTypeInfoResolver GetJsonTypeInfoResolver() => ClientsJsonContext.Default; } ``` `GetJsonTypeInfoResolver()` must be **pure and return a stable instance** — the `.Default` singleton above, or a `static readonly` field built once. The framework invokes it up to twice per host startup (the module's own registration and the bootstrapper's aggregate both contribute it) and collapses duplicates by *reference*, so a body that mints a resolver per call — typically `JsonTypeInfoResolver.Combine(A.Default, B.Default)` — is contributed twice. Hoist such a combination into a `static readonly` field and return that. The convention-based module hooks (`ConfigureServices`, `MapEndpoints`, `GetJsonTypeInfoResolver`, `ConfigureEndpointGroup`) and the core-vs-feature distinction are covered in [Modules](/docs/concepts/modules); the registration mechanics in [Source generation](/docs/concepts/source-generation). The two endpoint hooks may also be declared for a module from outside its assembly with [`[ModuleEndpoints]`](/docs/concepts/modules#declaring-the-hooks-outside-the-module-moduleendpoints) (unknown module name → `ELMOD004`; class without a recognized hook → `ELMOD005`). ## Project dependency rules [#project-dependency-rules] The boundary that matters: **the application declares intent; the host wires platform capabilities.** | Code | Belongs in | | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------- | | Generic handler / result / module / pipeline / RPC primitives | The framework packages (`Elarion`, `Elarion.Abstractions`) | | Feature-module composition and business handlers | Application project | | Concrete database / blob / mail / PDF / external-service implementations | Infrastructure, registered by the host as a platform capability | | Runtime capability providers (`Elarion.Caching`, `Elarion.Resilience`, `Elarion.FeatureFlags.*`) | API host (referenced and wired there) | | Middleware, authentication, telemetry exporters, app lifetime | API host | | Application-specific domain types | Domain / application projects | The **application never references the host or infrastructure**. Application modules may depend only on abstractions — DI, configuration, `IEndpointRouteBuilder`, and `System.Text.Json` metadata. They must **not** depend on the API host, `WebApplicationBuilder`, concrete infrastructure classes, or deployment-specific packages. A module must never call `builder.Build()`, `app.UseAuthentication()`, `app.MapElarionJsonRpc()`, or configure concrete providers — those belong to the host. The same boundary applies to **runtime capability packages**. The `[Cacheable]`/`[CacheInvalidate]`, `[Resilient]`, and `[FeatureGate]`/`[FeatureVariant]` attributes live in `Elarion.Abstractions` (and request validation uses standard `DataAnnotations` attributes), so application modules declare *intent* with attributes alone. The runtime that backs them ships in separate provider packages — `Elarion.Caching` (`AddElarionHandlerCaching()`), `Elarion.Resilience` (`AddElarionResilience()`), and `Elarion.FeatureFlags.OpenFeature` / `Elarion.FeatureFlags.FeatureManagement` (`AddElarionOpenFeature()` / `AddElarionFeatureManagement(configuration)`) — which the **host** references and wires. The application project stays on Abstractions-only attributes (pay-for-what-you-use, [ADR-0017](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0017-dependency-light-core.md)). Request validation is the one deliberate exception: the **application** project references `Elarion.Validation` so the per-module validation resolvers are generated (`ELVAL002` warns otherwise), and the host calls `AddElarionValidation()`. Cross-module references are **location-based**: depend on another module's published `[ModuleContract]` (used sparingly), a platform-capability **port** outside the modules, or the **shared kernel** — never a type placed *inside* another module (an entity, DTO, `[Service]`, handler, or `[EntityConfiguration]`). A shared-kernel entity is shareable because it lives outside every module, not because entities are special. The `ModuleBoundaryAnalyzer` (`ELMOD002`) flags violations. See [Cross-module communication](/docs/concepts/cross-module-communication). Module hooks, core vs. feature modules, and feature-flag gating. How the generators discover types and emit registration code. Every `EL*` diagnostic id, message, and fix. Walkthrough of laying out a new solution. # Diagnostics (/docs/reference/diagnostics) Elarion's source generators and its module-boundary analyzer report problems as compiler diagnostics at build time, so unsupported patterns fail (or warn) deterministically instead of breaking at runtime. Each diagnostic below lists its id, severity, what it means, and how to fix it, grouped by prefix and sorted by id. Looking for help by symptom (a build error message, a missing endpoint, a handler that never runs) rather than by id? Start with [Troubleshooting](/docs/reference/troubleshooting), then come back here for the specific diagnostic. ## ELRPC — JSON-RPC method generation [#elrpc--json-rpc-method-generation] JSON-RPC method emission for `[Handler]` handlers. See [JSON-RPC](/docs/capabilities/transports/json-rpc). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ELRPC001 | Warning | A `[Handler]` handler's namespace is not under any `[AppModule]`; it is registered unconditionally (not gated by a module feature flag). MCP reuses this id since it is built on `[Handler]`. | Move the handler under a module's namespace so its RPC/MCP registration is module-scoped and feature-gated. | | ELRPC002 | Warning | A `[Handler]` handler does not implement `IHandler` with a `Result` response, so no RPC method can be generated. | Make the handler implement `IHandler>` (or the `IHandler` sugar) so the request/response shape is resolvable. | | ELRPC003 | Warning | Two handlers resolve to the same operation name on the shared bus (e.g. an inferred name colliding with another inferred or explicit one); one would silently win at runtime. | Give one handler an explicit `[Handler("...")]` name so every operation name is unique across the bus. | | ELRPC004 | Error | A non-nullable member of a handler's response graph is annotated `[JsonIgnore(Condition = WhenWritingDefault)]` (or `WhenWritingNull` on a non-nullable reference). Non-nullable members are required on the wire, so the serializer must always write them. | Make the member nullable to declare it optional, or remove the ignore condition. | | ELRPC005 | Error | A `[Handler]` responds with `ElarionStreamedFile`, which only HTTP can carry: JSON-RPC, MCP and connections need a payload that serializes. No operation is registered. | Remove `[Handler]` and map the handler with `[HttpEndpoint]` alone, or respond with `ElarionFile` (small files) or a pending blob the client downloads (large files). | | ELRPC006 | Error | A `[RequestPreset]` field is not exported: its name is blank, it is not `static readonly`, it is not declared on a handler class, or its type is not that handler's request type. | Declare the preset as a `static readonly` field of the `[Handler]` class, holding a value of its request type, with a non-blank name. | | ELRPC007 | Error | A handler declares one request-preset name more than once. | Give each `[RequestPreset]` of a handler its own name. | | ELRPC008 | Error | A `[RequestPreset]` belongs to a handler that is not on JSON-RPC, so the preset has no method to belong to. | Expose the handler on JSON-RPC (its `[Handler]` `Transports`), or remove the preset. | | ELRPC009 | Error | A `[ClientConstants]` class exports nothing: it is not a static class, it is generic, it (or a type containing it) is private or protected, or its namespace is not under an `[AppModule]` of its assembly. | Make it a non-generic `static` class, at least `internal`, under a module's namespace. | | ELRPC010 | Error | A public member of a `[ClientConstants]` class cannot be exported: its type is not a number, string, boolean or enum (or an array, `IReadOnlyList`, `IReadOnlyCollection` or `ImmutableArray` of one), or it is mutable (a non-readonly static field, a property with a setter). | Use an exportable type and a `const`, `static readonly` field or get-only property, or make the member non-public so it is not exported. | | ELRPC011 | Error | Two members of one module's `[ClientConstants]` classes export the same (camel-cased) name. | Rename one; a constant name is unique per module. | | ELRPC012 | Warning | A JSON-RPC handler declares more than one static `SortMap` field, so the schema cannot tell which one its sort parameter uses and exports no `sortKeys` for it. | Keep one sort map per handler. | | ELRPC013 | Error | A `[ClientTag("timeout", …)]` value is not a timeout the generated TypeScript client reads, so the client would fall back to its default timeout for the method. Read: digits with an optional fraction, then `ms`, `s` or `m` in any case (a bare number is seconds), spaces or tabs around; above zero and at most 2147483647 ms. | Write a value such as `"1500ms"`, `"30s"` or `"3m"`. | | ELRPC014 | Warning | A command declares `[Writes("x")]`, but no query of the host (its own handlers and every referenced module's) reads `x`, so the declaration invalidates nothing in the generated client — usually a typo. | Fix the spelling, or declare `[Reads("x")]` on the queries that show it. | | ELRPC015 | Warning | A query declares `[Writes]`, or a command `[Reads]`. A query declares what it reads, any other operation what it writes; the other attribute is ignored. | Use `[Reads]` on a query and `[Writes]` on a command. | | ELRPC016 | Info | A `[Handler]`'s request or response type is declared in this assembly, but no `JsonSerializerContext` of the assembly lists it or reaches it through a listed type. Under the AOT-strict default the type has no JSON metadata, so a call over JSON-RPC, MCP or a connection fails at run time. A suggestion by default, because the assembly cannot see which transports its host maps; raise it with `dotnet_diagnostic.ELRPC016.severity = warning` in `.editorconfig`. Not reported in an assembly without a context, for types of other assemblies, or for a handler with `Transports = 0`. | Add `[JsonSerializable(typeof(…))]` for the type to the module's context. | | ELERR001 | Error | A `[ProducesError]` code is not lower-case ASCII letters, digits and underscores in dot-separated segments. | Use a code such as `token.malformed`. | | ELERR002 | Error | One error code is declared more than once on a handler (with its base classes), a decorator, a module or an assembly with a different kind or payload type. | Declare each code once per place; a code has exactly one kind and one payload. A narrower place may declare a code again to override a wider one. | | ELERR003 | Error | A `[RequiresDecision]` declares `Options` that are not an enum with members. | Pass `typeof` an enum whose members are the choices, or omit `Options` for a confirmation. | | ELERR004 | Warning | A handler declares an `IUploadedFiles` code with another payload than the one `IUploadedFiles` answers it with — typically `upload.too_large`, `upload.content_type` or `upload.file_extension` without one — so the schema and the generated client do not type the limit it carries. | Drop the declaration when the request's [`[UploadLimits]`](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member) implies it, or declare the payload: `[ProducesError(ErrorCodes.UploadTooLarge, ErrorKind.Validation, typeof(UploadTooLargeData))]`. | ## ELHTTP — HTTP endpoint generation [#elhttp--http-endpoint-generation] Minimal-API endpoint emission for `[HttpEndpoint]` handlers. See [HTTP endpoints](/docs/capabilities/transports/http-endpoints). | Id | Severity | Meaning | Fix | | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ELHTTP001 | Warning | An `[HttpEndpoint]` handler does not implement `IHandler` with a `Result` response, so no endpoint can be generated. | Make the handler implement `IHandler>` (or the `IHandler` sugar) so the request/response shape is resolvable. | | ELHTTP002 | Warning | Two handlers map the same HTTP verb + route template (for example, the same `GET /x`). | Change one handler's verb or route template so each verb+route pair is unique. | | ELHTTP003 | Warning | An `[HttpEndpoint]` handler's namespace is not under any `[AppModule]`; it is mapped unconditionally (not gated by any module feature flag) so it is never silently dropped. | Move the handler under a module's namespace so its endpoint is module-scoped and feature-gated. | | ELHTTP004 | Warning | An `[HttpEndpoint]` has no explicit verb and its request implements neither `ICommand` (POST) nor `IQuery` (GET), so the verb cannot be inferred. | Specify an explicit verb on `[HttpEndpoint]`, or make the request implement `ICommand` (POST) or `IQuery` (GET). | | ELHTTP005 | Warning | A member of a member-wise-bound request DTO cannot be bound from its wire source (route/query/header/form), so no endpoint is generated. Supported member types are `string`, enums, `IParsable` value types and their nullable forms, arrays of those from the query string, `IFormFile`/`IFormFileCollection`, and one `[FromBody]` member. | Change the member to a supported type, move complex payload data into a `[FromBody]` member, or bind the whole request from the JSON body (POST/PUT/PATCH without `[From*]`/file members). | | ELHTTP006 | Warning | An `[HttpEndpoint]` handler declares a `CustomizeEndpoint` method that is not `public static void CustomizeEndpoint(IEndpointConventionBuilder)`, so the per-endpoint convention hook is ignored. | Match the hook contract exactly: `public static void CustomizeEndpoint(IEndpointConventionBuilder)` — public, static, void, one parameter. | | ELHTTP007 | Error | A handler that responds with `ElarionStreamedFile` is `[Idempotent]` or `[Cacheable]`. A streamed file is written after the pipeline and cannot be stored, so the decorator is not attached. | Remove the attribute, or respond with `ElarionFile` if the response must be stored for a replay. | ## ELMCP — MCP customization [#elmcp--mcp-customization] MCP tool customization for `[McpHandler]`. See [MCP](/docs/capabilities/transports/mcp). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | ELMCP003 | Warning | A handler carries `[McpHandler]` (tool-name customization) but its `[Handler]` `Transports` flag does not include `HandlerTransports.Mcp`, so the customization has no effect. | Remove `[McpHandler]`, or include `HandlerTransports.Mcp` in the handler's `[Handler]` `Transports`. | ## ELEVT — Event consumers [#elevt--event-consumers] Event-consumer discovery for `[ConsumeEvent]`. See [Consuming events](/docs/capabilities/events/consuming-events). | Id | Severity | Meaning | Fix | | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ELEVT001 | Error | A method-form `[ConsumeEvent]` consumer method is declared on a class that is not annotated with `[Service]`. | Declare the consumer method on a `[Service]` class, or use the handler-form consumer instead. | | ELEVT002 | Error | A method-form `[ConsumeEvent]` consumer has an unsupported signature. Event consumers are fan-out subscribers, so it must be an accessible, non-generic, non-static instance method accepting exactly one `IDomainEvent`/`IIntegrationEvent` parameter (optionally `IEventContext` and/or `CancellationToken`) and returning `void`/`Task`/`ValueTask` or the non-generic `Result`/`Task`/`ValueTask`. | Return `void`/`Task`/`ValueTask` or the non-generic `Result` (a fan-out subscriber); a `Result` with a value is request/reply — call a handler by type with `IHandlerSender`/`IHandler` instead. | | ELEVT003 | Warning | A `[ConsumeEvent]` consumer's namespace is not under any `[AppModule]`, so it will not be registered. | Move the consumer under a module's namespace so it is wired by that module. | | ELEVT005 | Error | A class-level `[ConsumeEvent]` is on a type that does not implement exactly one `IHandler` (or `IHandler>`) whose request is an `IDomainEvent`/`IIntegrationEvent`; or it returns a non-`Unit` `Result` (event consumers are fan-out subscribers); or the marker is on a non-handler. | Implement exactly one `IHandler` (response `Result`) whose request is an `IDomainEvent`/`IIntegrationEvent`; for a typed reply use `IHandlerSender`/`IHandler` instead of the event bus. | | ELEVT006 | Error | Multiple `[ConsumeEvent]` declarations produce the same durable consumer identity — a service may have only one consumer method with a given name for an event type, and the identity keys inbox dedup. | Rename or split one of the colliding `[ConsumeEvent]` declarations so each consumer identity is unique. | ## ELACT — Actors [#elact--actors] Actor facade generation for `[Actor]` classes. See [Actors](/docs/concepts/actors). | Id | Severity | Meaning | Fix | | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELACT001 | Error | An `[Actor]` type is static, abstract, generic, or nested, so the facade generator cannot wrap it. | Declare the actor as a non-static, non-abstract, non-generic top-level class. | | ELACT002 | Error | A public method on an `[Actor]` class cannot be exposed through the facade: it is generic, returns something other than `Task`/`Task`/`ValueTask`/`ValueTask`, has `ref`/`out`/`in` or ref-struct parameters, or declares more than one `CancellationToken`. | Make the method a non-generic instance method returning `Task`/`Task`/`ValueTask`/`ValueTask` with plain by-value parameters and at most one `CancellationToken`. | | ELACT003 | Warning | An `[Actor]` class's namespace is not under any `[AppModule]`, so it will not be registered. | Move the actor under a module's namespace so it is wired by that module's `Add{Module}Actors`. | | ELACT004 | Error | An `[Actor]` class declares conflicting keys — multiple `IActorContext` constructor parameters with different key types, or an `[Actor(KeyType = ...)]` that contradicts the context parameter. | Declare a single `IActorContext` constructor parameter (the idiomatic way to make an actor keyed), or make `KeyType` match it. | | ELACT005 | Error | An `[Actor]` class does not have exactly one public constructor, so the generator cannot emit its activator. | Keep one public constructor carrying the activation dependencies (context + services). | | ELACT006 | Warning | `ConfigureAwait(false)` (or a `ConfigureAwaitOptions` value without `ContinueOnCapturedContext`) inside a `[Reentrant]` actor escapes the exclusive scheduler: the rest of the method resumes off the actor's single-threaded context — and only when the await actually suspends, so the escape is latent. | Remove `ConfigureAwait(false)` from the actor's own methods, helpers, and lambdas. Libraries the actor calls may use it internally without harm (context capture is per-method). Non-reentrant actors are exempt — their guarantee comes from the mailbox loop, not a scheduler. | | ELACT008 | Error | A keyed actor's `[ConsumeEvent]` method needs an actor key the generator cannot determine: the event has zero or more than one property assignable to the actor's key type, or the `[ActorKey(...)]` name does not resolve to such a property. | Add `[ActorKey(nameof(TheEvent.KeyProperty))]` naming the event property whose type is assignable to the actor's key type. Singleton actors need no key. See [Actors and events](/docs/concepts/actors/integrations#integration-events). | | ELACT009 | Error | `[ConsumeEvent]` is placed on a non-public `[Actor]` method. The generated relay reaches the actor through its public facade (the same call a hand-written relay makes), so the method must be on the facade. | Make the method `public`. | | ELACT010 | Error | `[ConsumeEvent]` on an `[Actor]` method consumes an `IDomainEvent`. Domain events run inside the emitting command's transaction and scope; an actor runs in its own scope, so awaiting one abandons the same-transaction contract. | Consume an `IIntegrationEvent` instead (publish one to react to a domain change), or call the actor from the command's handler after its transaction commits. | | ELACT012 | Error | An actor stream method (returning `IAsyncEnumerable`, ADR-0052) takes a `CancellationToken` or carries `[ConsumeEvent]`. The turn token is a pooled CTS whose lifetime ends with the attach turn — using it inside the returned stream would observe a recycled token; a relay cannot await a stream. | Drop the `CancellationToken` parameter (the generated facade adds a trailing token that cancels the attach and, linked with the enumerator's token, the stream) and keep `[ConsumeEvent]` on Task-shaped methods. | | ELACT013 | Error | An actor uses `Placement = VirtualShards` without a key. | Add an `IActorContext` constructor parameter or `Actor(KeyType = typeof(TKey))`; virtual-shard placement is only meaningful for keyed actors. | ## ELMOD — Module boundaries [#elmod--module-boundaries] App-module discovery and the `ModuleBoundaryAnalyzer`. See [Modules](/docs/concepts/modules) and [Cross-module communication](/docs/concepts/cross-module-communication). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ELMOD001 | Warning | Two `[AppModule]` types share the same namespace; generated transport handlers in that namespace are associated with the alphabetically first matching module (ambiguous ownership). | Give each module a distinct namespace so handler-to-module association is unambiguous. | | ELMOD002 | Warning | Location-based: a type in one `[AppModule]` depends (via constructor parameter, field, or property) on a type **inside** another module — an entity, DTO, `[Service]`, handler, or `[EntityConfiguration]` — that is not a published `[ModuleContract]`. Everything **outside** every module (the shared kernel and platform ports) is shareable; a shared-kernel entity is exempt because of *where it lives*, not because entities are special. | Reach the other module through its `[ModuleContract]` (used sparingly), a platform-capability port outside the modules, or move shared data/value types to the shared kernel. | | ELMOD003 | Warning | A referenced assembly advertises an Elarion manifest whose schema version this generator does not understand; its manifest entries (modules, HTTP/RPC endpoints, permission-catalog entries) are skipped rather than misparsed. | Rebuild the referenced assembly against a matching Elarion version so its manifest schema aligns with the consuming generator. | | ELMOD004 | Warning | A `[ModuleEndpoints("Name")]` class names a module no discovery produced; its endpoint hooks are skipped (mapping them ungated would defeat the feature gate the attribute reuses). | Fix the module name to match a discovered `[AppModule]`, or reference the assembly that declares the module. | | ELMOD005 | Warning | A `[ModuleEndpoints]` class declares neither a `static MapEndpoints(IEndpointRouteBuilder)` nor a `static ConfigureEndpointGroup(IEndpointRouteBuilder)` hook, so it contributes nothing. | Declare at least one of the two convention hooks (static, exactly one parameter), or remove the attribute. | | ELMOD006 | Error | Two `[AppModule]` declarations share one module name. Module names key generated registration, gating, and hint names, so the duplicate would crash a generator or emit uncompilable code; only the ordinal-first type (by fully-qualified name) is generated. | Rename one of the modules so every `[AppModule]` name is unique across the application. | | ELMOD007 | Warning | An entity has more than one **registered** `[ResourceFilter]`. Each becomes `IQueryAuthorizer`, and a single-service resolve — an injected authorizer, the filter-backed `[RequireResource]` check — gets only one of them, so the rule in force is silently one of its parts. Reported in the host (bootstrapper) compilation, which sees every assembly's filters. | Set `Register = false` on the filters that are building blocks and register the composed authorizer (`QueryAuthorizers.AnyOf`/`AllOf`), or merge the rules into one `[ResourceFilter]`. | | ELMOD008 | Warning | A type in one `[AppModule]` injects (constructor parameter) a `[ModuleContract]` of another **feature** module that its module's `DependsOn` does not name. The contract's implementation is registered with its owner, so it is gone when the owner is disabled, and the consumer fails when it is resolved. A Core module's contract needs no declaration. | Add the owner to `[AppModule(..., DependsOn = "Owner")]` (which also initializes it first), or reach the capability through a platform port outside the modules. | | ELMOD009 | Info | Modules depend on each other through `DependsOn` (a cycle, or a module naming itself), so no dependency orders them. The bootstrapper places them as one unit — after everything any of them depends on, before everything that depends on any of them — and among themselves Core first, then by name; the message names the modules and that order. Reported in the host (bootstrapper) compilation. | Nothing, when each module needs the other (`ELMOD008` is satisfied, and neither may rely on the other initializing first). Otherwise break the cycle: move what both need into a third module, or let one direction react to an event. Raise it with `dotnet_diagnostic.ELMOD009.severity = warning` to keep cycles out. | | ELMOD010 | Warning | A `DependsOn` names a module no `[AppModule]` of the application carries (a typo, or a module the host does not reference). The name orders nothing. Reported in the host (bootstrapper) compilation. | Correct the name, reference the module's assembly from the host, or remove it. | ## ELAUTH — Authorization [#elauth--authorization] Authorization-decorator attachment for `[RequirePermission]`/`[RequireRole]`/`[RequireClaim]`/`[RequirePolicy]`/`[RequireResource]`. See [Authorization](/docs/concepts/authorization). | Id | Severity | Meaning | Fix | | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELAUTH001 | Error | A handler declares an authorization requirement but its response type does not implement `IResultFailureFactory`, so the authorization check cannot short-circuit and would be silently skipped. | Return `Result` or `Result` from the authorized handler so the check can short-circuit to `Unauthorized`/`Forbidden`. | | ELAUTH002 | Error | A handler declares `[RequireResource]` with an `Id` path that does not resolve to a property on the request type. | Point `[RequireResource]` `Id` at an existing property path on the request, e.g. `nameof(Request.Id)` or a dotted path of existing properties. | | ELAUTH003 | Error | A response member marked `[VisibleWith]` is not nullable, so it cannot be hidden from a caller without the permission. | Make the member nullable (`T?`). | | ELAUTH004 | Error | A handler's response holds `[VisibleWith]` members the pipeline cannot hide: the response is not `Result`, or a type on the way is neither a record nor a struct, a rewritten member has no accessible `init`/`set`, a collection on the way is not an array, `List`, `ImmutableArray` or a read-only collection interface, an interface without `[JsonDerivedType]` holds a marked member, or a type is not accessible from the handler's assembly. | Reach marked members through records or structs with `init` members and the supported collections, and answer `Result`. See [Members only some callers see](/docs/concepts/authorization#members-only-some-callers-see). | | ELAUTH005 | Error | A `[VisibleWith]` names no permission (neither a constructor argument nor `AnyOf`), or one the generator cannot read, so it cannot hide the member: an argument that is not a constant, or names a constant another source generator emits into the same compilation other than `ElarionPermissions.Resource.Verb`. | Write each permission as a string constant, as `ElarionPermissions.Resource.Verb`, or as `(resource, verb)`. | | ELAUTH006 | Error | A `[RequireResource]` has an argument the generator cannot read (for example a constant or type another source generator emits into the same compilation), so it cannot bind the check. | Write the resource type, `Operation` and `Id` as literals, `nameof` or constants declared in source. | | ELAUTH007 | Error | A handler declares `[RequirePermissionFor]` with a member path that does not resolve to a public property on the request type. | Name the member with `nameof(Request.Member)` or a dotted path of existing properties. See [Permissions that depend on a request member](/docs/concepts/authorization#permissions-that-depend-on-a-request-member). | | ELAUTH008 | Error | The member a `[RequirePermissionFor]` names is not an enum or a nullable enum. | Type the member as an enum whose members name their resource with `[PermissionResource]`. | | ELAUTH009 | Error | A member of the enum a `[RequirePermissionFor]` reads has no `[PermissionResource]`, so no permission is known for that value. | Add `[PermissionResource("…")]` to every enum member (an alias of an earlier value needs none). | | ELAUTH010 | Error | A `[RequirePermissionFor]` or `[PermissionResource]` has an argument the generator cannot read (for example a constant another source generator emits into the same compilation other than `ElarionPermissions.Resource.Verb` in `AnyOf`), so it cannot bind the check. | Write the member, verb, resources and `AnyOf` permissions as literals, `nameof`, constants declared in source, or `ElarionPermissions.Resource.Verb`. | ## ELPOL — Authorization policies [#elpol--authorization-policies] Named-policy registration for `[AuthorizationPolicy]`. See [Authorization](/docs/concepts/authorization). | Id | Severity | Meaning | Fix | | -------- | -------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | ELPOL001 | Error | `[AuthorizationPolicy]` is applied to a type that does not implement `IAuthorizationPolicy`. | Apply `[AuthorizationPolicy("name")]` only to a class implementing `IAuthorizationPolicy`. | | ELPOL002 | Warning | An `[AuthorizationPolicy]` class's namespace is not under any `[AppModule]`, so it is not auto-registered. | Move the `[AuthorizationPolicy]` class under an `[AppModule]` namespace so it is auto-registered. | ## ELPERM — Permission catalog [#elperm--permission-catalog] Permission-catalog generation for `[GeneratePermissionCatalog]`. See [Authorization](/docs/concepts/authorization). | Id | Severity | Meaning | Fix | | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | | ELPERM001 | Warning | A handler declares authorization requirements but is not under any `[AppModule]` namespace, so they are not added to the runtime permission catalog. | Move the handler under an `[AppModule]` namespace so its `[RequirePermission]`/`[RequireRole]` enter the generated permission catalog. | | ELPERM002 | Warning | Two permissions map to the same generated `ElarionPermissions` typed accessor; the second is omitted from the typed accessors (both remain in `ElarionPermissions.All`). | Rename one permission so the generated typed accessors do not collide. | ## ELAPI — Module API facades [#elapi--module-api-facades] Typed in-process module API generation for `[GenerateModuleApi]` / `[ModuleApi]`. See [Cross-module communication](/docs/concepts/cross-module-communication). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | ELAPI001 | Error | An interface annotated with `[GenerateModuleApi]` is not declared `partial`, so the generated members cannot be emitted into it. | Declare the `[GenerateModuleApi]` interface as `partial`. | | ELAPI002 | Error | A `[GenerateModuleApi]` interface is nested inside another type instead of being declared at namespace scope. | Move the `[GenerateModuleApi]` interface to namespace (top-level) scope. | | ELAPI003 | Warning | A `[GenerateModuleApi]` interface's namespace is not under any `[AppModule]`, so no handlers can be associated and the facade is left empty. | Move the facade interface under a module's namespace so its handlers can be discovered. | | ELAPI004 | Error | A `[GenerateModuleApi]` facade maps more than one handler to the same method name (handlers share a type name); the duplicate handler is skipped. | Rename one of the conflicting handler types, or exclude one via `[ModuleApi(Exclude = true)]`, so each facade method name is unique. | ## ELEFC — Entity configuration [#elefc--entity-configuration] EF Core entity configuration discovery for `[EntityConfiguration]`. See [Entity Framework Core](/docs/capabilities/entity-framework). | Id | Severity | Meaning | Fix | | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | ELEFC001 | Warning | An `[EntityConfiguration]` class implements no `IEntityTypeConfiguration`, so no `DbSet` or configuration is generated for it. | Make the class implement at least one `IEntityTypeConfiguration`, or remove the `[EntityConfiguration]` attribute. | | ELEFC002 | Warning | Two `[EntityConfiguration]` entities share a short type name across namespaces and map to the same `DbSet` property name; the colliding `DbSet` is skipped (the first entity by name wins) to avoid a `CS0102` duplicate member. | Rename one of the entities, or place it in a differently-scoped context so the two never map onto the same context. | ## ELKEY — Keyset pagination [#elkey--keyset-pagination] Keyset-definition generation for `[Keyset]`. See [Pagination](/docs/capabilities/pagination). | Id | Severity | Meaning | Fix | | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | ELKEY001 | Error | A `[Keyset]` declares a column name that does not match any property on the target entity; no keyset is generated. | Correct the keyset column name to match an existing entity property. | | ELKEY002 | Error | A `[Keyset]` column maps to a property whose type is not supported for keyset pagination; no keyset is generated. | Use a supported (comparable) column type for keyset ordering, or remove that column from the keyset. | | ELKEY003 | Error | A `[Keyset]` column maps to a nullable property; keyset columns must be non-nullable for deterministic ordering. No keyset is generated. | Make the keyset column non-nullable, or choose a different non-nullable column for the ordering. | | ELKEY004 | Warning | The target entity has a primary-key property (a `[Key]`-annotated property, or the conventional `Id`/`{EntityType}Id`) that is not part of its `[Keyset]`, so paging order may not be deterministic (no unique tiebreaker). | Append the key (or another unique column) to the keyset so ordering is deterministic and cannot skip or repeat rows. | | ELKEY005 | Error | A `[Keyset]`-annotated class is nested or non-partial; the generator emits the `IKeysetDefinition` implementation into it and requires a non-nested partial class. | Declare the keyset class as a top-level (non-nested) `partial` class. | ## ELSG — Services, scheduled jobs [#elsg--services-scheduled-jobs] Service registration and scheduled-job discovery. See [Services](/docs/concepts/services) and [Scheduling](/docs/capabilities/scheduling). | Id | Severity | Meaning | Fix | | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ELSG001 | Error | A `[Service]` class that is an `IHostedService`/`BackgroundService` is registered with a non-singleton `ServiceScope`. Hosted services must be singletons. | Set the service's scope to `ServiceScope.Singleton` on its `[Service]` attribute. | | ELSG002 | Error | A `[Service]` declares an explicit contract type that the implementation class is not assignable to. | Make the implementation implement/inherit the declared contract, or correct the contract type on the `[Service]` attribute so it matches the implementation. | | ELSG003 | Error | A `[Service]` is declared on a generic (open) class; the generator cannot register an open-generic service. | Make the service a non-generic (closed) class, or register the open generic manually outside the generator. | | ELSG004 | Error | A `[ScheduledJob]` method has an unsupported signature. It must be accessible, non-generic, return `Task`/`ValueTask`, and accept only `IScheduledJobContext` and/or `CancellationToken` parameters. | Make the method accessible and non-generic, return `Task`/`ValueTask`, and take only `IScheduledJobContext` and/or `CancellationToken`. | | ELSG005 | Error | A scheduled-job type is generic or is nested inside a generic type. | Make the job type non-generic and not nested in a generic type. | | ELSG006 | Error | A runtime-schedulable job type does not implement exactly one `IScheduledJob` interface (zero or more than one). | Implement exactly one `IScheduledJob` on the job type. | | ELSG007 | Error | Two or more scheduled jobs declare the same job name. Names must be unique. | Give each scheduled job a unique name. | | ELSG008 | Error | A scheduled job's schedule is invalid: it must declare exactly one of `FixedRate`, `FixedDelay`, `Cron`, or `InitialDelay`-only one-time scheduling, and `InitialDelay`/`RunOnStart` cannot be combined with `Cron`. | Specify exactly one schedule mode, and do not combine `InitialDelay`/`RunOnStart` with `Cron`. | | ELSG009 | Error | A scheduled job's `MaxConcurrentRuns` is negative (must be 0 or greater). | Set `MaxConcurrentRuns` to 0 (unbounded) or a positive integer. | | ELSG010 | Warning | A `[ScheduledJob]` type's namespace is not under any `[AppModule]`; under a module-bootstrapper host it will not be registered. | Move the job under a module's namespace so it is wired by that module's gated registration. | | ELSG011 | Error | A `[Handler(Scope = ServiceScope.Singleton)]` handler has a constructor dependency that is registered scoped or transient — a singleton handler is constructed once from the root provider, so the dependency would be captured for the application lifetime. | Make the dependency singleton or keep the handler scoped. | | ELSG012 | Error | A singleton handler's constructor dependency cannot be verified as singleton at compile time (unknown registration, keyed service, or a `[Service]` contract declared with conflicting scopes). There is deliberately no escape hatch: a captive scoped dependency must be impossible to ship. | Annotate the dependency's implementation with `[Service(Scope = ServiceScope.Singleton)]` in this assembly, or keep the handler scoped. | | ELSG013 | Error | A singleton handler's pipeline attaches a scope-dependent feature — `[Idempotent]` (or the default integration-event inbox), `[Auditable]`, `[Cacheable]`/`[CacheInvalidate]`, an authorization requirement, a `[FeatureGate]`, request validation, a `[VisibleWith]` response member, a feature-variant dependency, or a custom decorator with a per-dispatch dependency (the transaction decorator's `IUnitOfWork` included). These resolve per-dispatch services when the chain is built once from the root provider. | Remove the feature or keep the handler scoped. Singleton handlers pair with singleton dependencies and `[Resilient]` (the resilience runner is a singleton). | | ELSG014 | Error | A `[GenerateContractSetRegistration]` method names a contract that is not an interface or abstract class (or is an open generic). A contract set composes implementations of a contract; a concrete or open-generic type cannot be one. The method is still implemented (empty) so this is the only error you see. | Point the attribute at the seam's interface or abstract base class. | | ELSG015 | Warning | A declared contract set has no implementations in this assembly — usually a typo'd contract or a refactor casualty. The generated method still exists and registers nothing; the registry consuming the set decides whether empty is fatal. | Check the contract type, or remove the declaration if the seam is gone. | | ELSG016 | Error | The same contract is declared by more than one `[GenerateContractSetRegistration]` method in this assembly, which would be ambiguous. The first declaration (by file position) gets the real implementation; later ones are implemented empty. | Keep exactly one contract-set method per contract per assembly. | | ELSG017 | Error | A generic class implements a declared contract-set contract; the generator cannot register an open-generic implementation (mirrors ELSG003). | Make the implementation a non-generic (closed) class, or register it manually. | | ELSG018 | Warning | A contract-set implementation also carries `[Service]` with the same contract among its resolved contracts — it would register twice, once module-gated and once unconditionally. | Pick one mechanism per contract: drop `[Service]` (or pin its explicit contracts elsewhere), or stop composing the contract as a set. | | ELSG019 | Error | A `[GenerateContractSetRegistration]` attribute sits on a method that is not a valid contract-set declaration. The generator fills in a partial method body, so the shape is fixed: `static partial IServiceCollection Name(this IServiceCollection services)` on a non-generic static partial class, with no hand-written implementation part. | Match the required signature — static, partial without an implementation, an extension method taking and returning `IServiceCollection`, non-generic. | | ELSG020 | Warning | A class the container creates (a `[Service]` or a handler) has a constructor parameter whose type is a `[Service]` class registered only under its interfaces, so resolving the constructor fails at run time. | Inject one of the interfaces, or set `[Service(AsSelf = true)]` on the injected class. Suppress it where the class is registered as itself by hand. | ## ELPIPE — Decorator pipelines [#elpipe--decorator-pipelines] Decorator attachment in handler registration. See [Decorator pipelines](/docs/concepts/decorator-pipelines). | Id | Severity | Meaning | Fix | | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELPIPE001 | Error | A decorator declares an `AppliesTo` attachment-predicate method that is not public, so the generated registration cannot call it to decide attachment. | Declare the predicate as `public static bool AppliesTo(HandlerMetadata handler)`. | | ELPIPE002 | Error | A decorator declares an `AppliesTo` method with an unsupported signature (e.g. the older `AppliesTo(System.Type request)`). | Use the one supported form, `public static bool AppliesTo(HandlerMetadata handler)`; for request-based checks use `handler.RequestType`. | | ELPIPE003 | Error | A handler carries `[Resilient]` but consumes a domain event (`request : IDomainEvent`), which is dispatched inline within the publisher's transaction; a Polly retry would re-apply the handler's tracked mutations inside that live transaction. | Remove `[Resilient]` from the domain-event consumer. Integration-event consumers run on a fresh post-commit scope and may be resilient. | | ELPIPE004 | Warning | A handler whose request is an `ICommand` carries `[Resilient]` but not `[Idempotent]`, and the referenced policy is not provably retry-free. A retrying policy can execute the command twice: the resilience decorator wraps the transaction, whose finalizing commit deliberately runs uncancellable — a per-attempt timeout abandons the attempt without waiting for it, the in-flight commit still completes in the background, the timeout exception is not a cancellation so the retry fires, and the command executes and commits again. | Add `[Idempotent]` so a retry replays the first committed outcome instead of re-executing. A timeout-only `[ResiliencePolicy]` declared in the same assembly is recognized and does not warn; suppress the diagnostic if the policy is declared elsewhere and never retries. | ## ELRES — Resilience policies [#elres--resilience-policies] Resilience-policy registration for `[ResiliencePolicy]`. See [Resilience](/docs/capabilities/resilience). The `ELRES001`/`ELRES002` ids are shared by two unrelated analyzers — the resilience-policy analyzer here (category `Elarion.Abstractions.Resilience`) and the EF Core [`[ResourceFilter]` family](#elres--resource-filter-ef-core) below (category `Elarion.EntityFrameworkCore`). Disambiguate by the diagnostic's **category**: only one of the two ever fires for a given declaration. | Id | Severity | Category | Meaning | Fix | | -------- | -------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | ELRES001 | Error | `Elarion.Abstractions.Resilience` | A `[ResiliencePolicy]` is invalid (the message includes the specific reason, for example bad retry/timeout option values). | Correct the resilience policy configuration per the reason in the diagnostic message. | | ELRES002 | Error | `Elarion.Abstractions.Resilience` | Two or more resilience policies declare the same policy name. | Give each resilience policy a unique name. | ## ELRES — Resource filter (EF Core) [#elres--resource-filter-ef-core] Data-level authorization list-filter generation for `[ResourceFilter]`. See [Resource authorization](/docs/concepts/resource-authorization). These EF Core ids share the `ELRES001`/`ELRES002` numbers with the resilience analyzer above but use a distinct category (`Elarion.EntityFrameworkCore`). | Id | Severity | Category | Meaning | Fix | | -------- | -------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | ELRES001 | Error | `Elarion.EntityFrameworkCore` | A `[ResourceFilter]` rule references a property name that does not match any property on the target entity. | Reference an existing entity property in the `[ResourceFilter]` rule. | | ELRES002 | Error | `Elarion.EntityFrameworkCore` | A `[ResourceFilter]` rule references a property whose type is not supported for the generated predicate. | Use a supported property type in the `[ResourceFilter]` rule. | | ELRES003 | Error | `Elarion.EntityFrameworkCore` | A `[ResourceFilter]`-annotated class is nested or non-partial. | Declare the `[ResourceFilter]` class as a top-level `partial` class. | | ELRES004 | Error | `Elarion.EntityFrameworkCore` | A `[ResourceFilter]` declares no rules, so no authorization predicate can be generated. | Add at least one rule (`OwnerProperty`/`TenantProperty`/`Shared`) to the `[ResourceFilter]`. | | ELRES005 | Error | `Elarion.EntityFrameworkCore` | A `[ResourceFilter]` `Shared` rule omits `ResourceTypeName`, which the grants `EXISTS` subquery requires. | Set `ResourceTypeName` on the `[ResourceFilter]` `Shared` rule. | | ELTEN001 | Error | `Elarion.EntityFrameworkCore` | A context is annotated with `[GenerateElarionTenantScoping]` but not `[GenerateDbSets]`, so the model-configuration seam that applies the tenant filter is not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionTenantScoping]`. | ## ELCACHE — Handler caching [#elcache--handler-caching] Handler caching configuration for `[Cacheable]` / `[CacheInvalidate]`. See [Caching](/docs/capabilities/caching). | Id | Severity | Meaning | Fix | | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELCACHE001 | Error | A handler is annotated with both `[Cacheable]` and `[CacheInvalidate]`; these are mutually exclusive. | Apply only one of `[Cacheable]` or `[CacheInvalidate]` to the handler. | | ELCACHE002 | Error | A handler's cache configuration defines no non-empty cache tag (at least one is required). | Define at least one non-empty cache tag on the handler's caching attribute. | | ELCACHE003 | Error | A handler declares a cache tag that fails validation (invalid format/value). | Replace the invalid cache tag with a valid tag value. | | ELCACHE004 | Error | A cacheable handler's cache duration is not positive (must define a positive duration). | Set a positive cache duration on the handler's `[Cacheable]` configuration. | | ELCACHE005 | Error | A handler carries `[Cacheable]` but consumes an event (`request : IDomainEvent`/`IIntegrationEvent`); caching a fan-out consumer's `Result` would silently skip the side effect on a legitimate re-delivery. | Remove `[Cacheable]` from the event consumer. (`[CacheInvalidate]` on a consumer is legitimate — reacting to an event by evicting caches — and is left attached.) | | ELCACHE006 | Error | A request property participating in the cache key has a type with no stable key formatting (it would fall back to `object.ToString()`, colliding across values and risking a cross-request cache leak). | Use a scalar key property (primitive, `string`, `char`, `bool`, `Guid`, enum, `DateTime`/`DateTimeOffset`/`DateOnly`/`TimeOnly`/`TimeSpan`, `decimal`, or a `Nullable` of those), or restrict the key with `[Cacheable(KeyProperties = ...)]`. | | ELCACHE007 | Error | A `[Cacheable(KeyProperties = ...)]` names a property that is not a public instance property on the request type, so it would be silently dropped from the key. | Reference an existing request property, e.g. `nameof(Request.Id)`. | ## ELFEAT — Feature gates [#elfeat--feature-gates] Feature-gate decorator attachment for `[FeatureGate]`. See [Feature flags](/docs/concepts/feature-flags). | Id | Severity | Meaning | Fix | | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | ELFEAT001 | Error | A handler declares a `[FeatureGate]` but its response type does not implement `IResultFailureFactory`, so the gate cannot short-circuit and would be silently skipped. | Return `Result` or `Result` from the gated handler so the gate can short-circuit to `AppError.NotFound`. | | ELFEAT002 | Warning | A handler declares a `[FeatureGate]` with no feature name (or a blank one); the gate has no effect. A gate naming `ElarionFeatureFlags.Names.X` of its own assembly is not blank: the decorator reads the names at run time. | Pass at least one non-blank feature name to `[FeatureGate]`, or remove it. | ## ELFLAG — Feature-flag declarations [#elflag--feature-flag-declarations] Declaration, ownership and wiring of feature flags (ADR-0079). See [Feature flags](/docs/concepts/feature-flags). | Id | Severity | Meaning | Fix | | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | ELFLAG001 | Error | A name used by `[FeatureGate]` or `[FeatureVariant]` is declared by no `[FeatureFlag]`/`[BackendFeatureFlag]` in this assembly or a referenced one. | Declare the flag once under its module, or fix the misspelled name. | | ELFLAG002 | Error | The same flag name is declared more than once — within one assembly or across referenced assemblies (read from the manifest). Neither declaration is registered. | Keep a single declaration; a flag has exactly one owner. | | ELFLAG003 | Error | `[FeatureFlag]` sits on a class that cannot own the flag: it does not implement `IFeatureFlagResolver`, or is abstract, static or generic. | Implement `IFeatureFlagResolver` on a concrete class, or use `[BackendFeatureFlag]` to leave evaluation to the backend. | | ELFLAG004 | Error | A flag is declared outside every `[AppModule]` namespace of its assembly, so no module registers it. | Move the declaration under its module's namespace. | | ELFLAG005 | Error | A flag declaration has a blank name. | Give the flag a non-blank name. | | ELFLAG006 | Warning | Two flag names map to the same `ElarionFeatureFlags` accessor (PascalCase collision); the second is omitted from the typed accessors but stays in `All`. | Rename one flag so the PascalCased accessors differ. | ## ELVAL — Request validation [#elval--request-validation] Validation-decorator attachment for handlers whose request DTO carries DataAnnotations validation attributes, and validation metadata for `[ValidationRoot]` types. See [Validation](/docs/concepts/validation). | Id | Severity | Meaning | Fix | | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELVAL001 | Error | A handler's request type carries validation attributes but its response type does not implement `IResultFailureFactory`, so the validation check cannot short-circuit and would be silently skipped (mirrors `ELAUTH001`). | Return `Result` or `Result` from the handler so the validation decorator can short-circuit to `AppError.Validation`. | | ELVAL002 | Warning | A handler's request type, or a `[ValidationRoot]` type, carries validation attributes but the compilation does not reference `Elarion.Validation`; the constraints are exported to every schema surface but **not enforced** at runtime, and no metadata exists for the root. | Reference `Elarion.Validation` and call `AddElarionValidation()` in the host, or remove the validation attributes — the gap must be a visible choice. | | ELVAL003 | Warning | (.NET 11) A handler's request graph has an `AsyncValidationAttribute` or an `IAsyncValidatableObject`; it is enforced, but in the validation decorator, before the handler's transaction — a lookup there is a time-of-check/time-of-use race. | Move database or service checks into the handler and return `AppError.Validation`/`AppError.Conflict`; suppress `ELVAL003` only when the check reads no shared state. | | ELVAL004 | Error | A `[ValidationRoot]` type carries validation attributes but lies outside the namespace of every module, so no module registers validation metadata for it and it could never be validated. | Move the type into the namespace of the module that validates it. | ## ELREQ — Self-typed request markers [#elreq--self-typed-request-markers] Consistency checks for the self-typed request markers (`IRequest`, `ICommand`, `IQuery`, `IStreamRequest`) that drive inferred dispatch (ADR-0065). Both mistakes compile but would otherwise surface only at runtime — as an invalid cast in the inferred dispatch overloads or as failed handler resolution. See [Command vs. query](/docs/concepts/handlers#self-typed-markers-declaring-the-response-type). | Id | Severity | Meaning | Fix | | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELREQ001 | Error | A type implements a self-typed marker whose `TSelf` names a different, unrelated type (usually a copy-paste slip); inferred dispatch of this request would throw `InvalidCastException`. | Make the marker name the implementing type itself: `record Query(…) : IQuery`. | | ELREQ002 | Warning | A handler pairs a request with a response that differs from the `TResponse` the request's marker declares, so inferred dispatch resolves a different `IHandler<,>` closure and will not find this handler. | Align the marker's `TResponse` with the handler's `Result` (or vice versa). A deliberate second handler with a different response for the same request stays reachable through the explicit-generic overloads; suppress the warning there. | | ELREQ003 | Warning | A stream handler's item type differs from the `TItem` the request's `IStreamRequest` marker declares, so inferred stream dispatch will not find this handler. | Align the marker's `TItem` with the stream handler's item type (or vice versa). | ## ELVAR — Variant services [#elvar--variant-services] Variant-service registration for `[FeatureVariant]` and `[ConfigurationVariant]`. See [Feature flags](/docs/concepts/feature-flags). (`ELVAR002` is intentionally unused.) | Id | Severity | Meaning | Fix | | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELVAR001 | Error | A variant key is declared more than once for the same contract. | Give each implementation of a contract a distinct `Variant`/`Value` (one default plus unique named variants). `[ConfigurationVariant]` values match case-insensitively, so values differing only by case also collide. | | ELVAR003 | Warning | A contract has no default implementation (one declared without a `Variant`/`Value`), so resolution when nothing matches will fail. | Add one implementation with no `Variant`/`Value` set as the default. | | ELVAR004 | Error | A contract is bound to more than one selector; a contract maps to exactly one feature or configuration key. | Use a single feature name (or configuration key) across all variant implementations of a contract. | | ELVAR005 | Warning | A variant service declares a blank feature name. | Pass a non-blank feature name to `[FeatureVariant]`. | | ELVAR006 | Error | A generic variant-service implementation is not supported. | Make the variant `[Service]` implementation non-generic (concrete). | | ELVAR007 | Error | A variant service is not also annotated with `[Service]`; `[FeatureVariant]`/`[ConfigurationVariant]` is a modifier on a service registration (the `[Service]` declares the service and its lifetime). | Add `[Service]` alongside the variant attribute on the implementation class. | | ELVAR008 | Error | A contract is bound by both `[FeatureVariant]` and `[ConfigurationVariant]`; a contract is selected by exactly one axis. | Pick one axis per contract: per-user feature allocation, or a global configuration value. | | ELVAR009 | Warning | A variant service declares a blank configuration key. | Pass a non-blank configuration key to `[ConfigurationVariant]`. | | ELVAR010 | Warning | Two variant selectors or values map to the same `ElarionVariants` accessor name (PascalCase collision); the second is omitted from the typed accessors, while every entry remains in the data surfaces (`All`/`ByKey`/…). | Rename one of the colliding selector keys or values so the PascalCased accessors differ. | | ELVAR011 | Error | A `[FeatureVariant]` or `[ConfigurationVariant]` has an argument the generator cannot read, typically `ElarionFeatureFlags.Names.X` declared in the same assembly (a source generator does not see another generator's output); the variant is not registered. | Write the feature name, configuration key or variant value as a string literal or a constant declared in source. | ## ELRG — Resource grants [#elrg--resource-grants] Resource-grants generation for `[GenerateElarionResourceGrants]`. See [Resource authorization](/docs/concepts/resource-authorization). | Id | Severity | Meaning | Fix | | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | | ELRG001 | Error | A context is annotated with `[GenerateElarionResourceGrants]` but not `[GenerateDbSets]`, so the resource-grants `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionResourceGrants]`. | ## ELID — Identifier minting [#elid--identifier-minting] The `Guid.CreateVersion7()` convention (ADR-0038), enforced by an analyzer rather than left to review. Category `Elarion.Identifiers` — this is about how a `Guid` value is minted, and is unrelated to the user-identity diagnostics below (`ELIDN`). See [Entity identity](/docs/capabilities/entity-framework#entity-identity). | Id | Severity | Meaning | Fix | | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELID001 | Warning | A reference to `Guid.NewGuid()` — called, or passed as a method group such as `AddSingleton>(Guid.NewGuid)` — mints a random v4 id. **Every** site is flagged deliberately: whether a given id becomes a primary key is not decidable at the call site, and a v7's time-ordered prefix keeps b-tree inserts append-mostly where v4 scatters across the index. | Use `Guid.CreateVersion7()`. If the id must be *unpredictable* (a token or capability code — a v7 leaks its creation instant and carries only 74 random bits), keep v4 and suppress `ELID001` at that site with a justification. There is no code fix: the replacement is a one-token edit named in the message. | ## ELIDN — Identity model generation [#elidn--identity-model-generation] Identity-model generation for `[GenerateElarionIdentity]`. See [Identity](/docs/capabilities/identity). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | | ELIDN001 | Error | A context is annotated with `[GenerateElarionIdentity]` but not `[GenerateDbSets]`, so the Identity `DbSet`s and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionIdentity]`. | ## ELIDEM — Idempotency [#elidem--idempotency] Idempotency-decorator attachment for `[Idempotent]`. See [Idempotency](/docs/concepts/idempotency). | Id | Severity | Meaning | Fix | | --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | ELIDEM001 | Error | A handler declares `[Idempotent]` but its response type does not implement `IResultFailureFactory`, so the idempotency decorator cannot synthesize the 400/409/422/replay outcomes and would be silently skipped. | Return `Result` or `Result` from the handler so the idempotency decorator can short-circuit. | | ELIDEM002 | Warning | A handler declares `[Idempotent]` but its request type is not an `ICommand`; idempotency only applies to state-changing commands, so the attribute has no effect. | Make the request implement `ICommand`, or remove `[Idempotent]`. | | ELIDEM003 | Error | A handler's `[Idempotent]` declares a `RetentionHours` outside 1 to 1 000 000 that is not `IdempotentAttribute.Permanent` (a larger value would overflow the expiry). | Set 1 to 1 000 000, or `IdempotentAttribute.Permanent` for a key that never expires. | | ELIDEM004 | Warning | A handler carries both `[Idempotent]` and `[Cacheable]`; caching is for queries, idempotency for commands. | Apply only one of `[Idempotent]` or `[Cacheable]` to the handler. | | ELIDEM005 | Error | `[Idempotent(Operation = …)]` names an empty or blank operation. | Name the shared operation, or remove `Operation` to give the handler its own key space. | | ELIDEM006 | Error | The handlers of one idempotent operation declare a different success type, `Scope` or `Fingerprint`, so a key used with one would replay an answer the other cannot return, or match differently. | Give every handler of the operation the same `Result`, `Scope` and `Fingerprint`. | ## ELINBX — Inbox (idempotent event consumers) [#elinbx--inbox-idempotent-event-consumers] Inbox attachment for handler-form integration-event consumers (on by default; `[AllowDuplicates]` opts out). See [Handling duplicates](/docs/capabilities/events/consuming-events#handling-duplicates). | Id | Severity | Meaning | Fix | | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | ELINBX001 | Warning | A handler declares `[AllowDuplicates]` but its request type is not an `IIntegrationEvent`; only handler-form integration-event consumers have a default-on inbox to opt out of (domain events are exactly-once by atomicity), so the attribute has no effect. | Remove `[AllowDuplicates]`, or make the handler consume an `IIntegrationEvent`. | ## ELPREV — Previewable commands [#elprev--previewable-commands] Preview-decorator attachment for handlers whose request implements `IPreviewableRequest`. See [Previewable commands](/docs/concepts/previewable-commands). | Id | Severity | Meaning | Fix | | --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | ELPREV001 | Error | A handler's request implements `IPreviewableRequest`, but its response is not `Result` with `T : IPreviewOutcome`, so the preview decorator cannot stamp and compare the outcome's fingerprint and the request's `Preview`/`PreviewFingerprint` would be silently ignored. | Return `Result` whose outcome implements `IPreviewOutcome`, or stop implementing `IPreviewableRequest`. | ## ELUPL — Declared upload limits [#elupl--declared-upload-limits] `[UploadLimits]` declarations on handler request members, which the pipeline enforces through `IUploadedFiles`. See [Declaring the limits on the member](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELUPL001 | Error | An `[UploadLimits]` on a handler request member is not enforced: the member holds no `UploadedFile` (nor a collection of them), `MaxBytes` is negative, a content type is blank, a file extension is not a dot followed by a name without white space or path separators (`"xlsx"`, `"."`, `".x ls"`), it declares no limit, or the member's getter is not accessible to the generated pipeline. | Declare it on an `UploadedFile`, `UploadedFile?` or collection member with `MaxBytes > 0`, at least one content type or at least one extension such as `".xlsx"`. See [Declaring the limits on the member](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member). | | ELUPL002 | Error | An `[UploadLimits]` is on a member of a type that is not the request type of a handler in the assembly (a nested DTO, a method parameter), where no pipeline applies it. | Declare the limits on a member of the handler's request type itself. | ## ELIDEMEF — Idempotency keys (EF Core) [#elidemef--idempotency-keys-ef-core] Idempotency-keys generation for `[GenerateElarionIdempotencyKeys]`. See [Idempotency](/docs/concepts/idempotency). | Id | Severity | Meaning | Fix | | ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | ELIDEMEF001 | Error | A context is annotated with `[GenerateElarionIdempotencyKeys]` but not `[GenerateDbSets]`, so the idempotency-keys `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionIdempotencyKeys]`. | ## ELAUD — Audit trail (EF Core) [#elaud--audit-trail-ef-core] Audit-log generation for `[GenerateElarionAuditing]`. See [Audit trail](/docs/concepts/auditing). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | | ELAUD001 | Error | A context is annotated with `[GenerateElarionAuditing]` but not `[GenerateDbSets]`, so the audit-log `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionAuditing]`. | ## ELOBX — Transactional outbox [#elobx--transactional-outbox] Outbox-table generation for `[GenerateElarionOutbox]`. See [Event bus backends](/docs/capabilities/events/backends). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | ELOBX001 | Error | A context is annotated with `[GenerateElarionOutbox]` but not `[GenerateDbSets]`, so the outbox `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionOutbox]`. | ## ELSCH — Scheduler claims (EF Core) [#elsch--scheduler-claims-ef-core] Scheduler-claims generation for `[GenerateElarionSchedulerClaims]`. See [Scheduling](/docs/capabilities/scheduling). | Id | Severity | Meaning | Fix | | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | ELSCH001 | Error | A context is annotated with `[GenerateElarionSchedulerClaims]` but not `[GenerateDbSets]`, so the scheduler-claims `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionSchedulerClaims]`. | ## ELSET — Settings (EF Core) [#elset--settings-ef-core] Settings-table generation for `[GenerateElarionSettings]`. See [Settings](/docs/concepts/settings). | Id | Severity | Meaning | Fix | | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | ELSET001 | Error | A context is annotated with `[GenerateElarionSettings]` but not `[GenerateDbSets]`, so the settings `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionSettings]`. | ## ELBLB — Blob storage and staged uploads (PostgreSQL) [#elblb--blob-storage-and-staged-uploads-postgresql] Blob-table generation for `[GenerateElarionBlobStorage]` and staged-upload-table generation for `[GenerateElarionStagedUploads]`. See [Blob storage](/docs/capabilities/blob-storage) and [Blob uploads](/docs/capabilities/blob-uploads). | Id | Severity | Meaning | Fix | | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | ELBLB001 | Error | A context is annotated with `[GenerateElarionBlobStorage]` but not `[GenerateDbSets]`, so the blob `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionBlobStorage]`. | | ELBLB002 | Error | A context is annotated with `[GenerateElarionStagedUploads]` but not `[GenerateDbSets]`, so the staged-upload `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionStagedUploads]`. | ## ELASN — Actor snapshots (PostgreSQL) [#elasn--actor-snapshots-postgresql] Snapshot-table generation for `[GenerateElarionActorSnapshots]`. See [Actor state and placement](/docs/concepts/actors/state-and-placement#durable-state-with-snapshots). | Id | Severity | Meaning | Fix | | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | ELASN001 | Error | A context is annotated with `[GenerateElarionActorSnapshots]` but not `[GenerateDbSets]`, so the actor-snapshot `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionActorSnapshots]`. | ## ELROLE — Role leases (PostgreSQL) [#elrole--role-leases-postgresql] Role-lease-table generation for `[GenerateElarionRoleLeases]` (ADR-0049). See [Actors — multiple instances and single-homing](/docs/concepts/actors/state-and-placement#multiple-instances-and-single-homing). | Id | Severity | Meaning | Fix | | --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | ELROLE001 | Error | A context is annotated with `[GenerateElarionRoleLeases]` but not `[GenerateDbSets]`, so the role-lease `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionRoleLeases]`. | ## ELAPW — App passwords (EF Core) [#elapw--app-passwords-ef-core] App-password table generation for `[GenerateElarionAppPasswords]` (ADR-0111). See [App passwords](/docs/capabilities/app-passwords). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | ELAPW001 | Error | A context is annotated with `[GenerateElarionAppPasswords]` but not `[GenerateDbSets]`, so the app-password `DbSet` and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionAppPasswords]`. | ## ELDAV — DAV store (EF Core) [#eldav--dav-store-ef-core] Store-table generation for `[GenerateElarionDavStore]` (ADR-0111). See [CalDAV](/docs/capabilities/caldav). | Id | Severity | Meaning | Fix | | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | ELDAV001 | Error | A context is annotated with `[GenerateElarionDavStore]` but not `[GenerateDbSets]`, so the store's `DbSet`s and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionDavStore]`. | ## ELDEV — Device identity (EF Core) [#eldev--device-identity-ef-core] Device-identity-table generation for `[GenerateElarionDeviceIdentity]` (ADR-0054). See [Device identity](/docs/capabilities/devices). | Id | Severity | Meaning | Fix | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | ELDEV001 | Error | A context is annotated with `[GenerateElarionDeviceIdentity]` but not `[GenerateDbSets]`, so the device identity `DbSet`s and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionDeviceIdentity]`. | ## ELWP — Web Push (EF Core) [#elwp--web-push-ef-core] Web Push table generation for `[GenerateElarionWebPush]` (ADR-0076). See [Web Push](/docs/capabilities/web-push). | Id | Severity | Meaning | Fix | | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | ELWP001 | Error | A context is annotated with `[GenerateElarionWebPush]` but not `[GenerateDbSets]`, so the Web Push `DbSet`s and model-configuration seam are not generated. | Add `[GenerateDbSets]` to the context alongside `[GenerateElarionWebPush]`. | ## ELCEV — Client events [#elcev--client-events] Generated client-event topic registration for `IClientEvent` contracts. See [Client events](/docs/capabilities/events/client-events). | Id | Severity | Meaning | Fix | | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | ELCEV001 | Warning | An `IClientEvent` contract's namespace is not under any `[AppModule]`, so no topic is registered for it. | Move the contract under an `[AppModule]` namespace, or register the topic manually via `AddElarionClientEvents`. | | ELCEV002 | Error | Two `IClientEvent` contracts resolve to the same topic name; the colliding topics are withheld. | Rename one contract, or disambiguate with an explicit `[ClientEvent("…")]` name. | | ELCEV003 | Warning | The compilation declares `IClientEvent` contracts but does not reference `Elarion.ClientEvents`, so no topics are registered. | Reference `Elarion.ClientEvents` (and map the endpoint from `Elarion.ClientEvents.AspNetCore`), or remove the contracts. | ## ELSHEET — Spreadsheet records [#elsheet--spreadsheet-records] Mapping generation for `[SpreadsheetRecord]` types (ADR-0108). See [Spreadsheets](/docs/capabilities/spreadsheets). As with `[SqlRecord]`, there is no reflection fallback: if a record builds, it maps. | Id | Severity | Meaning | Fix | | ---------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ELSHEET001 | Error | A property's type is not a supported column type (`string`, `bool`, a number, `DateTime`, `DateTimeOffset`, `DateOnly`, `TimeOnly`, `Guid`, an enum, or their nullable forms). | Change the type, mark the property `[SpreadsheetIgnore]`, or map a text property and convert it in the handler. | | ELSHEET002 | Error | A `[SpreadsheetRecord]` type is not `partial`, so the generated members (`ISpreadsheetRecord.SpreadsheetMapper`, `Columns`) cannot be added. | Add the `partial` modifier. | | ELSHEET003 | Error | Two columns' headers or aliases are equal ignoring case, so a file could not tell them apart. | Give one column another header or alias. | | ELSHEET004 | Error | The worksheet name in `[SpreadsheetRecord]` is empty, longer than 31 characters, contains one of `[ ] : * ? / \`, or starts or ends with an apostrophe. | Choose a name a spreadsheet application accepts. | | ELSHEET005 | Error | `TrueLabel`/`FalseLabel` is set on a property that is not a boolean, or only one of the two is set. | Set both labels, on a `bool` or `bool?` property only. | | ELSHEET006 | Error | `[SpreadsheetRecord]` is on a struct, or on a nested, generic or abstract type. | Use a top-level, non-generic, concrete class or record class. | | ELSHEET007 | Error | The record declares a member named `Columns` or `SpreadsheetMapper`, which collides with a generated member. | Rename the member; its column can keep its header through `[SpreadsheetColumn("…")]`. | | ELSHEET008 | Error | Two members of an enum that a record's column uses have a label (`[Display(Name)]`), name or `[SpreadsheetChoice]` alias that are equal ignoring case; the message names both. | Change the label or remove the alias, so that every spelling names one member. | | ELSHEET009 | Error | `[SpreadsheetColumn(Choices = …)]` is on a property that is not a `string`, names no static field or property of the record or its base types, names one that is not public or internal, or one whose type is not `IReadOnlyList`; or `StrictChoices` is set without `Choices`. The message says which. | Point `Choices` at a static `IReadOnlyList` (such as `string[]`) of the record with `nameof`, on a `string` property; use an enum property for an enum's members. | ## ELSQL — SQL row mapping and interpolation [#elsql--sql-row-mapping-and-interpolation] Mapper generation for `[SqlRecord]` types (ADR-0058) and checks on interpolated SQL statements (ADR-0077). See [SQL mapping](/docs/capabilities/sql-mapping). There is deliberately no runtime fallback behind the mapper errors: an unmapped type has no mapper to call, so every gap surfaces at build time. | Id | Severity | Meaning | Fix | | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | ELSQL001 | Error | A property's type is not a supported SQL column type. | Use a supported primitive, serialize the property as JSON with `[SqlJson]`, or exclude it with `[SqlIgnore]`. | | ELSQL002 | Error | Two properties map to the same column name — a silent last-wins would corrupt reads. | Rename one property or give it a distinct `[SqlColumn("…")]`. | | ELSQL003 | Error | A `required` property is excluded from mapping (`[SqlIgnore]` or non-writable), so the generated mapper could not construct the row. | Map the property or drop `required`. | | ELSQL004 | Error | A `[SqlRecord]` type has no mapped columns. | Add at least one readable, writable property of a supported type. | | ELSQL005 | Error | A `[SqlRecord]` type is nested, generic, or abstract. | Move the row type to a top-level, non-generic, concrete class, record, or struct. | | ELSQL006 | Error | No usable constructor: no accessible parameterless constructor with writable mapped properties, and no constructor whose parameters match mapped columns by name. | Add a parameterless constructor with `set`/`init` properties, or use a positional record. | | ELSQL007 | Error | A property carries `[SqlColumn]`/`[SqlJson]` but has no accessible setter or initializer. | Add `set`/`init`, or remove the mapping attribute (derived members are skipped silently). | | ELSQL010 | Error | A `[SqlRecord]` type is not `partial`, so the self-mapping members (`ISqlRecord.SqlMapper`, `Table`, `Select`) cannot be generated. | Add the `partial` modifier. (The mapper still generates, so the explicit-mapper overloads keep working meanwhile.) | | ELSQL011 | Error | A `[SqlRecord]` type declares a member named `SqlMapper`, `Table`, or `Select`, colliding with a generated self-mapping member. | Rename the member; a mapped column can keep its SQL name via `[SqlColumn("…")]`. | | ELSQL012 | Warning | A collection is interpolated where the SQL expects a single array value — directly inside `ANY(`, `ALL(`, or `SOME(` (any case, optional whitespace), or as an operand of `@>`, `<@`, or `&&`. A collection hole always expands to an `IN` list, so this renders `= ANY((@p0, @p1))`, which the database rejects at run time. Only the literal SQL adjacent to the hole in the same interpolated string is inspected. | Write `IN {collection}` for a list, or bind one array parameter with `{SqlArray.Of(collection)}` (PostgreSQL). | # Reference (/docs/reference) Reference pages are for looking things up while you work — accurate and complete, with no tutorials or opinions. For the reasoning behind the design, see [Why Elarion](/docs/why-elarion); to learn by building, see the [Tutorial](/docs/tutorial). What each Elarion package contains, its dependencies, and when you need it. Every configuration key and MSBuild property Elarion reads, with defaults. The full attribute catalog — parameters, defaults, and what each one triggers. Every `EL*` generator and analyzer diagnostic, what it means, and how to fix it. The naming and namespace conventions the generators depend on, and the dependency rules. `Result`, `AppError`, and `ErrorKind` — and how each kind maps to JSON-RPC and HTTP. Common symptoms when wiring Elarion, their likely cause, and the fix. # Packages (/docs/reference/packages) Elarion is split by capability and dependency boundary. Start with `Elarion`, then add only the providers and adapters the host uses. Generator-only implementation projects are bundled by their public packages and are intentionally absent from this list. ## Core application model [#core-application-model] These packages stay independent of ASP.NET Core, EF Core, and provider infrastructure. | Package | Add it when | | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.Abstractions` | A contract-only assembly needs handlers (including request-driven `IStreamHandler<,>`), results, attributes, seams, canonical JSON, or generation triggers without runtime behavior. | | `Elarion` | An application assembly needs modules, handlers, decorators, scheduling, streams, buffering, current user, rules composed into queries, or source generation. This is the normal starting package and bundles `Elarion.Generators`. | | `Elarion.Validation` | DataAnnotations on requests must be enforced at runtime through `Microsoft.Extensions.Validation`. | | `Elarion.Resilience` | `[Resilient]` handlers or deferred scheduler retries need the Polly-backed default runner. | | `Elarion.Caching` | `[Cacheable]`/`[CacheInvalidate]` need the HybridCache-backed `IHandlerCache`. | | `Elarion.Caching.PostgreSql` | HybridCache needs the recommended PostgreSQL `UNLOGGED` L2 instead of a separate Redis service. | | `Elarion.FeatureFlags.OpenFeature` | `[FeatureGate]`/`[FeatureVariant]` should evaluate through a host-supplied OpenFeature provider. | | `Elarion.FeatureFlags.FeatureManagement` | Feature flags should come directly from configuration through Microsoft.FeatureManagement's OpenFeature provider. | ## Hosting and handler transports [#hosting-and-handler-transports] Protocols remain host-neutral where possible; ASP.NET packages own only their wire/host integration. | Package | Add it when | | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.JsonRpc` | Handlers need the transport-neutral JSON-RPC dispatcher, MCP tool model, envelopes, telemetry, or schema export. | | `Elarion.Grpc` | A custom gRPC host needs typed unary or request-driven server-stream invocation, optional inline mapper delegates, one host-configured principal source, a correctly seeded dispatch scope, and stable startup `AppError` → `RpcException` translation without an ASP.NET dependency. | | `Elarion.Grpc.AspNetCore` | A grpc-dotnet ASP.NET Core host wants `AddGrpc().AddElarion()` plus `ServerCallContext.InvokeElarionAsync`/`InvokeElarionStreamAsync`, with `HttpContext.User` and `RequestServices` adopted automatically. This is the recommended gRPC host package. | | `Elarion.AspNetCore` | An ASP.NET host exposes JSON-RPC, `[HttpEndpoint]`, files, ordered or request-driven SSE streams, current user middleware, or the role-holder proxy. | | `Elarion.AspNetCore.OpenApi` | `[HttpEndpoint]` routes should appear in OpenAPI with canonical schema and idempotency metadata. | | `Elarion.AspNetCore.Mcp` | Handlers should be exposed as an MCP server over Streamable HTTP. This is the only package referencing the MCP SDK. | | `Elarion.AspNetCore.SchemaGeneration` | An ASP.NET build should export `rpc-schema.json` for client generation. | | `Elarion.AspNetCore.Identity` | An ASP.NET host needs Identity registration, EF stores, `ICurrentUser` claims mapping, and the default authorizer. | | `Elarion.AspNetCore.ProxyIdentity` | The app sits behind an authenticating reverse proxy (Cloudflare Access, Google IAP, oauth2-proxy, an OIDC gateway) and must validate the token it forwards in a header or cookie, refuse to start unauthenticated, and run locally with a stand-in identity. See [proxy identity](/docs/capabilities/proxy-identity). | | `Elarion.AppPasswords` | People connect calendar apps or subscribe to feeds with app passwords: `IAppPasswords` issues, lists, revokes and verifies them (only a hash is stored), over the `IAppPasswordStore` seam. NativeAOT-safe. See [app passwords](/docs/capabilities/app-passwords). | | `Elarion.AppPasswords.EntityFrameworkCore` | App passwords need a durable table on the application's `DbContext` (`[GenerateElarionAppPasswords]`). | | `Elarion.AppPasswords.AspNetCore` | Calendar apps authenticate with an app password over HTTP Basic, or a feed token in a feed URL: the `AddElarionAppPasswordAuthentication` scheme and its events, and `AddElarionIdentityAppPasswordPrincipals()`. | See [transport capabilities](/docs/capabilities/transports) and [writing a custom transport](/docs/capabilities/transports/custom-transports). ## Persistence, SQL, and transactions [#persistence-sql-and-transactions] Choose the EF Core tier or the NativeAOT SQL tier per host. EF applications keep authoring EF migrations but run them through the one migration plan (`Elarion.Migrations` + a provider + `Elarion.Migrations.EntityFrameworkCore`); an EF-free AOT host pairs `Elarion.Sql` with the database-neutral `Elarion.Migrations` engine and one provider package that picks the database for both subsystems — `Elarion.Sql.PostgreSql` (`AddElarionPostgreSql`) or `Elarion.Sql.Sqlite` (`AddElarionSqlite`). That single call registers one data source shared by the access tier and migrations; the registrations that follow (`AddElarionSqlUnitOfWork`, `AddElarionMigrations`) name no provider. | Package | Add it when | | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.EntityFrameworkCore` | EF models need generated `DbSet`s, entity configuration application, key conventions, keyset paging support, ambient tenant scoping (`[GenerateElarionTenantScoping]`, `ITenantScoped`), or the opt-in value-shape conventions (`UseElarionEnumStringConversions`, `HasElarionJsonStringArray`, `ElarionValueComparers`). Depends on `Microsoft.EntityFrameworkCore` (provider-neutral) for those conventions and on `Elarion.Abstractions` for the tenancy contracts. | | `Elarion.EntityFrameworkCore.UnitOfWork` | Handler transactions need the EF-backed `IUnitOfWork`, PostgreSQL lock timeout, and savepoints — and the transaction-scoped PostgreSQL row and advisory locks (`LockRowAsync`, `AdvisoryLockAsync`, `TryAdvisoryLockAsync`), and `RunEachInTransactionAsync` for a job that gives each row its own transaction. | | `Elarion.EntityFrameworkCore.LeasedWork` | An application queue table (outbound deliveries, webhook dispatches, a durable retry table) needs workers on several instances to claim rows one at a time: the lease-guarded claim/finalize of ADR-0073, giving up exhausted rows at claim, eligibility-guarded finalizes, batch release on shutdown, projected claims, the partial claim index, and retry backoff helpers, without holding a row lock across the external call. Provider-neutral; brings `Microsoft.EntityFrameworkCore.Relational`. The outbox is built on it. | | `Elarion.Paging` | EF queries need keyset/offset execution, opaque cursors, or sort maps. (`[ResourceFilter]` and `WhereAuthorized` moved to `Elarion.Abstractions`, so data-level authorization no longer pulls this in.) | | `Elarion.EntityFrameworkCore.BulkOperations` | EF code needs provider-neutral streaming `ExecuteInsertAsync` and the bulk provider seam. | | `Elarion.BulkOperations.PostgreSql` | EF bulk inserts should use PostgreSQL binary `COPY` on the context connection. | | `Elarion.Sql` | An EF-free NativeAOT host needs generated row mappers and injection-safe SQL interpolation with no reflection fallback. Also supplies the EF-free `IUnitOfWork` — `AddElarionSqlUnitOfWork()` registers a scoped `ISqlSession` so handler transactions commit atomically without EF. Stays Npgsql-free; `ISqlDatabase` is the application's database handle (the `DbContext`/`IDbContextFactory` counterpart): the scoped session opens from it, and `db.OpenSessionAsync()` serves singleton-eligible handlers. | | `Elarion.Sql.PostgreSql` | The EF-free tier should run on PostgreSQL. The single `AddElarionPostgreSql(connectionString)` picks the provider for **every** subsystem: it registers one central `NpgsqlDataSource` (the shared core, EF Core's `DbContext` analogue), the provider the session opens from, and the PostgreSQL migration engine (session advisory lock, 1–10 nodes) behind the neutral `AddElarionMigrations`. Also ships `UnpooledNpgsqlSession`, a self-owned unpooled connection for session-scoped work and per-test databases that never touches Npgsql's static pool registry. | | `Elarion.Sql.Sqlite` | The EF-free tier should run on a single-node / edge SQLite file. The single `AddElarionSqlite(connectionString)` picks SQLite for **every** subsystem — a `DbDataSource` over `Microsoft.Data.Sqlite` (which ships none) and the provider the session opens from, plus the SQLite migration engine (per-file in-process lock) behind the neutral `AddElarionMigrations`. The full mirror of `Elarion.Sql.PostgreSql`. | | `Elarion.Migrations` | A host needs the one migration plan (ADR-0081): embedded versioned/repeatable SQL scripts and C# `ICodeMigration` steps merged into one version-ordered sequence with one history and one lock, planned and executed roll-forward without a database driver — the provider-neutral `AddElarionMigrations` over a provider registered elsewhere (`Elarion.Sql.PostgreSql`, `Elarion.Sql.Sqlite`). NativeAOT-compatible; EF-free. | | `Elarion.Migrations.EntityFrameworkCore` | An EF host should run its EF migrations through the plan instead of `Database.MigrateAsync()`: each EF migration becomes a version-ordered step beside SQL scripts and code steps (expand → C# backfill → contract in one release), via `o.AddEntityFrameworkMigrations()`. Brings `Microsoft.EntityFrameworkCore.Relational`; not AOT. | | `Elarion.EntityFrameworkCore.Identity` | A persistence layer needs the web-free Identity model on a plain `DbContext`, or the Identity-backed `IPrincipalDirectory` that lets a resource rule list the principals a record is visible to (`AddElarionIdentityPrincipalDirectory`). | | `Elarion.Authorization.EntityFrameworkCore` | `[RequireResource]` should check a record through the entity's `IQueryAuthorizer` (`AddElarionResourceFilterCheck`, no grants table needed), or needs the EF-backed resource-grant store and authorizer (`AddElarionResourceAuthorization`). | | `Elarion.Idempotency.EntityFrameworkCore` | `[Idempotent]` and event inbox claims need durable PostgreSQL-backed storage in the handler transaction. | | `Elarion.Auditing.EntityFrameworkCore` | `[Auditable]` handlers and `[Audited]` entities need a durable audit trail and field-level change capture. | | `Elarion.Scheduling.EntityFrameworkCore` | Recurring occurrences must be claimed once across multiple PostgreSQL-backed instances. | | `Elarion.Coordination.PostgreSql` | A coarse named role needs heartbeat leases, holder address advertisement, and fail-closed election. | ## Events and browser updates [#events-and-browser-updates] | Package | Add it when | | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.Messaging.InMemory` | Integration events may be best-effort and process-local while still dispatching after the EF transaction commits. | | `Elarion.Messaging.Outbox` | Integration events must survive crashes and deliver at least once after the business transaction commits. | | `Elarion.ClientEvents` | Browsers need authorized at-most-once re-query hints, topic registration, subscription lifecycle, and in-process delivery. | | `Elarion.ClientEvents.PostgreSql` | Client-event hints must fan out across roughly 1–10 nodes over PostgreSQL `LISTEN/NOTIFY`. | | `Elarion.ClientEvents.AspNetCore` | Client events should stream to browsers over authorized Server-Sent Events. | | `Elarion.WebPush` | Users should be notified while the app is closed: Web Push (VAPID) delivery to their browsers/PWAs with dead-subscription cleanup, a subscription-store seam, and an in-memory default. | | `Elarion.WebPush.EntityFrameworkCore` | Push subscriptions and the VAPID key pair need durable EF tables (PostgreSQL or SQLite). | | `Elarion.WebPush.AspNetCore` | The browser package's default transport should call `MapElarionWebPush` endpoints rather than application handlers. | See [events and messaging](/docs/capabilities/events) for domain events, integration events, outbox, client events, and ordered streams, and [Web Push](/docs/capabilities/web-push) for notifying users whose app is closed. ## Actors, connections, and devices [#actors-connections-and-devices] Default to request/reply plus client events. Add these packages only when a live state machine, bidirectional connection, or device identity chain is actually the consistency boundary. | Package | Add it when | | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.Actors` | A live in-memory resource, hot ephemeral state, or decide-once coordinator needs a keyed mailbox and generated typed facade. Placement is explicit through `ActorPlacementMode.Local`, `SingleHome`, or fixed `VirtualShards` (ADR-0061). | | `Elarion.Actors.PostgreSql` | Actor snapshots need PostgreSQL durability/query access, single-homed actors need the `"actors"` role binding, or virtual-sharded actors need fixed `actors:partition-N` role leases via `AddElarionPostgreSqlActorSharding()`. | | `Elarion.Connections` | A bidirectional client/device link needs the node-local registry, protocol codec seam, bounded server invocation, and client-event bridge. | | `Elarion.Connections.AspNetCore` | A device/client gateway needs the WebSocket lifecycle adapter with app-owned authentication and codec. | | `Elarion.Connections.Tcp` | A proprietary protocol needs hosted TCP listen/dial, TLS-before-framing, reconnect, framing, bounded outbound delivery, idle handling, or runtime-managed endpoints. | | `Elarion.Connections.Simulation` | Connection tests or developer simulators need in-memory sinks, observers, framed clients, or the socket-free full TCP lifecycle. | | `Elarion.Connections.AspNetCore.Simulation` | WebSocket adapter tests need a real Kestrel upgrade, handshake, codec, and close path via `WebSocketTestHost`. | | `Elarion.Devices` | Device provisioning needs pairing codes, key-store seams, HMAC challenge verification, and the canonical device principal. | | `Elarion.Devices.EntityFrameworkCore` | Device keys and single-use pairing codes need durable EF/PostgreSQL stores. | Read the [actor decision guide](/docs/concepts/actors) before adding the actor packages. ## Blob storage and upload transports [#blob-storage-and-upload-transports] | Package | Add it when | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.Blobs` | Application code needs streaming provider-neutral blob contracts, pending/commit lifecycle, listing, staged upload seams, or the `IUploadedFiles` reader for handlers that take an `UploadedFile`. | | `Elarion.Blobs.PostgreSql` | Blobs and/or resumable upload staging should live in the application's PostgreSQL database. | | `Elarion.Blobs.Azure` | Blobs and staged uploads should use Azure Blob Storage and append blobs. | | `Elarion.Blobs.AspNetCore` | An ASP.NET host needs direct upload/cancel and owner-scoped streaming download endpoints. | | `Elarion.Blobs.Tus` | Large uploads should use the recommended tus 1.0 resumable transport over any staged-upload store. | ## Documents [#documents] | Package | Add it when | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Elarion.Typst` | The application renders PDFs (invoices, quotes, protocols, reports) from its own data with [Typst](/docs/capabilities/pdf-documents): `ITypstCompiler` runs the pinned CLI in one sandboxed workspace per document, with bounded time and concurrency and a self-deleting output stream. Its `buildTransitive` targets bundle the checksum-verified binary into every executable that references it (for that executable's RID) and copy the application's Typst package and fonts (`ElarionTypstAssetsDirectory`). Depends on `Elarion.Abstractions` and `Microsoft.Extensions` packages only; AOT-compatible. | | `Elarion.Spreadsheets` | The application exports lists as `.xlsx` files or fill-in templates, or imports master data from uploaded workbooks, with [spreadsheet records](/docs/capabilities/spreadsheets): `[SpreadsheetRecord]` classes mapped by a bundled generator, `SpreadsheetWorkbook` writing forward-only to a stream, an `ElarionFile` or an `ElarionStreamedFile`, and `SpreadsheetReader` reading `.xlsx`, `.xlsb` and `.xls` into a result with every row, every located problem and the columns the file states, or into plain rows. Depends on `Elarion.Abstractions`, `Microsoft.Extensions` abstractions and Sylvan.Data.Excel (behind an internal interface); AOT-compatible. Validating rows needs `Elarion.Validation`. | | `Elarion.Calendars` | The application imports uploaded `.ics` calendars with a preview or publishes calendars and feeds, with [calendars](/docs/capabilities/calendars): `CalendarReader` reading leniently into events and to-dos with every problem located under a stable `calendar.*` code, a lossless component tree, time-zone resolution, recurrence expansion within a window, and `CalendarWriter` writing deterministically to a stream, an `ElarionFile` or an `ElarionStreamedFile`. Depends on `Elarion.Abstractions` and `Microsoft.Extensions` abstractions only; AOT-compatible. | | `Elarion.WebDav` | The WebDAV core of [CalDAV](/docs/capabilities/caldav) and [CardDAV](/docs/capabilities/carddav), without a wire: the hardened XML reader and writer, the `DavDispatcher` for `OPTIONS`, `PROPFIND`, `REPORT` and `GET` over principals, homes, published collections and their objects, RFC 6578 `sync-collection`, the `IDavCollectionStore` store seam and the `IDavProtocol` seam. Depends on `Elarion.Abstractions` and `Microsoft.Extensions` abstractions only; AOT-compatible. | | `Elarion.WebDav.EntityFrameworkCore` | Published calendars need their durable store and change journal on the application's `DbContext` (`[GenerateElarionDavStore]`), joining its transaction. PostgreSQL. | | `Elarion.WebDav.AspNetCore` | An ASP.NET host serves [CalDAV](/docs/capabilities/caldav#the-host): `MapElarionDav()` maps the DAV route group (only the app-password scheme, dispatch scope seeded with the DAV principal, exempt from cross-origin protection) and `/.well-known/caldav` (and `/.well-known/carddav` with [CardDAV](/docs/capabilities/carddav)). Depends on `Elarion.WebDav` and `Elarion.AspNetCore`. | | `Elarion.CalDav` | People see the application's calendars in iOS, macOS, Thunderbird, DAVx5 or Evolution: [calendar sources](/docs/capabilities/caldav#calendar-sources-who-sees-which-calendar) (`ICalDavSource` handlers deciding who sees which calendar), `ICalDavPublisher` publishing `Elarion.Calendars` objects in the handler's transaction, the calendar properties and reports (`calendar-multiget`, `calendar-query`, `free-busy-query`), ICS feeds behind feed tokens, and `CalDavClient`, which discovers external accounts and syncs their calendars step by step. Depends on `Elarion.WebDav`, `Elarion.Calendars` and `Elarion.AppPasswords`; AOT-compatible. | | `Elarion.CardDav` | People see the application's contacts in iOS, macOS, Thunderbird, DAVx5 or Evolution: [address-book sources](/docs/capabilities/carddav#address-book-sources-who-sees-which-address-book) (`ICardDavSource` handlers deciding who sees which address book), `ICardDavPublisher` publishing `Elarion.Contacts` contacts as vCard 3.0 in the handler's transaction, and the address-book properties and reports (`addressbook-multiget`, `addressbook-query`, vCard 4.0 on request), read-only, on the same store, host and app passwords as CalDAV. Depends on `Elarion.WebDav` and `Elarion.Contacts`; AOT-compatible. | | `Elarion.Contacts` | The application imports address books people upload as `.vcf` files, or hands contacts out as a file phones and mail programs import, with [contacts](/docs/capabilities/contacts): `ContactReader` reads vCard 2.1, 3.0 and 4.0 from any common producer into a fixed `Contact` model over a lossless property list, with every contact kept and every error coded and located, and `ContactWriter` writes vCard 3.0 or 4.0 forward-only to a stream, an `ElarionFile` or an `ElarionStreamedFile`. Depends on `Elarion.Abstractions` and `Microsoft.Extensions` abstractions only; AOT-compatible. | ## Runtime settings [#runtime-settings] | Package | Add it when | | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Elarion.Settings` | Application code needs declared, typed runtime settings resolved through one layered resolver (default, store, configuration pin), plus the in-process default store/change source. | | `Elarion.Settings.EntityFrameworkCore` | Settings need durable relational storage with optimistic concurrency (provider-neutral; PostgreSQL and SQLite are exercised by the test suite). | | `Elarion.Settings.Configuration` | The effective global settings (secrets excluded) should project into `IConfiguration`/`IOptionsMonitor` with live reload. | | `Elarion.Settings.DataProtection` | Secret settings must be encrypted at rest with ASP.NET Core Data Protection (the opt-in `ISettingValueProtector`; secret definitions fail startup without a protector). | | `Elarion.Settings.PostgreSql` | Setting changes must notify every node over PostgreSQL `LISTEN/NOTIFY`. | ## npm packages [#npm-packages] | Package | Add it when | | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `@swimmesberger/elarion-jsonrpc-client-generator` | A TypeScript client should be generated from `rpc-schema.json` with Zod validation and typed client-event subscriptions. | | `@swimmesberger/elarion-contributions` | A frontend needs typed extension points, declarative module contributions, capability gating, action gating from the RPC contract (`canCall` over the generated `rpcMethodInfo`), and optional React/Angular/TanStack Router bindings. | | `@swimmesberger/elarion-webpush` | A browser/PWA should subscribe to Web Push: availability detection (including the iOS Home Screen requirement), gesture-safe permission, subscribe/refresh helpers, and the service-worker handlers. | | `@swimmesberger/elarion-pwa` | The frontend should install as an app: install-prompt capture with iOS instructions, reloading into a new deploy only on a safe page change, renewing an expired authenticating-proxy session, a service-worker shell router (`/sw`) that never caches the API, personal pages, or redirects, and a Vite plugin (`/vite`) publishing the build version. See [Installable apps (PWA)](/docs/capabilities/pwa). | ## Dependency rules [#dependency-rules] * `Elarion.Abstractions` contains implementation-neutral contracts; `Elarion` supplies dependency-light runtime behavior and bundles the core generator (`Elarion.Generators`); provider packages such as `Elarion.EntityFrameworkCore` and `Elarion.Sql` bundle their own generators. * Provider-neutral cores (`Blobs`, `Connections`, `ClientEvents`, settings seams) never depend on a concrete provider or wire adapter. * `Elarion.JsonRpc` has no ASP.NET dependency; `Elarion.AspNetCore` owns HTTP hosting. * EF packages own EF mapping and providers; NativeAOT SQL packages stay EF-free. * Generators emit deterministic code and diagnostics rather than scanning at runtime. Reference `Elarion` directly in every assembly that needs its bundled analyzer; analyzer assets are not transitive. ## Typical references [#typical-references] | Project | Usual starting references | | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Application/module assembly | `Elarion`; optionally `Elarion.Validation` and provider-neutral capability packages | | EF persistence assembly | `Elarion.EntityFrameworkCore` plus the exact EF-backed capability packages it maps | | EF host running migrations | `Elarion.Migrations` + `Elarion.Migrations.EntityFrameworkCore` + `Elarion.Sql.PostgreSql` (or `.Sqlite`) for the plan's connection and lock | | EF-free NativeAOT host (PostgreSQL) | `Elarion.Sql` + `Elarion.Sql.PostgreSql` + `Elarion.Migrations` | | EF-free NativeAOT host (SQLite, single-node / edge) | `Elarion.Sql` + `Elarion.Sql.Sqlite` + `Elarion.Migrations` | | ASP.NET Core host | `Elarion`, `Elarion.JsonRpc`, `Elarion.AspNetCore`; opt in to OpenAPI, MCP, schema generation, Identity, SSE, and blob transports as needed | | Assembly that renders PDF documents | `Elarion.Typst`, with `ElarionTypstAssetsDirectory` pointing at its Typst package and fonts; the executables referencing it get the binary | | Module assembly that exports or imports spreadsheets | `Elarion.Spreadsheets` (its generator is bundled), plus `Elarion.Validation` when the records carry validation attributes | | Module assembly that imports or publishes calendars | `Elarion.Calendars` | | Module assembly that imports or exports contacts | `Elarion.Contacts` | | Frontend | `@swimmesberger/elarion-jsonrpc-client-generator`; optionally `@swimmesberger/elarion-contributions`, `@swimmesberger/elarion-pwa`, and `@swimmesberger/elarion-webpush` | # Result & error model (/docs/reference/result-and-errors) A lookup reference for the result and error types. For the conceptual model and how these flow through handlers and decorators, see [Results & errors](/docs/concepts/results-and-errors). All four core types live in `Elarion.Abstractions`. The two mappers live in the transport packages: `Elarion.JsonRpc.AppErrorMapper` (JSON-RPC) and `Elarion.AspNetCore.HttpAppErrorMapper` (HTTP). ## `Result` [#resultt] `Elarion.Abstractions.Result` — a `readonly struct` wrapping either a success value or an `AppError`. It implements `IResultLike`, `IResultError`, and `IResultFailureFactory>`. ```csharp title="Result" public readonly struct Result : IResultLike, IResultError, IResultFailureFactory> { public bool IsSuccess { get; } public T Value { get; } // valid only when IsSuccess is true public AppError Error { get; } // valid only when IsSuccess is false public static Result Success(T value); public static Result Failure(AppError error); public static implicit operator Result(T value); // success public static implicit operator Result(AppError error); // failure } ``` The implicit conversions let a handler return a response value or an `AppError` directly: ```csharp return new Response(project.Id); // implicit Success return AppError.NotFound($"Project {id} not found"); // implicit Failure ``` ## `Result` (non-generic) [#result-non-generic] `Elarion.Abstractions.Result` — the no-value companion for operations that produce no response, returned by the `IHandler` convenience interface. It converts to `Result` so it never enters the generic dispatch/decorator pipeline. ```csharp title="Result" public readonly struct Result : IResultLike, IResultError, IResultFailureFactory { public bool IsSuccess { get; } public AppError Error { get; } // valid only when IsSuccess is false public static Result Success(); public static Result Failure(AppError error); public static implicit operator Result(AppError error); // failure public Result ToResultUnit(); public static implicit operator Result(Result result); } ``` ## `Unit` [#unit] `Elarion.Abstractions.Results.Unit` — a `readonly struct` with exactly one value, used as the "no value" payload for `Result`. All `Unit` values are equal. ```csharp title="Unit" public readonly struct Unit : IEquatable { public static Unit Value => default; // the single value // == always true, != always false, ToString() => "()" } ``` `Unit` lives in the dedicated `Elarion.Abstractions.Results` namespace — **not** the root `Elarion.Abstractions` namespace that handlers import for `IHandler`/`Result`/`AppError`. `Unit` is a common domain noun (units of measure, org units, rental units), so keeping it out of the always-imported namespace avoids `CS0104` ambiguity with a domain `Unit` type. You rarely name `Unit` directly — prefer the `IHandler` sugar and `Result.Success()`. When you do, add `using Elarion.Abstractions.Results;`, and if a domain `Unit` is also in scope, alias one of them: ```csharp using ResultUnit = Elarion.Abstractions.Results.Unit; // or: using DomainUnit = MyApp.Domain.Unit; ``` ## `IResultLike` [#iresultlike] `Elarion.Abstractions.IResultLike` — the non-generic seam decorators use to inspect success/failure without knowing `T`: ```csharp title="IResultLike" public interface IResultLike { bool IsSuccess { get; } } ``` Both `Result` and `Result` implement it, so a decorator can branch on the outcome. In generic code use `ResultInspection.IsSuccess`, `IsFailure`, and `TryGetError` (for `IResultError`): they inspect the response without boxing a struct result, which an inline `response is IResultLike { … }` pattern does under .NET 11 runtime async: ```csharp if (ResultInspection.IsSuccess(response)) { await transaction.CommitAsync(ct); } else { await transaction.RollbackAsync(ct); } ``` ## `AppError` [#apperror] `Elarion.Abstractions.AppError` — a transport-agnostic `sealed record` describing the *kind* of failure, not how a protocol should report it: ```csharp title="AppError" public sealed record AppError { public required ErrorKind Kind { get; init; } public required string Message { get; init; } public string Code { get; init; } // always present; the kind's default code when none was set public object? Data { get; init; } // typed payload for this Code // Shared singleton for the generic internal-failure case. public static readonly AppError InternalError; // Kind = Internal, Message = "Internal error" } ``` `Code` is the contract clients branch on; `Message` is prose. An error built without a specific code carries its kind's default code (see [Error codes](#error-codes)). ### Factory methods [#factory-methods] Every factory takes the same optional `code` and `data`, so any kind can carry a specific code and a typed payload. | Factory | `Kind` | Notes | | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `AppError.Validation(string message, string? code = null, object? data = null)` | `Validation` | | | `AppError.Validation(string message, IReadOnlyList errors, string? code = null)` | `Validation` | Wraps `errors` in `ValidationErrorData` as `Data`. | | `AppError.Validation(string message, IReadOnlyDictionary fieldErrors, string? code = null)` | `Validation` | Wraps messages keyed by wire-named field path (e.g. `"address.street"`; empty key = not field-specific) in `ValidationErrorData`, deriving the flat `Errors` list by flattening in ordinal key order. | | `AppError.NotFound` / `Conflict` / `Unauthorized` / `Forbidden` / `BusinessRule` / `Internal` `(string message, string? code = null, object? data = null)` | the matching kind | | | `AppError.DecisionRequired(string code, string message, object? data = null)` | `DecisionRequired` | The code is required: it names the decision the handler declares with `[RequiresDecision]`. | | `AppError.Create(ErrorKind kind, string message, string? code = null, object? data = null)` | any | The general factory the others call. | ```csharp AppError.Validation("Invalid command.", new[] { "Name is required.", "Email is invalid." }); AppError.NotFound($"Client {id} was not found."); AppError.Conflict("The seat is taken.", code: "seat.taken", data: new SeatTaken(seatId)); ``` An invalid code throws `ArgumentException` at the call site. Two errors are equal when kind, message, effective code and payload are equal, so an explicit default code equals an omitted one. `ValidationErrorData` is the payload shape for both structured overloads: ```csharp title="ValidationErrorData" public sealed record ValidationErrorData { public required IReadOnlyList Errors { get; init; } // Keyed by wire-named field path per the canonical JSON naming policy (e.g. "address.street", // "deliveries[1].street"); null when the error was built from a flat message list. public IReadOnlyDictionary? FieldErrors { get; init; } } ``` The framework [`ValidationDecorator`](/docs/concepts/validation) produces the field-keyed shape; the HTTP mapper surfaces `FieldErrors` as the RFC 7807 `errors` extension, and the JSON-RPC error carries the whole payload in `error.data.data` under the code `validation`. ## Error codes [#error-codes] `Elarion.Abstractions.ErrorCodes` holds the default code of every `ErrorKind` and the codes the pipeline itself produces. A code is lower-case ASCII letters, digits and underscores in dot-separated segments, never renamed or reused once shipped. | `ErrorKind` | Default code | | ------------------ | -------------------------------------------------------------------------------------------- | | `Validation` | `validation` | | `NotFound` | `not_found` | | `Conflict` | `conflict` | | `Unauthorized` | `unauthorized` | | `Forbidden` | `forbidden` | | `BusinessRule` | `business_rule` | | `DecisionRequired` | `decision_required` (a decision normally carries the code its `[RequiresDecision]` declares) | | `Internal` | `internal` | Pipeline codes: `idempotency.key_required` (`Validation`), `idempotency.in_progress` (`Conflict`), `idempotency.key_reused` (`BusinessRule`), `preview.changed` (`Conflict`, the new outcome as payload) and `preview.unsupported` (`Internal`). Package codes: `paging.sort_key_unknown` (`Validation`, from `SortMap.Validate`), `settings.pinned`, `settings.concurrency_conflict`, and the `IUploadedFiles` codes `upload.not_found`, `upload.too_large` (`UploadTooLargeData`), `upload.content_type` (`UploadContentTypeData`) and `upload.file_extension` (`UploadFileExtensionData`) — `Validation`, returned by the handler that reads an [uploaded file](/docs/capabilities/blob-uploads#passing-an-upload-to-a-handler), and implied by the `[UploadLimits]` its request declares. Every framework answer carries its specific code, so a client never matches the message text. `ErrorCodes.IsValid(code)` checks the format. ## `[ProducesError]` — the declared error contract [#produceserror--the-declared-error-contract] A handler declares the failures it can produce, so the schema export and the generated clients describe them ([ADR-0080](https://github.com/swimmesberger/Elarion/blob/main/docs/decisions/0080-errors-are-a-declared-contract-with-a-stable-code.md)). ```csharp [Handler] [ProducesError("token.malformed", ErrorKind.Validation, typeof(TokenProblem))] // specific code + typed payload [ProducesError(ErrorKind.NotFound)] // kind-default code, no payload public sealed class RedeemToken(...) : IHandler> { ... } ``` | Constructor | Declares | | ----------------------------------------------------------- | -------------------------------------- | | `ProducesError(ErrorKind kind)` | the kind's default code, no payload | | `ProducesError(ErrorKind kind, Type dataType)` | the kind's default code with a payload | | `ProducesError(string code, ErrorKind kind)` | a specific code, no payload | | `ProducesError(string code, ErrorKind kind, Type dataType)` | a specific code with a payload | The generator adds the failures the framework attaches where they are statically knowable and publishes the merged list (sorted by code) with the operation, in the assembly manifest and the `HandlerDispatcher` registration: | Handler has | Implied errors | | ------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | validatable request (with `Elarion.Validation`) | `validation` with `ValidationErrorData` | | `[Require*]` attribute | `unauthorized`, `forbidden` | | `[FeatureGate]` | `not_found` | | `[Idempotent]` | `idempotency.key_required`, `idempotency.in_progress`, `idempotency.key_reused` | | an `IPreviewableRequest` with a `Result`, `T : IPreviewOutcome` | `preview.changed` with `T`, `preview.unsupported` | | a request member with [`[UploadLimits]`](/docs/capabilities/blob-uploads#declaring-the-limits-on-the-member) | `upload.not_found`, and per declared limit `upload.too_large` with `UploadTooLargeData`, `upload.content_type` with `UploadContentTypeData`, `upload.file_extension` with `UploadFileExtensionData` | ### Declaring errors for many operations [#declaring-errors-for-many-operations] A failure that many handlers share does not need an attribute on each of them. `[ProducesError]` also goes on the places that cover a group of operations, and the generator merges those declarations into every operation in scope: | Placed on | Declares the error for | | ------------------------------------------------------- | ----------------------------------------- | | the handler class (or a base class) | that operation | | a decorator in the handler's resolved `[DecoratorList]` | every operation the decorator wraps | | the `[AppModule]` class | every operation in the module | | the assembly (`[assembly: ProducesError(...)]`) | every operation declared in that assembly | ```csharp // Kind-default codes the handlers of this assembly return, declared once. [assembly: ProducesError(ErrorKind.NotFound)] [assembly: ProducesError(ErrorKind.Conflict)] // A failure the decorator adds to every command it wraps, with its payload. [ProducesError("db.constraint", ErrorKind.Conflict, typeof(ConstraintViolation))] public sealed class DbConstraintDecorator(IHandler inner) : IHandler where TRequest : ICommand { ... } ``` * **Precedence.** When several places declare the same code, the one closest to the handler wins: the handler's own declaration, then the framework's implied errors (the table above), then the decorators in pipeline order (outermost first), then the module, then the assembly. A default never changes a code the handler declares itself, so a handler can add a typed payload to a kind-default code the assembly declares. * **Decorators.** The generator resolves the decorator list the same way the pipeline does (handler, then module, then assembly pipeline attribute), and skips a decorator whose generic constraints exclude the handler. An `AppliesTo` predicate is evaluated at runtime, so a conditional decorator's errors are declared for every operation it can wrap. The framework's own decorators (validation, authorization, feature gates, idempotency) are covered by the implied errors. * **Scope.** An assembly declaration covers the operations declared in that assembly only, not the operations of referenced module assemblies. Each assembly publishes its merged contracts in its manifest, so a host sees them without declaring anything again. * **Trade-off.** A default is a promise that an operation *may* fail with that code. An operation in scope that never returns it carries a variant in the schema and the client union that its callers never see. Declare a default on the narrowest scope that fits: the module rather than the assembly, a decorator rather than its handlers. Diagnostics: `ELERR001` (invalid code), `ELERR002` (one code declared twice on the same handler, decorator, module or assembly with different kinds or payloads). Whether a handler *body* returns an undeclared code is not statically knowable, so it is checked at runtime in the Development environment: `IErrorContractMonitor` logs each distinct undeclared code (or kind mismatch) once as a warning. A code that a decorator, module or assembly declares counts as declared and is not reported. `internal` failures and the default `unauthorized`/`forbidden` codes (which authorization defaults can attach without a per-handler attribute) are always admitted. Production does no checking. ## Wire shape [#wire-shape] Every transport carries the code, and the typed payload where the transport has a place for it. | Transport | Code | Typed payload | | --------- | ---------------------------- | ---------------------------------------------------------------------------------------- | | JSON-RPC | `error.data.code` | `error.data.data` (omitted when none) | | HTTP | ProblemDetails member `code` | ProblemDetails member `data` (a validation payload is the standard `errors` map instead) | | gRPC | `elarion-error-code` trailer | not carried (the kind goes in `elarion-error-kind`) | | MCP | structured content `code` | structured content `data` | An exception that escaped the handler pipeline additionally carries its support reference: `error.data.reference` on JSON-RPC, structured content `reference` on MCP, the ProblemDetails member `reference` on HTTP (see [Unexpected errors](/docs/concepts/results-and-errors#unexpected-errors)). ```json title="JSON-RPC error" { "code": -32002, "message": "The seat is taken.", "data": { "code": "seat.taken", "data": { "seat": 4 } } } ``` The numeric JSON-RPC `error.code` stays the coarse kind mapping below. Protocol-level failures carry `parse_error`, `invalid_request`, `method_not_found`, `invalid_params` and `internal`. An `[Idempotent]` replay returns the stored `AppError`, so the code and payload are identical to the original response. The payload is serialized by its runtime type, so it must be registered in a source-generated `JsonSerializerContext`. ### A refused request body [#a-refused-request-body] A body the canonical serializer cannot read as the request type is refused before the handler pipeline runs, after the authentication and permission checks. JSON-RPC answers `-32602` with `data.code` `invalid_params` and, as `data.data`, the refused members in the shape of a failed validation (`ValidationErrorData`): the member path as the `fieldErrors` key, with one of three messages, the constants of `RequestBodyRefusal`. | Message | When | | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `A value is required.` | a member that must be sent is missing | | `Null is not allowed.` | a member was sent as `null` and does not admit it | | `The value is not valid for this member.` | a wrong JSON type, a malformed id or date, an unknown enum name, or an enum value that is no declared member | ```json title="JSON-RPC error" { "code": -32602, "message": "Invalid params: items[1].kind: The value is not valid for this member.", "data": { "code": "invalid_params", "data": { "errors": ["The value is not valid for this member."], "fieldErrors": { "items[1].kind": ["The value is not valid for this member."] } } } } ``` An MCP tool call answers the same message as its error text and the same data. An `[HttpEndpoint]` refuses the same bodies with its problem response, without member names. ## `ErrorKind` [#errorkind] `Elarion.Abstractions.ErrorKind` — the semantic category. The transport layer maps it to protocol-specific codes. | `ErrorKind` | Meaning | | ------------------ | -------------------------------------------------------------------------------------------------------------------------- | | `Validation` | Invalid input or constraint violation. | | `NotFound` | The requested resource does not exist. | | `Conflict` | The operation conflicts with existing state (duplicate, concurrent modification). | | `Unauthorized` | The caller is not authenticated (missing or invalid credentials). | | `Forbidden` | The caller is authenticated but not authorized to perform this operation. | | `BusinessRule` | A domain business rule was violated. | | `DecisionRequired` | The request is valid but needs the caller's decision; the caller answers through `IDecidingRequest.Decisions` and resends. | | `Internal` | An unexpected internal error occurred. | ## `ErrorKind` mappings [#errorkind-mappings] `Kind` is the seam between application semantics and protocol codes. Each host owns its mapping; the tables below are the framework defaults. The unknown/default branch of both mappers falls through to the `Internal` row. ### JSON-RPC error code [#json-rpc-error-code] From `Elarion.JsonRpc.AppErrorMapper.MapToCode(ErrorKind)`. Protocol-level kinds reuse the JSON-RPC 2.0 spec codes; the remaining application kinds use the reserved server range (`-32000` to `-32099`). `AppErrorMapper.ToRpcError(AppError)` wraps the code with the error's `Message` and `{ code, data }`. | `ErrorKind` | JSON-RPC code | Note | | ------------------ | ------------- | ----------------------------- | | `Validation` | `-32602` | Spec "Invalid params". | | `NotFound` | `-32001` | Server range. | | `Conflict` | `-32002` | Server range. | | `Forbidden` | `-32003` | Server range. | | `BusinessRule` | `-32004` | Server range. | | `Unauthorized` | `-32005` | Server range. | | `DecisionRequired` | `-32006` | Server range. | | `Internal` | `-32603` | Spec "Internal error". | | *(default)* | `-32603` | Falls back to internal error. | ### HTTP status code [#http-status-code] From `Elarion.AspNetCore.HttpAppErrorMapper.MapToStatusCode(ErrorKind)`, used by `ElarionHttpResults` when translating a failed `Result` into an RFC 7807 ProblemDetails response. | `ErrorKind` | HTTP status | | ------------------ | --------------------------- | | `Validation` | `400 Bad Request` | | `NotFound` | `404 Not Found` | | `Conflict` | `409 Conflict` | | `Unauthorized` | `401 Unauthorized` | | `Forbidden` | `403 Forbidden` | | `BusinessRule` | `422 Unprocessable Entity` | | `DecisionRequired` | `409 Conflict` | | `Internal` | `500 Internal Server Error` | | *(default)* | `500 Internal Server Error` | The JSON-RPC table is the default applied when an operation is mapped onto the dispatcher (e.g. `dispatcher.Map("x")` or `dispatcher.MapDelegate("x", fn)`). Applications that need different codes supply their own mapping. Why handlers return outcomes as values and how errors stay transport-agnostic. How decorators inspect a Result through IResultLike. # Troubleshooting (/docs/reference/troubleshooting) Most Elarion problems surface at build time as a missing generated method or an analyzer diagnostic rather than a runtime failure. This table maps the common symptoms to fixes. ## Generation and registration [#generation-and-registration] | Symptom | Likely cause | Fix | | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Add{Module}Handlers` is missing | `[assembly: UseElarion]` / `[assembly: GenerateModuleHandlers]` absent, or the generator is not referenced as an analyzer. | Add the trigger attribute and the analyzer project/package reference. | | `Add{Module}Services` is missing | Trigger absent, no `[Service]` classes found in the module namespace, or the analyzer reference is missing. | Add the trigger, annotate service classes with `[Service]`, verify the analyzer reference. | | A handler is not registered | The class does not implement `Elarion.Abstractions.IHandler`, or it is outside the module namespace. | Check the interface namespace and module namespace containment. | | A service is not registered | `[Service]` class is outside the module namespace, the explicit contract is invalid, or no contract could be resolved. | Move it under the module namespace; verify contract resolution. | | Hosted service registration fails a diagnostic | The hosted service uses `Scoped`/`Transient` scope. | Use `Scope = ServiceScope.Singleton`. | | Generic service registration fails a diagnostic | `[Service]` is on a generic type or one nested in a generic type. | Register open generics manually for now. | | Validation attributes are not enforced (`ELVAL002`) | The request DTO carries `DataAnnotations` attributes but the compilation does not reference `Elarion.Validation`, or the host never calls `AddElarionValidation()`. | Reference `Elarion.Validation` from the application project and call `services.AddElarionValidation()` in the host. | | Event consumer never runs (`ELEVT003`) | The `[ConsumeEvent]` consumer's namespace is under no `[AppModule]`, so it is not registered. | Move the consumer under a module's namespace so that module wires it. | | Handler-form consumer fails a diagnostic (`ELEVT005`) | A class-level `[ConsumeEvent]` is not on an `IHandler>` (or `IHandler`) whose request is an event, or the handler returns a non-`Unit` `Result` (event consumers — domain or integration — are fan-out only). | Implement the handler interface with an event request and return `Result` / `Result`; for a typed reply use `IHandlerSender`/`IHandler` instead of the event bus. | | RPC method is missing | The host lacks `[GenerateModuleBootstrapper]`, the handler lacks `[Handler]`, the handler's namespace is under no `[AppModule]`, or the handler does not implement `IHandler>` (`ELRPC002`). | Add the trigger, move the handler under a module, add the marker, and implement the handler interface with a `Result` response. | | Module services do not run | The module is disabled via `Modules:{Name}:Enabled=false`, or `[AppModule]` is missing. | Check configuration and the module attribute. | ## JSON-RPC and schema generation [#json-rpc-and-schema-generation] | Symptom | Likely cause | Fix | | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | Build-time schema generation does not run | `ElarionJsonRpcGenerateSchema` is not `true`, the schema package is not referenced, or `…GenerateSchemaOnBuild` was disabled. | Add the private package reference and set `ElarionJsonRpcGenerateSchema=true`, or invoke `GenerateElarionJsonRpcSchema` manually. | | Schema generation fails after loading the app | Startup code before `builder.Build()` threw, or no frozen `JsonRpcDispatcher` was registered before build. | Register the dispatcher before `builder.Build()` and guard expensive startup work with `JsonRpcSchemaGeneration.IsRunning`. | | Generated frontend RPC types are stale | `rpc-schema.json` was updated but the client generator was not rerun. | Export the schema and re-run the client generator. | | Client generator fails on schema composition | The schema uses unsupported constructs such as `oneOf` or `allOf`, or a file payload inside a union (`anyOf`). | Adjust the exported DTO shape, or extend the generator deliberately. C# unions themselves (`anyOf`) are supported. | | A union request fails with "JSON value type 'Object' is ambiguous for union type" | System.Text.Json picks a union case by JSON token kind only, and two cases are objects. | Add `[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]` to the union and give each object case a property the others lack. | ## Persistence and serialization [#persistence-and-serialization] | Symptom | Likely cause | Fix | | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Handler writes are not rolled back on failure; a warning says the in-memory (no-op) `IUnitOfWork` is in use | No durable unit of work is registered, so the transaction decorator falls back to the no-op default. | Reference `Elarion.EntityFrameworkCore.UnitOfWork` and call `services.AddElarionUnitOfWork()` (EF-free hosts: `AddElarionSqlUnitOfWork()`). | | `System.Text.Json` cannot serialize a DTO under AOT | The type is missing from a module JSON context. | Add `[JsonSerializable(typeof(…))]` to the relevant module context. | | `DbSet` is missing for an entity | The entity has no `[EntityConfiguration]` (no `IEntityTypeConfiguration` marked with `[EntityConfiguration]`), or its config's scope does not intersect the `[GenerateDbSets("scope")]` context. | Add an `[EntityConfiguration]` for the entity with a matching scope. | | A newly added same-assembly `[EntityConfiguration]` produces no `DbSet` until the IDE is restarted | Not a generator bug — `dotnet build` and the CLI always reflect current source. Rider/ReSharper's source-generator host refreshes generated code lazily and can lag when a **new** `[EntityConfiguration]` is added in the **same assembly** as the `[GenerateDbSets]` context. (A configuration in a *referenced* assembly never looks stale because it only becomes available after you build the producing project, and that build refreshes the host.) | Build the project, or **File → Invalidate Caches / Restart**, to refresh the IDE host; the generated `DbSet` is correct once the host re-runs. | | `DbUpdateConcurrencyException` when replacing a tracked parent's children (`Children.Clear()` + `Add(new … { Id = … })`) — but only on a real database | EF's insert-vs-update heuristic misreads a set id on a key the model claims *generated* and issues an `UPDATE` for a row that was never inserted; the InMemory provider skips the affected-rows check, so tests stay green. On `[GenerateDbSets]` contexts the generated model already declares domain Guid PKs client-assigned, so this points at an entity outside the generated pass (foreign assembly, explicit `ValueGeneratedOnAdd`, or a hand-built context). | Declare the key `ValueGeneratedNever()` for client-assigned ids (see [Entity identity](/docs/capabilities/entity-framework#entity-identity)), and cover replace-children flows with a real-database (Testcontainers) test. | | A PostgreSQL test suite's memory grows with every test; a heap dump shows thousands of `NpgsqlDataSource` instances | `new NpgsqlConnection(connectionString)` registers a data source per distinct connection string in Npgsql's static pool manager for the life of the process (also with `Pooling=false`, and also through `ClearPool(new NpgsqlConnection(cs))`); with one database per test every test adds entries. Undisposed `NpgsqlDataSource.Create(…)` instances are retained by Npgsql's static metrics list. | Open dedicated sessions with `UnpooledNpgsqlSession.OpenAsync` (`Elarion.Sql.PostgreSql`), dispose every data source you create, and clear pools with `dataSource.Clear()` on the data source the host uses. See [One database per test](/docs/concepts/persistence-and-transactions#one-database-per-test-and-npgsqls-pool-registry). | | Inserts fail with a `Guid.Empty` duplicate key after upgrading | The entity relied on EF's client-side Guid generator (`Id` never set in code); the generated model now declares domain Guid PKs `ValueGeneratedNever` (ADR-0038). | Set ids at the creation site (`Id = Guid.CreateVersion7()`, recommended), or opt that entity back in with `builder.Property(e => e.Id).ValueGeneratedOnAdd()` — explicit configuration wins. | Still stuck? Open an issue at [github.com/swimmesberger/Elarion/issues](https://github.com/swimmesberger/Elarion/issues) with a minimal repro. # Background work (/docs/tutorial/background-work) Creating an invoice should return instantly; actually delivering the email — over flaky SMTP — should happen in the background and survive a transient failure. That is exactly what [scheduling](/docs/capabilities/scheduling) and [resilience](/docs/capabilities/resilience) are for. This page builds the Invoicing module around that flow, announces each creation as a durable [integration event](/docs/capabilities/events) delivered after commit, and adds a nightly cron job that flags overdue invoices. ### Define the email port [#define-the-email-port] The Invoicing module depends on an *interface* it owns; the concrete sender is a platform capability the host supplies. This keeps the flaky external dependency behind a port the resilience policy can wrap. ```csharp title="src/Billing.Application/Modules/Invoicing/Services/IInvoiceEmailSender.cs" namespace Billing.Application.Modules.Invoicing.Services; public interface IInvoiceEmailSender { Task SendAsync(InvoiceEmail email, CancellationToken ct); } public sealed record InvoiceEmail { public required string To { get; init; } public required string InvoiceNumber { get; init; } public required long AmountCents { get; init; } public required string Currency { get; init; } } ``` The implementation lives in infrastructure and is registered by the host (see [Host the API](/docs/tutorial/hosting)). It is deliberately thin — the SMTP details are not the interesting part; the retry around them is. ```csharp title="src/Billing.Infrastructure/Email/SmtpInvoiceEmailSender.cs" using Billing.Application.Modules.Invoicing.Services; using Microsoft.Extensions.Logging; namespace Billing.Infrastructure.Email; public sealed class SmtpInvoiceEmailSender(ILogger logger) : IInvoiceEmailSender { public async Task SendAsync(InvoiceEmail email, CancellationToken ct) { // Swap this for MailKit / SES / SendGrid. The contract — and the cancellation token, // which the resilience timeout depends on — stays the same. logger.LogInformation("Sending invoice {Number} to {To}", email.InvoiceNumber, email.To); await Task.Delay(TimeSpan.FromMilliseconds(200), ct); } } ``` The sender accepts and honors a `CancellationToken`. The resilience `Timeout` cancels that token when an attempt runs too long, so a real SMTP call must pass it through to actually stop. ### Declare the resilience policy [#declare-the-resilience-policy] A named [resilience policy](/docs/capabilities/resilience) is neutral metadata the generator turns into a typed reference. This one retries up to four times with exponential backoff and jitter, and caps each attempt at 30 seconds. ```csharp title="src/Billing.Application/Modules/Invoicing/InvoiceEmailPolicy.cs" using Elarion.Abstractions.Resilience; namespace Billing.Application.Modules.Invoicing; [ResiliencePolicy( "invoice-email", MaxRetryAttempts = 4, Delay = "10s", Backoff = ResilienceBackoffType.Exponential, MaxDelay = "5m", UseJitter = true, Timeout = "30s")] public static partial class InvoiceEmailPolicy; ``` The generator emits `InvoiceEmailPolicy.Name` and `InvoiceEmailPolicy.Reference`, plus the registration method the host calls. You will reference both below. ### Write the resilient send job [#write-the-resilient-send-job] The actual delivery is a runtime job — `IScheduledJob` — so it can be enqueued on demand with a typed payload. It loads the invoice, sends the email, and marks the invoice `Sent`. The no-op-if-not-`Draft` guard makes it **idempotent**, which matters because deferred retry may run a fresh attempt after a transient failure. ```csharp title="src/Billing.Application/Modules/Invoicing/Jobs/SendInvoiceEmailJob.cs" using Billing.Application.Domain; using Billing.Application.Modules.Invoicing.Services; using Billing.Application.Persistence; using Elarion.Abstractions.Scheduling; using Microsoft.EntityFrameworkCore; namespace Billing.Application.Modules.Invoicing.Jobs; public sealed record SendInvoiceEmailPayload { public required Guid InvoiceId { get; init; } } [ScheduledJob("invoicing.sendInvoiceEmail")] public sealed class SendInvoiceEmailJob( BillingDbContext db, IInvoiceEmailSender email, TimeProvider clock ) : IScheduledJob { public async ValueTask ExecuteAsync( SendInvoiceEmailPayload payload, IScheduledJobContext context, CancellationToken ct) { var invoice = await db.Invoices.FirstOrDefaultAsync(i => i.Id == payload.InvoiceId, ct); if (invoice is null || invoice.Status != InvoiceStatus.Draft) { return; // already sent, or rolled back — nothing to do } var client = await db.Clients.FirstAsync(c => c.Id == invoice.ClientId, ct); await email.SendAsync(new InvoiceEmail { To = client.Email, InvoiceNumber = invoice.Number, AmountCents = invoice.AmountCents, Currency = invoice.Currency, }, ct); invoice.Status = InvoiceStatus.Sent; invoice.SentAt = clock.GetUtcNow(); await db.SaveChangesAsync(ct); } } ``` Notice the job class itself carries no `[Resilient]` attribute and no reference to `InvoiceEmailPolicy`. That is deliberate: it runs under **deferred retry**, where the policy is supplied by the *caller* at enqueue time (`ResiliencePolicy = InvoiceEmailPolicy.Reference` in the next step), not declared on the job. A job has no fixed resilience behavior of its own — different callers could enqueue it with different policies, or none. Compare this to `OverdueReminderJob` further down, which uses **inline** resilience via `[Resilient(InvoiceEmailPolicy.Name)]` directly on the method, because there the schedule itself owns the retry behavior. ### React after commit with an integration event [#react-after-commit-with-an-integration-event] Sending the email is one reaction to a new invoice; there will be others — a search-index update, an activity feed, an outbound webhook — and none of them should be wired into the create handler or block it. That is what [integration events](/docs/capabilities/events) are for: published inside the command, delivered **after it commits**, on their own scope, retried independently. The event is a record carrying the marker that binds it to the after-commit plane: ```csharp title="src/Billing.Application/Modules/Invoicing/Events/InvoiceCreated.cs" using Elarion.Abstractions.Messaging; namespace Billing.Application.Modules.Invoicing.Events; public sealed record InvoiceCreated(Guid InvoiceId) : IIntegrationEvent; ``` A consumer is a handler whose request *is* the event — an `IHandler` annotated with a class-level `[ConsumeEvent]`, returning `Result`. It runs on a fresh scope once the invoice has committed, so it reads its own data and its failures never touch the original command. Its request is an `IIntegrationEvent`, so the default [inbox](/docs/capabilities/events/consuming-events) wraps it in place of the [transaction decorator](/docs/tutorial/features#define-the-decorator-pipeline): it runs inside a transaction that records the delivery, so a consumer that *writes* commits atomically with its dedup claim, while this read-only one simply doesn't use it: ```csharp title="src/Billing.Application/Modules/Invoicing/Events/InvoiceNotifications.cs" using Billing.Application.Domain; using Billing.Application.Persistence; using Elarion.Abstractions; using Elarion.Abstractions.Messaging; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Billing.Application.Modules.Invoicing.Events; [ConsumeEvent] public sealed class InvoiceNotifications( BillingDbContext db, ILogger logger ) : IHandler { public async ValueTask HandleAsync(InvoiceCreated e, CancellationToken ct) { var invoice = await db.Invoices.FirstOrDefaultAsync(i => i.Id == e.InvoiceId, ct); if (invoice is null) { return Result.Success(); } var client = await db.Clients.FirstAsync(c => c.Id == invoice.ClientId, ct); // A real consumer would push to a webhook, search index, or notification service. logger.LogInformation("Invoice {Number} created for {Email}", invoice.Number, client.Email); return Result.Success(); } } ``` Delivery is **at-least-once** — the consumer may run more than once for one event (a retry, or a redelivery after a crash). Keep it idempotent. The `CancellationToken` here is the delivery host's shutdown token, not the create request's; by the time this runs, that request is long done. `CreateInvoice` (next step) publishes this **immediately before `SaveChanges`**, so the event row is written in the same transaction as the invoice — commit them both, or neither. The consumer is a `[ConsumeEvent]` handler, so it is discovered, registered, and module-gated automatically like every other handler; the host only chooses *how* delivery happens by wiring the [EF Core outbox](/docs/capabilities/events/backends#ef-core-transactional-outbox) in [Host the API](/docs/tutorial/hosting), which is what makes the event survive a crash between commit and delivery. ### Create the invoice and enqueue the send [#create-the-invoice-and-enqueue-the-send] `CreateInvoice` persists a `Draft` invoice and **enqueues** the send job with the resilience policy in **deferred-retry** mode. Deferred retry releases scheduler capacity between attempts and exposes a `WaitingRetry` status — the right model when the caller wants to observe progress. The handler returns the stable `JobId` so the frontend can poll it. ```csharp title="src/Billing.Application/Modules/Invoicing/Handlers/CreateInvoice.cs" using System.ComponentModel; using System.ComponentModel.DataAnnotations; using Billing.Application.Domain; using Billing.Application.Modules.Core.Contracts; using Billing.Application.Modules.Invoicing.Events; using Billing.Application.Modules.Invoicing.Jobs; using Billing.Application.Persistence; using Elarion.Abstractions; using Elarion.Abstractions.Caching; using Elarion.Abstractions.Identity; using Elarion.Abstractions.Messaging; using Elarion.Abstractions.Scheduling; using Microsoft.EntityFrameworkCore; namespace Billing.Application.Modules.Invoicing.Handlers; [Handler("invoices.create")] [CacheInvalidate("invoices")] [Description("Creates a draft invoice and sends it to the client in the background.")] public sealed class CreateInvoice( BillingDbContext db, ICurrentUser user, IJobScheduler scheduler, IIntegrationEventBus integrationEvents, IAccountStanding accountStanding, TimeProvider clock ) : IHandler> { public sealed record Command : ICommand { public required Guid ClientId { get; init; } [Description("Invoice total in minor units, e.g. 1999 = €19.99.")] [Range(1, long.MaxValue)] public required long AmountCents { get; init; } [Length(3, 3)] public required string Currency { get; init; } public required DateOnly DueDate { get; init; } } public sealed record Response(Guid InvoiceId, string Number, Guid SendJobId); public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var clientExists = await db.Clients .AnyAsync(c => c.OwnerId == user.UserId && c.Id == command.ClientId, ct); if (!clientExists) { return AppError.NotFound($"Client {command.ClientId} was not found."); } // Cross-module domain call: Core's published account-standing policy decides if this customer // may be invoiced (ADR-0002) — Invoicing depends on the contract, not on Core's internals. var standing = await accountStanding.EnsureCanInvoiceAsync(command.ClientId, command.AmountCents, ct); if (!standing.IsSuccess) { return standing.Error; } var count = await db.Invoices.CountAsync(i => i.OwnerId == user.UserId, ct); var invoice = new Invoice { Id = Guid.CreateVersion7(), OwnerId = user.UserId, ClientId = command.ClientId, Number = $"INV-{count + 1:D6}", AmountCents = command.AmountCents, Currency = command.Currency, Status = InvoiceStatus.Draft, DueDate = command.DueDate, CreatedAt = clock.GetUtcNow(), }; db.Invoices.Add(invoice); // Record the integration event in the same unit of work — it commits with the invoice, or not at all. await integrationEvents.PublishAsync(new InvoiceCreated(invoice.Id), ct); await db.SaveChangesAsync(ct); var handle = await scheduler.EnqueueAsync( new SendInvoiceEmailPayload { InvoiceId = invoice.Id }, new ScheduledJobOptions { ResiliencePolicy = InvoiceEmailPolicy.Reference, ResilienceMode = ScheduledJobResilienceMode.DeferredRetry, CorrelationId = invoice.Id.ToString(), }, ct); return new Response(invoice.Id, invoice.Number, handle.JobId); } } ``` The `[Range]` and `[Length]` attributes on the `Command` are the input rules — enforced by the auto-attached [validation gate](/docs/concepts/validation) before the transaction opens, and exported to the JSON-RPC schema and the frontend's Zod client. The existence check on `ClientId` is a database question, so it stays in the handler. ### Observe the send [#observe-the-send] The frontend wants to show "Sending…", "Sent", or "Retrying". Expose the scheduler's in-memory state through `IJobSchedulerInspector` as a plain query. The query takes the **`JobId`** the create handler returned — not the `RunId`. That distinction matters here: `JobId` identifies the *logical* "send this invoice's email" operation and stays stable across every deferred-retry attempt, while each attempt gets its own `RunId`. `GetJob(jobId)` returns the aggregate state — `WaitingRetry` between attempts, `Succeeded` only once an attempt actually delivers, `Failed` once retries are exhausted — which is exactly what a caller asking "is the whole send done yet?" needs. `RunId` is for operator/diagnostic tooling acting on one specific attempt from a [snapshot](/docs/capabilities/scheduling/inspection); polling it would lose the handle the moment a retry starts a new run. See [JobId vs. RunId](/docs/capabilities/scheduling/runtime-jobs#jobid-vs-runid). ```csharp title="src/Billing.Application/Modules/Invoicing/Handlers/GetSendStatus.cs" using Elarion.Abstractions; using Elarion.Abstractions.Scheduling; namespace Billing.Application.Modules.Invoicing.Handlers; [Handler("invoices.sendStatus")] public sealed class GetSendStatus(IJobSchedulerInspector scheduler) : IHandler> { public sealed record Query(Guid JobId) : IQuery; public sealed record Response( string Status, int Attempt, int MaxAttempts, DateTimeOffset? NextAttemptAt, string? LastError); public ValueTask> HandleAsync(Query query, CancellationToken ct) { var state = scheduler.GetJob(query.JobId); Result result = state is null ? AppError.NotFound($"No send job {query.JobId} is currently tracked.") : new Response( state.Status.ToString(), state.Attempt, state.MaxAttempts, state.NextAttemptDueTimeUtc, state.LastError); return ValueTask.FromResult(result); } } ``` Scheduler state is **in-memory**. `GetJob` returns `null` after the process restarts or once a terminal state ages out of retention — which the `NotFound` branch handles. For status that must survive restarts, persist it yourself; this is the lightweight, in-process model by design. ### List invoices (cached) [#list-invoices-cached] The invoices table reads through a cached query, invalidated by the `invoices` tag whenever `CreateInvoice` succeeds. ```csharp title="src/Billing.Application/Modules/Invoicing/Handlers/ListInvoices.cs" using System.Collections.Generic; using Billing.Application.Domain; using Billing.Application.Persistence; using Elarion.Abstractions; using Elarion.Abstractions.Caching; using Elarion.Abstractions.Identity; using Microsoft.EntityFrameworkCore; namespace Billing.Application.Modules.Invoicing.Handlers; [Cacheable("invoices", DurationSeconds = 30)] [Handler("invoices.list")] public sealed class ListInvoices(BillingDbContext db, ICurrentUser user) : IHandler> { public sealed record Query : IQuery; public sealed record Item( Guid Id, string Number, long AmountCents, string Currency, string Status, DateOnly DueDate); public sealed record Response(IReadOnlyList Invoices); public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var items = await db.Invoices .Where(i => i.OwnerId == user.UserId) .OrderByDescending(i => i.CreatedAt) .Select(i => new Item( i.Id, i.Number, i.AmountCents, i.Currency, i.Status.ToString(), i.DueDate)) .ToListAsync(ct); return new Response(items); } } ``` ### Chase overdue invoices nightly [#chase-overdue-invoices-nightly] A recurring [scheduled job](/docs/capabilities/scheduling/schedules) flags sent-but-unpaid invoices as overdue every morning. It uses **inline** resilience (`[Resilient]`) — short, idempotent work where one occurrence owns its retries — and a config placeholder for the schedule so operators can retune it without a redeploy. ```csharp title="src/Billing.Application/Modules/Invoicing/Jobs/OverdueReminderJob.cs" using Billing.Application.Domain; using Billing.Application.Persistence; using Elarion.Abstractions.Resilience; using Elarion.Abstractions.Scheduling; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Billing.Application.Modules.Invoicing.Jobs; public sealed class OverdueReminderJob( BillingDbContext db, TimeProvider clock, ILogger logger ) { [Resilient(InvoiceEmailPolicy.Name)] [ScheduledJob( "invoicing.overdueReminders", Cron = "${Invoicing:OverdueCron:-0 0 8 * * *}", TimeZone = "Europe/Vienna", Enabled = "${Modules:Invoicing:Enabled:-true}")] public async ValueTask RunAsync(CancellationToken ct) { var today = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime); var overdue = await db.Invoices .Where(i => i.Status == InvoiceStatus.Sent && i.DueDate < today) .ToListAsync(ct); foreach (var invoice in overdue) { invoice.Status = InvoiceStatus.Overdue; } await db.SaveChangesAsync(ct); logger.LogInformation("Flagged {Count} invoices as overdue", overdue.Count); } } ``` The schedule defaults to `0 0 8 * * *` (daily at 08:00 `Europe/Vienna`) and re-resolves `Modules:Invoicing:Enabled` before every occurrence — so disabling the module also stops this job. ### Register the JSON metadata [#register-the-json-metadata] ```csharp title="src/Billing.Application/Modules/Invoicing/InvoicingJsonContext.cs" using System.Text.Json.Serialization; using Billing.Application.Modules.Invoicing.Handlers; namespace Billing.Application.Modules.Invoicing; [JsonSerializable(typeof(CreateInvoice.Command))] [JsonSerializable(typeof(CreateInvoice.Response))] [JsonSerializable(typeof(ListInvoices.Query))] [JsonSerializable(typeof(ListInvoices.Response))] [JsonSerializable(typeof(GetSendStatus.Query))] [JsonSerializable(typeof(GetSendStatus.Response))] public sealed partial class InvoicingJsonContext : JsonSerializerContext; ``` ## What you have so far [#what-you-have-so-far] * A create flow that returns immediately and delivers email in the background. * A retrying, idempotent send job that survives transient SMTP failures via deferred retry. * An `InvoiceCreated` integration event, published in the same transaction and delivered durably after commit through the EF Core outbox — the seam for any further after-the-fact reactions. * A pollable send status and a nightly cron job that keeps invoice state honest. All of this still runs nowhere until the host composes the modules and registers the scheduler and resilience runtimes — that is the next step. Compose the modules, publish JSON-RPC, expose MCP tools, and wire telemetry. # Write the features (/docs/tutorial/features) The Clients module is where most of Elarion's cross-cutting machinery earns its keep. You will set up a [decorator pipeline](/docs/concepts/decorator-pipelines) once, then write handlers that get validation, transactions, logging, current-user scoping, and caching **for free** — declared next to the code, generated into the wiring. This page builds Clients in full. The Invoicing module follows the same patterns and is built in [Background work](/docs/tutorial/background-work). ### Define the decorator pipeline [#define-the-decorator-pipeline] Elarion auto-attaches its framework gates — authorization, feature gating, and [request validation](/docs/concepts/validation) — from the handler's own attributes; you never list those. What you define is the pipeline itself — your app-specific cross-cutting behavior, such as logging, plus the framework's transaction boundary — exposed with `[DecoratorList]`. A decorator can declare *where it attaches* — by a generic constraint (`where TRequest : ICommand`) or a `static bool AppliesTo(HandlerMetadata handler)` predicate the generator evaluates per handler — so **one** pipeline serves commands, queries, and event handlers alike. ```csharp title="src/Billing.Application/Decorators/Decorators.cs" using Elarion.Abstractions; using Microsoft.Extensions.Logging; namespace Billing.Application.Decorators; public sealed class LoggingDecorator( IHandler inner, ILogger> logger ) : IHandler { public async ValueTask HandleAsync(TRequest request, CancellationToken ct) { logger.LogInformation("Handling {Request}", typeof(TRequest).DeclaringType?.Name ?? typeof(TRequest).Name); return await inner.HandleAsync(request, ct); } } ``` You do **not** write the transaction decorator. The framework's `Elarion.Pipeline.TransactionDecorator<,>` opens a unit of work through the `IUnitOfWork` seam (the host registers the EF Core implementation over `BillingDbContext` in [Host the API](/docs/tutorial/hosting)), commits on a successful `Result`, and rolls back otherwise. Its `static bool AppliesTo` predicate attaches it at compile time only to **commands** — queries and domain-event handlers skip it, and so do handlers whose pipeline already owns the unit of work: `[Idempotent]` commands (the idempotency decorator commits the key with the writes) and integration-event consumers (the default [inbox](/docs/capabilities/events/consuming-events) commits its claim with the writes). Once the handler has succeeded the commit ignores cancellation, so a late cancel can never roll back completed work. Now expose **one** pipeline for the whole application. A single pipeline is correct everywhere, with no second "read-only" pipeline to define and no per-handler tag. ```csharp title="src/Billing.Application/Pipeline/Pipelines.cs" using Billing.Application.Decorators; using Elarion.Abstractions.Pipeline; namespace Billing.Application.Pipeline; [DecoratorList( typeof(LoggingDecorator<,>), typeof(Elarion.Pipeline.TransactionDecorator<,>))] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class)] public sealed class DefaultPipelineAttribute : Attribute; ``` Decorators run **outermost first**, in list order. Logging wraps everything; the transaction wraps only the handler — and only on commands, since its `AppliesTo` predicate keeps the generator from attaching it to queries, event handlers, or handlers whose pipeline already owns the unit of work. The framework's validation gate runs *before* this whole list, so a bad request is rejected without ever opening a transaction. Apply the pipeline across the whole assembly: ```csharp title="src/Billing.Application/ElarionAssembly.cs" using Billing.Application.Pipeline; using Elarion.Abstractions; [assembly: DefaultPipeline] [assembly: UseElarion] ``` ### Add a cross-module capability (`[ModuleContract]`) [#add-a-cross-module-capability-modulecontract] `Invoicing` needs a decision that isn't its own to make: *may this customer be invoiced right now, or would a new invoice breach their credit limit?* That is a **domain policy** the foundation **Core** module owns. A module never reaches into another module's internals ([ADR-0002](/docs/concepts/cross-module-communication)); it depends on a **published contract**. So Core publishes the policy as a [`[ModuleContract]`](/docs/concepts/cross-module-communication) and keeps the implementation `internal`: ```csharp title="src/Billing.Application/Modules/Core/Contracts/IAccountStanding.cs" using Elarion.Abstractions; using Elarion.Abstractions.Modules; namespace Billing.Application.Modules.Core.Contracts; [ModuleContract] public interface IAccountStanding { ValueTask EnsureCanInvoiceAsync(Guid clientId, long amountCents, CancellationToken ct = default); } ``` ```csharp title="src/Billing.Application/Modules/Core/Services/AccountStanding.cs" using Billing.Application.Domain; using Billing.Application.Modules.Core.Contracts; using Billing.Application.Persistence; using Elarion.Abstractions; using Microsoft.EntityFrameworkCore; namespace Billing.Application.Modules.Core.Services; [Service(typeof(IAccountStanding))] internal sealed class AccountStanding(BillingDbContext db) : IAccountStanding { private const long CreditLimitCents = 1_000_000; // €10,000 per customer, for the sample public async ValueTask EnsureCanInvoiceAsync(Guid clientId, long amountCents, CancellationToken ct = default) { var outstanding = await db.Invoices .Where(i => i.ClientId == clientId && (i.Status == InvoiceStatus.Sent || i.Status == InvoiceStatus.Overdue)) .SumAsync(i => i.AmountCents, ct); return outstanding + amountCents > CreditLimitCents ? AppError.BusinessRule("Credit limit exceeded.") : Result.Success(); } } ``` `[Service(typeof(IAccountStanding))]` registers the internal impl against the contract in Core's generated `ConfigureDefaultServices` — no host wiring. `Invoicing` injects `IAccountStanding` (a contract, so `ELMOD002` allows the cross-module dependency) and consults it before raising an invoice — you'll see that in `CreateInvoice`. The rule lives in Core, written and tested once, rather than being reimplemented in each module that invoices. A `[ModuleContract]` is for a genuine, bespoke **domain** call between modules. It is *not* a platform *port* (intent-only infrastructure like sending email lives outside the modules, with an adapter in `Billing.Infrastructure`), and it is *not* for cross-cutting concerns the framework already solves — **auditing** (`[Auditable]`, next), validation, and authorization all attach in the pipeline with no contract to publish. ### Record who did what (the framework audit trail) [#record-who-did-what-the-framework-audit-trail] Compliance usually needs a durable record of *who performed which action, with what outcome*. Don't hand-roll it — tag a handler `[Auditable]` and the framework [audit trail](/docs/concepts/auditing) writes one structured record per invocation, committed **atomically** with the handler's transaction (a rolled-back command leaves no misleading "success" row) and capturing denied and failed attempts too. Turn it on with one host line — the durable EF sink over the same `BillingDbContext` (the `elarion_audit_log` table is mapped beside the outbox): ```csharp title="src/Billing.Api/Program.cs (excerpt)" builder.Services.AddElarionAuditingEntityFrameworkCore(); ``` ```csharp title="src/Billing.Application/Persistence/BillingDbContext.cs (excerpt)" modelBuilder.UseElarionAuditing(); // maps the elarion_audit_log table ``` A handler opts in with `[Auditable]` (you'll see it on `CreateClient` next). An entity opts into automatic field-level change capture with `[Audited]`, excluding sensitive columns with `[AuditIgnore]` — nothing on your entities is needed for the record *itself*; `[Audited]` only adds the `old → new` diffs: ```csharp title="src/Billing.Application/Domain/Client.cs (excerpt)" [Audited] public sealed class Client { public Guid Id { get; set; } // … [AuditIgnore] // PII kept out of the audit trail's change capture public required string Email { get; set; } } ``` See [Audit trail](/docs/concepts/auditing) for the full model — including the distinction from an app-owned *activity log*, when history is a queryable feature rather than a compliance record. ### Add a module-owned service [#add-a-module-owned-service] Clients get a human-friendly number like `C-000123`. A `[Service]` keeps that policy in one place. ```csharp title="src/Billing.Application/Modules/Clients/Services/ClientNumberGenerator.cs" using Billing.Application.Persistence; using Elarion.Abstractions; using Microsoft.EntityFrameworkCore; namespace Billing.Application.Modules.Clients.Services; public interface IClientNumberGenerator { ValueTask NextAsync(string ownerId, CancellationToken ct); } [Service(typeof(IClientNumberGenerator))] public sealed class ClientNumberGenerator(BillingDbContext db) : IClientNumberGenerator { public async ValueTask NextAsync(string ownerId, CancellationToken ct) { var count = await db.Clients.CountAsync(c => c.OwnerId == ownerId, ct); return $"C-{count + 1:D6}"; } } ``` ### Write the command handler [#write-the-command-handler] `CreateClient` is a state change, so its request is a nested `Command`. It runs through the pipeline (the framework's validation gate, then authorization, then logging → transaction), scopes the row to the current user, invalidates the clients cache on success, and is exposed over JSON-RPC. `[RequirePermission("clients", "create")]` enforces the `clients.create` permission claim in the handler pipeline — transport-neutral, so the same gate protects the JSON-RPC and MCP surfaces alike ([Authorization](/docs/concepts/authorization)). `[Auditable]` records the compliance audit trail automatically (`audit.SetResource` just pins *which* client was acted on, using the same `clients` resource vocabulary). `[Handler]` names the operation; the name is optional, and when omitted Elarion infers `{module}.{operation}` by convention (here `clients.createClient` from module `Clients` and the handler type name minus its `Handler`/`Command`/`Query`/`Request` suffix, camelCased). An explicit name like `"clients.create"` is recommended for stable public/wire contracts. The `[Description]` attributes flow straight through to the [MCP tool](/docs/capabilities/transports/mcp) surface. ```csharp title="src/Billing.Application/Modules/Clients/Handlers/CreateClient.cs" using System.ComponentModel; using System.ComponentModel.DataAnnotations; using Billing.Application.Domain; using Billing.Application.Modules.Clients.Services; using Billing.Application.Persistence; using Elarion.Abstractions; using Elarion.Abstractions.Auditing; using Elarion.Abstractions.Authorization; using Elarion.Abstractions.Caching; using Elarion.Abstractions.Identity; using Microsoft.EntityFrameworkCore; namespace Billing.Application.Modules.Clients.Handlers; [Handler("clients.create")] [RequirePermission("clients", "create")] // pipeline-enforced: caller needs the "clients.create" permission claim [CacheInvalidate("clients")] [Auditable] // framework audit trail: one compliance record per invocation (SetResource pins which client) [Description("Creates a new client for the current account.")] public sealed class CreateClient( BillingDbContext db, ICurrentUser user, IClientNumberGenerator numbers, IAuditScope audit, TimeProvider clock ) : IHandler> { public sealed record Command : ICommand { [Description("The client's display name.")] [StringLength(200, MinimumLength = 1)] public required string Name { get; init; } [Description("The client's billing email address.")] [EmailAddress, MaxLength(320)] public required string Email { get; init; } } public sealed record Response(Guid Id, string Number); public async ValueTask> HandleAsync(Command command, CancellationToken ct) { var exists = await db.Clients .AnyAsync(c => c.OwnerId == user.UserId && c.Email == command.Email, ct); if (exists) { return AppError.Conflict($"A client with email {command.Email} already exists."); } var client = new Client { Id = Guid.CreateVersion7(), OwnerId = user.UserId, Number = await numbers.NextAsync(user.UserId, ct), Name = command.Name, Email = command.Email, CreatedAt = clock.GetUtcNow(), }; db.Clients.Add(client); await db.SaveChangesAsync(ct); audit.SetResource("clients", client.Id.ToString()); // audit resource type = the [RequirePermission] vocabulary return new Response(client.Id, client.Number); } } ``` The handler returns a value, never throws for expected failures: a duplicate email becomes `AppError.Conflict`, which the host later maps to a JSON-RPC error code. Only a **successful** result triggers the `clients` cache invalidation. Runtime feature gating uses the same declarative shape: `[FeatureGate("client-portal")]` on a handler makes it return the generic not-found outcome while the flag is off — the feature's existence is never leaked ([Feature flags](/docs/concepts/feature-flags)). The Billing tutorial doesn't gate any handler, so the attribute appears here only for completeness. ### Validate the command [#validate-the-command] The `[StringLength]`/`[EmailAddress]`/`[MaxLength]` attributes on the `Command` **are** the input rules — there is no validator class. Because the request carries validation attributes, the generator auto-attaches the framework [`ValidationDecorator`](/docs/concepts/validation), which rejects a bad request with field-keyed `AppError.Validation` errors before logging or the transaction ever run. Requiredness needs no attribute at all: `required string Name` already means the member must be present. The same attributes flow into every contract surface — the exported `rpc-schema.json`, the MCP tool input schemas, and the generated Zod client (which pre-validates the form input with the identical rules, in [Build the frontend](/docs/tutorial/frontend)). Enforcement comes from the `Elarion.Validation` package added during [scaffolding](/docs/tutorial#scaffold-the-solution); the host registers it with one line in [Host the API](/docs/tutorial/hosting): ```csharp title="src/Billing.Api/Program.cs (excerpt)" builder.Services.AddElarionValidation(); ``` Business rules stay in the handler: the duplicate-email check above is a database question, so it runs **inside the transaction** and returns `AppError.Conflict` — see [Validation](/docs/concepts/validation) for where that dividing line sits. ### Write the cached read handlers [#write-the-cached-read-handlers] Reads are `IQuery` types, so `TransactionDecorator`'s `AppliesTo` predicate excludes them — no per-handler tag, no transaction around a read. `GetClient` is marked `[Cacheable]`: the generator inserts a cache decorator that keys off the request and only runs the handler on a miss. The default `CurrentUser` scope isolates entries per account, so one user's cached client is never served to another. ```csharp title="src/Billing.Application/Modules/Clients/Handlers/GetClient.cs" using Billing.Application.Persistence; using Elarion.Abstractions; using Elarion.Abstractions.Caching; using Elarion.Abstractions.Identity; using Microsoft.EntityFrameworkCore; namespace Billing.Application.Modules.Clients.Handlers; [Cacheable("clients", DurationSeconds = 120)] [Handler("clients.get")] public sealed class GetClient(BillingDbContext db, ICurrentUser user) : IHandler> { public sealed record Query(Guid Id) : IQuery; public sealed record Response(Guid Id, string Number, string Name, string Email); public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var client = await db.Clients .Where(c => c.OwnerId == user.UserId && c.Id == query.Id) .Select(c => new Response(c.Id, c.Number, c.Name, c.Email)) .FirstOrDefaultAsync(ct); return client is null ? AppError.NotFound($"Client {query.Id} was not found.") : client; } } ``` `ListClients` is the read the frontend's table calls. It is cached under the same `clients` tag, so `CreateClient`'s `[CacheInvalidate("clients")]` clears it the moment a client is added. ```csharp title="src/Billing.Application/Modules/Clients/Handlers/ListClients.cs" using System.Collections.Generic; using Billing.Application.Persistence; using Elarion.Abstractions; using Elarion.Abstractions.Caching; using Elarion.Abstractions.Identity; using Microsoft.EntityFrameworkCore; namespace Billing.Application.Modules.Clients.Handlers; [Cacheable("clients", DurationSeconds = 60)] [Handler("clients.list")] public sealed class ListClients(BillingDbContext db, ICurrentUser user) : IHandler> { public sealed record Query : IQuery; public sealed record Item(Guid Id, string Number, string Name, string Email); public sealed record Response(IReadOnlyList Clients); public async ValueTask> HandleAsync(Query query, CancellationToken ct) { var items = await db.Clients .Where(c => c.OwnerId == user.UserId) .OrderBy(c => c.Number) .Select(c => new Item(c.Id, c.Number, c.Name, c.Email)) .ToListAsync(ct); return new Response(items); } } ``` Caching is opt-in per handler and composes with the rest of the pipeline. The default `CurrentUser` scope fits Billing perfectly. For genuinely shared, non-personalized data — say a list of supported currencies — you would set `Scope = HandlerCacheScope.Global` so all accounts share one entry. ### Register the JSON metadata [#register-the-json-metadata] Each module contributes [source-generated JSON metadata](/docs/capabilities/serialization) for its request/response types. Add an entry per type the module exposes. ```csharp title="src/Billing.Application/Modules/Clients/ClientsJsonContext.cs" using System.Text.Json.Serialization; using Billing.Application.Modules.Clients.Handlers; namespace Billing.Application.Modules.Clients; [JsonSerializable(typeof(CreateClient.Command))] [JsonSerializable(typeof(CreateClient.Response))] [JsonSerializable(typeof(GetClient.Query))] [JsonSerializable(typeof(GetClient.Response))] [JsonSerializable(typeof(ListClients.Query))] [JsonSerializable(typeof(ListClients.Response))] public sealed partial class ClientsJsonContext : JsonSerializerContext; ``` ## What you have so far [#what-you-have-so-far] * One handler that is simultaneously a use case, a DI registration, a JSON-RPC method, and an MCP tool. * A pipeline that applies logging and transactions to every command — declared once — with request validation attached automatically from the DTO's DataAnnotations. * Per-user reads that are cached and invalidated by tag, with no manual key management. The Invoicing module: a resilient email job, runtime scheduling, and a nightly cron reminder. # Build the frontend (/docs/tutorial/frontend) The backend exports `rpc-schema.json` on every build. The frontend turns that into a typed, Zod-validated client and calls handlers as if they were local async functions — with full request cancellation. We use **Vite**, **Tailwind v4**, **shadcn/ui**, and **TanStack Query**, all current and deliberately pragmatic. To run the whole chain with one command, add the web app to the Aspire app host with `builder.AddViteApp("web", "../../web").WithReference(api).WithEnvironment("VITE_API_URL", api.GetEndpoint("http"))`, capturing the API resource as `var api = builder.AddProject("api")…` (package `Aspire.Hosting.JavaScript`). Then `dotnet run` on the app host starts PostgreSQL, the API, and the Vite dev server together, with the API URL injected as `VITE_API_URL`. The runnable [`samples/Billing`](https://github.com/swimmesberger/Elarion/tree/main/samples/Billing) wires it this way. ### Scaffold the React app [#scaffold-the-react-app] ```bash npm create vite@latest web -- --template react-ts cd web npm install ``` ### Add Tailwind v4 and shadcn/ui [#add-tailwind-v4-and-shadcnui] Install Tailwind and its Vite plugin, then point your CSS at it: ```bash npm install tailwindcss @tailwindcss/vite npm install -D @types/node ``` ```css title="web/src/index.css" @import "tailwindcss"; ``` Register the plugin and the `@` path alias in Vite, and mirror the alias in `tsconfig`: ```ts title="web/vite.config.ts" import path from "path" import tailwindcss from "@tailwindcss/vite" import react from "@vitejs/plugin-react" import { defineConfig } from "vite" export default defineConfig({ plugins: [react(), tailwindcss()], resolve: { alias: { "@": path.resolve(__dirname, "./src") } }, }) ``` ```json title="web/tsconfig.json (and tsconfig.app.json)" { "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./src/*"] } } } ``` Initialize shadcn/ui and pull in the components the UI needs: ```bash npx shadcn@latest init npx shadcn@latest add button input table dialog sonner ``` ### Generate the typed client [#generate-the-typed-client] Install the generator and TanStack Query (plus Zod, which the generated schemas import): ```bash npm install @tanstack/react-query zod npm install -D @swimmesberger/elarion-jsonrpc-client-generator ``` Add a script so regenerating is one command, and run it against the schema the backend emits: ```json title="web/package.json" { "scripts": { "gen:rpc": "elarion-jsonrpc-client-generator --schema ../rpc-schema.json --out src/generated" } } ``` ```bash npm run gen:rpc ``` This writes `rpc-types.ts`, `rpc-schemas.ts`, and `rpc-client.ts` into `src/generated`. Re-run it whenever a handler's request/response shape changes — the frontend types follow the backend. ### Wrap the client with auth [#wrap-the-client-with-auth] `createRpcApi` is framework-neutral. Wrap it once with your base URL and a token resolver. Passing `headers` as a function means each request reads the current token. ```ts title="web/src/lib/rpc.ts" import { createRpcApi } from "@/generated/rpc-client" import { getAccessToken } from "@/lib/auth" export const rpc = createRpcApi({ url: import.meta.env.VITE_API_URL + "/rpc", headers: () => ({ Authorization: `Bearer ${getAccessToken()}` }), }) ``` ### Provide the query client [#provide-the-query-client] ```tsx title="web/src/main.tsx" import { StrictMode } from "react" import { createRoot } from "react-dom/client" import { QueryClient, QueryClientProvider } from "@tanstack/react-query" import { Toaster } from "@/components/ui/sonner" import App from "./App" import "./index.css" const queryClient = new QueryClient() createRoot(document.getElementById("root")!).render( , ) ``` ### Write the data hooks [#write-the-data-hooks] TanStack Query hands every `queryFn` an `AbortSignal`. Forward it to the generated client, and a query that is no longer needed — a stale list, an unmounted view — **cancels its in-flight request** automatically. The result types come straight from the C# handlers. ```ts title="web/src/hooks/useClients.ts" import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" import { rpc } from "@/lib/rpc" export function useClients() { return useQuery({ queryKey: ["clients"], queryFn: ({ signal }) => rpc.clients.list({}, { signal }), // ^ AbortSignal forwarded to fetch — the request is cancelled on cleanup }) } export function useCreateClient() { const queryClient = useQueryClient() return useMutation({ mutationFn: (input: { name: string; email: string }) => rpc.clients.create(input), onSuccess: () => queryClient.invalidateQueries({ queryKey: ["clients"] }), }) } ``` The invoice flow adds a small twist: creating an invoice returns a `sendJobId`, and we poll its status until the background email lands. ```ts title="web/src/hooks/useInvoices.ts" import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" import { rpc } from "@/lib/rpc" export function useInvoices() { return useQuery({ queryKey: ["invoices"], queryFn: ({ signal }) => rpc.invoices.list({}, { signal }), }) } export function useCreateInvoice() { const queryClient = useQueryClient() return useMutation({ mutationFn: (input: { clientId: string; amountCents: number; currency: string; dueDate: string }) => rpc.invoices.create(input), onSuccess: () => queryClient.invalidateQueries({ queryKey: ["invoices"] }), }) } const SETTLED = new Set(["Succeeded", "Failed", "Cancelled"]) export function useSendStatus(jobId: string | undefined) { return useQuery({ queryKey: ["send-status", jobId], enabled: !!jobId, queryFn: ({ signal }) => rpc.invoices.sendStatus({ jobId: jobId! }, { signal }), // Poll while the job is still working; stop once it settles. refetchInterval: (query) => query.state.data && SETTLED.has(query.state.data.status) ? false : 1500, }) } ``` ### Build the UI [#build-the-ui] The components are ordinary shadcn/ui. Here is the clients table and a create dialog wired to the hooks above. ```tsx title="web/src/components/ClientsTable.tsx" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" import { useClients } from "@/hooks/useClients" export function ClientsTable() { const { data, isPending, isError } = useClients() if (isPending) return

Loading clients…

if (isError) return

Failed to load clients.

return ( Number Name Email {data.clients.map((c) => ( {c.number} {c.name} {c.email} ))}
) } ``` ```tsx title="web/src/components/CreateClientDialog.tsx" import { useState } from "react" import { toast } from "sonner" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { useCreateClient } from "@/hooks/useClients" export function CreateClientDialog() { const [open, setOpen] = useState(false) const [name, setName] = useState("") const [email, setEmail] = useState("") const createClient = useCreateClient() function submit() { createClient.mutate({ name, email }, { onSuccess: (res) => { toast.success(`Created client ${res.number}`) setOpen(false) setName("") setEmail("") }, onError: (err) => toast.error(err.message), }) } return ( New client setName(e.target.value)} /> setEmail(e.target.value)} /> ) } ``` `err.message` carries whatever your host mapped from `AppError` — a duplicate email (`AppError.Conflict`) or a server-side validation failure surfaces as a typed JSON-RPC error the mutation rejects with, so the toast shows a real message without any extra plumbing. Shape errors usually never reach the server at all: the generated client pre-validates params against the schema's constraints (the DataAnnotations you put on the `Command`) and rejects locally with an `RpcParamsValidationError`.
### One round-trip for the dashboard [#one-round-trip-for-the-dashboard] The dashboard needs both lists at once. The generated `$batch` helper sends them in a single HTTP request and preserves order; each item resolves independently, so one failure does not sink the other. ```ts title="web/src/hooks/useDashboard.ts" import { useQuery } from "@tanstack/react-query" import { rpc } from "@/lib/rpc" export function useDashboard() { return useQuery({ queryKey: ["dashboard"], queryFn: () => rpc.$batch([ rpc.$request.clients.list({}), rpc.$request.invoices.list({}), ] as const), }) } ```
## What you built [#what-you-built] A fullstack billing app where a single C# handler is a use case, a DI registration, a JSON-RPC method, an MCP tool, a schema-exported contract, and — after `npm run gen:rpc` — a typed, cancellable frontend call. The backend pieces compose through generated wiring; the frontend stays a thin, type-safe shell over the same contract. From here, the natural next moves: Point the OTLP exporter at a collector and watch RPC, cache, scheduler, and resilience spans nest under each handler. Refine tool names and descriptions, and connect an AI agent to the `/mcp` endpoint you exposed. Tune overlap, misfire, and inspection for the jobs you added. The reasoning behind compile-time wiring, handlers, and a thin host. # Host the API (/docs/tutorial/hosting) The application project declared *what* the app does. The host wires *how* it runs: the database provider, the scheduler and resilience runtimes, caching, authentication, the JSON-RPC and MCP endpoints, and telemetry. None of this leaks back into the modules. ### Add the generated host partial [#add-the-generated-host-partial] One partial class tells the generator to emit the cross-module wiring **in the host assembly**. ```csharp title="src/Billing.Api/ElarionAssembly.cs" using Elarion.AspNetCore; [assembly: GenerateModuleBootstrapper] ``` `ElarionBootstrapper` gains `AddElarion`, `MapElarionEndpoints`, `RegisterHandlers` (the single transport-neutral registry feeding both JSON-RPC and MCP), `GetMcpMetadata` (MCP), and `GetAllJsonTypeInfoResolvers`. Every transport is **feature-flag-gated per module**, so a disabled module disappears from all of them at once. The project layout is your choice: the bootstrapper discovers handlers both from referenced module assemblies and from the host compilation itself, so a single-project app wires identically. This tutorial uses the multi-project split because it is the shape that grows well. ### Install the remaining host packages [#install-the-remaining-host-packages] The host adds authentication and OpenTelemetry on top of the Elarion packages from [the overview](/docs/tutorial#scaffold-the-solution): ```bash cd src/Billing.Api dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer dotnet add package OpenTelemetry.Extensions.Hosting dotnet add package OpenTelemetry.Instrumentation.AspNetCore dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol cd ../.. ``` Handler caching and resilience are opt-in packages — `Elarion.Caching` (`[Cacheable]`/`[CacheInvalidate]`) and `Elarion.Resilience` (`[Resilient]` and deferred scheduler retries). Since ADR-0017 the Elarion core no longer ships these runtimes, so reference each package only when you use it; the [installation page](/docs/getting-started/installation) lists them. ### Register the services [#register-the-services] Compose the host. Each block is a platform capability the modules consume through an abstraction. ```csharp title="src/Billing.Api/Program.cs" using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using Billing.Api; // the generated ElarionBootstrapper lives in the host's root namespace using Billing.Application; using Billing.Application.Modules.Invoicing.Services; using Billing.Application.Persistence; using Billing.Infrastructure.Email; using Elarion.Abstractions.Diagnostics; using Elarion.Abstractions.Messaging; using Elarion.Diagnostics; using Elarion.Abstractions.Scheduling; using Elarion.AspNetCore; using Elarion.AspNetCore.Identity; using Elarion.AspNetCore.Mcp; using Elarion.Auditing.EntityFrameworkCore; using Elarion.Authorization; using Elarion.Caching; using Elarion.EntityFrameworkCore.UnitOfWork; using Elarion.Messaging.Outbox; using Elarion.JsonRpc; using Elarion.Resilience; using Elarion.Scheduling; using Elarion.Validation; using Microsoft.EntityFrameworkCore; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; var builder = WebApplication.CreateSlimBuilder(args); // Clock — used by handlers, jobs, and the current-user snapshot. builder.Services.AddSingleton(TimeProvider.System); // Database: the context lives in the application's persistence layer (the database is application logic); // handlers inject the concrete BillingDbContext. Provider registration (UseNpgsql + connection) is the host's job. builder.Services.AddDbContext(o => o.UseNpgsql(builder.Configuration.GetConnectionString("billing"))); // The unit of work behind Elarion.Pipeline.TransactionDecorator (and the inbox/idempotency decorators): // every transactional handler begins, commits, and rolls back on the billing context. builder.Services.AddElarionUnitOfWork(); // Integration events: durable, after-commit delivery via the EF Core outbox on the billing context. builder.Services.AddElarionOutbox(); // Framework audit trail (ADR-0045): the durable EF sink over the billing context, so [Auditable] handlers // record one compliance AuditRecord per invocation (committed with the transaction; denials included). builder.Services.AddElarionAuditingEntityFrameworkCore(); // Infrastructure capability: the concrete email sender behind the module's port. (The account-standing // policy is a Core [ModuleContract] with a Core-internal [Service] impl — so it self-registers.) builder.Services.AddScoped(); // Scheduler runtime. Job descriptors and event consumers are composed per module by the // services.AddElarion(...) call below — there is no explicit Add…ScheduledJobs call. builder.Services.AddElarionScheduler(builder.Configuration); // Resilience: generated policy metadata + the Microsoft/Polly-backed runtime. The generated method // name is Add{AssemblyName}ResiliencePolicies with dots replaced by underscores. builder.Services.AddBilling_ApplicationResiliencePolicies(); builder.Services.AddElarionResilience(); // Per-user handler caching, backed by HybridCache. builder.Services.AddElarionHandlerCaching(); // Request validation: enforces the DataAnnotations on request DTOs through the generated // per-module resolvers (the same constraints the schemas and the Zod client export). builder.Services.AddElarionValidation(); // Transport-neutral current user, filled from the authenticated principal. builder.Services.AddElarionCurrentUser(options => options.UserIdClaimType = "sub"); // Authentication: a JWT bearer issuer of your choice (Entra, Auth0, Keycloak, …). builder.Services.AddAuthentication("Bearer") .AddJwtBearer(options => { options.Authority = builder.Configuration["Auth:Authority"]; options.Audience = builder.Configuration["Auth:Audience"]; }); builder.Services.AddAuthorization(); // Handler authorization: the IAuthorizer that the generated decorator consults for [RequirePermission]. builder.Services.AddElarionAuthorization(); // Compose every module's services — handlers, services, validation metadata, scheduled jobs, and event // consumers — each gated by Modules:{Name}:Enabled. This also contributes every enabled module's // source-generated JSON context to the canonical serializer every subsystem reads. builder.Services.AddElarion(builder.Configuration); // JSON-RPC: methods gated per module. Serialization comes from the canonical IElarionJsonSerialization // (customize it via ConfigureElarionJson) — no hand-built JsonSerializerOptions is threaded in. builder.Services.AddElarionJsonRpc(ElarionBootstrapper.RegisterHandlers); // MCP: a thin adapter over the same handler bus, equally gated; both surfaces share one registry. builder.Services.AddElarionMcp( builder.Configuration.GetMcpMetadata(), ElarionBootstrapper.RegisterHandlers, o => o.ServerName = "Billing"); // Telemetry: register the Elarion sources/meters; the host owns the exporters. builder.Services.AddOpenTelemetry() .WithTracing(t => t .AddSource( JsonRpcTelemetry.ActivitySourceName, SchedulerTelemetry.ActivitySourceName, HandlerCacheTelemetry.ActivitySourceName, ResilienceTelemetry.ActivitySourceName, HandlerTelemetry.ActivitySourceName, EventTelemetry.ActivitySourceName) .AddAspNetCoreInstrumentation() .AddOtlpExporter()) .WithMetrics(m => m .AddMeter( JsonRpcTelemetry.MeterName, SchedulerTelemetry.MeterName, HandlerCacheTelemetry.MeterName, ResilienceTelemetry.MeterName, HandlerTelemetry.MeterName, EventTelemetry.MeterName) .AddAspNetCoreInstrumentation() .AddOtlpExporter()); ``` ### Build, order the middleware, and map endpoints [#build-order-the-middleware-and-map-endpoints] `UseElarionCurrentUser()` must run **after** authentication so the principal exists, and before the endpoints so handlers can read it. ```csharp title="src/Billing.Api/Program.cs (continued)" var app = builder.Build(); // Apply pending migrations on startup, against the Aspire-provisioned database. using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await db.Database.MigrateAsync(); } app.UseAuthentication(); app.UseElarionCurrentUser(); // snapshot claims into the scoped ICurrentUser app.UseAuthorization(); app.MapElarionEndpoints(app.Configuration); app.MapElarionJsonRpc().RequireAuthorization(); // POST /rpc app.MapElarionMcp().RequireAuthorization(); // /mcp — independent of /rpc app.Run(); ``` `Database.MigrateAsync()` keeps this tutorial short. Once a release needs a C# backfill or a SQL script between two EF migrations, run them all through the one [migration plan](/docs/capabilities/migrations) instead: `AddElarionMigrations(o => o.AddEntityFrameworkMigrations())` replaces the `MigrateAsync()` call. `MapElarionEndpoints` publishes every handler that carries `[HttpEndpoint]` as a minimal-API REST route — the same handler, pipeline, and `Result` mapping as JSON-RPC, just a different projection. None of the Billing handlers opt in so far; making one RESTful is a single attribute: ```csharp [HttpEndpoint("clients/{id}")] // verb inferred from the IQuery marker → GET /clients/{id} [Handler("clients.get")] // …and still exposed over JSON-RPC/MCP — one handler, two transports public sealed class GetClient(BillingDbContext db) : IHandler> { /* … */ } ``` See [HTTP endpoints](/docs/capabilities/transports/http-endpoints) for routing, binding, and verb rules. The JSON-RPC dispatcher, the MCP server, and schema export all read the **one** canonical `IElarionJsonSerialization` — so the generated TypeScript types match exactly what the server serializes. `AddElarion(builder.Configuration)` contributes every module's source-generated context automatically; use [`ConfigureElarionJson`](/docs/capabilities/serialization) only to change naming or add an extra resolver. JSON-RPC and MCP are thin adapters over one handler bus, so you could expose MCP without ever calling `MapElarionJsonRpc()`. Add the scheduler section to configuration so the in-memory runtime is enabled: ```json title="src/Billing.Api/appsettings.json" { "Scheduler": { "Enabled": true, "MaxConcurrentExecutions": 8 } } ``` ### Export the schema on every build [#export-the-schema-on-every-build] Wire the [build-time schema exporter](/docs/capabilities/transports/schema-generation) so `rpc-schema.json` is written to the repo root whenever the host compiles. The frontend client is generated from it. ```xml title="src/Billing.Api/Billing.Api.csproj" true $(MSBuildProjectDirectory)/../../rpc-schema.json ``` The target launches the host up to `builder.Build()`, reads the frozen dispatcher, and writes the schema. Code after `builder.Build()` does not run during generation, so there is nothing to guard here. ### Run it [#run-it] Run the **Aspire app host** — it starts PostgreSQL, applies migrations, and launches the API, then opens the Aspire dashboard with traces and metrics: ```bash dotnet run --project src/Billing.AppHost ``` With a valid bearer token, create a client over JSON-RPC (use the API URL the dashboard shows): ```bash curl -s http://localhost:5000/rpc \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "clients.create", "params": { "name": "Acme Inc.", "email": "billing@acme.test" } }' ``` A success returns `{ "id": "…", "number": "C-000001" }`; a duplicate email returns the JSON-RPC error your host mapped from `AppError.Conflict`. The MCP server is live at `/mcp` for any MCP client, exposing `clients.create`, `invoices.create`, and the rest as tools. For local runs without a real issuer, stamp a development principal before `UseElarionCurrentUser()` (Development only) so `ICurrentUser` resolves and `RequireAuthorization()` passes — exactly what the runnable [`samples/Billing`](https://github.com/swimmesberger/Elarion/tree/main/samples/Billing) app does. In production the JWT bearer registration above takes over. ## What the host owns — and what it doesn't [#what-the-host-owns--and-what-it-doesnt] The host owns the database provider, authentication, middleware order, the scheduler/resilience/cache runtimes, telemetry exporters, and endpoint publication. It owns **nothing** about clients or invoices beyond registering one email capability. Swap PostgreSQL for SQL Server, or the OTLP exporter for Prometheus, without touching a single module. Generate the typed client and call these handlers from React with TanStack Query. # Tutorial (/docs/tutorial) The [Quickstart](/docs/getting-started/quickstart) gets one handler onto the wire. This tutorial goes the whole way: a small but realistic **billing application** with a .NET backend and a typed React frontend, exercising every opinionated Elarion feature on its happy path. You will build **Billing** — a single-tenant-per-user app where a signed-in account manages its **clients** and issues **invoices**. Each feature below earns its place in that story; nothing is bolted on just to demo an attribute. ## What you will build [#what-you-will-build] Two feature modules and a core module, handlers exposed over JSON-RPC, declarative request validation, a transactional decorator pipeline, and per-user result caching. Invoice emails sent through a resilient, retrying background job, plus a nightly cron job that chases overdue invoices. The same handlers exposed to AI agents as MCP tools, with OpenTelemetry traces across RPC, caching, scheduling, and resilience. A Vite + React app using shadcn/ui and TanStack Query, calling a generated, Zod-validated client with full request cancellation via `AbortSignal`. ## How each feature maps to the app [#how-each-feature-maps-to-the-app] Every Elarion capability shows up exactly where it pulls its weight in a real billing flow: | App concern | Elarion feature | Where it appears | | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------- | | Feature boundaries (`Clients`, `Invoicing`) and a shared foundation | [Modules](/docs/concepts/modules) (feature + core) | [Model the domain](/docs/tutorial/modeling) | | Reads and writes as named use cases | [Handlers](/docs/concepts/handlers) + [Results](/docs/concepts/results-and-errors) | [Write the features](/docs/tutorial/features) | | Data access without a repository layer | [EF Core `BillingDbContext`](/docs/capabilities/entity-framework) | [Model the domain](/docs/tutorial/modeling) | | Rejecting bad input | [Validation](/docs/concepts/validation) | [Write the features](/docs/tutorial/features) | | Transactions + logging around every command | [Decorator pipelines](/docs/concepts/decorator-pipelines) | [Write the features](/docs/tutorial/features) | | "Who is calling?" for scoping and audit | [Current user](/docs/capabilities/current-user) | [Write the features](/docs/tutorial/features) | | Fast, per-user reads that stay fresh on writes | [Caching](/docs/capabilities/caching) | [Write the features](/docs/tutorial/features) | | Flaky SMTP that must not drop an invoice | [Resilience](/docs/capabilities/resilience) | [Background work](/docs/tutorial/background-work) | | Send-in-the-background + nightly reminders | [Scheduling](/docs/capabilities/scheduling) | [Background work](/docs/tutorial/background-work) | | After-commit reactions that must not be lost | [Events](/docs/capabilities/events) (durable outbox) | [Background work](/docs/tutorial/background-work) | | A number generator, an email port | [Services](/docs/concepts/services) | [Background work](/docs/tutorial/background-work) | | A typed, optional transport | [JSON-RPC](/docs/capabilities/transports/json-rpc) | [Host the API](/docs/tutorial/hosting) | | The same handlers as AI tools | [MCP server](/docs/capabilities/transports/mcp) | [Host the API](/docs/tutorial/hosting) | | Traces and metrics, no SDK lock-in | [Telemetry](/docs/capabilities/telemetry) | [Host the API](/docs/tutorial/hosting) | | A frontend that calls handlers like functions | [TypeScript client](/docs/capabilities/transports/typescript-client) | [Build the frontend](/docs/tutorial/frontend) | ## The shape of the solution [#the-shape-of-the-solution] Billing follows the [recommended layout](/docs/getting-started/project-structure): the application project declares intent, infrastructure provides concrete capabilities, and the host wires platform concerns. ```text billing/ ├─ Billing.sln ├─ src/ │ ├─ Billing.Application/ # modules (behavior), handlers, services, jobs, policies ← Elarion + generators │ │ ├─ Domain/ # shared-kernel entities + enums (plain classes, under no [AppModule]) │ │ └─ Persistence/ # the database is app logic: [EntityConfiguration], BillingDbContext, migrations │ ├─ Billing.Infrastructure/ # intent-only mechanism adapters: the SMTP email sender │ ├─ Billing.Api/ # ASP.NET Core host ← Elarion.JsonRpc + Elarion.AspNetCore (+ MCP) │ └─ Billing.AppHost/ # .NET Aspire orchestration → provisions PostgreSQL, runs the API └─ web/ # Vite + React + TanStack Query frontend ``` Entities live in a shared-kernel **namespace** (`Billing.Application.Domain`), not a separate project, and their `[EntityConfiguration]` schema lives in a shared `Persistence` layer (configuration is part of the shared data layer, not feature-owned) — see [Solution structure](/docs/concepts/solution-structure) for why. The dependency direction is `Api → Infrastructure → Application`. The application project never references the host or concrete infrastructure — that boundary is what lets the generators wire modules without a central registration list. ## Prerequisites [#prerequisites] * **.NET 10 SDK** or later (see [Installation](/docs/getting-started/installation)). * **Node.js 20.11+** and **npm** for the frontend and client generator. * **Docker** or **Podman** — the .NET Aspire app host provisions PostgreSQL in a container. * The EF Core CLI for migrations: `dotnet tool install --global dotnet-ef`. ## Scaffold the solution [#scaffold-the-solution] ### Create the projects [#create-the-projects] ```bash mkdir billing && cd billing dotnet new sln -n Billing dotnet new classlib -n Billing.Application -o src/Billing.Application dotnet new classlib -n Billing.Infrastructure -o src/Billing.Infrastructure dotnet new web -n Billing.Api -o src/Billing.Api dotnet new aspire-apphost -n Billing.AppHost -o src/Billing.AppHost dotnet sln add src/Billing.Application src/Billing.Infrastructure src/Billing.Api src/Billing.AppHost ``` ### Wire project references [#wire-project-references] The onion points inward — infrastructure and the host depend on the application, never the reverse. ```bash dotnet add src/Billing.Infrastructure reference src/Billing.Application dotnet add src/Billing.Api reference src/Billing.Infrastructure src/Billing.Application dotnet add src/Billing.AppHost reference src/Billing.Api ``` ### Add the Elarion packages [#add-the-elarion-packages] The source generators ship **inside** their runtime packages — the Elarion generator in `Elarion`, the EF Core generator in `Elarion.EntityFrameworkCore` — so there are no separate analyzer packages to install or mark `PrivateAssets="all"`. Because NuGet analyzer assets are not transitive, each project that needs a generator references its package directly. The **application** project holds your modules, entities, and the `[GenerateDbSets]` concrete `BillingDbContext`. It uses EF Core for data access and `Elarion.Validation` so the DataAnnotations input rules on request DTOs are enforced (and the per-module validation resolvers generated): ```bash cd src/Billing.Application dotnet add package Elarion dotnet add package Elarion.Validation dotnet add package Elarion.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore cd ../.. ``` The application's **persistence layer** owns the concrete `BillingDbContext`, the PostgreSQL provider, the EF Core integration-event outbox, and the migrations — because the database is application logic, not an infrastructure detail. The generated class-side `DbSet`s and entity configuration are emitted there beside the configurations (so no cross-assembly manifest is involved): ```bash cd src/Billing.Application dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL dotnet add package Microsoft.EntityFrameworkCore.Design dotnet add package Elarion.Messaging.Outbox dotnet add package Elarion.Auditing.EntityFrameworkCore cd ../.. ``` The **host** project references the JSON-RPC transport, the ASP.NET Core integration, and the MCP server. It also references `Elarion` directly so the bundled generator runs in the host (it emits the RPC map and module bootstrapper), and registers the scheduler, the opt-in resilience and handler-caching runtimes, and EF Core design-time tooling. ```bash cd src/Billing.Api dotnet add package Elarion dotnet add package Elarion.JsonRpc dotnet add package Elarion.AspNetCore dotnet add package Elarion.AspNetCore.Mcp dotnet add package Elarion.Resilience dotnet add package Elarion.Caching dotnet add package Elarion.EntityFrameworkCore.UnitOfWork dotnet add package Microsoft.EntityFrameworkCore.Design cd ../.. ``` ### Turn on the generators [#turn-on-the-generators] Opt the application assembly into Elarion generation once. We will add the pipeline attribute to this file in [Write the features](/docs/tutorial/features). ```csharp title="src/Billing.Application/ElarionAssembly.cs" using Elarion.Abstractions; [assembly: UseElarion] ``` `[assembly: UseElarion]` enables generation for module handlers, services, scheduled jobs, and resilience policies across the assembly. ### Provision PostgreSQL with .NET Aspire [#provision-postgresql-with-net-aspire] Rather than starting a database by hand, let the Aspire app host provision PostgreSQL and inject its connection string into the API. Add the PostgreSQL hosting integration and orchestrate the resources: ```bash dotnet add src/Billing.AppHost package Aspire.Hosting.PostgreSQL ``` ```csharp title="src/Billing.AppHost/AppHost.cs" var builder = DistributedApplication.CreateBuilder(args); var postgres = builder.AddPostgres("postgres").WithDataVolume(); var billingDb = postgres.AddDatabase("billing"); builder.AddProject("api") .WithReference(billingDb) // injects ConnectionStrings__billing into the API .WaitFor(billingDb); builder.Build().Run(); ``` Running the app host (in [Host the API](/docs/tutorial/hosting)) starts the database container and the API together — no manual connection string, and the API reads it via `builder.Configuration.GetConnectionString("billing")`. The host applies EF migrations on startup, so a fresh database is ready on first run. Aspire needs a container runtime (Docker or Podman). The Aspire dashboard it opens also collects the OpenTelemetry traces and metrics the host emits — no separate collector to run locally. The skeleton is in place. Next, model the domain and define the modules that own it. Entities, the `[GenerateDbSets]` concrete `BillingDbContext`, and the Core / Clients / Invoicing modules. # Model the domain (/docs/tutorial/modeling) Billing has two entities — `Client` and `Invoice` — and three modules. **Clients** and **Invoicing** are feature modules; **Core** is an always-on foundation module that owns shared services. In this step you define the data model and the module boundaries; the handlers come in [Write the features](/docs/tutorial/features). ### Define the entities [#define-the-entities] Entities are plain classes — generation is driven by an `[EntityConfiguration]` on each entity's `IEntityTypeConfiguration` (which you add a couple of steps down), not by a marker on the entity itself. Both carry an `OwnerId` — the id of the signed-in account that owns the row — which is what later lets reads and caches be scoped per user. ```csharp title="src/Billing.Application/Domain/Client.cs" namespace Billing.Application.Domain; public sealed class Client { public Guid Id { get; set; } public required string OwnerId { get; set; } public required string Number { get; set; } public required string Name { get; set; } public required string Email { get; set; } public DateTimeOffset CreatedAt { get; set; } } ``` ```csharp title="src/Billing.Application/Domain/Invoice.cs" namespace Billing.Application.Domain; public sealed class Invoice { public Guid Id { get; set; } public required string OwnerId { get; set; } public Guid ClientId { get; set; } public required string Number { get; set; } public long AmountCents { get; set; } public required string Currency { get; set; } public InvoiceStatus Status { get; set; } public DateOnly DueDate { get; set; } public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset? SentAt { get; set; } } public enum InvoiceStatus { Draft, Sent, Paid, Overdue, Cancelled } ``` Money is stored as integer minor units (`AmountCents`) to avoid floating-point rounding. The handlers expose it as cents on the wire too, so the frontend formats it once at the edge. ### Plan the data access [#plan-the-data-access] Handlers inject the concrete `BillingDbContext` directly — the database *is* application logic, accessed on its own terms, so there is [no repository layer](/docs/concepts/handlers#accessing-data) and no context interface. You abstract intent-only dependencies (sending email behind an `IEmailSender`); you do not abstract the database, because you depend on its specifics — constraints, indexes, raw SQL. The context itself, its `[EntityConfiguration]` classes, and the migrations all live in the application's shared `Persistence` layer; only provider registration (`UseNpgsql` plus the connection string) is the host's job. You define `BillingDbContext` a couple of steps down. It carries `[GenerateDbSets]`, and the [EF Core generator](/docs/capabilities/entity-framework) emits a `DbSet` for every `[EntityConfiguration]` entity straight onto that concrete class — `DbSet Clients` and `DbSet Invoices` after the next build. ### Add entity configuration [#add-entity-configuration] Configuration is part of the shared **data layer**, not feature-owned, and the generator discovers it wherever it lives. The `[EntityConfiguration]` attribute on each `IEntityTypeConfiguration` is the single source of truth for an entity's participation — it drives both the generated `DbSet` and the `Configure(...)` application, so a configured entity is a discovered entity (a plain `IEntityTypeConfiguration` with no attribute is ignored). Because configuration is part of the shared data layer, it lives in a `Persistence` layer — a sibling of `Modules`, under no `[AppModule]` — not inside a feature module; see [solution structure](/docs/concepts/solution-structure). It references only the shared-kernel entity, so it never crosses a module boundary (ELMOD002 only inspects constructor/field/property surface, never the `Configure` body). The generator emits direct `ApplyConfiguration` calls — no `ApplyConfigurationsFromAssembly` reflection. ```csharp title="src/Billing.Application/Persistence/ClientConfiguration.cs" using Billing.Application.Domain; using Elarion.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Billing.Application.Persistence; [EntityConfiguration] public sealed class ClientConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { builder.HasKey(c => c.Id); builder.HasIndex(c => new { c.OwnerId, c.Number }).IsUnique(); builder.Property(c => c.Name).HasMaxLength(200); builder.Property(c => c.Email).HasMaxLength(320); } } ``` ```csharp title="src/Billing.Application/Persistence/InvoiceConfiguration.cs" using Billing.Application.Domain; using Elarion.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Billing.Application.Persistence; [EntityConfiguration] public sealed class InvoiceConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { builder.HasKey(i => i.Id); builder.HasIndex(i => new { i.OwnerId, i.Number }).IsUnique(); builder.HasIndex(i => new { i.OwnerId, i.Status, i.DueDate }); builder.Property(i => i.Currency).HasMaxLength(3); builder.Property(i => i.Status).HasConversion(); } } ``` ### Implement the concrete context in the persistence layer [#implement-the-concrete-context-in-the-persistence-layer] The concrete `BillingDbContext` lives in the application's persistence layer — the database is application logic, not an infrastructure detail — beside the configurations and migrations. Annotate it with `[GenerateDbSets]`: the generator emits the matching `DbSet` properties into this partial class and a `ConfigureEntities` call that applies every discovered configuration. ```csharp title="src/Billing.Application/Persistence/BillingDbContext.cs" using Elarion.EntityFrameworkCore; using Elarion.Messaging.Outbox; using Microsoft.EntityFrameworkCore; namespace Billing.Application.Persistence; [GenerateDbSets] public sealed partial class BillingDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); ConfigureEntities(modelBuilder); // generated modelBuilder.UseElarionOutbox(); // integration-event outbox table (Elarion.Messaging.Outbox) } } ``` `[GenerateDbSets]` goes on the concrete context, the single declaration point for the model. The generated `DbSet`s and `ConfigureEntities` are emitted onto this class, so handlers query it directly. ### Define the modules [#define-the-modules] A module is a static partial class marked with `[AppModule]` at the root of a namespace. Everything under that namespace belongs to the module, and the generators register its handlers, services, and validation metadata for you — the host bootstrapper calls a generated `ConfigureDefaultServices`, gated by the module's feature flag, so there are no `Add{Module}…()` calls to write. A module declares only its JSON resolver and any extra, non-generated wiring in `ConfigureServices`. See [Conventions](/docs/reference/conventions). **Core** is a foundation module — `Kind = AppModuleKind.Core` keeps it always enabled and initialized before feature modules. It owns always-on *domain* capabilities other modules build on — such as the account-standing (credit) policy you add next, which Core publishes as a `[ModuleContract]` so `Invoicing` can consult it before raising an invoice. ```csharp title="src/Billing.Application/Modules/Core/CoreModule.cs" using Elarion.Abstractions.Modules; namespace Billing.Application.Modules.Core; [AppModule("Core", Kind = AppModuleKind.Core)] public static partial class CoreModule { } ``` **Clients** and **Invoicing** are feature modules — enabled by default, switchable with configuration. Each publishes its handlers, services, validation metadata, and JSON metadata. ```csharp title="src/Billing.Application/Modules/Clients/ClientsModule.cs" using System.Text.Json.Serialization.Metadata; using Elarion.Abstractions.Modules; namespace Billing.Application.Modules.Clients; [AppModule("Clients")] public static partial class ClientsModule { public static IJsonTypeInfoResolver GetJsonTypeInfoResolver() => ClientsJsonContext.Default; } ``` ```csharp title="src/Billing.Application/Modules/Invoicing/InvoicingModule.cs" using System.Text.Json.Serialization.Metadata; using Elarion.Abstractions.Modules; namespace Billing.Application.Modules.Invoicing; [AppModule("Invoicing")] public static partial class InvoicingModule { public static IJsonTypeInfoResolver GetJsonTypeInfoResolver() => InvoicingJsonContext.Default; } ``` The `ClientsJsonContext` and `InvoicingJsonContext` referenced above are created in the next step, as you add handlers — each module contributes its own [source-generated JSON metadata](/docs/capabilities/serialization). Because Invoicing is a feature module, an operator can switch it off entirely with `"Modules": { "Invoicing": { "Enabled": false } }` — handlers, endpoints, JSON metadata, **and** scheduled jobs disappear together. Core ignores that flag by design. ### Create the migration [#create-the-migration] With the model and context in place, generate the initial migration and apply it. The host is the startup project (it owns the connection string); the migration lands in the application's persistence layer beside `BillingDbContext`. The host needs to register `BillingDbContext` before EF tooling can find it. Add this to `Program.cs` for now (the [Host the API](/docs/tutorial/hosting) step fleshes the rest out): ```csharp title="src/Billing.Api/Program.cs" using Billing.Application; using Billing.Application.Persistence; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateSlimBuilder(args); builder.Services.AddDbContext(o => o.UseNpgsql(builder.Configuration.GetConnectionString("billing"))); var app = builder.Build(); app.Run(); ``` Handlers inject `BillingDbContext` directly. The transaction boundary does not need the context at all: it goes through the `IUnitOfWork` seam, which [Host the API](/docs/tutorial/hosting) registers over this context. ```bash dotnet ef migrations add Initial \ --project src/Billing.Application \ --startup-project src/Billing.Api ``` You do not run `dotnet ef database update` by hand: the host applies pending migrations on startup (`await db.Database.MigrateAsync()` in [Host the API](/docs/tutorial/hosting)), against the database the Aspire app host provisions. To scaffold migrations without launching the host, add a [design-time factory](https://learn.microsoft.com/ef/core/cli/dbcontext-creation#from-a-design-time-factory) that supplies `UseNpgsql(...)` — the runnable sample includes one. ## What you have so far [#what-you-have-so-far] * Two entities, each with an `[EntityConfiguration]`, and a `BillingDbContext` that handlers will query directly. * A `BillingDbContext` whose `DbSet`s and configuration calls are generated, not reflected. * Three modules — one core, two feature — each owning its own surface. Handlers, declarative validation, the decorator pipeline, current-user, and per-user caching. # Why Elarion (/docs/why-elarion) Elarion is opinionated on purpose. This page collects the reasoning behind those opinions in one place, so you can decide whether the trade-offs fit your project before adopting the framework. Each principle links to the page where it is applied. ## The guiding principle [#the-guiding-principle] > Auto-detect application patterns, explicitly wire platform capabilities. Your code already states its intent: a handler says "I handle this request", an annotated request DTO says "this is what a valid command looks like", a `[Service]` class says "this is a module service". Repeating those facts in a separate registration list (`Program.cs`, hand-written `AddXyz()` methods) creates a **parallel model that drifts** from the code it describes. Elarion declares intent next to the type and generates the wiring. The host stays a thin composition and transport shell. Everything below follows from that one idea. ## Compile-time generation over runtime reflection [#compile-time-generation-over-runtime-reflection] Discovery happens at build time through Roslyn generators, not at startup through assembly scanning. **Why:** startup is deterministic and AOT-friendly; the generated code is ordinary DI registration you can read and step through; and mistakes — a missing trigger, an invalid contract, a scoped hosted service — become **build errors instead of runtime surprises**. Registration drift is caught by the compiler. → [Source generation](/docs/concepts/source-generation) · [Why auto-detection is the default](/docs/concepts#why-auto-detection-is-the-default) ## Handlers are the use-case boundary [#handlers-are-the-use-case-boundary] The unit of application logic is an `IHandler`, not a controller, a route lambda, or a service method. **Why:** a handler is a single named use case with one entry point. It is transport-agnostic — it does not know whether it was called over JSON-RPC, HTTP, a scheduled job, or a test — which makes it trivial to test and to reuse across transports. Cross-cutting behavior lives in [decorators](/docs/concepts/decorator-pipelines) wrapped around it in a deterministic order, so the handler body stays focused on business orchestration. → [Handlers](/docs/concepts/handlers) ## Cross-cutting gates are declarative and transport-neutral [#cross-cutting-gates-are-declarative-and-transport-neutral] Authorization and feature gating are **class-level attributes on the handler**, not transport middleware. `[RequirePermission]`/`[RequireRole]`/`[RequirePolicy]` and `[FeatureGate]` describe the same kind of thing — a precondition the request must satisfy before the handler body runs — so they are expressed the same way and enforced the same way: a generated decorator in the [pipeline](/docs/concepts/decorator-pipelines), authorization outermost and the feature gate just inside it. **Why:** a gate that lives in the pipeline runs **identically under JSON-RPC, MCP, and HTTP**, because all three call the same handler. There is no per-transport policy to keep in sync, and the gate is visible right next to the use case it guards. A denied authorization fails closed with `AppError.Unauthorized`/`Forbidden` (401/403); a **closed feature gate short-circuits to `AppError.NotFound` (404)** — a gated-off operation is indistinguishable from one that doesn't exist, so the feature name is never leaked (MS-MVC-style hide-the-roadmap). Module flags decide *whether a feature ships at all* (compose-time — the module disappears); feature gates decide *who sees it now* (runtime — gradual rollouts, targeting, kill switches without a redeploy), and the flag backend is any OpenFeature provider behind one seam. → [Authorization](/docs/concepts/authorization) · [Feature flags](/docs/concepts/feature-flags) ## Results over exceptions for expected failures [#results-over-exceptions-for-expected-failures] Handlers return `Result` carrying either a value or a transport-agnostic `AppError`, rather than throwing for expected outcomes like "not found" or "validation failed". **Why:** expected failures are normal return values, so they are explicit in the type and cheap to produce. `AppError.Kind` describes *what kind* of failure occurred, not how a protocol should report it — the host maps it to a JSON-RPC code or an HTTP status **once, centrally**. The same handler behaves correctly behind any transport. → [Results & errors](/docs/concepts/results-and-errors) ## Modules own their surface [#modules-own-their-surface] A module is a namespace plus an `[AppModule]` marker. Adding a handler, service, or JSON context under that namespace is enough to publish it. **Why:** ownership follows structure. Moving a type between modules changes its ownership through namespace containment; deleting a type deletes its registration on the next build. The host never needs to know a module's internals — it composes modules and maps transports. Feature flags decide which modules are exposed. → [Modules](/docs/concepts/modules) · [Project structure](/docs/getting-started/project-structure) ## Composition over inheritance [#composition-over-inheritance] You compose framework capabilities onto your own types; you do not inherit framework base classes. **Why:** inheritance forces your type into the framework's hierarchy, and only one base class can win. Composition keeps your type yours and lets capabilities stack. It is a through-line, not a slogan: * Your `DbContext` is a plain `DbContext`. Entities are composed in through `[EntityConfiguration]` and `[GenerateDbSets]` — with no repository or `IAppDbContext` in front of it — not by deriving a base context. * ASP.NET Core Identity is composed in with `[GenerateElarionIdentity<…>]`: the generator emits the Identity `DbSet`s and model configuration onto your context **instead of inheriting `IdentityDbContext`**. * Cross-cutting behavior wraps a handler through the [decorator pipeline](/docs/concepts/decorator-pipelines), not a handler base class. * Modules are composed by namespace + `[AppModule]`, not a module base type. The common shape is the one the framework uses everywhere: a marker attribute states intent, a generator emits the wiring onto *your* partial type, and nothing forces a base class. That is also what makes [authorization](/docs/concepts/authorization) provider-neutral — handlers depend on the `ICurrentUser` claims abstraction, so the authentication provider composes underneath without the handler inheriting anything. → [Authorization](/docs/concepts/authorization) · [Entity Framework Core](/docs/capabilities/entity-framework) ## The database is application logic, not an abstraction [#the-database-is-application-logic-not-an-abstraction] Handlers work **directly** against the concrete `DbContext` — its `DbSet`s, LINQ, raw SQL, and provider-specific functions. There is no repository layer, and no context interface in front of it. **Why:** the rule for *what to hide behind an abstraction* is whether you depend on a dependency's **intent** or its **specifics**. Email is intent-only — you say "send this", and SMTP vs SES is interchangeable — so it belongs behind a port (`IEmailSender`). The database is the opposite: a unique constraint *is* a business rule, an index exists for a specific query, and the SQL you write is provider-specific. You depend on its **specifics**, so wrapping it (a repository, or an `IAppDbContext` interface) only hides the model you are actually programming against — and forces a leaky escape hatch the moment you need raw SQL. So the database *is* your data access: handlers use the concrete `DbContext`. The framework wires the *connection* (`UseNpgsql` and the connection string are the host's job); what lives in the database is application logic and yours. This line is **intent-vs-specifics, not database-vs-no-database** — so infrastructure may still own its own persisted state and stay infrastructure. A scheduler's tables, or Elarion's EF Core outbox table, are *mechanism state*: your domain code reaches them only through a port (`IJobScheduler`, `IIntegrationEventBus`) and never queries them as domain. Your **domain model** is application logic; a mechanism's private bookkeeping is infrastructure, even when it shares the same database. → [Entity Framework Core](/docs/capabilities/entity-framework) · [Handlers → Accessing data](/docs/concepts/handlers#accessing-data) ## JSON-RPC for internal APIs [#json-rpc-for-internal-apis] When you need a network transport, JSON-RPC is offered as a first-class (but optional) one because it exposes **operations, not resources** — a method maps one-to-one to a handler. **Why:** it removes an entire category of REST design work (paths, verbs, status-code mapping, resource modeling). The generated, typed client makes a frontend call feel like invoking the handler directly, so the iteration loop is just *add handler → regenerate client → call it*. That fits internal, first-party APIs where one team controls both ends. It is deliberately optional and outside the core package, and modules can expose Minimal API endpoints instead when REST semantics are what you need. → [Why JSON-RPC?](/docs/capabilities/transports/json-rpc#why-json-rpc) ## Observability without lock-in [#observability-without-lock-in] The runtime emits OpenTelemetry-compatible traces and metrics through `System.Diagnostics`, but depends on **no** OpenTelemetry SDK. **Why:** the framework instruments its own boundaries (JSON-RPC, scheduling, caching, resilience) while letting the host choose exporters and which sources to collect. You get observability for free without the framework dictating your telemetry stack. → [Telemetry & observability](/docs/capabilities/telemetry) ## A small reusable contract; the platform stays in the host [#a-small-reusable-contract-the-platform-stays-in-the-host] The framework packages stay domain-neutral and small. Authentication, middleware, database providers, telemetry exporters, and concrete capability implementations are the host's job. **Why:** keeping platform mechanics out of the reusable packages is what lets modules move between hosts unchanged and keeps the framework's public surface stable. Explicit registration is preserved exactly where explicitness is the point. → [Packages](/docs/reference/packages) ## The trade-off [#the-trade-off] The cost of all this is that **you accept conventions**: handler names, the `IHandler<,>` request/response shape, namespace containment, and pipeline attributes matter because the generators use them. In exchange you get less host boilerplate, inherent modularity, fewer runtime scans and faster, more predictable startup, and a clear line between application policy and host mechanics. ## How Elarion differs from ASP.NET Core [#how-elarion-differs-from-aspnet-core] Elarion is intentionally **not** a thin wrapper around the default ASP.NET Core style. It chooses a more application-centric architecture where modules and handlers are the source of truth, while the ASP.NET Core host becomes a composition and transport shell. The differences below are the same principles above, viewed against idiomatic ASP.NET Core. | Topic | Idiomatic ASP.NET Core | Elarion | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Registration | Explicit `services.AddScoped<…>()`, endpoint maps, and feature wiring in `Program.cs`. | Source-generated auto-registration from handler, module, and RPC attributes. Explicit registration remains for infrastructure. | | Application shape | Controllers, Minimal API lambdas, or endpoint classes are the use-case boundary. | `IHandler` is the use-case boundary; transport adapters call handlers. | | Modularity | Folder/project organization plus manually maintained `AddXyz()` methods. | First-class modules with `[AppModule]`: feature flags, ordering, handler/service aggregation, endpoint hooks, JSON metadata hooks. | | Cross-cutting behavior | Middleware, endpoint filters, MVC filters, MediatR behaviors, or nested services. | Generated decorator pipelines wrap handlers in a deterministic order chosen by assembly, module, or handler. | | Feature gating | MVC `[FeatureGate]` / middleware — HTTP-only, and a closed gate typically 404s only on MVC actions. | `[FeatureGate]` as a generated pipeline decorator — transport-neutral (identical under JSON-RPC/MCP/HTTP), closed gate returns 404 over every transport, any OpenFeature provider behind one seam. | | Validation | `[ApiController]` model validation or a validator library — enforced at HTTP binding, invisible to other transports and to exported contracts. | DataAnnotations on the request DTO, enforced by a generated pipeline decorator under every transport and exported to the JSON-RPC schema, OpenAPI, MCP tool schemas, and the Zod client; business rules in the handler. | | Discovery | Runtime reflection scanning for handlers, controllers, endpoint modules. | Compile-time source generation for deterministic startup, AOT friendliness, and inspectable code. | | Host responsibilities | The host often knows every feature and registers most feature services. | The host owns platform capabilities, middleware, auth, telemetry, database setup, and transports; modules own composition. | | Serialization metadata | Global JSON options plus reflection fallback. | Modules contribute `JsonSerializerContext` resolvers following the module boundary. | | EF Core model wiring | Hand-written `DbSet` and `ApplyConfigurationsFromAssembly(…)`. | Optional generator: `[GenerateDbSets]` on the concrete `DbContext`, explicit `[EntityConfiguration]` (single source of truth for DbSet + schema), optional scopes, and direct `ApplyConfiguration` calls. Handlers use the concrete context — no interface. | | Background work | Individual `BackgroundService` loops own their timers, overlap, logging, and cancellation. | Source-generated scheduled jobs share one scheduler with typed invocation, explicit overlap, `TimeProvider`, and telemetry. | | Error model | Exceptions, `ProblemDetails`, action results, or ad-hoc DTOs. | Handlers return `Result` with transport-agnostic `AppError`; the host maps errors per transport. | | Transport | HTTP REST is the default API. | HTTP, JSON-RPC, and MCP are parallel first-class optional transports over the same handlers; JSON-RPC and MCP live outside the core package. | | Client contracts | Frontends hand-write DTOs or ad-hoc REST helpers. | JSON-RPC clients consume generated TypeScript/Zod artifacts and a portable fetch client from the schema. | ## Is Elarion for me? [#is-elarion-for-me] Elarion pays for its conventions when your application's *shape* is the thing you want to keep stable, and it gets in the way when each endpoint needs to be bespoke. **A good fit if you are building:** * a modular application or service where features should register, gate, and move as units; * a first-party, internal API where one team controls both ends and a typed [.NET↔TypeScript contract](/docs/capabilities/transports/typescript-client) removes hand-written DTOs; * something with AOT or trimming goals, where [compile-time generation](/docs/concepts/source-generation) and a reflection-free startup matter; * an app with [in-process background work](/docs/capabilities/scheduling), domain/integration [events](/docs/capabilities/events), or cross-cutting concerns you want expressed as [decorator pipelines](/docs/concepts/decorator-pipelines) instead of scattered middleware. **Probably not a good fit if you need:** * maximum freedom in how each endpoint is shaped — bespoke routes, verbs, content negotiation, and status-code mapping per operation; * a public or third-party REST API where resource modeling and stable URLs are part of the contract; * to stay on the idiomatic ASP.NET Core path with controllers/Minimal APIs as the use-case boundary and explicit registration everywhere. In those cases idiomatic ASP.NET Core fits better. Elarion does not try to be a universal web framework — it is opinionated where the opinions buy you modularity and a thin host. ## Influences [#influences] The model will feel familiar if you have used annotation-driven frameworks such as **Spring Boot** — components live below a namespace boundary, attributes declare their role, defaults cover the common path, and explicit configuration remains for the exceptional case. Elarion implements that philosophy with **.NET source generation** rather than runtime classpath scanning, which is what makes it deterministic and AOT-friendly.