Onboarding guide
4. Domain & Integration Events + Outbox Dual-Dispatch
What this chapter covers. This group is the codebase's event spine: how an aggregate says "something happened", how that fact is persisted so it cannot be lost, and how it eventually reaches every interested handler, whether that handler lives in the same process or in an extracted microservice across a broker. Three questions drive the whole design. How do we publish events reliably when persistence and dispatch are separate steps that can each fail independently? How do we keep application code identical whether a module ships inside the monolith or as its own service? And how does a small single-process application avoid paying for machinery it does not need? The answer to the first is the transactional outbox with an at-least-once background drainer (ADR-003); the answer to the second is a transport-agnostic message bus plus a consumer-side inbox (ADR-006, ADR-008, ADR-021); the answer to the third is a pair of resolved posture flags that turn the outbox and the inbox on for a broker and off for the in-process transport, each stating its choice once at startup. The types here implement all three: the event contracts, the in-process dispatcher, the outbox and inbox tables with their background services and admin surface, and the swappable in-process/broker buses. Two opt-in capabilities are built on top of that spine and live here too: outbound webhooks, which carry an integration event to an external subscriber as a signed HTTP POST (ADR-142), and the process-manager primitive, which drives a long-running process from domain events and timeouts (ADR-143).
If you have not yet met the Result pattern, aggregate roots and domain events, or the database-per-service rule, skim primer §2 first: this chapter builds directly on them.
The two kinds of event
Everything starts with two marker interfaces in the Domain layer. IDomainEvent is
the base contract: a DateOccurred timestamp (when the business action happened, not when it was
dispatched, MMCA.Common.Domain/Interfaces/IDomainEvent.cs:10) and a MessageId GUID used for
consumer-side deduplication (MMCA.Common.Domain/Interfaces/IDomainEvent.cs:13).
IIntegrationEvent extends IDomainEvent and adds no members
(MMCA.Common.Domain/Interfaces/IIntegrationEvent.cs:15): it is a pure role marker. The distinction
is semantic and load-bearing. A domain event is intra-module (raised and handled inside one
bounded context); an integration event is inter-module (one module publishes, others react,
for example Identity's UserRegistered consumed by another module). Because integration events are
domain events, they ride the exact same outbox machinery; the system never needs a second capture
pipeline. What differs is only how they are delivered after capture, which the routing rules below
make precise.
The base records supply the defaults. BaseDomainEvent stamps DateOccurred at
construction (MMCA.Common.Domain/DomainEvents/BaseDomainEvent.cs:28) and mints a fresh MessageId
(MMCA.Common.Domain/DomainEvents/BaseDomainEvent.cs:35), both init so a deserialized event keeps
the values it was created with. Its remarks call out the trap that follows from being a record:
structural equality is not a deduplication mechanism, because those two defaults differ per
instance, so two logically identical events are never equal (BaseDomainEvent.cs:9-17). Dedup is the
inbox's job, keyed on MessageId. A second remark defends the creation-time stamp as a domain-modelling
choice rather than an untestable clock: an event's occurrence instant is the moment the aggregate
raises it, and threading a TimeProvider through every aggregate to move that stamp would not improve
the model (BaseDomainEvent.cs:18-25).
BaseIntegrationEvent adds a virtual SchemaVersion defaulting to 1
(MMCA.Common.Domain/DomainEvents/BaseIntegrationEvent.cs:33). Additive or optional field changes keep
the version, but a breaking change (a renamed, removed, or retyped field) requires a NEW event type
plus an upcaster, never a silent reshape of an existing contract
(ADR-010). That
upcaster is a registration, not a convention
(ADR-090): the module calls
services.AddEventUpcaster<FooV1, FooV2, FooUpcaster>(), and a host still receiving the retired
contract over a broker adds RegisterUpcastedIntegrationEventConsumer<FooV1>() beside its
RegisterIntegrationEventConsumer<FooV2>() (BaseIntegrationEvent.cs:22-31). Handlers are then
written once, against the newest contract. Declaring SchemaVersion virtual with a default is what
kept adding the member a non-breaking change for every event that already existed.
Two reusable shapes sit on top of those bases.
EntityChangedEvent<TIdentifierType> is a CRUD-lifecycle event
carrying a DomainEntityState
(Added/Updated/Deleted) and the affected EntityId
(MMCA.Common.Domain/DomainEvents/EntityChangedEvent.cs:24-27), so entities do not each hand-roll
three near-identical event records; its own remarks reserve it for generic lifecycle events and send
state-machine transitions such as OrderPaid back to BaseDomainEvent
(EntityChangedEvent.cs:16-20). OutputCacheEvictionRequested is the
framework's one concrete integration event
(MMCA.Common.Domain/IntegrationEvents/OutputCacheEvictionRequested.cs:29): a tag list broadcast to
every host that serves output-cached responses, because ASP.NET Core's output cache is per host and a
write in the owning service otherwise leaves a stale response in front of every other replica
(OutputCacheEvictionRequested.cs:12-17). Its Tags list defaults to empty rather than being
required, so a message arriving without the field deserializes into a harmless no-op instead of
faulting a consumer (OutputCacheEvictionRequested.cs:37), and it carries an explicit
[EventName("Common.OutputCacheEvictionRequested.v1")] identity
(OutputCacheEvictionRequested.cs:28).
This split (markers and base records in Domain, all dispatch and persistence machinery in
Application/Infrastructure) is textbook [Rubric §3, Clean Architecture] (the domain declares
what an event is; outer layers decide how it travels) and [Rubric §6, CQRS & Event-Driven] (an
explicit, first-class event model rather than implicit side effects). The SchemaVersion plus
upcaster convention is the [Rubric §9, API & Contract Design] angle: an event on the wire is a
versioned contract like any API surface.
Stored identity: what a row remembers an event as
An event in memory is a CLR type; an event in a table is a string. Which string it is decides
whether a row survives a refactoring, and EventNameResolver is the single
cached lookup that answers it for both storage sites
(MMCA.Common.Infrastructure/Persistence/Outbox/Processing/EventNameResolver.cs:19). An event that declares
EventNameAttribute is stored under that
declared name, which no rename, namespace move, or assembly move changes. An event without one keeps
exactly the identity it had before this type existed: GetStorageName falls back to the
assembly-qualified name for the outbox (EventNameResolver.cs:47-51) and GetInboxName to the short
type name for the inbox (EventNameResolver.cs:59-60). That fallback is what makes adoption opt-in
and leaves rows already in flight unaffected. The declared name is cached per type, including the
null "no attribute" answer, so the common unannotated case pays one reflection lookup per type per
process rather than one per event (EventNameResolver.cs:26,35-38). The reverse direction, resolving a
stored name that is not a CLR name, scans loaded assemblies lazily and degrades to the types that did
load when a dependency is missing (EventNameResolver.cs:75-81,90-100).
Raising and capturing: where the outbox is written
Aggregates raise events by calling AddDomainEvent() (see
AuditableAggregateRootEntity<TIdentifierType>
in G02), which simply buffers them on the entity. Nothing is dispatched yet; the events ride along
until the next save. The actual capture happens in EF Core's save pipeline, in
DomainEventSaveChangesInterceptor
(G07). On SavingChanges it snapshots the change tracker's aggregate roots that have buffered events
and calls OutboxMessage.FromDomainEvent(...) on each, serializing the event to JSON
with cycle-ignoring options, resolving its stored EventType through EventNameResolver, capturing
the current W3C trace and span IDs, and copying the caller's ambient
OutboxOrigin (user, roles, permission claims, tenant, correlation id) onto the row
(MMCA.Common.Infrastructure/Persistence/Outbox/OutboxMessage.cs:180-222). Those
OutboxMessage rows are Added to the same DbContext, so the outbox row and the
aggregate change land in one atomic transaction
(MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:288-307).
This is the single most important guarantee in the chapter: if the business data committed, the event
is durably recorded; if the transaction rolled back, neither exists. There is no window where they
disagree. [Rubric §8, Data Architecture] (transactional integrity) and [Rubric §6] both hinge on
this atomicity. Crucially, the rows go to the same physical database as the aggregate: every
relational source owns its own OutboxMessages table, never a shared one
(ADR-006; the table, its origin
columns, and its three filtered indexes, pending, processed, and ordering, are configured in
MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:903-970, with the inbox's
table and its unique (message, consumer) index at ApplicationDbContext.cs:759-786; see the
primer on database-per-service).
Two details of the capture exist to stop duplicate rows. The interceptor snapshots exactly the events
it captured and removes exactly those again after dispatch, so anything a handler raises mid-dispatch
survives to a later capture instead of being wiped
(DomainEventSaveChangesInterceptor.cs:247-251,455-459). And a save that started but never completed (a failed
save followed by an execution-strategy retry) has its still-Added outbox rows detached before the next
capture, so the retry does not write a second row per event
(DomainEventSaveChangesInterceptor.cs:239,341-357).
The routing split: local events dispatch in-process, integration events wait for the bus
Here is the detail that most people get wrong, and it is the heart of the design. After the
transaction commits (SavedChanges), the interceptor does not treat all captured events the same.
Pure domain events (the local events) are dispatched in-process through
IDomainEventDispatcher and their outbox rows are then marked processed.
Integration events are deliberately not dispatched in-process at all: their outbox rows stay
unprocessed, and the background OutboxProcessor later publishes them through
IMessageBus, so the registered transport (in-process for the monolith, broker for an
extracted service) decides delivery (DomainEventSaveChangesInterceptor.cs:264-289,423-426). That
routing is what makes AddDomainEvent(someIntegrationEvent) broker-correct: without it, such an event
would be dispatched locally and marked processed, silently never reaching the wire. On the asynchronous
save path the local rows are also inserted already leased: each save stamps them with a
LockedUntil of LeaseSeconds ahead under a fresh LockToken, so the processor cannot claim a local
row while its in-process dispatch is still running (DomainEventSaveChangesInterceptor.cs:101-103,286,323-334,
OutboxSettings.cs:89-100); the synchronous path never dispatches in-process, so its rows go in unleased
(DomainEventSaveChangesInterceptor.cs:113-116). When the context
has no outbox table (Cosmos) or the host turned the outbox off, the interceptor falls back to
dispatching everything in-process, since nothing would carry integration events to a processor
anyway (DomainEventSaveChangesInterceptor.cs:69,262,297-303). One more subtlety: when the save runs inside
a Transactional command's transaction, all this post-save work is deferred until after commit
(DomainEventSaveChangesInterceptor.cs:371-377), flushed by
DbContextFactory once the commit succeeds and
dropped on rollback, so handler side effects never act on state that could still roll back.
The mark-processed step is not a second nested SaveChanges. It goes through
OutboxFinalizer, which stamps every row in the batch with a single set-based
ExecuteUpdate and then re-syncs the change tracker (original value first, then clearing IsModified)
so a later save does not re-issue the statement
(MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxFinalizer.cs:27-54), keeping the hottest write
path (every event-raising command) free of an extra full save. The ProcessedOn stamp comes from an
injected TimeProvider, so a test's fake clock moves it together with the processor's lease, backoff,
and retention arithmetic (OutboxFinalizer.cs:21-25,36).
Which rows reach that step is decided one event at a time. InProcessDispatch
is the dispatch loop the interceptor and InProcessEventBus share, so the two
cannot drift on how a failing event is settled
(MMCA.Common.Infrastructure/Persistence/Outbox/Processing/InProcessDispatch.cs:8-14). Its
DispatchBackedAsync hands the dispatcher one event per call and reports which outbox rows were
delivered and which were not, so the caller marks processed exactly the events that succeeded. A failure
holds back only the later events that share the failed event's ordering key, handed to the processor
unattempted so that key stays in order, while unkeyed events and other keys carry on
(InProcessDispatch.cs:16-28,36-74); each failure is one Warning naming the event type
(InProcessDispatch.cs:143-144). DispatchUnbackedAsync is the path with no outbox row behind it (the
outbox is off, or the engine is not relational): nothing retries such an event, so each failure is
logged at Error and the next event still dispatches (InProcessDispatch.cs:76-109). In both, the
isolation is per event, not per handler: the dispatcher runs one event's handlers in sequence, so a
throwing handler still skips the handlers registered after it for that event. The undelivered rows go
back through ReleaseLeaseAsync, which clears their lease guarded by the save's own token, so a row a
processor has since claimed is left alone, and the processor can take them once the processing delay has
elapsed instead of waiting out the full lease (InProcessDispatch.cs:111-142, delegating to
OutboxFinalizer.cs:67; called at DomainEventSaveChangesInterceptor.cs:420,437). That release is best
effort: a failure there is logged and the rows simply wait out the lease.
The dispatcher itself
(DomainEventDispatcher) is a small, performance-conscious piece of
machinery. For each event it resolves every registered
IDomainEventHandler<in TDomainEvent> and, if the event is also
an integration event, every
IIntegrationEventHandler<in TIntegrationEvent>
(MMCA.Common.Application/Services/Events/DomainEventDispatcher.cs:60-81), invoking each through a compiled
expression-tree delegate cached per (event type, handler interface) so the generic HandleAsync call
avoids reflection and boxing at runtime (DomainEventDispatcher.cs:49-57,108-123,136-149), relevant to
[Rubric §12, Performance & Scalability]. The integration branch runs the event through
IEventUpcasterRegistry first, so a retired
contract (including one deserialized from an outbox row written before an upgrade) reaches the handlers
written against its successor (DomainEventDispatcher.cs:76); the domain-event branch is deliberately
untouched, because intra-module handlers keep receiving the original type and instance.
Handlers that perform side effects (email, downstream writes) derive from one of two bases, and the
contract of both is the opposite of what "safe" suggests.
SafeDomainEventHandler<TDomainEvent> logs the failure with
handler and event context and then lets the exception propagate unchanged, through an exception
filter so the log write precedes any unwinding and the stack trace stays intact
(MMCA.Common.Application/DomainEvents/SafeDomainEventHandler.cs:40-51,65-74);
OperationCanceledException passes straight through with no log line, because host shutdown is not a
delivery failure (SafeDomainEventHandler.cs:46). Swallowing would make the "the outbox will retry it"
promise false: a handler that reports success gets its outbox row marked processed, so nothing retries
and the side effect is lost (SafeDomainEventHandler.cs:14-19). Redelivery is per event, as the
class remarks state: the shared dispatch loop settles each event on its own and leaves unprocessed only
the failed event and any later event sharing its ordering key, and the whole batch goes back to the
processor only when the dispatch is cancelled or the mark-processed step itself fails
(SafeDomainEventHandler.cs:21-33, InProcessDispatch.cs:16-28). What the processor repeats is every
handler of the failed event, including the ones that had already succeeded before the throw.
ScopedIntegrationEventHandlerBase<TIntegrationEvent>
is its cross-module sibling and adds the one thing integration handlers all need: because they are
registered as singletons they cannot constructor-inject a scoped service, so the base opens an
AsyncServiceScope per delivery and hands the subclass that scope's provider
(MMCA.Common.Application/DomainEvents/ScopedIntegrationEventHandlerBase.cs:76-87), with the same
log-and-rethrow envelope and an overridable LogHandlerFailure for source-generated logging
(ScopedIntegrationEventHandlerBase.cs:89,128-133). On a broker consume it also stages the handler's
inbox row in that scope before the subclass runs and revokes it if the subclass throws, covered in the
inbox section below (ScopedIntegrationEventHandlerBase.cs:79-84,96-103). Subclasses of either base
must be idempotent: on the outbox path a redelivery re-runs every handler of the failed event, and on
the broker path the per-handler inbox narrows that to the failed handler and the ones after it.
Who the delivery runs as: the captured origin
A delivered event runs a poll cycle later, on another thread and possibly in another process, so
without help it would run as an anonymous, tenant-less system call: a handler reading
ICurrentUserService would see nobody, its writes would carry the system audit sentinel, a
shared-database host would read across tenants, and the delivery could not be joined back to the
interaction that produced it. OutboxOrigin is the record struct that closes that
gap: five positional values (user id, roles as a comma-separated list, permission claims as a JSON
array of strings, tenant id, correlation id,
MMCA.Common.Infrastructure/Persistence/Outbox/OutboxOrigin.cs:31-36). It is deliberately the
mirror of InternalCommandOrigin so the two
background hops capture the same values through the same helper and cannot drift
(OutboxOrigin.cs:14-16). It carries no trace context, because OutboxMessage's
TraceId/SpanId already do and are stamped from the ambient Activity rather than from a scope
(OutboxOrigin.cs:16-18). A default value means "nothing was captured", which is exactly what a
seeder, a design-time write, or a row written before these columns existed reads back as
(OutboxOrigin.cs:20-24); FromDomainEvent's origin parameter is defaulted for the same reason, so
a caller with nothing to capture keeps the single-argument call it always made
(OutboxMessage.cs:179).
Capture is one read per save, not one per event. The interceptor is a singleton and cannot reach a
scoped service, so DbContextFactory attaches a
live accessor to the scoped context (DbContextFactory.cs:157-159) and the interceptor reads it once
through CurrentOutboxOrigin (ApplicationDbContext.cs:176,182,
DomainEventSaveChangesInterceptor.cs:268-273); the two event buses do the same once per batch
(InProcessEventBus.cs:132, BrokerEventBus.cs:82). One save is one scope's work, so every row
of that save carries the same origin by construction. The values land on five nullable columns of the
row (OutboxMessage.cs:135-162): tenant, roles, and correlation id are mapped with explicit widths, while
the permissions column is unbounded and never truncated (OutboxMessage.cs:155,
ApplicationDbContext.cs:714-716).
Restore is per row, immediately before delivery, and on a scope of the row's own. The processor creates
a FRESH DI scope for each row, for the batch's target, and hands the row's five values to the shared
AmbientOrigin helper, which writes them onto
that scope before the payload is even deserialized, stamping the rebuilt identity with an Outbox
authentication type (OutboxProcessor.cs:84,675-689). A fresh scope is what lets the tenant change
between rows of one shared-target batch, since the tenant context refuses a change once resolved, and it
means one row's identity can never answer for another's; the cycle scope's context still holds the
claimed rows and writes the lease renewals and the outcomes, so only delivery moves to the row scope
(OutboxProcessor.cs:575-584). The
in-process path then gets the right ambient context for free, and on the broker path
BrokerMessageBus reads those same scoped services back out to stamp tenant,
user, roles, permissions, and correlation headers on the outgoing message, collecting only values that are actually
present so an absent header keeps meaning "the publisher had nothing to say" rather than becoming a
false answer (BrokerMessageBus.cs:126-154). On the far side,
IntegrationEventConsumer<TEvent> applies the mirror step through
ConsumerOriginRestore before the inbox is touched, because under database-per-tenant the restored
tenant is what routes the store to the right database, and a message from an older publisher carries no
headers and restores nothing (IntegrationEventConsumer.cs:76, the helper itself in
G14). The restore handle stays open for
the whole consume, so a handler that opens its own scope from the root factory still runs as the
publisher's origin (IntegrationEventConsumer.cs:76). The identity rebuilt from those
headers is stamped with an IntegrationEvent authentication type, which is what makes it count as
authenticated and names the hop it came back from (IntegrationEventConsumer.cs:51). One mechanism
therefore carries the authorization principal, the audit stamps, the tenant routing, and the
correlation id across both asynchronous hops: [Rubric §17, Security & Compliance] and
[Rubric §13, Observability & Operability] at the same time.
The safety net: how the processor schedules itself
The OutboxProcessor is a BackgroundService and the most intricate type in the
group; most of its complexity is about not wasting work. It exists because the steps between
commit and mark-processed can be interrupted: the process can crash, or in-process dispatch can
throw. When that happens the row stays unprocessed (and the interceptor releases its lease and signals
the processor on its failure path, DomainEventSaveChangesInterceptor.cs:415-422,428-441) and the processor
catches it on a later cycle. This is the at-least-once guarantee of
ADR-003. Its unavoidable cost is
that the same event may be delivered more than once, so handlers must be idempotent. That is not
a wart; it is the documented contract and a healthy discipline regardless.
The processor never blindly polls on a fixed clock. Its loop is the shared PollingLoop
(MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:136-148): after a five second startup delay
(MMCA.Common.Infrastructure/Persistence/Polling/PollingLoop.cs:18,59) it drains every outbox
target once per cycle and aggregates the per-target results into an
OutboxCycleResult (OutboxProcessor.cs:171), then waits on
IOutboxSignal for whichever comes first: a signal (a writer called Signal()
after persisting a row; OutboxSignal is a thin wrapper over the shared WakeUpSignal,
a SemaphoreSlim(0, 1) whose single-permit cap deliberately absorbs a burst of surplus signals, since
one batch drains everything anyway,
MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxSignal.cs:10-23,
MMCA.Common.Infrastructure/Persistence/Polling/WakeUpSignal.cs:18-30), the moment the earliest
pending-but-not-yet-eligible row becomes eligible (the smart wait), or the fallback
PollingIntervalSeconds (PollingLoop.cs:94, arithmetic in ComputeWaitTime at
PollingLoop.cs:117-130 with a one second floor so an overdue row cannot hot-loop the service,
PollingLoop.cs:21). A target is one owned relational source against the shared database, plus one
extra unit per tenant that keeps its own copy of a source, because a tenant database has its own
OutboxMessages table that nothing else would ever open; the processor asks the injected
FrameworkTableTargets for that list (OutboxProcessor.cs:66,161). Each target is visited in its
own DI scope with the tenant set before the context is asked for, since the tenant is what routes the
factory to the right database (the same per-target scoping the admin surface documents,
OutboxAdministration.cs:22-24).
Rows are eligible ProcessingDelaySeconds after creation, and that delay defaults to 0 (range 0 to
600), so an integration event is published as soon as the post-save signal wakes the processor, tens of
milliseconds after the save (OutboxSettings, OutboxSettings.cs:38-50). The fetched
batch is split against a cutoff computed once per cycle (OutboxProcessor.cs:206,213-217, fetch at
OutboxProcessor.cs:340,374-377). That delay sets eligibility only; the property's own remarks are explicit
that it does not bound the duplicate-dispatch window, because local rows of an asynchronous save are
inserted under the LeaseSeconds lease, so the in-process pipeline (save, dispatch, mark processed)
races the processor only once that lease expires, and handlers must be idempotent regardless. A host
raises it only to hold rows back deliberately, for example to give a failed in-process local dispatch a
pause before the processor retries it (OutboxSettings.cs:41-48). The smart wait means that even
when the fallback interval is raised in a deployed environment (the default is 2s and the property's
own remarks name 300 as the deployed value to cut idle polling, OutboxSettings.cs:28-36), a signalled
event still goes out promptly and a held-back row goes out as soon as its delay elapses. Batches are 50
rows (OutboxSettings.cs:17). One
unreachable database cannot starve the others: the targets are drained through the shared
PollingLoop.DrainAllAsync with a per-source error callback, and a failing target simply contributes
nothing (and zero backlog) to this cycle (OutboxProcessor.cs:171).
Claiming, scale-out, and ordered delivery
Because a deployment may run more than one replica, each cycle claims its eligible prefix with a
lease (LockedUntil plus LockToken,
MMCA.Common.Infrastructure/Persistence/Outbox/OutboxMessage.cs:62-75) via a conditional
ExecuteUpdate before dispatching (OutboxProcessor.cs:494-497), and the poll query skips rows under
an unexpired lease (OutboxProcessor.cs:374-377). Two replicas therefore can never double-dispatch the
same row, and a replica that dies mid-batch releases its rows when the lease expires (LeaseSeconds,
default 300, OutboxSettings.cs:100). When the claim comes back partial, the processor works only the
ids that carry its own token (OutboxProcessor.cs:506-514). That is scale-out
safety by construction, not merely by the minReplicas: 1 deployment convention. The claim is not the
end of it, because one lease covers the whole batch and a slow batch could outlive it: before each row
the remaining lease is checked against the clock, and once less than half of LeaseSeconds is left the
processor flushes its buffered stamps and renews every not-yet-dispatched row of the batch in ONE
statement guarded on the batch's lock token; a row that renewal finds under another token is skipped
(OutboxProcessor.cs:661-665,823-836,958-996). Outcomes are written two ways. A failed row's retry or
dead-letter state is written, token-guarded, as soon as that row is done (OutboxProcessor.cs:873-884,1118-1140).
Delivered rows are buffered and stamped processed together, by one guarded set-based update per flush:
at the end of the batch, before a lease renewal, and on every early exit (a shutdown, a failed write)
(OutboxProcessor.cs:38-41,1011-1049), in chunks of at most 500 ids, well under SQL Server's parameter
limit (OutboxProcessor.cs:89-93). A replica that lost a row mid-dispatch therefore drops its stale stamp
instead of overwriting the new owner's. A shutdown signalled while a row is in flight still records the
outcomes of the rows already done, under a five second budget of its own
(OutboxProcessor.cs:107-114,900-918,1053-1060); what a crash (or a failed exit flush) costs is the rows
delivered since the last flush, which are redelivered once their lease expires (OutboxProcessor.cs:44-48).
The claim is also where ordered delivery is enforced. An event that opts in by implementing
IHasOrderingKey has its key copied onto the
outbox row at capture (OutboxMessage.cs:128,203), and the claim predicate then refuses that row while
any earlier unprocessed, non-dead-lettered row shares the key, expressed as a correlated NOT EXISTS
inside the update itself so a racing replica loses on the row rather than on a check made before the
race (OutboxProcessor.cs:406-416,555-566). The fetch applies the same guard before the window is cut,
but only when the plain fetch returned a keyed row: the window is then fetched again without the rows
their key blocks, so a blocked or bursty key occupies at most one of the BatchSize slots instead of
the whole window (OutboxProcessor.cs:260-289,379-401). Within one cycle, SelectOrderedCandidates
keeps at most the first row per key (OutboxProcessor.cs:476,524-540), and a cycle that deferred such
key-mates, or whose key-aware fetch hid them, asks for an immediate re-poll once it delivers anything,
rather than serializing a key at one row per polling interval (OutboxProcessor.cs:246-255,418-442). A
batch containing no keyed row skips that predicate entirely, so hosts that never declare a key pay
nothing for the feature (OutboxProcessor.cs:284-285,487-492). The cost is head-of-line blocking,
documented on the interface itself: a retrying keyed row blocks its successors until it succeeds or is
dead-lettered, at which point it stops blocking so a poison event cannot freeze its key
(OutboxProcessor.cs:456-458); keys must therefore be as narrow as the requirement really is (one per
aggregate, never a constant).
Failures, dead-letters, and keeping the table (and telemetry) bounded
Delivery failures split into outcomes worth keeping straight. A transient failure (a handler or
broker publish throwing) increments the row's RetryCount, records LastError, and re-leases the
row for an explicit exponential backoff rather than leaving this cycle's claim on it
(OutboxProcessor.cs:764-775). The backoff is RetryBackoffBaseSeconds * 2^(n-1) (base 10s,
OutboxSettings.cs:117) multiplied by a random jitter factor in [0.8, 1.2] and capped at the lease
(OutboxProcessor.cs:1244-1245, delegating to PollingLoop.cs:197); the jitter is what stops fifty rows that failed together on one
dependency outage from retrying in lockstep against that same dependency. Abandonment is an explicit
state on the row rather than a reading of RetryCount against the setting: once a failure brings
RetryCount to MaxRetries (5 by default, OutboxSettings.cs:26) the row is dead-lettered, which
stamps DeadLetteredOn from the processor's clock, records a DeadLetterReason, and clears the lease,
counts it on the outbox.dead_letter.count counter with reason=retries_exhausted, and writes one loud
Error log line at the moment of exhaustion (OutboxProcessor.cs:795-806,1232-1237,1334). Every poll,
claim and pending count filters on DeadLetteredOn being null (OutboxProcessor.cs:316,376,552), so a
dead letter leaves the poll whatever MaxRetries is later changed to: raising the setting no longer
silently replays old dead letters, and lowering it no longer silently abandons rows still pending
(OutboxMessage.cs:80-101). A row whose stored EventType resolves to nothing is treated more
gently: the FIRST such attempt is retried through the normal backoff with a Warning
naming the fix (give the event an [EventName]), because the declaring assembly may simply not be
loaded yet; only the second attempt is terminal, and it dead-letters the row the same way (ProcessedOn
left null, DeadLetteredOn and the reason stamped), counting it with reason=type_unresolvable
(OutboxProcessor.cs:1196-1221,1328). The row therefore leaves the poll, so an undeliverable payload
cannot block the queue behind it, yet stays a dead letter an operator can find and replay. A host
configured with MaxRetries of 1 gets no retry here either (OutboxProcessor.cs:1200-1202). Bus
publishes additionally run inside a circuit breaker built from
BrokerResilienceDefaults and carrying no
retry strategy of its own, since the outbox already owns retry; a host shutdown's
OperationCanceledException does not count toward its failure ratio
(OutboxProcessor.cs:118-133,1247-1266). The breaker wraps only the IMessageBus publish of an
integration event: that is the broker hop on a host with broker messaging, but on a monolith the default
InProcessMessageBus runs the integration-event handlers inside the breaker, so failing handlers can
open it too. The pure domain-event branch and every database call stay outside it, since a breaker on
those would open exactly when the processor most needs to persist retry state
(OutboxProcessor.cs:926-948). An open circuit is a rejection, not a delivery attempt: the row does not
spend a retry and cannot be dead-lettered by it, so a long outage cannot walk every undelivered row
through its whole budget without one real attempt (OutboxProcessor.cs:750-759). It is reported
as its own fact: one BrokerMetrics.CircuitOpenCounter increment per row and one Warning per batch
rather than fifty identical lines (OutboxProcessor.cs:652-655,779-793), and the rejected row is
re-leased for a backoff derived from the breaker's break duration, capped at the lease,
instead of the per-attempt exponential one (OutboxProcessor.cs:772-775, PollingLoop.cs:219).
The instruments themselves live in OutboxMetrics, a single OpenTelemetry meter
named MMCA.Common.Outbox (MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxMetrics.cs:19)
carrying the dead-letter counter (OutboxMetrics.cs:41-44), a success counter
(OutboxMetrics.cs:47-50), an end-to-end delivery lag histogram in seconds, the number that
answers "how far behind is eventual consistency right now" (OutboxMetrics.cs:57-60, recorded at
OutboxProcessor.cs:1103-1108), an observable backlog depth gauge
(OutboxMetrics.cs:75-79), and an oldest-pending age gauge per data source, which is what an alert
on a wedged outbox fires on (OutboxMetrics.cs:98-102). Both gauges are per instance, not fleet-wide,
and both are derived from the fetch wherever they can be: the poll is already ordered by OccurredOn,
so its first row is the oldest (OutboxProcessor.cs:278-282), and a short batch is the whole
backlog, so only a saturated batch pays for a COUNT (OutboxProcessor.cs:291-319). This is dense
[Rubric §13, Observability & Operability] and [Rubric §31, Cost/FinOps] territory: the poll, the
key-aware re-fetch and that count each run inside a named OutboxPoll activity
(OutboxProcessor.cs:78,311,337,357) which
OutboxPollFilterProcessor (G16)
suppresses from telemetry export, so a fleet of idle services polling around the clock does not flood
Application Insights, and the per-message success line is Debug for the same reason
(OutboxProcessor.cs:1319). Each dispatched message also re-parents an OutboxProcess consumer
activity onto the trace context stored on its row, so the broker hop stays linked to the request that
raised the event. The parent is rebuilt with the row's stored W3C trace flags, the request's sampling
decision, so a parent-based sampler exports the delivery span only when the request itself was sampled,
and a row with no stored flags reads as not sampled (OutboxMessage.cs:109-116,
OutboxProcessor.cs:1268-1295).
A sibling OutboxCleanupService keeps the tables bounded. It runs three
sweeps, each on its OWN retention window, so turning one off never silently turns another off with it
(MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxCleanupService.cs:17-33). Every
CleanupIntervalHours (default 6, OutboxSettings.cs:87; the first sweep waits one whole interval so it
never competes with startup, OutboxCleanupService.cs:88-94) it purges processed rows older than
RetentionDays (default 7, OutboxCleanupService.cs:63,133-136, OutboxSettings.cs:77), then purges
dead-lettered rows on their own DeadLetterRetentionDays window, falling back to RetentionDays when
that setting is left at its default of zero (OutboxCleanupService.cs:69-71,138-141, OutboxSettings.cs:130),
since those rows never get a ProcessedOn and would otherwise accumulate forever inside the pending
index that every poll re-scans. That window runs from the row's DeadLetteredOn stamp, so a replayed
and re-dead-lettered row gets a full window again; every dead-letter deletion is logged at Warning
with its count (OutboxCleanupService.cs:162-200,255). The third sweep purges inbox rows older than
the inbox's own RetentionDays (default 30, independent of the outbox window), read through
InboxPosture, which reports 0 for a host with no inbox, so that sweep runs only
where the inbox is enabled (OutboxCleanupService.cs:74,143-146). Setting a window to 0 keeps those
rows forever, and the service does not run at all only when all three windows are 0
(OutboxCleanupService.cs:97-109). The purge is idempotent, so with a distributed lock registered
(AddInfrastructure always registers one) it runs on one replica per interval rather than on every
replica (OutboxCleanupService.cs:80-85). Because payloads may contain personal data, this sweep is also part of
the privacy posture of ADR-005.
Both background services take an injected TimeProvider (OutboxProcessor.cs:59-67,
OutboxCleanupService.cs:44-45,56) so tests can drive an hour-scale loop deterministically instead of
waiting on wall-clock time, a small but real [Rubric §14, Testability] win.
Dead letters are not only swept, they are operable. OutboxAdministration
is the scoped EF-backed admin surface behind
IOutboxAdministration: it lists dead letters
with merged paging across every target and a hard 500-row page cap
(MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxAdministration.cs:48,90,99), counts pending rows
(OutboxAdministration.cs:299-312), and replays dead letters as one set-based UPDATE per target, which
clears the dead-letter stamp, followed by a Signal() so the processor picks them up immediately rather
than on the next interval (OutboxAdministration.cs:153,172,184-186,207). Its fourth operation,
RepublishProcessedAsync, re-publishes the integration events processed within a UTC window of at most
7 days: it asks each source for the distinct stored names in the window, resolves them as the processor
would, updates only the names that resolve to an IIntegrationEvent, and signals the processor
(OutboxAdministration.cs:64,223-292,351-353). It refuses to run unless the consumer inbox is enabled,
because the inbox is what turns a republish into a harmless duplicate, and it refuses a window that
starts before the inbox horizon, because consumers dead-letter such old events unrun; both answers come
from InboxPosture (OutboxAdministration.cs:34-36,75-87,228-238,338-349). It visits
the same tenant-expanded targets in the same per-scope way the two background services do
(OutboxAdministration.cs:16-27), and its validation failures come back as
Result errors rather than exceptions
(OutboxAdministration.cs:55-83).
The pluggable transport, and the posture flags that decide it
Here is the boundary that makes a module extractable without rewriting its handlers. Application code
that wants to publish an integration event depends on IEventBus (or on the lower-level
IMessageBus, both defined in Application, so neither ever sees a broker client).
Infrastructure supplies two interchangeable implementations of each, selected by registration:
- Monolith mode (the defaults,
MMCA.Common.Infrastructure/DependencyInjection.cs:408,414).InProcessEventBuswrites the events to the outbox in one save under a lease, dispatches them in-process, and marks them processed through the sameOutboxFinalizerpath as the interceptor (MMCA.Common.Infrastructure/Messaging/InProcessEventBus.cs:130-194), settling each event on its own throughInProcessDispatch, and falls back to a plain dispatch when the context has no outbox support or the host disabled the outbox (InProcessEventBus.cs:117-128). Inside an open transaction both branches defer the dispatch to the same post-commit hook the save interceptor uses, so handlers see only committed state and a rollback runs none of them (InProcessEventBus.cs:98-102,110-123).InProcessMessageBusjust hands the event straight to the dispatcher (MMCA.Common.Infrastructure/Messaging/InProcessMessageBus.cs:21-32); it is what theOutboxProcessorcalls when draining an integration-event row in monolith mode. - Broker mode (
AddBrokerMessaging, which replaces both registrations,DependencyInjection.Messaging.cs:128,134).BrokerEventBuswrites the whole batch to the outbox in ONE save and then signals the processor without dispatching in-process (MMCA.Common.Infrastructure/Messaging/BrokerEventBus.cs:58-108), because the consumers live in other processes, so an in-process dispatch would be wrong; a data source with no outbox support throws loudly here rather than silently dropping events (BrokerEventBus.cs:71-78). TheOutboxProcessorthen drains the row and publishes it throughBrokerMessageBus, which serializes the event as its runtime type and publishes it on that type's topic, so routing binds to the concrete event class rather than theIIntegrationEventbase interface (MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs:58-62,83-87). The bytes go out through theIBrokerPublisherof whichever transportMessageBus:Providerselects: RabbitMQ and PostgreSQL are built in, and a vendor adapter such asMMCA.Common.AzureorMMCA.Common.Awsregisters its own (BrokerMessageBus.cs:14-18,46-51). The bus starts a Producer span and writes its W3Ctraceparentandtracestateas message headers, so distributed traces stay connected across the broker hop (BrokerMessageBus.cs:70-81,106-118).
Whether the outbox exists at all is itself configuration, and it resolves from the transport.
MessageBusSettings exposes
IsOutboxEnabled and IsInboxEnabled, each defaulting to ON for a broker provider and OFF for
InProcess (MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:140,176). A single-process
application dispatches every event inside the process that raised it, so store-and-forward buys it two
background services, a table and a poll loop and nothing else; a broker deployment cannot deliver at all
without it. An explicit value wins in both directions for the in-process transport, so a monolith that
wants at-least-once delivery across a crash sets MessageBus:EnableOutbox=true
(MessageBusSettings.cs:151), but turning the outbox OFF under a broker is refused at registration with
a startup failure rather than honored, because it would drop every cross-service event silently
(DependencyInjection.Messaging.cs:265-268). Neither posture is allowed to be invisible: with the outbox off,
OutboxDisabledNoticeService logs one startup Information line naming
the changed guarantee (MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxDisabledNoticeService.cs:22-38,
registered at DependencyInjection.cs:305), and with the inbox explicitly off under a broker,
InboxDisabledWarningService logs one Warning
(MMCA.Common.Infrastructure/Persistence/Inbox/InboxDisabledWarningService.cs:20-36,
DependencyInjection.Messaging.cs:162). The level difference is deliberate: the first is the default posture of a
small application, the second is an opt-out of a safety feature.
The inbox has a second dimension besides on or off: how long its rows dedupe.
InboxSettings binds the optional Inbox section and carries one value,
RetentionDays, default 30 and range 0 to 3650, deliberately independent of Outbox:RetentionDays so
the dedup window and the outbox table size are two separate decisions
(MMCA.Common.Infrastructure/Persistence/Inbox/InboxSettings.cs:10-33). That value is the host's
deduplication horizon: an event redelivered after its inbox rows were purged would run its handlers
again, so the broker receive pipeline dead-letters, without running a handler, an event whose
DateOccurred is older than the horizon, and the republish operation refuses a window starting before
it; 0 keeps the rows forever and turns both checks off (InboxSettings.cs:15-31).
InboxPosture is the one rule every reader of that horizon resolves through, so the
cleanup sweep, the republish guard and the receive pipeline cannot disagree: IsEnabled mirrors
MessageBusSettings.IsInboxEnabled, RetentionDays is the configured value only when the inbox is
enabled and 0 otherwise, and Horizon is that many days or null when it is 0
(MMCA.Common.Infrastructure/Persistence/Inbox/InboxPosture.cs:13-41). A host with no inbox therefore has
no inbox rows to purge and no horizon to enforce, whatever Inbox:RetentionDays says. It is registered
as a singleton beside the bound Inbox options (DependencyInjection.cs:162-171), and the broker wiring
builds the same posture from configuration to hand the receive pipeline its horizon
(DependencyInjection.Messaging.cs:113-116).
The selection between transports is a pure DI swap: no application or domain code changes. That is the
whole point of [Rubric §7, Microservices Readiness]: transport choices live at the edges, and the
architecture transport-boundary rule forbids Application/Domain/Shared from referencing a broker
client at all (RabbitMQ, Azure Service Bus, Amazon SQS and SNS, and MassTransit, which is banned outright)
(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Layering/ArchitectureRules.Transport.cs:14-23,
MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Layering/MicroserviceExtractionTests.cs:7,
ADR-007 and
ADR-008). Note the deliberate
division of labor: the *EventBus types own outbox persistence (write and signal); the
*MessageBus types own delivery only and are invoked by the processor when draining
already-persisted rows.
Consuming from the broker: the inbox and the generic consumer
On the receiving side of a broker hop, application code keeps writing plain
IIntegrationEventHandler<TEvent> implementations; there is no broker-specific consumer class to
author per event. The generic IntegrationEventConsumer<TEvent> is
the single adapter that bridges a broker-delivered TEvent to all the registered in-process handlers
(MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumer.cs:10-17,62), registered per
event type with RegisterIntegrationEventConsumer<TEvent>() on the
IBrokerConsumerBuilder that the
configureConsumers callback of AddBrokerMessaging receives
(MMCA.Common.Infrastructure/Messaging/Broker/IBrokerConsumerBuilder.cs:6-8,26). Each call adds one
subscription that binds the event's topic to the host's single queue, and registering the same event (or
the same event name) twice throws (MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:47-62).
Because a host has one queue, two services consuming the same event never compete for one queue and there
is no per-consumer endpoint configuration; no separate fault consumer is registered either, since a
message that exhausts its in-process retries and its redeliveries is dead-lettered by
BrokerReceivePipeline, which logs it once
at Error and adds one to the broker.fault.count counter (IBrokerConsumerBuilder.cs:9-14,
BrokerReceivePipeline.cs:177-201). Two siblings sit beside it:
RegisterUpcastedIntegrationEventConsumer<TEvent>() drains a retired contract through
UpcastingIntegrationEventConsumer<TEvent>
into the handlers of its successor (IBrokerConsumerBuilder.cs:29-40,
ADR-090); the builder picks
the closed consumer type from the subscription kind (BrokerConsumerBuilder.cs:36-45), and registering
both kinds for one event is exactly the duplicate it rejects (BrokerConsumerBuilder.cs:51-57). And
IntegrationEventConsumerExtensions adds
RegisterOutputCacheEvictionConsumer(), an extension(IBrokerConsumerBuilder) member that is the named
shorthand for the framework's own eviction broadcast, forwarding to
RegisterIntegrationEventConsumer<OutputCacheEvictionRequested>()
(MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumerExtensions.cs:13,28-33). The handlers themselves run
through the shared InboxHandlerLoop
(IntegrationEventConsumer.cs:83-90). A handler that throws is logged at Error with the failing
handler's type and rethrown with nothing recorded for it, so the framework receive pipeline retries it in
a fresh scope (exponential backoff, MessageBusSettings.RetryLimit retries) and then redelivers or
dead-letters it (MMCA.Common.Infrastructure/Messaging/Consumers/InboxHandlerLoop.cs:93-105), and a
message with no registered handler in this process is completed with an Information line rather than
being retried forever (IntegrationEventConsumer.cs:92-98).
Because broker delivery is also at-least-once, the consumer guards against duplicates with the
inbox (ADR-021), and the
shape of that guard is the subtle part: it is keyed per handler, not per message. An
InboxMessage row records that one consumer processed one MessageId
(MMCA.Common.Infrastructure/Persistence/Inbox/InboxMessage.cs:3-14), and the consumer is named by
InboxConsumer: the handler's
InboxConsumerNameAttribute value when it declares one, otherwise its full
type name truncated to the 256-character column, resolved once per handler type
(MMCA.Common.Application/DomainEvents/InboxConsumer.cs:32-47,
MMCA.Common.Application/DomainEvents/InboxConsumerNameAttribute.cs:28). The attribute exists for
renames: without it, renaming or moving a handler class changes its key and the next redelivery of an
already-processed message runs it once more, so a team applies it, with the CURRENT full type name,
before the rename (InboxConsumerNameAttribute.cs:3-22). IInboxStore is a two-method
contract: GetProcessedConsumersAsync returns, in one read, the consumer names already recorded for a
message (possibly including the empty legacy name), and RecordAsync records one consumer, idempotently
(MMCA.Common.Infrastructure/Persistence/Inbox/IInboxStore.cs:3-41), so a message costs about k + 1
round trips for k handlers. InboxHandlerLoop
drives it in registration order: it takes that one read when the first handler comes up (a message with
no handler touches no inbox), skips a handler the set names (or every handler when a legacy row is
present), and otherwise runs the handler and then records it
(MMCA.Common.Infrastructure/Messaging/Consumers/InboxHandlerLoop.cs:45-80). A throw stops the loop
with the earlier handlers already recorded, so the retry or redelivery runs only the failed handler and
the ones after it (InboxHandlerLoop.cs:11-18).
The atomic half lives on the handler side. Around each handler, and its record, the loop sets an
InboxConsumeScope marker: an AsyncLocal Entry of message id and
consumer name, whose disposable Handle restores the previous marker so a nested consume
never leaks into the outer one; the entry also carries a Staged flag that tells the record step
whether the handler staged its own row
(MMCA.Common.Infrastructure/Persistence/Inbox/InboxConsumeScope.cs:16-77, InboxHandlerLoop.cs:67-77).
ScopedIntegrationEventHandlerBase<TIntegrationEvent>
resolves the optional IInboxRecorder from the scope it
opens and stages the row before the subclass runs (ScopedIntegrationEventHandlerBase.cs:79-84).
EfInboxRecorder adds that row, unsaved, to the scope's context for the inbox data
source, but only when the marker matches both the message and the consumer, so the in-process dispatcher
path and a nested event's handler never stage one; a staging marks the entry as staged
(MMCA.Common.Infrastructure/Persistence/Inbox/EfInboxRecorder.cs:36-59,83-85). A subclass that saves
on that scope therefore commits the dedup row in the same transaction as its writes, closing the window
where a crash between "handler committed" and "inbox written" re-ran it; that atomicity holds when the
handler writes to the same physical source the inbox lives in (EfInboxRecorder.cs:13-23). Because the
row rides the scope's first successful save, a subclass that saves and then throws has already committed
it, so the base revokes it from a fresh scope under a five second budget, a set-based delete of that
handler's row only; a revoke that fails is logged at Error and the handler's original exception
propagates (ScopedIntegrationEventHandlerBase.cs:63,96-103,152-178, EfInboxRecorder.cs:61-81).
EfInboxStore is the consume-scope half. GetProcessedConsumersAsync is one query over
the (MessageId, Consumer) index whatever the number of handlers
(MMCA.Common.Infrastructure/Persistence/Inbox/EfInboxStore.cs:47-59). RecordAsync reads before it
writes only when the handler staged its own row during this consume, the one case where the handler's
save may already have committed it, and then writes nothing if the row is there; every other handler is
recorded with a single insert after it returned (EfInboxStore.cs:61-97). Concurrent duplicate deliveries
are absorbed by the unique index on (MessageId, Consumer) (ApplicationDbContext.cs:778-780): the
store detaches the rejected row, re-queries, and treats the rejection as recorded, rethrowing any other
write failure so a message is never acknowledged with its record missing (EfInboxStore.cs:99-114). A
row with an empty consumer is a legacy message-wide row and answers "processed" for every handler, which
is the value the column's '' default backfills, so an upgrade never re-runs a message the old inbox
recorded (EfInboxStore.cs:41-45,117-131, InboxMessage.cs:25-35, ApplicationDbContext.cs:766-773).
The event half of the row is EventNameResolver.GetInboxName(...), kept for diagnostics only
(IntegrationEventConsumer.cs:78-81). With the inbox enabled the EF store and the recorder are
registered; with it disabled the no-op NoOpInboxStore is registered, which never
dedups and records nothing, and with no recorder nothing is staged
(MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:143,149,157,
MMCA.Common.Infrastructure/Persistence/Inbox/NoOpInboxStore.cs:3-17). The outbox is the
producer-side idempotency mechanism; the inbox is its consumer-side mirror.
Together they make the cross-service event flow effectively-once per handler on top of at-least-once transport
([Rubric §6], [Rubric §29, Resilience & Business Continuity]).
Outbound webhooks: the spine reaching outside the system
Integration events can also leave the system entirely, as signed HTTP POSTs to subscriber URLs
(ADR-142). The feature
is opt-in twice: a host calls AddWebhooks(configuration) and sets Webhooks:Enabled, which defaults to
false (WebhookSettings,
MMCA.Common.Application/Webhooks/WebhookSettings.cs:5-17); with it off the fan-out stays inert, every
administration endpoint answers 404 and no context maps the WebhookSubscriptions table, because
WebhookSubscriptionModelContributor, the
IModelContributor AddWebhooks registers, applies
the mapping before the entity passes and only to the source Webhooks:DataSourceName names while
Webhooks:Enabled is true
(MMCA.Common.Infrastructure/Persistence/Webhooks/WebhookSubscriptionModelBuilderExtensions.cs:63-87,
WebhookServiceCollectionExtensions.cs:79). Turning it on
also takes pipeline.AddWebhookDelivery(), one AddWebhookEvent<TEvent>(name) per published event, the
migration on the Webhooks:DataSourceName database, and a controller deriving from
WebhookSubscriptionsControllerBase granted webhooks:manage
(WebhookServiceCollectionExtensions,
MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:24-40).
WebhookSubscription is the aggregate: a target URL plus the webhook types it
lists (or every type), with its signing secret stored as the host's data-protection layer protected it
and returned in plaintext only once, at create or rotate. After a rotation the previous secret keeps
signing beside the new one until it expires, so a receiver can switch without dropping deliveries
(MMCA.Common.Domain/Webhooks/WebhookSubscription.cs:7-20; the grace is PreviousSecretGraceHours,
default 24, WebhookSettings.cs:58-60). Its tenant is a plain column the store filters explicitly, not
an ITenantEntity (WebhookSubscription.cs:21-24).
DataProtectionWebhookSecretProtector implements
IWebhookSecretProtector under the purpose MMCA.Common.Webhooks.Secret.v1;
a multi-replica host needs the shared key ring, and a secret one replica cannot read surfaces as
Webhooks.SecretUnreadable, never as an exception
(MMCA.Common.Infrastructure/Webhooks/DataProtectionWebhookSecretProtector.cs:9-14). The admin surface,
WebhookSubscriptionsControllerBase, lists, lists the publishable
event types, creates, updates, rotates, disables, enables and deletes, every call scoped to the caller's
tenant, with refusals such as Webhooks.TargetNotAllowed (400), Webhooks.NotFound (404, also for
another tenant's id) and Webhooks.LimitReached (409)
(MMCA.Common.API/Controllers/Webhooks/WebhookSubscriptionsControllerBase.cs:12-37); that limit is
MaxSubscriptionsPerTenant, 25 by default and soft under concurrent creates (WebhookSettings.cs:62-67).
Behind it sit IWebhookSubscriptionService /
WebhookSubscriptionService and the EF store
EFWebhookSubscriptionStore. A target is checked at registration by
DnsWebhookTargetValidator (the default
IWebhookTargetValidator), which applies the outbound address policy and,
unless insecure targets are allowed, refuses a host whose DNS answer is empty or contains ANY address
that is not public; that is an early answer for the operator, and the connect-time check stays
authoritative (MMCA.Common.Infrastructure/Webhooks/DnsWebhookTargetValidator.cs:11-16).
Delivery rides two pipelines this chapter already described.
WebhookFanOutHandler<TEvent> is an ordinary
ScopedIntegrationEventHandlerBase<TIntegrationEvent>
subclass registered by AddWebhookEvent<TEvent>(name), so it receives the event through whichever
transport the host runs (MMCA.Common.Application/Webhooks/Delivery/WebhookFanOutHandler.cs:17-20,35). It
returns at once unless webhooks are on and WebhookEventCatalog knows the event's
webhook name (WebhookFanOutHandler.cs:62-67), lists the enabled subscriptions of the event's tenant that
subscribe to that name, skips with one warning an event whose serialized payload exceeds
MaxPayloadBytes (65536 by default), because redelivering it cannot make it smaller
(WebhookFanOutHandler.cs:69-86, WebhookSettings.cs:51-56), and otherwise schedules one
DeliverWebhookInternalCommand per matching subscription inside ONE
transaction (WebhookFanOutHandler.cs:88-115). The WebhookDeliveryId is derived
from the event's MessageId and the subscription id, so a redelivered event schedules rows with an
unchanged webhook-id; a failed schedule throws so the outbox or the broker redelivers the event
(WebhookFanOutHandler.cs:28-31,91,117-120). Every delivery is therefore an internal-command row, and
its retries and dead-lettering come from the InternalCommands settings rather than a webhook-specific
budget (WebhookSettings.cs:5-10).
Those rows are drained not by the shared internal-command loop but by
WebhookDeliveryLane, a dedicated InternalCommandLaneProcessor keyed by
subscription, so a slow or failing receiver cannot delay the other internal commands, a failing
subscription is cooled down on its own, and two deliveries to one subscription never run at once
(MMCA.Common.Infrastructure/Webhooks/WebhookDeliveryLane.cs:14-20). The lane sends up to
DeliveryConcurrency (default 4) deliveries at once per replica, starts no delivery after
TimeoutSeconds (default 10) into a batch, and cools a failed subscription for
ReceiverCooldownSeconds (default 60), during which each delivery that comes due spends one attempt
(WebhookDeliveryLane.cs:29-48, WebhookSettings.cs:34,41,49). It is registered only when both
Webhooks:Enabled and InternalCommands:Enabled are true (WebhookDeliveryLane.cs:51-64).
DeliverWebhookInternalCommandHandler runs each row: it reads
the subscription under the tenant the processor restored for the row, posts the signed envelope, and maps
the outcome onto the subscription's last-outcome columns and onto the row. A 2xx, a 410 and a refused
target complete the row, because retrying cannot change them; everything else fails it so the processor
retries with backoff
(MMCA.Common.Application/Webhooks/Delivery/DeliverWebhookInternalCommandHandler.cs:12-17,73-77).
HttpWebhookSender, the default IWebhookSender, sends one POST
through the MMCA.Webhooks named client, signed once per readable secret with the current one first,
and maps the outcome from the status code or the exception alone, never reading the response body; a
target that fails the address policy is refused before anything is sent
(MMCA.Common.Infrastructure/Webhooks/HttpWebhookSender.cs:14-19,33,62). The signature is the Standard
Webhooks scheme in WebhookSignature: a whsec_-prefixed secret of 32 random
bytes, the webhook-id, webhook-timestamp and webhook-signature headers, and a v1,-prefixed
HMAC-SHA256 over {id}.{timestamp}.{body} that a receiver verifies with Verify or any Standard Webhooks
library (MMCA.Common.Application/Webhooks/Delivery/WebhookSignature.cs:8-32). The client's primary
handler follows no redirect, uses no proxy and keeps no cookies; every host-default handler (a resilience
pipeline, service discovery) is cleared so the internal-command queue is the only retry policy; its
default loggers are removed so the target URL, which often carries the receiver's token, is never logged
by the client stack; and no traceparent, tracestate or baggage header reaches the receiver
(WebhookServiceCollectionExtensions.cs:41-55). The authoritative guard against server-side request
forgery is WebhookConnectCallback: the client's connect callback resolves the
host itself (through IWebhookDnsResolver) and, unless insecure targets are
allowed, throws WebhookTargetRefusedException before opening a socket
when any resolved address is not public, and it never dials an address it did not check, which is what
holds the policy against DNS rebinding
(MMCA.Common.Infrastructure/Webhooks/WebhookConnectCallback.cs:7-15,48). The development switch that
allows insecure targets is honored only in a Development environment, decided in one place by
WebhookInsecureTargets (WebhookInsecureTargets.cs:6-10), and
InsecureWebhookTargetsNoticeService is the startup notice for
that switch when it is ignored (WebhookServiceCollectionExtensions.cs:24-27). This is the
[Rubric §17, Security & Compliance] face of the event spine, with its delivery reliability inherited
from the internal-command queue ([Rubric §29]).
Process managers: a long-running process as an aggregate
The spine also drives multi-step processes
(ADR-143).
ProcessManagerAggregateRoot<TIdentifierType> is the base
for an aggregate that IS the state of a process: its own status columns decide every step, and it declares
no property and no field, so deriving from it changes neither the EF model nor any migration snapshot
(MMCA.Common.Domain/ProcessManagers/ProcessManagerAggregateRoot.cs:5-17). Its one notion of time is
GetLastTransitionOn(), LastModifiedOn or else CreatedOn, a method rather than a property for that
same reason (ProcessManagerAggregateRoot.cs:20-31). Its one decision is DecideTimeout, which an
override implements by matching the fired ProcessTimeout by name and re-deriving the
due instant from stored state, so a stale or re-armed timeout is a no-op by construction
(ProcessManagerAggregateRoot.cs:33-44). A ProcessTimeout is a named, strictly positive window measured
from the last transition (MMCA.Common.Domain/ProcessManagers/ProcessTimeout.cs:3-21), and the answer is a
ProcessTimeoutDecision built only through its factories, NotApplicable
(the default), NotYetDue(dueAt), Applied, or Rejected(errors) with at least one error, whose
outcome is a ProcessTimeoutOutcome
(MMCA.Common.Domain/ProcessManagers/ProcessTimeoutDecision.cs:10-54).
Steps run on domain events through
ProcessDomainEventHandlerBase<TDomainEvent, TProcess, TProcessId>,
an IDomainEventHandler<TDomainEvent> that opens one scope, runs one transaction on its unit of work,
loads the correlated process tracked, and hands it with a ProcessStepContext to
the subclass's HandleStepAsync
(MMCA.Common.Application/ProcessManagers/ProcessDomainEventHandlerBase.cs:31-71). The step owns its
saves: the base never calls SaveChangesAsync, and the transaction refuses to commit unsaved changes, so
a step that forgets to save fails loudly (ProcessDomainEventHandlerBase.cs:17-18). A missing process
leaves the event handled (ProcessDomainEventHandlerBase.cs:59-63); a failed Result rolls the unit back
and the default OnStepFailed throws ProcessStepFailedException so the
outbox redelivers the event, unless an override returns normally
(ProcessDomainEventHandlerBase.cs:21-25,120-124). The context carries the event's scope, its unit of
work, and the timeout scheduler, which is null unless the host called AddProcessManagers()
(MMCA.Common.Application/ProcessManagers/ProcessStepContext.cs:6-33).
Timeouts are internal commands, not timers. A step arms one through
IProcessTimeoutScheduler; the default
ProcessTimeoutScheduler refuses a zero or negative delay with
ProcessManagers.TimeoutNotInFuture and otherwise writes one internal-command row due at the injected
clock's now plus the delay, the same clock the handler later decides with
(MMCA.Common.Application/ProcessManagers/ProcessTimeoutScheduler.cs:6-39). The row is a consumer-owned
IProcessTimeoutCommand<TProcessId>
(MMCA.Common.Application/ProcessManagers/IProcessTimeoutCommand.cs:5-17), handled by a sealed subclass of
ProcessTimeoutHandlerBase<TCommand, TProcess, TProcessId>
that the module scan registers as a closed command handler inside the decorator pipeline
(MMCA.Common.Application/ProcessManagers/ProcessTimeoutHandlerBase.cs:25-28). The handler loads the
process tracked, lets it decide against the injected TimeProvider, and saves once, only when the timeout
applied (ProcessTimeoutHandlerBase.cs:49-98). Every outcome completes the row with success except a save
failure that is not a concurrency conflict, which propagates so the row retries with backoff; a lost
concurrency race means another writer already moved the process
(ProcessTimeoutHandlerBase.cs:13-19,86-94). A NotYetDue decision completes the row without scheduling
another, so a step that still wants the timeout arms it again and a host keeps a reconciliation sweep for
what no step covers (ProcessTimeoutHandlerBase.cs:20-24). Each handled command yields a
ProcessTimeoutReport<TProcessId> tagged with a
ProcessTimeoutHandling value for an OnHandled override to log
(ProcessTimeoutHandlerBase.cs:113-125). The primitive adds no table and no configuration key (ADR-143);
it is testable because every decision runs against an injected clock ([Rubric §14, Testability]) and
correct under redelivery because every decision is re-derived from stored state ([Rubric §6]).
Putting it together, one event's life
To see the whole spine at once, follow a single integration event from a producer service to a consumer
service in broker mode. (1) A command mutates an aggregate, which raises an integration event via
AddDomainEvent(...); the interceptor captures it into an OutboxMessage in the same
transaction, stores its identity through EventNameResolver, and, because it is
an integration event, deliberately does not dispatch it in-process: it only signals the processor.
(2) Once the row is eligible (after ProcessingDelaySeconds) and unblocked by any earlier row sharing
its OrderingKey, the OutboxProcessor claims it under a lease, deserializes it,
sees it is an IIntegrationEvent, and publishes it through
IMessageBus behind the broker circuit breaker, which in broker mode is
BrokerMessageBus to the selected transport's publisher to the broker, then stamps the row processed and
records its delivery lag on OutboxMetrics. (3) In the consumer service,
IntegrationEventConsumer<TEvent> receives it and, per
IIntegrationEventHandler<TEvent>, asks the IInboxStore whether that handler already
processed this MessageId, skips it if so, and otherwise runs it (a scoped handler committing its own
inbox row with its writes) and records it, so a redelivery re-runs only the handlers that have not
succeeded. (4) Back on the producer,
OutboxCleanupService eventually purges the processed row, and anything that
dead-lettered stays visible to OutboxAdministration until its own retention
window closes. In monolith mode steps 2 and 3 collapse: with the outbox on, the registered
IMessageBus is InProcessMessageBus, which hands the event to
the same DomainEventDispatcher that local events already flow through, and
application code that publishes directly uses InProcessEventBus to write,
dispatch, and finalize in one call; with the outbox off (the in-process default) that same call is a
straight synchronous dispatch and no row is written at all. The contracts the application code touches
never change, which is exactly the property that lets a module graduate to its own service without a
rewrite (ADR-008). For the
mechanics of why each design choice was made,
ADR-003 (outbox and at-least-once),
ADR-006 (per-service outbox),
ADR-010 (event
versioning), ADR-090
(upcaster registration), ADR-021
(consumer inbox), and ADR-007 with
ADR-008 (transport at the
edge) are the primary references.
InboxConsumerNameAttribute
MMCA.Common.Application ·
MMCA.Common.Application.DomainEvents·MMCA.Common/Source/Core/MMCA.Common.Application/DomainEvents/InboxConsumerNameAttribute.cs:25· Level 0 · class (sealed attribute)
- What it is: an opt-in class attribute that gives an integration-event handler a STABLE inbox identity, stored in the
Consumercolumn of every inbox row that handler records in place of its full type name (InboxConsumerNameAttribute.cs:3-14). It targets classes only, is not inherited and may appear once (InboxConsumerNameAttribute.cs:24). - Depends on: nothing first-party; BCL
Attribute. It is read byInboxConsumer. - Concept introduced, a per-handler inbox key that survives a rename. The consumer-side inbox is keyed per handler, message id plus consumer name, so a redelivery after one handler failed re-runs only the handlers that have not succeeded yet (
InboxConsumerNameAttribute.cs:7-8, ADR-021). By default the consumer name is the handler's full type name, so renaming the class or moving its namespace changes the key, and the next redelivery of a message the old name already processed runs the handler once more (InboxConsumerNameAttribute.cs:8-11). Handlers are idempotent by contract, so that is one extra run rather than a correctness break; the attribute removes even that (InboxConsumerNameAttribute.cs:11-12).[Rubric §10, Messaging & Integration Architecture]assesses delivery guarantees across a process boundary; this attribute keeps the at-least-once dedupe key independent of refactoring. The remarks give the usage rule: apply it BEFORE a rename with the CURRENT full type name as its value, and keep it unique among the handlers of one event in one service (InboxConsumerNameAttribute.cs:15-21). - Walkthrough
MaxLength = 256(InboxConsumerNameAttribute.cs:28) is the width of the inboxConsumercolumn, and the EF model uses the same constant for it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:989), so the two cannot drift apart.Name(InboxConsumerNameAttribute.cs:31) is initialised from the primary-constructor parameter throughValidated.Validated(InboxConsumerNameAttribute.cs:40-45) throws on a null, empty or whitespace name (InboxConsumerNameAttribute.cs:42) and on one longer thanMaxLength(InboxConsumerNameAttribute.cs:43).
- Why it's built this way: the validation runs at construction because both bad shapes would only fail later and quietly. A blank name would collide with the legacy inbox rows, whose empty consumer means "every handler ran", and an oversized one would fail the inbox insert on every delivery (
InboxConsumerNameAttribute.cs:33-37). - Where it's used: resolved only by
InboxConsumer.NameOf(MMCA.Common/Source/Core/MMCA.Common.Application/DomainEvents/InboxConsumer.cs:38); exercised byInboxConsumerTests(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/DomainEvents/InboxConsumerTests.cs:47). - Caveats / not-in-source: uniqueness among the handlers of one event is a documented obligation (
InboxConsumerNameAttribute.cs:16); nothing in the attribute or its reader checks it.
ProcessTimeoutHandling
MMCA.Common.Application ·
MMCA.Common.Application.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessTimeoutHandling.cs:4· Level 0 · enum
- What it is: the six outcomes
ProcessTimeoutHandlerBase<TCommand, TProcess, TProcessId>can reach for one fired timeout:ProcessMissing,NotApplicable,NotYetDue,Applied,Rejected,LostRace. - Depends on: nothing first-party.
- Concept: an application-layer widening of the aggregate's own verdict. The domain's
ProcessTimeoutOutcomeonly knows what the aggregate decided; this enum adds the two outcomes only the handler can observe (no process row at all, and a save that lost a concurrency race).[Rubric §13, Observability & Operability]assesses whether a system tells an operator what it did; every handled timeout ends in exactly one of these values, handed to theOnHandledlogging hook inside aProcessTimeoutReport<TProcessId>. - Walkthrough: explicitly numbered members (
ProcessTimeoutHandling.cs:7,10,13,16,19,22). OnlyApplied = 3means a save happened (ProcessTimeoutHandling.cs:16); every other member's doc comment records that nothing was saved, andRejectedadds that the row is not retried (ProcessTimeoutHandling.cs:18-19). - Why it's built this way: none of the six outcomes fails the internal-command row. The handler returns
Result.Success()for all of them (ProcessTimeoutHandlerBase.cs:63,83,93,97) because each is decided by stored state, so a retry could not change it (ProcessTimeoutHandlerBase.cs:13-18). The enum is therefore a reporting vocabulary, not a retry signal. Recorded in ADR-143. - Where it's used: mapped from the domain outcome in the handler's switch (
ProcessTimeoutHandlerBase.cs:69-76) and carried as the first positional member ofProcessTimeoutReport<TProcessId>(ProcessTimeoutReport.cs:17).
InboxConsumer
MMCA.Common.Application ·
MMCA.Common.Application.DomainEvents·MMCA.Common/Source/Core/MMCA.Common.Application/DomainEvents/InboxConsumer.cs:16· Level 1 · class (static)
- What it is: the static helper that names the consumer half of an inbox key (message id plus consumer, ADR-021): the identity under which one integration-event handler records that it processed one message (
InboxConsumer.cs:7-9). - Depends on:
InboxConsumerNameAttribute(Level 0),EventNameAttribute; BCLConcurrentDictionaryand reflection. - Concept: see
InboxConsumerNameAttributefor the per-handler key. What this type adds is a single naming rule shared by both writers of an inbox row: the broker consumer andScopedIntegrationEventHandlerBase<TIntegrationEvent>both callNameOfon the same handler type, so the row a handler stages in its own scope and the row the consumer records after it are the same key (InboxConsumer.cs:10-13).[Rubric §10, Messaging & Integration Architecture]: a dedupe key computed in two places by two rules would let one delivery record two rows; one function removes that risk. - Walkthrough
- Two caches,
Namesper handler type andEventNamesper event type (InboxConsumer.cs:19,22), because the attribute lookup is reflection. NameOf(Type handlerType)(InboxConsumer.cs:32) null-guards, then returns the declaredInboxConsumerNameAttribute.Namewhen present (InboxConsumer.cs:38-40), otherwise the full type name truncated toInboxConsumerNameAttribute.MaxLength(InboxConsumer.cs:42-45). The result is never empty.EventNameOf(Type eventType)(InboxConsumer.cs:57-60) isinternaland supplies the event half of an inbox row's diagnostics: the event'sEventNameAttributevalue when declared, otherwise its short type name.
- Two caches,
- Why it's built this way:
EventNameOfrestates the broker consumer's rule (Infrastructure'sEventNameResolver.GetInboxName) because the Application layer cannot reference Infrastructure (InboxConsumer.cs:50-53); seeEventNameResolver. Truncation rather than rejection on the fallback path is deliberate: only a pathological generic name reaches 256 characters (InboxConsumer.cs:26-28), and the column must still accept the insert. - Where it's used:
ScopedIntegrationEventHandlerBase<TIntegrationEvent>(MMCA.Common/Source/Core/MMCA.Common.Application/DomainEvents/ScopedIntegrationEventHandlerBase.cs:70,83) and the broker consumer'sInboxHandlerLoop(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/InboxHandlerLoop.cs:56); named in the docs ofIInboxRecorder,IInboxStoreandInboxMessage. Tested byInboxConsumerTests(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/DomainEvents/InboxConsumerTests.cs:10). - Caveats / not-in-source: two handler types whose full names share the first 256 characters would truncate to the same key; the source accepts that as unreachable in practice rather than guarding it.
ProcessStepFailedException
MMCA.Common.Application ·
MMCA.Common.Application.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessStepFailedException.cs:10· Level 2 · class
- What it is: the exception the default
OnStepFailedofProcessDomainEventHandlerBase<TDomainEvent, TProcess, TProcessId>throws when a step returned a failed result, so the outbox redelivers the event (ProcessStepFailedException.cs:5-9). - Depends on:
Error; BCLException. - Concept: the one deliberate bridge from
Resultback to an exception. Domain-event handlers returnTask, notResult, so the only way for a handler to tell the outbox "this did not work, try again" is to throw. See the outbox at ADR-003 and ADR-143. - Walkthrough: the three standard exception constructors (
ProcessStepFailedException.cs:13,19,27) plus a process constructor (ProcessStepFailedException.cs:36) that setsProcessType,ProcessIdandErrors(ProcessStepFailedException.cs:45,48,51,Errorsfalls back to empty at line 41).BuildMessagejoins the error codes, or saysno error code(ProcessStepFailedException.cs:53-59). - Why it's built this way: the message carries codes only, never error descriptions, so a log line names the failure without copying step detail.
ProcessIdis a string formatted with the invariant culture by the caller (ProcessDomainEventHandlerBase.cs:122), which keeps the exception non-generic. - Where it's used: thrown only by
ProcessDomainEventHandlerBase.OnStepFailed(ProcessDomainEventHandlerBase.cs:120-124).
ProcessTimeoutReport<TProcessId>
MMCA.Common.Application ·
MMCA.Common.Application.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessTimeoutReport.cs:16· Level 2 · record
- What it is: what
ProcessTimeoutHandlerBase<TCommand, TProcess, TProcessId>did with one fired timeout, handed to itsOnHandledhook for logging (ProcessTimeoutReport.cs:5-8). - Depends on:
ProcessTimeoutHandling,Error. - Concept: see
ProcessTimeoutHandling.[Rubric §13, Observability & Operability]: the record gives a consumer one structured value to log per timeout instead of a set of ad-hoc overrides. - Walkthrough: six positional members (
ProcessTimeoutReport.cs:16-22):Handling,ProcessId,TimeoutName,DueAt(filled forNotYetDueonly),Errors(filled forRejectedonly) andStateBefore(the state described before the aggregate decided,ProcessTimeoutReport.cs:13-15).TProcessId : notnull(ProcessTimeoutReport.cs:23). - Why it's built this way: the handler builds the decision-bearing report directly from the aggregate's decision (
ProcessTimeoutHandlerBase.cs:82) and every other one through a private helper that leavesDueAtnull andErrorsempty (ProcessTimeoutHandlerBase.cs:120-125). - Where it's used: only inside the handler base and its tests.
SafeDomainEventHandler<TDomainEvent>
MMCA.Common.Application ·
MMCA.Common.Application.DomainEvents·MMCA.Common.Application/DomainEvents/SafeDomainEventHandler.cs:36· Level 2 · class (abstract)
- What it is: a base class for domain-event handlers that must log their own failure with handler
and event context before the exception continues to the dispatcher. It wraps an abstract
HandleSafelyAsyncin an exception filter that writes one error line and then lets the exception propagate unchanged (MMCA.Common.Application/DomainEvents/SafeDomainEventHandler.cs:40-51). Despite the name, it does not swallow anything. - Depends on:
BaseDomainEvent(Level 1),IDomainEventHandler<in TDomainEvent>(Level 1); externallyMicrosoft.Extensions.Logging.ILogger, taken through the primary constructor (SafeDomainEventHandler.cs:36). - Concept introduced, log-and-propagate handlers and the at-least-once delivery contract.
[Rubric §6, CQRS & Event-Driven]assesses whether event delivery is reliable end to end, and the class comment (SafeDomainEventHandler.cs:13-20) states why swallowing would defeat it: a handler that reports success has its outbox row marked processed, so nothing retries and the side effect is lost with only a log line to show for it. Propagating hands the decision to the delivery mechanism, which is built for exactly this.[Rubric §29, Resilience & Business Continuity]: on theOutboxProcessorpath the failed message keeps its retry count, backs off, and dead-letters afterOutbox:MaxRetriesattempts (default 5,OutboxSettings,MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxSettings.cs:26; the dead-letter branch that stamps an exhausted row isOutboxProcessor.cs:795-801, and the fetch predicate stops picking it up through itsDeadLetteredOn == nullfilter,OutboxProcessor.cs:376).[Rubric §13, Observability & Operability]: the one job the base class keeps is the error line naming the concrete handler and the event type, so an operator can tell which handler failed for which event without every subclass hand-rolling that context. - Concept introduced, per-event redelivery. The class comment states the contract
(
SafeDomainEventHandler.cs:21-33): the events of one save (or one published batch) are dispatched one at a time and each is settled on its own outcome, so a rethrowing handler leaves only its own event unprocessed, together with the later events of the batch that share its ordering key. The interceptor implements exactly that.DomainEventSaveChangesInterceptorhands the outbox-backed local events of one save toInProcessDispatch.DispatchBackedAsync(MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:420-422), which dispatches them one at a time and reports each outcome (MMCA.Common.Infrastructure/Persistence/Outbox/Processing/InProcessDispatch.cs:47-71). Only the events that succeeded are marked processed (DomainEventSaveChangesInterceptor.cs:428); a failed event, plus any later event that shares its ordering key (held back unattempted so that key stays in order,InProcessDispatch.cs:52-56), goes back to the outbox processor. A cancellation or a failed finalize still hands every local row of the save back, including rows whose handlers already ran but were not yet stamped processed (DomainEventSaveChangesInterceptor.cs:444-455). The dispatcher runs one event's handlers in sequence, so a redelivered event runs every one of its handlers again, including those that succeeded the first time (SafeDomainEventHandler.cs:29-30). Delivery is therefore at-least-once, and subclasses must be idempotent for a repeat of their own event and, in the rare whole-batch case, for a repeat of a sibling event raised by the same save (SafeDomainEventHandler.cs:30-32). - Walkthrough
- Primary constructor takes an
ILogger(SafeDomainEventHandler.cs:36), constrainedwhere TDomainEvent : BaseDomainEvent(SafeDomainEventHandler.cs:37). HandleAsync(SafeDomainEventHandler.cs:40) awaitsHandleSafelyAsync(SafeDomainEventHandler.cs:44) insidecatch (Exception ex) when (ex is not OperationCanceledException && LogAndRethrow(ex))(SafeDomainEventHandler.cs:46).OperationCanceledExceptionis excluded from the filter, so host shutdown propagates with no log line, because it is not a delivery failure.LogAndRethrow(SafeDomainEventHandler.cs:65) logs the exception withGetType().Nameandtypeof(TDomainEvent).Nameunder the message"Domain event handler {HandlerType} failed for event {EventType}. The event is redelivered by the outbox processor when the outbox is on."(SafeDomainEventHandler.cs:67-71) and always returnsfalse(SafeDomainEventHandler.cs:73), so the filter never matches and the exception keeps propagating. The message's closing clause is conditional on purpose: redelivery happens only when the outbox is enabled for the host, so the log line does not promise a retry the deployment may not run. Thethrow;inside the catch body is unreachable and is commented as such (SafeDomainEventHandler.cs:48-49).- Doing the log in a filter rather than a catch block is the point, and the method doc says so
(
SafeDomainEventHandler.cs:60-64): filters run on the first pass, ahead of any unwinding, so the handler context is recorded even if an outer frame wraps or rethrows, and the original stack trace stays untouched. HandleSafelyAsync(SafeDomainEventHandler.cs:58) is the abstract method subclasses implement; its doc restates the idempotency obligation and points back to the class remarks for the per-event redelivery contract (SafeDomainEventHandler.cs:53-57).
- Primary constructor takes an
- Why it's built this way: it puts the at-least-once contract of
ADR-003 where that ADR expects
the retry decision to live, in the delivery mechanism rather than in each handler. The handler
reports the truth and the outbox decides on retry, backoff, and dead-lettering, and the ADR's
matching obligation is that handlers stay idempotent.
[Rubric §1, SOLID]: this is a template method, the invariant (log, then propagate, except on cancellation) is sealed in the base and only the varying step is abstract, so no subclass can accidentally re-introduce swallowing. A failed handler still does not roll back the primary save, but that is the caller's doing rather than the base class's: the interceptor's flush runs after the data is committed, the per-event dispatch loop catches the propagated exception itself (InProcessDispatch.cs:63-66), and the flush releases the lease on the undelivered rows and signals the processor so they are picked up (DomainEventSaveChangesInterceptor.cs:430-437). - Where it's used: reached at runtime through
DomainEventDispatcher, whichever caller dispatched the event (the save-changes interceptor afterSaveChangesAsync,InProcessEventBusorInProcessMessageBus, or the backgroundOutboxProcessor). The only subclass in the workspace today isTestSafeDomainEventHandler(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/DomainEvents/SafeDomainEventHandlerTests.cs:124), driven bySafeDomainEventHandlerTests, which pin the three behaviours: log and propagate, the log lands before the caller sees the exception, andOperationCanceledExceptionpasses through unlogged. The cross-module sibling for integration events isScopedIntegrationEventHandlerBase<TIntegrationEvent>, which is the base the applications actually derive from. - Caveats / not-in-source: the redelivery contract in the class remarks
(
SafeDomainEventHandler.cs:21-33) describes the callers, not this class: the base class only logs and propagates, and the per-event settlement lives inInProcessDispatch.cs:47-71and the interceptor's flush. The base class cannot enforce the idempotency it demands: that stays a subclass obligation with no compile-time or runtime guard. Not determinable from source: how a real side-effect handler behaves under redelivery, because no application (ADC, Store, or Helpdesk) derives from this base class today, so only the Common unit tests exercise it.
ScopedIntegrationEventHandlerBase<TIntegrationEvent>
MMCA.Common.Application ·
MMCA.Common.Application.DomainEvents·MMCA.Common.Application/DomainEvents/ScopedIntegrationEventHandlerBase.cs:57· Level 3 · class (abstract)
- What it is: the base class for integration-event handlers, the cross-module sibling of
SafeDomainEventHandler<TDomainEvent>. It supplies the two blocks every such handler would otherwise repeat: the DI scope preamble and the log-and-rethrow envelope (MMCA.Common.Application/DomainEvents/ScopedIntegrationEventHandlerBase.cs:8-11). - Depends on:
IIntegrationEventHandler<in TIntegrationEvent>(Level 2),IIntegrationEvent(Level 1),InboxConsumer(Level 1) andIInboxRecorder(Level 0, resolved optionally from the scope); externallyMicrosoft.Extensions.DependencyInjection.IServiceScopeFactoryandMicrosoft.Extensions.Logging.ILogger, both taken through the primary constructor (ScopedIntegrationEventHandlerBase.cs:57-59), constrainedwhere TIntegrationEvent : IIntegrationEvent(ScopedIntegrationEventHandlerBase.cs:60). - Concept introduced, why a singleton handler has to open its own scope.
[Rubric §29, Resilience, Reliability & Business Continuity]assesses whether repeated infrastructure ceremony is factored out of business code, and[Rubric §1, SOLID]covers the template-method shape that does it. The class doc states the constraint (ScopedIntegrationEventHandlerBase.cs:12-19):IIntegrationEventHandler<T>implementations are registered as singletons by the module scan, so they cannot constructor-inject a scoped service such asIUnitOfWorkwithout a captive-dependency bug. Each handler therefore has to open its own scope per delivery. This base runs the subclass inside anIServiceScopeFactory.CreateAsyncScope()-derived async scope and hands it that scope'sIServiceProvider, so a handler body is only its own resolutions plus its own logic, and the scope is always disposed. That last guarantee is the reason to have a base class at all: anawait usingthat every handler hand-rolled would eventually be forgotten in one of them. - Concept reinforced, log-and-propagate, identical to the domain-event side. The exception
handling matches
SafeDomainEventHandler<TDomainEvent>exactly, and the doc says so (ScopedIntegrationEventHandlerBase.cs:20-25): the subclass body runs inside an exception filter that writes one error log line and then lets the exception propagate unchanged, whileOperationCanceledExceptionpasses straight through with no log line because host shutdown is not a delivery failure.[Rubric §29, Resilience & Business Continuity]: the third doc paragraph (ScopedIntegrationEventHandlerBase.cs:26-34) spells out what propagating buys on each of the two delivery paths, which is the detail that distinguishes this class from its domain-event sibling. On the outbox path the message keeps its retry count, backs off, and dead-letters afterOutbox:MaxRetriesattempts; on the broker path this handler's inbox row is never recorded and the framework broker receive pipeline (BrokerReceivePipeline) retries, redelivers and then moves the message to the dead-letter queue (ScopedIntegrationEventHandlerBase.cs:31-33). Delivery is at-least-once either way, so subclasses must be idempotent. - Concept introduced, the per-handler inbox row staged in the handler's own transaction.
[Rubric §10, Messaging & Integration Architecture]assesses exactly-once effects over an at-least-once transport. On the broker path the base stages this handler's inbox row (ADR-021) in the scope it opens, throughIInboxRecorder, BEFORE the subclass runs (ScopedIntegrationEventHandlerBase.cs:35-43). A subclass that saves on that scope commits the row in the same transaction as its own writes, so a rollback discards both and a crash cannot separate them; the redelivery then skips this handler and runs only the ones that have not succeeded yet. A subclass that never saves leaves the row unsaved, and the broker consumer records it after the handler returns. With the inbox disabled, or outside a broker consume, nothing is staged. Because the row rides the scope's FIRST successful save, a subclass that saves and THEN fails has already committed it, so the base revokes the row whenever the subclass throws, cancellation included, and the redelivery runs the handler again (ScopedIntegrationEventHandlerBase.cs:44-51). - Walkthrough
RevokeBudgetSeconds = 5(ScopedIntegrationEventHandlerBase.cs:63) caps the post-failure revoke.HandleAsync(ScopedIntegrationEventHandlerBase.cs:66) null-guards the event (ScopedIntegrationEventHandlerBase.cs:68) and computes the consumer name once withInboxConsumer.NameOf(GetType())(ScopedIntegrationEventHandlerBase.cs:70). It then opens the scope withscopeFactory.CreateAsyncScope()(ScopedIntegrationEventHandlerBase.cs:76), disposes it throughawait using (scope.ConfigureAwait(false))(ScopedIntegrationEventHandlerBase.cs:77), stages the inbox row withGetService<IInboxRecorder>()?.Stage(messageId, eventName, consumer), which is a no-op when no recorder is registered (ScopedIntegrationEventHandlerBase.cs:79-84), and passesscope.ServiceProviderto the subclass (ScopedIntegrationEventHandlerBase.cs:86).- That block sits inside an inner
catch (Exception ex) when (ex is not OperationCanceledException && LogAndRethrow(ex, integrationEvent))(ScopedIntegrationEventHandlerBase.cs:89). As on the domain-event side, thethrow;in the catch body is unreachable and commented as such (ScopedIntegrationEventHandlerBase.cs:91-93); the filter is the mechanism, so the log write lands ahead of any unwinding and the original stack trace is preserved. - An outer
catch (Exception)(ScopedIntegrationEventHandlerBase.cs:96-103) catches every failure, cancellation included, awaitsRevokeInboxRowAsyncand then rethrows the original exception unchanged (ScopedIntegrationEventHandlerBase.cs:101-102). RevokeInboxRowAsync(ScopedIntegrationEventHandlerBase.cs:152-178) resolves the recorder from a FRESH scope (ScopedIntegrationEventHandlerBase.cs:156-162), because the handler's scope is already disposed and its context may be the very one the failure left unusable (ScopedIntegrationEventHandlerBase.cs:137-143). It runsRevokeAsyncunder its own 5-secondCancellationTokenSourcerather than the delivery token, which is already cancelled on shutdown (ScopedIntegrationEventHandlerBase.cs:164-165). A failing revoke is logged at Error with the consumer and message id and swallowed (ScopedIntegrationEventHandlerBase.cs:168-177), so the caller still rethrows the handler's ORIGINAL exception.HandleScopedAsync(ScopedIntegrationEventHandlerBase.cs:116-119) is the abstract member a subclass implements. Its signature takes the event, the scope'sIServiceProvider, and the cancellation token; its doc restates that the scope is opened before the call and disposed after it, and that implementations must be idempotent (ScopedIntegrationEventHandlerBase.cs:106-111).LogHandlerFailure(ScopedIntegrationEventHandlerBase.cs:128-133) isvirtual, not private, and that is the one genuine extension point beyondHandleScopedAsync. The default writes"Integration event handler {HandlerType} failed for event {EventType}. The delivery mechanism will redeliver the event."withGetType().Nameandtypeof(TIntegrationEvent).Name. Its doc (ScopedIntegrationEventHandlerBase.cs:121-127) tells a subclass to override it in order to log the event's own identifiers through a source-generated[LoggerMessage]method, and imposes the two rules that follow from where it runs: the override executes inside the exception filter, so it must not throw and must not rethrow.LogAndRethrow(ScopedIntegrationEventHandlerBase.cs:185-190) is the private filter predicate. It callsLogHandlerFailureand always returnsfalse, so the filter never matches and the exception keeps travelling.
- Why it's built this way: it is the same ADR-003 division of labour as
SafeDomainEventHandler<TDomainEvent>, with the retry decision left to the delivery mechanism, plus the scope management that the singleton handler lifetime forces, plus the per-handler inbox staging and revoke of ADR-021, which only work if every handler opens its scope the same way. Sealing these concerns in a base class means a new integration-event handler in any module is a constructor, an override, and nothing else, which is why the applications derive from this class where they derive from its domain-event sibling not at all. - Where it's used: it is the base of the integration-event handlers across both apps, for example
ADC's
UserRegisteredHandler(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Users/IntegrationEventHandlers/UserRegisteredHandler.cs:63),SpeakerLinkedToUserHandler(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Speakers/IntegrationEventHandlers/SpeakerLinkedToUserHandler.cs:46),SpeakerUnlinkedFromUserHandler(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Speakers/IntegrationEventHandlers/SpeakerUnlinkedFromUserHandler.cs:31),TicketHolderInvitedHandler(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/IntegrationEventHandlers/TicketHolderInvitedHandler.cs:36), the Engagement points handlers (AttendeeCheckedInPointsHandler,EventFeedbackSubmittedPointsHandler,SessionFeedbackSubmittedPointsHandler,UserDeletedPointsHandler), and Store'sCustomerErasedHandler(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Reviews/IntegrationEventHandlers/CustomerErasedHandler.cs:48). Its behaviour is pinned byScopedIntegrationEventHandlerBaseTests, and its inbox staging and revoke byIntegrationEventConsumerInboxTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Consumers/IntegrationEventConsumerInboxTests.cs). At runtime the subclasses are reached either throughDomainEventDispatcherin monolith mode or throughIntegrationEventConsumer<TEvent>in broker mode. - Caveats / not-in-source: the base cannot enforce the idempotency it requires, and it cannot stop
a
LogHandlerFailureoverride from throwing inside the filter; both stay subclass obligations documented in the remarks (ScopedIntegrationEventHandlerBase.cs:33,ScopedIntegrationEventHandlerBase.cs:123-124). A revoke that itself fails leaves a committed row behind, so the redelivery skips this handler for that message; the source only surfaces this through the Error log line (ScopedIntegrationEventHandlerBase.cs:145-149,174), it does not repair it.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
IProcessTimeoutCommand<TProcessId>
MMCA.Common.Application ·
MMCA.Common.Application.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/IProcessTimeoutCommand.cs:17· Level 4 · interface
- What it is: the contract for a consumer-owned internal command that fires a named timeout on one process aggregate (
IProcessTimeoutCommand.cs:5-9). - Depends on:
IInternalCommand;InternalCommandNameAttributeby convention. - Concept: a process timeout is not a new mechanism; it is an ordinary durable internal command (ADR-114) with a due time. This interface only adds the correlation (
ProcessId) the generic handler needs. The doc comment asks every implementation for a stable[InternalCommandName]and a handler derived fromProcessTimeoutHandlerBase<TCommand, TProcess, TProcessId>(IProcessTimeoutCommand.cs:6-8), and the convention test baseProcessTimeoutConventionTestsBaseinMMCA.Common.Testing.Architecturechecks it ([Rubric §34, Architecture Governance & Documentation]). - Walkthrough: one member,
ProcessId(IProcessTimeoutCommand.cs:21). It may be an explicit interface implementation over the command's own id property;System.Text.Jsondoes not serialize explicit implementations, so adopting the interface does not change what stored rows carry (IProcessTimeoutCommand.cs:10-15). - Why it's built this way: keeping the payload shape stable lets an existing internal command become a process timeout without a data migration. See ADR-143.
- Where it's used: the parameter type of
IProcessTimeoutScheduler.ArmAsyncand theTCommandconstraint of the handler base (ProcessTimeoutHandlerBase.cs:41).
IProcessTimeoutScheduler
MMCA.Common.Application ·
MMCA.Common.Application.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/IProcessTimeoutScheduler.cs:9· Level 5 · interface
- What it is: the one service of the process-manager primitive: arm a timeout command to run after a delay.
- Depends on:
IProcessTimeoutCommand<TProcessId>,Result. - Concept: see
IProcessTimeoutCommand<TProcessId>.[Rubric §6, CQRS & Event-Driven]assesses whether long-running workflows are modelled explicitly; a step arms its next deadline through this interface instead of a timer, so the deadline survives a restart as a stored row. - Walkthrough:
ArmAsync<TProcessId>(timeout, after, cancellationToken)returnsTask<Result<Guid>>(IProcessTimeoutScheduler.cs:24-28): the scheduled row id, aProcessManagers.TimeoutNotInFuturevalidation failure for a zero or negative delay, or the internal command scheduler's own failure (IProcessTimeoutScheduler.cs:20-23). The write inherits that scheduler's atomicity: enrolled in the active transaction when there is one, saved outright otherwise (IProcessTimeoutScheduler.cs:11-15). - Why it's built this way: arming inside the step's transaction means the state change and its deadline commit or roll back together. See ADR-143 and the earlier deferral in ADR-086.
- Where it's used: registered scoped by
AddProcessManagers()(DependencyInjection.ProcessManagers.cs:26) and exposed to steps asProcessStepContext.Timeouts.
ProcessTimeoutScheduler
MMCA.Common.Application ·
MMCA.Common.Application.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessTimeoutScheduler.cs:13· Level 6 · class (sealed)
- What it is: the
IProcessTimeoutSchedulerimplementation: a guard plus one call to the internal command scheduler. - Depends on:
IInternalCommandScheduler,Error; BCLTimeProvider. - Concept: see
IProcessTimeoutScheduler.[Rubric §14, Testability]: the clock is the injectedTimeProvider(ProcessTimeoutScheduler.cs:15), so a test fixes "now" and checks the due time exactly. - Walkthrough:
TimeoutNotInFutureCode = "ProcessManagers.TimeoutNotInFuture"(ProcessTimeoutScheduler.cs:18).ArmAsync(ProcessTimeoutScheduler.cs:21) null-checks the command (:27), returns a validation failure forafter <= TimeSpan.Zero(ProcessTimeoutScheduler.cs:29-35), and otherwise callsScheduleAsync(timeout, timeProvider.GetUtcNow() + after, cancellationToken)(ProcessTimeoutScheduler.cs:38). - Why it's built this way: no state of its own, so transactional behavior is exactly the internal command scheduler's (ADR-114).
AddProcessManagers()also addsTimeProvider.SystemwithTryAddSingleton, so a host's own clock wins (DependencyInjection.ProcessManagers.cs:26-27). - Where it's used: resolved through
ProcessStepContextby process steps.
ProcessTimeoutHandlerBase<TCommand, TProcess, TProcessId>
MMCA.Common.Application ·
MMCA.Common.Application.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessTimeoutHandlerBase.cs:36· Level 8 · class (abstract)
- What it is: the generic handler for a fired process timeout: load the process tracked, let the aggregate decide against the injected clock, save once when it applied (
ProcessTimeoutHandlerBase.cs:8-11). - Depends on:
ICommandHandler<in TCommand, TResult>,IUnitOfWork,IConcurrencyConflictDetector,ProcessManagerAggregateRoot<TIdentifierType>,ProcessTimeout,ProcessTimeoutOutcome,ProcessTimeoutReport<TProcessId>; BCLTimeProvider. - Concept introduced, the process-manager timeout.
[Rubric §6, CQRS & Event-Driven]assesses whether long-running workflows have explicit state and deadlines. The aggregate owns the rule (DecideTimeout,ProcessTimeoutHandlerBase.cs:67); this base owns only loading, saving and classifying.[Rubric §29, Resilience & Business Continuity]: every outcome decided by stored state completes the row with success, and only a save failure that is not a concurrency conflict propagates so the row retries with backoff (ProcessTimeoutHandlerBase.cs:13-18). - Walkthrough:
Includesdefaults to none (ProcessTimeoutHandlerBase.cs:46).HandleAsync(ProcessTimeoutHandlerBase.cs:49) resolves the timeout first (:53), loads withasTracking: true(ProcessTimeoutHandlerBase.cs:56-58), and reportsProcessMissingwhen the row is gone (:60-64).- It captures
DescribeStatebefore deciding (:66-67), maps the outcome with a switch whose default arm isNotApplicable(ProcessTimeoutHandlerBase.cs:69-76), and for anything butAppliedreports without saving (:78-84). - On
Appliedit callsSaveChangesAsynconce (:88); a concurrency conflict becomesLostRace(ProcessTimeoutHandlerBase.cs:90-94), otherwiseApplied(:96). - Extension points: abstract
ResolveTimeout(:103), virtualDescribeStatereturning null (:111), virtual no-opOnHandled(ProcessTimeoutHandlerBase.cs:116).
- Why it's built this way: a
NotYetDuedecision schedules nothing new, so each step that still wants the timeout re-arms it and the host keeps a reconciliation sweep for the rest (ProcessTimeoutHandlerBase.cs:20-23; compensation and reconciliation in ADR-054). One sealed subclass per command lets the module scan register a closedICommandHandler<TCommand, Result>the decorator pipeline wraps (ProcessTimeoutHandlerBase.cs:24-27). See ADR-143. - Where it's used: consumer subclasses found by the module scan (
DependencyInjection.ProcessManagers.cs:19-22); the architecture rules inArchitectureRules.ProcessTimeouts.cscheck the convention. - Caveats / not-in-source: no subclass exists in
MMCA.ADC/Sourcetoday; the in-repo subclasses are test fixtures. Which consumer, if any, derives it is not determinable from the Common and ADC sources read here.
ProcessStepContext
MMCA.Common.Application ·
MMCA.Common.Application.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessStepContext.cs:11· Level 11 · class (sealed)
- What it is: the bundle a process step receives: the event's scope provider, its unit of work, and the timeout scheduler when registered.
- Depends on:
IUnitOfWork,IProcessTimeoutScheduler; BCLIServiceProvider. - Concept: a parameter object. See
ProcessDomainEventHandlerBase<TDomainEvent, TProcess, TProcessId>for the step model. - Walkthrough: the constructor null-checks both arguments (
ProcessStepContext.cs:16-19) and resolves the scheduler withGetService, notGetRequiredService(ProcessStepContext.cs:23).Services,UnitOfWork(the step owns every save) and nullableTimeouts(ProcessStepContext.cs:27,30,33). - Why it's built this way:
Timeoutsis null when the host never calledAddProcessManagers()(ProcessStepContext.cs:32), so a process that needs no deadlines works without that registration. Passing one object keeps the abstractHandleStepAsyncsignature stable if the context grows. - Where it's used: constructed per step inside the transaction (
ProcessDomainEventHandlerBase.cs:68).
ProcessDomainEventHandlerBase<TDomainEvent, TProcess, TProcessId>
MMCA.Common.Application ·
MMCA.Common.Application.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessDomainEventHandlerBase.cs:31· Level 12 · class (abstract)
- What it is: runs one process step per domain event: one scope, one transaction, the correlated process loaded tracked, then the consumer's
HandleStepAsync(ProcessDomainEventHandlerBase.cs:11-14). - Depends on:
IDomainEventHandler<in TDomainEvent>,IDomainEvent,ProcessManagerAggregateRoot<TIdentifierType>,IUnitOfWork,ProcessStepContext,ProcessStepFailedException;IServiceScopeFactory. - Concept: the event-driven half of the process manager (the timeout half is
ProcessTimeoutHandlerBase<TCommand, TProcess, TProcessId>).[Rubric §6, CQRS & Event-Driven]: a domain event moves a stored process aggregate one step, inside its own transaction (ADR-107).[Rubric §10, Messaging & Integration]: a failed step throws by default, so the outbox redelivers the event (ADR-003). - Walkthrough:
HandleAsync(ProcessDomainEventHandlerBase.cs:41) callsOnStepStartingbefore any scope (:45), opens an async scope (ProcessDomainEventHandlerBase.cs:47-48) and resolves that scope'sIUnitOfWork(:50).- Inside
ExecuteInTransactionAsync(ProcessDomainEventHandlerBase.cs:52) it loads byCorrelateProcessIdwithasTracking: true(:55-57); a missing process callsOnProcessMissingand succeeds (ProcessDomainEventHandlerBase.cs:59-63); otherwise it returnsHandleStepAsyncwith a newProcessStepContext(:65-69). - A failed result calls
OnStepFailedafter the rollback (ProcessDomainEventHandlerBase.cs:73-76), whose default throwsProcessStepFailedExceptionwith the process type name and the id formatted invariantly (ProcessDomainEventHandlerBase.cs:120-124). - Extension points: abstract
CorrelateProcessIdandHandleStepAsync(:83,94), virtualIncludes(:38),OnStepStarting,OnProcessMissing(ProcessDomainEventHandlerBase.cs:102,108) andOnStepFailed.
- Why it's built this way: the base never saves; the transaction refuses to commit unsaved changes, so a step that forgets to save fails loudly (
ProcessDomainEventHandlerBase.cs:16-18). A step's own exception propagates unchanged and cancellation is never caught (ProcessDomainEventHandlerBase.cs:20-24). An override ofOnStepFailedthat returns normally keeps the event handled. See ADR-143, ADR-054 and ADR-086. - Where it's used: consumer subclasses found by the module scan (
DependencyInjection.ProcessManagers.cs:19-22);AddApplication()registers none of this (:22). - Caveats / not-in-source: no subclass exists in
MMCA.ADC/Sourcetoday; the in-repo subclasses are test fixtures inProcessDomainEventHandlerBaseTests.cs.
WebhookDeliveryId
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookDeliveryId.cs:9· Level 0 · class (static)
- What it is: computes the deterministic
webhook-idof one (event, subscription) pair, so a redelivered event schedules the same id and a receiver can dedupe on it (WebhookDeliveryId.cs:5-8). - Depends on: nothing first-party; BCL
System.Security.Cryptography.SHA256. - Concept introduced, outbound webhooks and receiver-side idempotency.
[Rubric §10, Messaging & Integration Architecture](assesses at-least-once delivery paired with an idempotency key the other side can use): MMCA.Common can push integration events to tenant-registered HTTP endpoints (ADR-142). Delivery is at-least-once, so every attempt for the same event and subscription must carry the same id; this type is the inboundIDomainEventMessageIdidea turned outward. - Walkthrough: one method,
For(eventId, subscriptionId)(WebhookDeliveryId.cs:18). It writes the two GUIDs into a 32-byte stack buffer (WebhookDeliveryId.cs:20-22), hashes it with SHA-256 into a second stack buffer (WebhookDeliveryId.cs:24-25), and returns the first 16 hash bytes as aGuid(WebhookDeliveryId.cs:26). No allocation beyond the result. - Why it's built this way: a hash of the pair is stable across retries, replicas and redeliveries without storing anything, and it does not expose the raw event id to the receiver.
- Where it's used:
WebhookFanOutHandler<TEvent>stamps it into eachDeliverWebhookInternalCommand(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookFanOutHandler.cs:91), andDeliverWebhookInternalCommandHandlersends it as thewebhook-idheader value (DeliverWebhookInternalCommandHandler.cs:62).
WebhookDeliveryRequest
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookDeliveryRequest.cs:8· Level 0 · record
- What it is: the input to
IWebhookSender: what one POST sends (WebhookDeliveryRequest.cs:3). - Depends on: nothing first-party at the type level (BCL
Uri,IReadOnlyList<string>). - Concept: part of the outbound webhook delivery path introduced at
WebhookDeliveryId. - Walkthrough: four positional members (
WebhookDeliveryRequest.cs:4-8):Target(the subscription URL),WebhookId(thewebhook-idheader value),Body(theWebhookEnvelopeJSON, sent verbatim), andProtectedSecrets(the signing secrets still protected, current first; one signature is sent per readable secret). - Why it's built this way: carrying the secrets protected keeps the plaintext key out of the
Application layer; only the sender unprotects them
(
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/HttpWebhookSender.cs:123).[Rubric §11, Security](assesses secret handling) applies to that choice. - Where it's used: built by
DeliverWebhookInternalCommandHandler(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/DeliverWebhookInternalCommandHandler.cs:60-64) and consumed byHttpWebhookSender.
WebhookEnvelope
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookEnvelope.cs:11· Level 0 · class (static)
- What it is: builds the delivery body in the Standard Webhooks payload shape
{"type":...,"timestamp":...,"data":...}, with the event payload carried verbatim (WebhookEnvelope.cs:7-10). - Depends on: nothing first-party; BCL
StringBuilder,System.Text.Json.JsonSerializer. - Concept:
[Rubric §9, API & Contract Design](assesses stable, documented external contracts): the receiver-facing body follows a published shape instead of an MMCA-specific one, so any Standard Webhooks consumer can parse it. - Walkthrough: one method,
Build(eventType, occurredOn, payloadJson)(WebhookEnvelope.cs:18). It rejects a blank type or payload (WebhookEnvelope.cs:20-21), normalizesoccurredOnto UTC (Localis converted,Unspecifiedis relabelled as UTC,WebhookEnvelope.cs:23-29), then concatenates with a pre-sizedStringBuilder(WebhookEnvelope.cs:31):typeis JSON-escaped viaJsonSerializer.Serialize(WebhookEnvelope.cs:32-33),timestampis the round-trip"O"format in the invariant culture (WebhookEnvelope.cs:34-35), anddatais the payload string appended without re-serialization (WebhookEnvelope.cs:36-37). - Why it's built this way: appending the payload verbatim avoids a parse-and-reserialize round trip and keeps the signed body byte-identical to what the fan-out serialized.
- Where it's used: called by
DeliverWebhookInternalCommandHandler(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/DeliverWebhookInternalCommandHandler.cs:63). - Caveats / not-in-source:
payloadJsonis not validated as JSON here; the method trusts its caller (the fan-out'sJsonSerializer.Serialize,WebhookFanOutHandler.cs:80).
WebhookSendStatus
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookSendStatus.cs:4· Level 0 · enum
- What it is: how one webhook POST ended, classified by what the delivery handler should do next.
- Depends on: nothing first-party.
- Concept:
[Rubric §29, Resilience & Business Continuity](assesses retry with a clear line between transient and permanent failure): every member's doc comment states whether it is retried. - Walkthrough: six explicitly numbered members.
Delivered = 0(WebhookSendStatus.cs:7): 2xx.Rejected = 1(WebhookSendStatus.cs:10): any other status, redirects included; retried.Gone = 2(WebhookSendStatus.cs:13): 410, the subscription is disabled.TargetRefused = 3(WebhookSendStatus.cs:19): a non-public address at connect time or a scheme the host does not accept; retrying cannot change it.TransportFailed = 4(WebhookSendStatus.cs:22): transport failure, timeouts included; retried.SecretUnreadable = 5(WebhookSendStatus.cs:25): the current signing secret could not be unprotected, nothing was sent; retried. - Why it's built this way: the sender classifies, the handler decides; keeping the classification
in one enum lets
DeliverWebhookInternalCommandHandlermap each status to complete-or-retry in one place. - Where it's used: produced by
HttpWebhookSender(for example 2xx versus other atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/HttpWebhookSender.cs:109, 410 atHttpWebhookSender.cs:106); carried byWebhookSendOutcome.
WebhookErrorCodes
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/WebhookErrorCodes.cs:4· Level 0 · class (static)
- What it is: the eleven stable
Webhooks.*error codes the outbound-webhook feature returns inside anError. - Depends on: nothing first-party (string constants only).
- Concept: a per-feature error-code catalog, the same convention the Result pattern uses everywhere (see
Error).[Rubric §9, API & Contract Design]assesses whether clients get stable, machine-readable failures; each constant's doc comment pins both the error type and the HTTP status it surfaces as, so the code is the contract a subscriber-management client can switch on. - Walkthrough: nine codes surface to API callers:
NotFound(404,WebhookErrorCodes.cs:7); the validation setUrlInvalid,TargetNotAllowed,EventTypesRequired,TooManyEventTypes(more than 20),EventTypeUnknown,DescriptionTooLong(over 200 characters),SecretRequired(400,WebhookErrorCodes.cs:10,13,16,19,22,25,28); andLimitReached(409,WebhookErrorCodes.cs:31). Two are queue-only failures that never reach a caller:DeliveryFailed(WebhookErrorCodes.cs:34), which makes the internal-command processor retry, andSecretUnreadable(WebhookErrorCodes.cs:37), raised when the stored signing secret cannot be unprotected on the current replica. - Why it's built this way: one class keeps the code strings in one place for the Application service, the Infrastructure validators and the delivery handler, which live in different assemblies. See ADR-142.
- Where it's used:
WebhookSubscriptionService(WebhookSubscriptionService.cs:70,192,225,240),DnsWebhookTargetValidator(DnsWebhookTargetValidator.cs:58),DataProtectionWebhookSecretProtector(DataProtectionWebhookSecretProtector.cs:54),WebhookSignature(WebhookSignature.cs:128) andDeliverWebhookInternalCommandHandler(DeliverWebhookInternalCommandHandler.cs:47,118,122).
WebhookEventRegistration
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/WebhookEventRegistration.cs:6· Level 0 · record
- What it is: one positional record pairing an integration-event CLR type with the webhook event type name subscribers list (for example
ticket.opened,WebhookEventRegistration.cs:3-5). - Depends on: nothing first-party;
System.Type. - Concept: a DI-registered descriptor. Instead of a mutable static registry, each
AddWebhookEvent<TEvent>(eventType)call adds one singleton instance of this record (DependencyInjection.Webhooks.cs:79), andWebhookEventCatalogreceives the whole set throughIEnumerable<WebhookEventRegistration>. See ADR-142. - Walkthrough: two members,
EventClrTypeandEventType(WebhookEventRegistration.cs:6). - Why it's built this way: registrations live in the service collection, so
AddWebhookEventcan inspect the earlier ones before adding another: the same type under the same name is a no-op, and a name reused for a different type, or a type registered under a second name, throwsInvalidOperationException(DependencyInjection.Webhooks.cs:52-77). - Where it's used: written by
AddWebhookEvent(DependencyInjection.Webhooks.cs:79) and read by theWebhookEventCatalogconstructor (WebhookEventCatalog.cs:20).
WebhookSettings
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/WebhookSettings.cs:11· Level 0 · class
What it is: the outbound-webhook options bound from the
Webhooksconfiguration section; nothing is delivered and theWebhookSubscriptionstable is not mapped untilEnabledis true (WebhookSettings.cs:5-10).Depends on: nothing first-party;
System.ComponentModel.DataAnnotationsfor[Range].Concept: fail-fast options.
[Rubric §29, Resilience & Business Continuity]assesses whether one bad dependency can degrade the rest; here the knobs that bound a slow receiver (timeout, per-replica concurrency, cooldown) are explicit, range-checked and defaulted low. Infrastructure binds the section withValidateDataAnnotations()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:72-74), so an out-of-range value fails startup (ADR-070).Walkthrough:
Member Line Default Range / note SectionNameWebhookSettings.cs:14"Webhooks"const EnabledWebhookSettings.cs:17falsemaster switch DataSourceNameWebhookSettings.cs:23"Default"database holding WebhookSubscriptionsTimeoutSecondsWebhookSettings.cs:3410 1 to 30 ( :33); also the HttpClient timeout (WebhookServiceCollectionExtensions.cs:93)DeliveryConcurrencyWebhookSettings.cs:414 1 to 16 ( :40); never two deliveries to one subscription at onceReceiverCooldownSecondsWebhookSettings.cs:4960 5 to 120 ( :48); a cooling subscription's due deliveries each spend one attemptMaxPayloadBytesWebhookSettings.cs:5665536 1024 to 1048576 ( :55); a larger event is skipped with a warningPreviousSecretGraceHoursWebhookSettings.cs:6024 0 to 168 ( :59); rotated-out secret keeps signingMaxSubscriptionsPerTenantWebhookSettings.cs:6725 1 to 500 ( :66); soft limit, concurrent creates can exceed itAllowInsecureTargetsInDevelopmentWebhookSettings.cs:73falsehonoured only in Development, else one startup warning Why it's built this way: retries are deliberately absent. Each delivery is one internal-command row, so retry counts come from the
InternalCommands:*settings (WebhookSettings.cs:8-9); this class only owns what is webhook-specific. TheTimeoutSecondsremarks explain why the timeout is kept low: one slow receiver holds one lane slot for up to that many seconds per attempt (WebhookSettings.cs:26-32). See ADR-142.Where it's used:
WebhookDeliveryLane(WebhookDeliveryLane.cs:43,47),WebhookFanOutHandler<TEvent>for the payload cap (WebhookFanOutHandler.cs:82),WebhookServiceCollectionExtensions,WebhookInsecureTargets, and the startup checkWebhookRegistrationValidator.
WebhookSendOutcome
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookSendOutcome.cs:7· Level 1 · record
- What it is: the result of one webhook POST (
WebhookSendOutcome.cs:3). - Depends on:
WebhookSendStatus(Level 0). - Concept: see
WebhookSendStatusfor the retry classification. - Walkthrough: three positional members (
WebhookSendOutcome.cs:4-7):Status,HttpStatusCode(int?, set only when the receiver answered) andDetail(string?, the failure detail in the form"ExceptionType: message"when there is one). - Why it's built this way: a plain value instead of an exception lets the handler record transport failures and HTTP rejections on the subscription the same way.
- Where it's used: returned by
IWebhookSender(IWebhookSender.cs:10); read byApplyOutcomeinDeliverWebhookInternalCommandHandler(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/DeliverWebhookInternalCommandHandler.cs:79), which turnsHttpStatusCodeinto anHTTP {code}reason (DeliverWebhookInternalCommandHandler.cs:127-130) and falls back toDetail, then to the status name (DeliverWebhookInternalCommandHandler.cs:142-143).
WebhookEventCatalog
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/WebhookEventCatalog.cs:10· Level 1 · class (sealed partial)
- What it is: the host's two-way map between webhook event type names and integration-event CLR types, built from every registered
WebhookEventRegistration; empty when nothing is registered (WebhookEventCatalog.cs:6-9). - Depends on:
WebhookEventRegistration; BCLGeneratedRegex,NotNullWhen. - Concept: an allow-list for an outbound contract.
[Rubric §11, Security]assesses whether data leaves the system only on purpose; a subscription may name only a registered event type (or"*"), so no integration event reaches a third party unless the host opted it in withAddWebhookEvent. - Walkthrough:
- Two dictionaries,
_byName(ordinal comparer) and_byType(WebhookEventCatalog.cs:15-16,24-25). The constructor fills both withTryAdd(WebhookEventCatalog.cs:26-30), so a duplicate is ignored here;AddWebhookEventalready rejected conflicting ones. EventTypesis the ordinal-sorted name list (WebhookEventCatalog.cs:32,36).Contains(eventType)is null-safe (WebhookEventCatalog.cs:41);TryGetEventType(Type, out string?)maps the other way (WebhookEventCatalog.cs:47).IsValidEventTypeName(internal) accepts 1 toMaxEventTypeLength = 100characters (WebhookEventCatalog.cs:13,56-57) matching^[a-z][a-z0-9]*([._-][a-z0-9]+)*$with a 1000 ms regex timeout (WebhookEventCatalog.cs:59-60).
- Two dictionaries,
- Why it's built this way:
TryAddSingletonin bothAddWebhookEventandAddWebhookDelivery(DependencyInjection.Webhooks.cs:81,100) means the catalog exists whichever is called first, and the name rule lives on the catalog so registration (DependencyInjection.Webhooks.cs:44-50) and validation share one definition. See ADR-142. - Where it's used:
WebhookSubscriptionServiceexposesEventTypesand checksContains(WebhookSubscriptionService.cs:37,234);WebhookFanOutHandler<TEvent>resolves the published name withTryGetEventType(WebhookFanOutHandler.cs:64); Infrastructure also registers it (WebhookServiceCollectionExtensions.cs:87).
IWebhookSender
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/IWebhookSender.cs:4· Level 2 · interface
- What it is: posts one signed webhook delivery (
IWebhookSender.cs:3). - Depends on:
WebhookDeliveryRequest,WebhookSendOutcome. - Concept:
[Rubric §3, Clean Architecture](assesses that the Application layer owns abstractions and Infrastructure owns I/O): the delivery handler in Application depends on this port, and theHttpClientcode lives behind it in Infrastructure. - Walkthrough: one member,
SendAsync(request, cancellationToken)(IWebhookSender.cs:10). Its contract (IWebhookSender.cs:6-9): it signs and posts, never reads the response body, and lets cancellation propagate. - Why it's built this way: not reading the body bounds what a hostile receiver can make the host allocate; returning an outcome instead of throwing keeps failure classification inside the sender.
- Where it's used: implemented by
HttpWebhookSender(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/HttpWebhookSender.cs:25), registered scoped byAddWebhooks(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:84), and injected intoDeliverWebhookInternalCommandHandler.
WebhookSignature
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookSignature.cs:13· Level 3 · class (static)
- What it is: the Standard Webhooks signing scheme: a
whsec_-prefixed Base64 secret, and av1,-prefixed Base64 HMAC-SHA256 over{id}.{timestamp}.{body}; receivers verify withVerifyor any Standard Webhooks library (WebhookSignature.cs:8-12). - Depends on:
ResultandError(G01),WebhookErrorCodes; BCLHMACSHA256,RandomNumberGenerator,CryptographicOperations. - Concept introduced, signed outbound webhooks.
[Rubric §11, Security](assesses authenticity, replay protection and constant-time comparison of secrets): a receiver can only trust a webhook it can authenticate, so every delivery is signed with a per-subscription key and stamped with a send time the receiver checks for freshness. Following a published scheme (ADR-142) means the receiver does not need MMCA code to verify. - Walkthrough: constants first:
SecretPrefix = "whsec_"(WebhookSignature.cs:16) and the three header nameswebhook-id,webhook-timestamp,webhook-signature(WebhookSignature.cs:19,22,25), plus the private"v1,"version prefix and a 32-byte key size (WebhookSignature.cs:27-28).GenerateSecret()(WebhookSignature.cs:32) is the prefix plus Base64 of 32 random bytes.DecodeSecret(secret)(WebhookSignature.cs:38) returns aResult<byte[]>: a missing prefix or an empty or invalid Base64 tail (WebhookSignature.cs:40,47) is aWebhooks.SecretUnreadableerror of typeError.Unexpected(WebhookSignature.cs:126-130), never an exception.Compute(webhookId, timestamp, body, key)(WebhookSignature.cs:61) UTF-8 encodes{id}.{timestamp}.{body}in the invariant culture (WebhookSignature.cs:66-67) and returnsv1,plus the Base64 HMAC (WebhookSignature.cs:68).Verify(...)(WebhookSignature.cs:84) rejects null or blank inputs (WebhookSignature.cs:93), rejects a timestamp outside the tolerance (WebhookSignature.cs:98), then accepts if any space-separatedv1,entry matches the recomputed signature underCryptographicOperations.FixedTimeEquals(WebhookSignature.cs:103-107). The privateIsWithinTolerance(WebhookSignature.cs:114) saturates both bounds at thelongrange so a hostile timestamp cannot overflow the comparison (WebhookSignature.cs:121-122). - Why it's built this way: a space-separated list of signatures lets a rotated subscription send one signature per still-valid secret, so a receiver keeps verifying through a rotation; constant-time comparison and the saturated window close timing and overflow attacks on the receiver side.
- Where it's used:
HttpWebhookSenderjoins oneComputeper readable key into the signature header (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/HttpWebhookSender.cs:62,70);WebhookSubscriptionServicemints secrets withGenerateSecret(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/WebhookSubscriptionService.cs:81,143).Verifyhas no production caller in MMCA.Common; it is exposed for receivers and exercised byWebhookSignatureTests.
DeliverWebhookInternalCommand
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/DeliverWebhookInternalCommand.cs:17· Level 4 · record
- What it is: one webhook delivery, as a durable internal-command row the fan-out schedules per
matching subscription. The row is the delivery history (attempts, last error, dead letter, requeue)
(
DeliverWebhookInternalCommand.cs:5-9). - Depends on:
IInternalCommand(G14) andInternalCommandNameAttribute(G14). - Concept:
[Rubric §29, Resilience & Business Continuity]: rather than a bespoke delivery table, each attempt rides the internal-command lane, so retry with backoff, dead-lettering and requeue come from the existingInternalCommandProcessor(ADR-142). - Walkthrough: six positional members (
DeliverWebhookInternalCommand.cs:18-23):SubscriptionId,DeliveryId(fromWebhookDeliveryId),EventType,EventId(the event'sMessageId),OccurredOn(itsDateOccurred) andPayloadJson(the event serialized by its runtime type with web defaults). The stable storage name is pinned by[InternalCommandName("MMCA.Webhooks.Deliver.v1")](DeliverWebhookInternalCommand.cs:16), so a rename of the CLR type cannot orphan queued rows. - Why it's built this way: the payload is captured at fan-out time, so a delivery replays exactly what was scheduled even if the event type later changes shape.
- Where it's used: created by
WebhookFanOutHandler<TEvent>(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookFanOutHandler.cs:88-96); handled byDeliverWebhookInternalCommandHandler, registered atMMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Webhooks.cs:97; its rows are drained byWebhookDeliveryLane, which resolves the storage name and filters on the type (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookDeliveryLane.cs:27,44).
DeliverWebhookInternalCommandHandler
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/DeliverWebhookInternalCommandHandler.cs:24· Level 6 · class (internal sealed partial)
- What it is: delivers one
DeliverWebhookInternalCommand: reads the subscription under the tenant the processor restored for the row, posts the signed envelope, and maps the outcome onto the subscription and onto the row. It is notITransactional: the outcome is recorded on its own save (DeliverWebhookInternalCommandHandler.cs:12-17). - Depends on:
IWebhookSubscriptionStore,IWebhookSender,ITenantContext(G05),WebhookSettings,WebhookEnvelope,WebhookSubscription,WebhookErrorCodes; implementsICommandHandler<in TCommand, TResult>(G05); BCLTimeProvider,IOptions<T>,ILogger<T>. - Concept:
[Rubric §29, Resilience & Business Continuity]: success completes the row, failure returns a failedResultso the internal-command processor retries with backoff and dead-letters after its attempt limit (DeliverWebhookInternalCommandHandler.cs:113-114).[Rubric §13, Observability & Operability]: one source-generated log line per outcome (DeliverWebhookInternalCommandHandler.cs:145-161). - Walkthrough:
HandleAsync(DeliverWebhookInternalCommandHandler.cs:37) first fails whenWebhooks:Enabledis false, returning anError.UnexpectedwithWebhooks.DeliveryFailed(DeliverWebhookInternalCommandHandler.cs:41-49), so a row queued before webhooks were switched off retries and dead-letters where it stays requeue-able. A missing, deleted or disabled subscription completes the row with nothing sent (DeliverWebhookInternalCommandHandler.cs:52-57). Otherwise it builds theWebhookDeliveryRequestwith the delivery id formatted"D", the envelope, and the signing secrets valid now (DeliverWebhookInternalCommandHandler.cs:59-64), sends it (DeliverWebhookInternalCommandHandler.cs:66), applies the outcome (DeliverWebhookInternalCommandHandler.cs:67) and saves the subscription (DeliverWebhookInternalCommandHandler.cs:69).ApplyOutcome(DeliverWebhookInternalCommandHandler.cs:79):Deliveredrecords success (DeliverWebhookInternalCommandHandler.cs:85-90);TargetRefusedrecords a fixed reason ("not a public address" or "not an https address", chosen by the stored URL scheme,DeliverWebhookInternalCommandHandler.cs:33-34,137-140) and completes, keeping the address-bearing detail to the server-side warning (DeliverWebhookInternalCommandHandler.cs:92-99);Gonerecords the failure, disables the subscription and completes (DeliverWebhookInternalCommandHandler.cs:106-111);Rejected,TransportFailedandSecretUnreadablerecord the failure and return a failedResult(DeliverWebhookInternalCommandHandler.cs:115-124): an unreadable secret is anError.UnexpectedwithWebhooks.SecretUnreadable, while a rejected or failed send is anError.UnavailablewithWebhooks.DeliveryFailed. - Why it's built this way: a delivery's own save means the outcome survives even when the row is
about to retry; recording a fixed refusal reason keeps resolved internal addresses out of the tenant
admin API, which returns
LastFailure(DeliverWebhookInternalCommandHandler.cs:94-95). - Where it's used: registered scoped as
ICommandHandler<DeliverWebhookInternalCommand, Result>(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Webhooks.cs:97) and invoked by the internal-command processor for rows on theWebhookDeliveryLane.
WebhookRegistrationValidator
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/WebhookRegistrationValidator.cs:13· Level 6 · class (internal sealed)
- What it is: an
IValidateOptions<WebhookSettings>that fails startup whenAddWebhookDelivery()was called but noIWebhookSubscriptionStoreis registered (WebhookRegistrationValidator.cs:7-11). - Depends on:
WebhookSettings,IWebhookSubscriptionStore;IServiceProviderIsService,IValidateOptions<T>. - Concept: a wiring check expressed as options validation.
[Rubric §15, Best Practices & Code Quality]: the Application layer cannot reference the Infrastructure store, so it asks the container whether one exists and turns a per-row runtime failure into one startup error (ADR-070). - Walkthrough:
Validate(WebhookRegistrationValidator.cs:17) returnsSuccesswhenIsService(typeof(IWebhookSubscriptionStore))(:18-19), else a failure namingservices.AddWebhooks(configuration)fromMMCA.Common.Infrastructure.Webhooks(WebhookRegistrationValidator.cs:20-22). - Why it's built this way: it ignores
Enabledon purpose: a missing store is a mistake whatever the switch says (WebhookRegistrationValidator.cs:9-10).ValidateOnStart()makes it run at host start (DependencyInjection.Webhooks.cs:98-99). - Where it's used: registered only by
AddWebhookDelivery()(DependencyInjection.Webhooks.cs:99).
WebhookFanOutHandler<TEvent>
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Delivery·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookFanOutHandler.cs:35· Level 8 · class (internal sealed partial)
- What it is: turns one published integration event into one
DeliverWebhookInternalCommandper enabled subscription of the event's tenant that lists its webhook type (or"*"), all scheduled inside one transaction (WebhookFanOutHandler.cs:17-21). - Depends on:
ScopedIntegrationEventHandlerBase<TIntegrationEvent>(its base),IIntegrationEvent,WebhookSettings,WebhookEventCatalog,IWebhookSubscriptionStore,WebhookDeliveryId,ITenantContext(G05),IUnitOfWork(G07),IInternalCommandScheduler(G14); BCLSystem.Text.Json. - Concept:
[Rubric §10, Messaging & Integration Architecture]: the bridge from the internal event stream to external HTTP subscribers. It consumes the same at-least-once integration event as any other handler, and hands each delivery to the durable internal-command lane rather than posting inline (ADR-142). - Walkthrough: two constructors: one with a logger (
WebhookFanOutHandler.cs:45) and one that usesNullLoggerfor a container with no logging (WebhookFanOutHandler.cs:54).HandleScopedAsync(WebhookFanOutHandler.cs:60) returns early unlessWebhookSettings.Enabledis true and the catalog mapsTEventto a webhook type (WebhookFanOutHandler.cs:62-67). It lists the tenant's enabled subscriptions (WebhookFanOutHandler.cs:69-72) and keeps those that subscribe to the type (WebhookFanOutHandler.cs:74). It serializes the event by its runtime type withJsonSerializerDefaults.Web(WebhookFanOutHandler.cs:38,80); a payload overMaxPayloadBytesis logged and skipped (WebhookFanOutHandler.cs:81-86), because redelivery cannot shrink it. It builds one command per match (WebhookFanOutHandler.cs:88-96), schedules all of them insideIUnitOfWork.ExecuteInTransactionAsync(WebhookFanOutHandler.cs:101-115), and throws when any schedule fails (WebhookFanOutHandler.cs:117-123). - Why it's built this way: throwing on a failed schedule makes the outbox or broker redeliver the
event, and the deterministic delivery id keeps the redelivered rows'
webhook-idunchanged (WebhookFanOutHandler.cs:27-31); one transaction means a partial fan-out is never committed. Being inert without settings (WebhookFanOutHandler.cs:23-26) letsAddWebhookEventregister it in any host. - Where it's used: registered per event by
AddWebhookEvent<TEvent>(name)as a singletonIIntegrationEventHandler<TEvent>(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Webhooks.cs:80), so it runs alongside the event's otherIIntegrationEventHandler<in TIntegrationEvent>registrations.
IDomainEvent
MMCA.Common.Domain ·
MMCA.Common.Domain.Interfaces·MMCA.Common/Source/Core/MMCA.Common.Domain/Interfaces/IDomainEvent.cs:7· Level 0 · interface
- What it is: the marker contract for domain events: something meaningful happened inside an aggregate boundary, to be dispatched after successful persistence.
- Depends on: nothing first-party (BCL
DateTime/Guidonly). - Concept introduced, domain events + idempotency keys.
[Rubric §6, CQRS & Event-Driven](assesses reliable events, idempotent consumers, and events carrying enough context) and[Rubric §4, DDD](aggregates raise events on state change). An aggregate does not call other modules directly; it records that something happened (for example "SessionScored") as anIDomainEvent, and the framework dispatches it after the data is safely saved, the basis of the Outbox pattern (ADR-003). - Walkthrough: two properties, and the whole file is 14 lines.
DateOccurred(IDomainEvent.cs:10) is when the business action happened, not when it was dispatched, and the XML doc says exactly that.MessageId(aGuid,IDomainEvent.cs:13) is a unique per-instance id used for consumer-side idempotency (inbox dedup), so a redelivered event is processed once. ThatMessageIdis what makes consumers safe under at-least-once delivery: it is minted at event creation byBaseDomainEvent(MMCA.Common/Source/Core/MMCA.Common.Domain/DomainEvents/BaseDomainEvent.cs:35, alongside theDateOccurreddefault on line 28), survives outbox serialization inside the JSON payload, travels through the broker, and lands in anInboxMessageas the dedup key (ADR-021). - Why it's built this way: a minimal marker keeps the domain free of dispatch mechanics, and the
two members are exactly what the outbox/inbox machinery needs (ordering and eligibility by
occurrence time, dedup by id). Note what is not here: no
Version, no routing key, no transport metadata. Those live one layer out, onOutboxMessageand onBaseIntegrationEvent. - Where it's used: implemented by concrete domain events in each module; raised by
AuditableAggregateRootEntity<TIdentifierType>(G02), captured from aggregates duringSaveChangesAsyncbyDomainEventSaveChangesInterceptor(G07), serialized into anOutboxMessagebyOutboxMessage.FromDomainEvent(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/OutboxMessage.cs:141), and dispatched byIDomainEventDispatcheror theOutboxProcessor.
ProcessTimeout
MMCA.Common.Domain ·
MMCA.Common.Domain.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Domain/ProcessManagers/ProcessTimeout.cs:7· Level 0 · record
- What it is: a named time window measured from a process's last transition. A process aggregate
matches a fired timeout by its
Nameand computes when it is due withDueAfter(ProcessTimeout.cs:3-6). - Depends on: nothing first-party (BCL
TimeSpan/DateTimeand theArgumentExceptionguards). - Concept introduced, the timeout half of a process manager.
[Rubric §6, CQRS & Event-Driven](assesses long-running workflows coordinated through events and commands rather than call chains): a process manager advances on events, but it also has to advance when nothing happens (an unanswered request, an expired hold). This record is the vocabulary for that "nothing happened in time" step; the aggregate that interprets it isProcessManagerAggregateRoot<TIdentifierType>(ADR-143). - Walkthrough: a sealed record with an explicit constructor (
ProcessTimeout.cs:14) that rejects a blank name (ProcessTimeout.cs:16) and a zero or negative window (ProcessTimeout.cs:17), so an invalid timeout cannot exist.Name(ProcessTimeout.cs:24) andWindow(ProcessTimeout.cs:27) are get-only.DueAfter(lastTransitionOn)(ProcessTimeout.cs:32) is justlastTransitionOn + Window: the due instant is always derived, never stored. - Why it's built this way: keeping the due instant a pure function of the stored last-transition
time is what lets a stale or re-armed timeout become a no-op (the aggregate re-derives it and answers
ProcessTimeoutDecisionNotYetDue); the record carries no process id and no state, so it is safe to construct anywhere. - Where it's used: passed to
ProcessManagerAggregateRoot.DecideTimeout(MMCA.Common/Source/Core/MMCA.Common.Domain/ProcessManagers/ProcessManagerAggregateRoot.cs:43); produced by the abstractResolveTimeout(TCommand)ofProcessTimeoutHandlerBase<TCommand, TProcess, TProcessId>(MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessTimeoutHandlerBase.cs:103), whoseNameis copied into theProcessTimeoutReport<TProcessId>(ProcessTimeoutHandlerBase.cs:82).
ProcessTimeoutOutcome
MMCA.Common.Domain ·
MMCA.Common.Domain.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Domain/ProcessManagers/ProcessTimeoutOutcome.cs:4· Level 0 · enum
- What it is: what a process aggregate decided about a fired timeout (
ProcessTimeoutOutcome.cs:3). - Depends on: nothing first-party.
- Concept: the result vocabulary of the process-manager timeout step introduced at
ProcessTimeout;[Rubric §6, CQRS & Event-Driven]applies the same way. - Walkthrough: four explicitly numbered members.
NotApplicable = 0(ProcessTimeoutOutcome.cs:7) is the default: the timeout does not apply to the process in its current state or by its name.NotYetDue = 1(ProcessTimeoutOutcome.cs:10): it applies, but a stale or re-armed row fired early.Applied = 2(ProcessTimeoutOutcome.cs:13): the aggregate transitioned.Rejected = 3(ProcessTimeoutOutcome.cs:16): the aggregate refused the transition. - Why it's built this way: making the no-op the zero value means an aggregate that never overrides
DecideTimeoutis safe by default (the base returnsNotApplicable,MMCA.Common/Source/Core/MMCA.Common.Domain/ProcessManagers/ProcessManagerAggregateRoot.cs:44). - Where it's used: carried by
ProcessTimeoutDecision; mapped one-to-one ontoProcessTimeoutHandlingby the timeout handler base (MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessTimeoutHandlerBase.cs:71-74).
IIntegrationEvent
MMCA.Common.Domain ·
MMCA.Common.Domain.Interfaces·MMCA.Common/Source/Core/MMCA.Common.Domain/Interfaces/IIntegrationEvent.cs:15· Level 1 · interface
- What it is: a marker interface distinguishing integration events (cross-module or cross-service) from plain domain events (intra-module).
- Depends on:
IDomainEvent(Level 0), which it extends. - Concept introduced, domain versus integration events.
[Rubric §6, CQRS & Event-Driven](reliable events across module boundaries) and[Rubric §7, Microservices Readiness](loose coupling via events). The doc comment draws the line (IIntegrationEvent.cs:8-13): domain events are intra-module, raised and handled within the same bounded context byIDomainEventHandler<in TDomainEvent>; integration events are facts that other modules, possibly in other processes, need to react to, handled byIIntegrationEventHandler<in TIntegrationEvent>and transported throughIMessageBus. Because it still extendsIDomainEvent, an integration event flows through the same outbox pipeline (at-least-once); the marker only tells theOutboxProcessorto route it through the message bus rather than the in-process dispatcher. The interface is empty (public interface IIntegrationEvent : IDomainEvent;,IIntegrationEvent.cs:15): membership itself is the marker. - Why it's built this way: making integration events a subtype of domain events means one outbox
mechanism serves both, and the routing decision is a single
is IIntegrationEventpattern match in the processor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:928), with no parallel capture pipeline to keep in step. - Where it's used: implemented by integration events across modules and by
BaseIntegrationEvent, which adds theSchemaVersionconvention; routed by theOutboxProcessortoIMessageBus(OutboxProcessor.cs:928); published byInProcessEventBusandBrokerEventBus; consumed viaIntegrationEventConsumer<TEvent>, whose type parameter is constrained toclass, IIntegrationEvent(IntegrationEventConsumer.cs:45).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
ProcessTimeoutDecision
MMCA.Common.Domain ·
MMCA.Common.Domain.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Domain/ProcessManagers/ProcessTimeoutDecision.cs:10· Level 2 · record
- What it is: the decision a process aggregate returns from
DecideTimeout. OnlyNotYetDuecarriesDueAtand onlyRejectedcarriesErrors(ProcessTimeoutDecision.cs:5-9). - Depends on:
ProcessTimeoutOutcome(Level 0) andError(G01). - Concept: the process-manager timeout step is introduced at
ProcessTimeout. The shape here is a closed set of named factories over a private constructor, the same idea asResult: invalid combinations cannot be built. - Walkthrough: the constructor is private (
ProcessTimeoutDecision.cs:12). Three get-only properties:Outcome(ProcessTimeoutDecision.cs:20),DueAt(ProcessTimeoutDecision.cs:23) andErrors(ProcessTimeoutDecision.cs:26). Four factories:NotApplicable()(ProcessTimeoutDecision.cs:30),NotYetDue(dueAt)(ProcessTimeoutDecision.cs:35),Applied()(ProcessTimeoutDecision.cs:39) andRejected(errors)(ProcessTimeoutDecision.cs:45), which throws when the list is empty (ProcessTimeoutDecision.cs:50) and stores a copy of it (ProcessTimeoutDecision.cs:53). - Why it's built this way: a rejected decision with no reason would be unreportable, so the guard makes it impossible; the defensive copy keeps the decision immutable after the aggregate returns it.
- Where it's used: returned by
ProcessManagerAggregateRoot.DecideTimeout(MMCA.Common/Source/Core/MMCA.Common.Domain/ProcessManagers/ProcessManagerAggregateRoot.cs:43); read byProcessTimeoutHandlerBase<TCommand, TProcess, TProcessId>(MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessTimeoutHandlerBase.cs:67), which copiesDueAtandErrorsinto theProcessTimeoutReport<TProcessId>(ProcessTimeoutHandlerBase.cs:82).
ProcessManagerAggregateRoot<TIdentifierType>
MMCA.Common.Domain ·
MMCA.Common.Domain.ProcessManagers·MMCA.Common/Source/Core/MMCA.Common.Domain/ProcessManagers/ProcessManagerAggregateRoot.cs:17· Level 5 · class (abstract)
- What it is: the base class for an aggregate that is the state of a long-running process (a
process manager, or saga): its own status columns decide every step, and named timeouts are applied
by re-deriving the due instant from what is stored (
ProcessManagerAggregateRoot.cs:5-8). - Depends on:
AuditableAggregateRootEntity<TIdentifierType>(G02),ProcessTimeout,ProcessTimeoutDecision. - Concept introduced, the process manager as an aggregate.
[Rubric §4, DDD](assesses whether aggregates own their invariants) and[Rubric §6, CQRS & Event-Driven](assesses coordination of multi-step workflows): instead of a separate saga-state row kept in step with the business aggregate, the business aggregate itself is the process state. Event-driven steps run throughProcessDomainEventHandlerBase<TDomainEvent, TProcess, TProcessId>and timeouts throughProcessTimeoutHandlerBase<TCommand, TProcess, TProcessId>(ProcessManagerAggregateRoot.cs:9-14; ADR-143; see also ADR-054 and ADR-086). - Walkthrough:
GetLastTransitionOn()(ProcessManagerAggregateRoot.cs:29) returnsLastModifiedOn ?? CreatedOnthrough a private static helper (ProcessManagerAggregateRoot.cs:31).DecideTimeout(timeout, utcNow)(ProcessManagerAggregateRoot.cs:43) is virtual and returnsNotApplicableby default (ProcessManagerAggregateRoot.cs:44). Its doc comment (ProcessManagerAggregateRoot.cs:33-42) fixes the override recipe: check the timeout's name and the stored state, returnNotYetDuewhentimeout.DueAfter(GetLastTransitionOn())lies afterutcNow, otherwise apply the transition; a stale or re-armed timeout is then a no-op by construction. - Why it's built this way: the base declares no property and no field (
ProcessManagerAggregateRoot.cs:9-11), andGetLastTransitionOnis a method rather than a property on purpose: a property declared here would map into every adopter's EF model (ProcessManagerAggregateRoot.cs:25-28). Deriving from it therefore leaves migrations unchanged. - Where it's used: the
TProcessconstraint of both process handler bases (MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessTimeoutHandlerBase.cs:42,MMCA.Common/Source/Core/MMCA.Common.Application/ProcessManagers/ProcessDomainEventHandlerBase.cs:34); the timeout base callsDecideTimeout(ProcessTimeoutHandlerBase.cs:67). - Caveats / not-in-source: whether an MMCA.ADC aggregate derives from it today is not determinable from the brief's usage sites, which list only MMCA.Common source and tests.
OutboxOrigin
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/OutboxOrigin.cs:31· Level 0 · record struct (public readonly)
- What it is: the five pieces of ambient context (
UserId,UserRoles,UserPermissions,TenantIdandCorrelationId) captured onto anOutboxMessagerow at write time, so a handler running a poll cycle later sees the same principal, tenant and correlation the raising request did. - Depends on: nothing first-party beyond the module's
UserIdentifierTypealias; a plainreadonly record structwith five positional properties and no body. - Concept introduced, ambient-context capture for asynchronous delivery.
[Rubric §10, Messaging & Integration Architecture](the outbox row carries the caller's context across the process/thread boundary) and[Rubric §29, Resilience & Business Continuity](a crash-and-retry replay still restores the original principal rather than an anonymous one). A synchronous handler readsICurrentUserServiceandITenantContextdirectly; an outbox-delivered handler runs on a background poll with neither populated, soOutboxMessage.FromDomainEventcaptures this struct at write time and the delivery path restores it before the handler runs. - Walkthrough: five positional properties, all nullable (
OutboxOrigin.cs:31-36):UserId(UserIdentifierType?, line 32),UserRoles(string?, a comma-separated list, line 33),UserPermissions(string?, a JSON array of the raising user's permission claims, null when they hold none, line 34; parameter doc at line 28),TenantId(string?, line 35) andCorrelationId(string?, line 36).UserPermissionsis an ordinary positional parameter, third in the list, so every construction site passes all five values. Every field is optional because the struct's own default value (all nulls) is exactly what a caller with nothing to capture, or every row written before these columns existed, reads back as. - Why it's built this way: a single positional struct groups the five values so
FromDomainEvent(domainEvent, origin = default)takes one extra optional parameter instead of five, and a defaulted struct argument costs a caller nothing when there is no ambient context to capture (an unauthenticated background job, for instance). Keeping it arecord structrather than a class avoids a heap allocation on the hot save path for what is, per row, five small fields copied once. - Where it's used: constructed in
DbContextFactory's origin accessor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:157) fromICurrentUserService,AmbientOrigin.FlattenRoles, the tenant context and the correlation context, and exposed throughApplicationDbContext.OutboxOriginAccessor/CurrentOutboxOrigin(ApplicationDbContext.cs:183,189, the latter falling back todefault); read byOutboxMessage.FromDomainEventto populate the row's five capture columns (OutboxMessage.cs:194-198,UserPermissionsat 196). - Caveats / not-in-source: the struct itself does not restore anything, it only carries the values;
the restore side (putting the captured user/tenant/correlation back onto a delivery scope) is the
outbox processor and
AmbientOriginhelper's job, not this type's.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
Entry
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/InboxConsumeScope.cs:52· Level 0 · record (internal sealed, nested)
- What it is: the value
InboxConsumeScopeholds while a broker consume runs: one handler consuming one message, as the pair(MessageId, Consumer), plus a flag that records whether that handler staged its own inbox row (InboxConsumeScope.cs:49-70). - Depends on: nothing first-party (BCL
Guid,stringandStringComparison). Nested in, and only constructed by,InboxConsumeScope. - Concept: the ambient consume marker is introduced at
InboxConsumeScope; this record is its payload.[Rubric §6, CQRS & Event-Driven]applies through that type. - Walkthrough: a positional record with two positional members and a small body.
MessageIdis the broker message id andConsumeris the handler's inbox consumer name, the same nameInboxMessagestores in itsConsumercolumn (InboxConsumeScope.cs:50-52).Staged(InboxConsumeScope.cs:59) is aboolwith a private setter, flipped only byMarkStaged()(InboxConsumeScope.cs:62). Its doc names the reason the flag lives on the entry object (InboxConsumeScope.cs:54-58): the same instance is shared by every scope on the flow, so the consumer sees the flag after the handler returns.Matches(messageId, consumer)(InboxConsumeScope.cs:68-69) is the one comparison every reader uses: the same message id and an ordinally equal consumer name.
- Why it's built this way: the identity pair is immutable and a fresh instance is set per
Entercall;null(theEntry?the scope exposes,InboxConsumeScope.cs:21) is the "outside any broker consume" state. The one mutable member is theStagedflag, and it is mutable on purpose: the handler-side recorder sets it inside the handler's own scope, and the consume-side store reads it afterwards to decide whether recording must read before it writes. Readers do not lean on record equality (which would also compareStaged): they callMatches, which compares the two identity fields only. - Where it's used: created in
InboxConsumeScope.Enter(InboxConsumeScope.cs:34), held in the scope'sAsyncLocal<Entry?>(InboxConsumeScope.cs:18), exposed throughCurrent(InboxConsumeScope.cs:21), read byInboxConsumeScope.HasStaged(InboxConsumeScope.cs:46-47), and captured as the value to restore byHandle(InboxConsumeScope.cs:73).EfInboxRecordercallsMatchesand thenMarkStagedinStage(EfInboxRecorder.cs:41,48) andMatchesagain in its revoke guard (EfInboxRecorder.cs:84-85). - Caveats / not-in-source: the simple name collides with an unrelated nested
EntryinCachedHealthReportProvider(G16, the health-report cache slot); the two share nothing but the name.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
IInboxStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/IInboxStore.cs:18· Level 0 · interface
- What it is: the consumer-side idempotency port, keyed per handler. It answers whether one
integration event handler has already processed one message, and records that it has, so an
at-least-once redelivery skips exactly the handlers that already succeeded (
IInboxStore.cs:3-8). - Depends on: nothing first-party (BCL
Guid/Task). Conceptually keyed byIDomainEvent'sMessageIdplus the handler's consumer name fromInboxConsumer(InboxConsumer.NameOf, which honorsInboxConsumerNameAttribute), and backed byInboxMessagerows in the EF implementation. - Concept introduced, the consumer-side Inbox (ADR-021).
[Rubric §6, CQRS & Event-Driven](idempotent consumers) and[Rubric §29, Resilience & Business Continuity](assesses tolerance of duplicate or redelivered messages). The inbox is the consumer-side complement to the outbox. Every reliable broker guarantees at-least-once delivery, so the same message can arrive more than once after a transient failure. The inbox records which handlers have processed which message; on redelivery the store answers "already processed" for those handlers and the consumer skips them without re-running their side effects. The doc comment states the protocol (IInboxStore.cs:9-16): oneGetProcessedConsumersAsyncread per message, then, per handler, skip when the set names it (or holds a legacy message-wide row), or run the handler ->RecordAsync, which comes to about k + 1 round trips for k handlers. A handler built onScopedIntegrationEventHandlerBase<TIntegrationEvent>has usually committed its own row already, staged throughIInboxRecorderin its own scope and saved with its own writes, soRecordAsyncthen finds the row and writes nothing. - Concept introduced, why the key is the handler and not the message. With several handlers for
one event, a message-wide row cannot say which of them succeeded: a redelivery after one handler
failed would either re-run them all or skip them all. Keyed per handler, the redelivery runs only
the handlers with no row yet (
InboxMessage.cs:8-12). A legacy row with an empty consumer, written when the key was message-wide, still answers "processed" for every handler, so an upgrade never re-runs a message the old inbox recorded (IInboxStore.cs:21-23). - Walkthrough: two members, both abstract.
GetProcessedConsumersAsync(Guid messageId, CancellationToken)(IInboxStore.cs:28): returns, in one read, the set of inbox consumer names already recorded for the message, compared ordinally and empty when nothing is recorded. The set may containstring.Empty, the legacy message-wide row that means every handler already ran (IInboxStore.cs:20-27). The port answers with data, not a verdict: deciding which handler to skip is the caller's job.RecordAsync(Guid messageId, string eventType, string consumer, CancellationToken)(IInboxStore.cs:41): records that the handler processed the message, on the consume scope. The contract calls itself idempotent: a row the handler already committed, or one a concurrent duplicate delivery wrote first, counts as recorded, while any other write failure surfaces so the message is not acknowledged with its record missing (IInboxStore.cs:30-35).eventTypeis the event's inbox name, kept for diagnostics (IInboxStore.cs:37).
- Why it's built this way: the port lets the no-op and EF-backed implementations be swapped by
configuration without touching consumer code, a §1/§6 dependency-inversion win. Reading the whole
recorded set once per message, instead of asking per handler, keeps the check to one query whatever
the number of handlers. Keeping the port to two data operations leaves the per-handler ordering rule
(check, run, record) in one place,
InboxHandlerLoop, which both broker consumers share. ADR-021 records this inbox as the broker-consume sibling of ADR-003's outbox (producer side) and ADR-017's HTTP-edge idempotency, deduping broker redeliveries per (message, handler) in the consumer's own database with a unique index as the race guard. - Where it's used: taken as a primary-constructor parameter by
IntegrationEventConsumer<TEvent>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumer.cs:42) andUpcastingIntegrationEventConsumer<TEvent>(UpcastingIntegrationEventConsumer.cs:33), both of which hand it toInboxHandlerLoop.RunAsync(IntegrationEventConsumer.cs:83-84,UpcastingIntegrationEventConsumer.cs:92-93). The loop callsGetProcessedConsumersAsynconce, lazily when the first handler comes up, so a message with no handler touches no inbox (InboxHandlerLoop.cs:45-59), skips a handler whose name or the legacy empty name is in the set (InboxHandlerLoop.cs:61-65), and callsRecordAsyncafter a handler returns, inside the consume marker (InboxHandlerLoop.cs:69-77); a handler exception records nothing and is rethrown, so the receive pipeline's retry runs that handler again. The loop adds each recorded consumer to its local copy of the set, so a handler type registered twice still runs once per message (InboxHandlerLoop.cs:49-50,79). Implemented byEfInboxStoreandNoOpInboxStore. - Caveats / not-in-source: both registrations live inside
AddBrokerMessaging(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:63), which returns early when the configured provider is in-process (DependencyInjection.Messaging.cs:72-74), so a monolith host that never calls it has noIInboxStorein the container at all. That is consistent (nothing consumes the port without a broker consumer) but it does mean the inbox posture is a broker-mode decision, not a container-wide one.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
InboxDisabledWarningService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/InboxDisabledWarningService.cs:20· Level 0 · class (internal sealed partial,IHostedService)
- What it is: a one-shot hosted service that writes a single Warning at startup when a host runs broker messaging with consumer-side inbox deduplication explicitly turned off. It does nothing else: no timer, no per-message work.
- Depends on:
ILogger<InboxDisabledWarningService>via primary constructor (InboxDisabledWarningService.cs:20) andMicrosoft.Extensions.Hosting.IHostedService(InboxDisabledWarningService.cs:21). It namesNoOpInboxStorein its doc comment but has no code dependency on it. - Concept introduced, making a disabled safety feature audible.
[Rubric §13, Observability & Operability](assesses whether an operator can tell the running posture of the system from its own output) and[Rubric §29, Resilience & Business Continuity](duplicate tolerance). The class comment states the argument (InboxDisabledWarningService.cs:6-17): a silently disabled safety feature is indistinguishable from an enabled one until the first duplicate side effect reaches a customer, so the off state is made loud exactly once, at startup, where it costs one log line and nothing per message. Because the inbox now defaults to ON for every broker transport (MessageBusSettings.IsInboxEnabled,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:140), reaching this service means the host setMessageBus:EnableInbox=falsedeliberately, so the text reads as an opt-out record rather than a nudge about a default (InboxDisabledWarningService.cs:12-17). This is the deliberate opposite of the per-message success log inOutboxProcessor, which is Debug precisely because it recurs. - Walkthrough:
StartAsync(InboxDisabledWarningService.cs:24-28) calls the source-generatedLogInboxDisabledand returnsTask.CompletedTask;StopAsync(InboxDisabledWarningService.cs:31) is a completed task. The message itself is the teaching artifact (InboxDisabledWarningService.cs:33-36): it names the setting and the store that produced the posture, states that the broker default is ON, explains that at-least-once delivery means every redelivered message runs its handlers again and duplicates their side effects until each handler is idempotent on its own, gives the remedy (remove the setting or set it totrue), and notes that theInboxMessagestable is already part of the model, so turning it back on needs no schema work. - Why it's built this way: registering the warning only on the disabled branch means a host
that keeps the default never constructs this service at all, so the correct configuration pays
nothing. Emitting it from
StartAsyncrather than from the DI registration puts it in the host's startup log next to the rest of the boot sequence, where an operator reads it. - Where it's used: added by
AddBrokerMessaginginside theelsebranch of theIsInboxEnabledcheck, immediately after theNoOpInboxStoreregistration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:157-162, theAddHostedServicecall at line 117). Covered byInboxDisabledWarningServiceTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Inbox/InboxDisabledWarningServiceTests.cs:11), which is what makes a log-only class testable at all ([Rubric §14, Testability]). - Caveats / not-in-source: because the whole registration sits inside
AddBrokerMessaging, which returns early for the in-process provider (DependencyInjection.Messaging.cs:67-70), a monolith host never sees this warning. That is correct (in-process dispatch does not redeliver) but it does mean the absence of the line is not by itself evidence that dedup is on.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
InboxMessage
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/InboxMessage.cs:14· Level 0 · class (public sealed)
- What it is: a deduplication record saying "this handler already processed the integration
event with this
MessageId" (InboxMessage.cs:3-7). It is an EF entity that lives in the consumer service's own database, mirroring the outbox. - Depends on: nothing first-party (BCL only). Its
MessageIdcarriesIDomainEvent's id semantics, itsConsumercarries the nameInboxConsumerderives for a handler, and it is read and written throughIInboxStoreandEfInboxRecorder. - Concept introduced, the inbox row (idempotency table), keyed per handler.
[Rubric §6, CQRS & Event-Driven](idempotent consumers) and[Rubric §8, Data Architecture](a deliberate dedup table per service). The key is the PAIR (message, handler): with several handlers for one event, a redelivery after one of them failed runs only the handlers with no row yet, which a message-wide row could not tell apart (InboxMessage.cs:8-12). A row is either staged byEfInboxRecorderinto the handler's own scope and committed by the handler's own save, or written byEfInboxStoreafter the handler returns. Because the table lives in the consumer's own database, the dedup respects the database-per-service boundary (ADR-006) and can be committed in the same transaction as a handler's own writes. - Walkthrough: five
init-only properties (InboxMessage.cs:17-38).Id(surrogateGuidPK defaulted toGuid.NewGuid(),InboxMessage.cs:17) is the EF key.MessageId(required,InboxMessage.cs:20) is the event's own id.EventType(required,InboxMessage.cs:23) is retained for diagnostics.Consumer(required,InboxMessage.cs:35) is the handler's[InboxConsumerName]value, else its full type name; the empty string is reserved for rows written before the key was per handler, and such a row means every handler of that message already ran (InboxMessage.cs:25-34).ProcessedOn(InboxMessage.cs:38) is the UTC timestamp of the record. The shape only makes sense together with its EF configuration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:977-1004): the table isdbo.InboxMessages(ApplicationDbContext.cs:980),EventTypeis capped at 500 non-Unicode characters (ApplicationDbContext.cs:982),Consumeris required, non-Unicode, capped atInboxConsumerNameAttribute.MaxLengthand defaulted to''in the database so the migration that adds it backfills every existing row with the legacy value (ApplicationDbContext.cs:984-991). The pair carries a unique index namedIX_InboxMessages_MessageId_Consumer, which replaces the old unique index onMessageIdalone in the same migration (kept, it would reject the second handler's row), with the leadingMessageIdcolumn still serving per-message lookups (ApplicationDbContext.cs:993-998).ProcessedOncarries a second, non-unique indexIX_InboxMessages_ProcessedOn(ApplicationDbContext.cs:1002-1003) purely so the age-based retention purge has something to seek instead of scanning the table (ApplicationDbContext.cs:1000-1001,[Rubric §12, Performance & Scalability]). - Why it's built this way: separating
Id(the PK for EF internals) from the business dedup key (the unique pair) follows the surrogate-key convention used elsewhere in the codebase, and the unique index is what turns a racing duplicate delivery into a catchableDbUpdateExceptionrather than a read-then-write race. Storing it as a plain entity lets the same EF stack purge it (seeOutboxCleanupService) and lets a handler's ownSaveChangesAsynccommit it. ADR-021 governs the mechanism, and the row lives in the consumer's own database (ADR-006). - Where it's used: written and queried by
EfInboxStore(EfInboxStore.cs:83,122-131); staged and revoked byEfInboxRecorder(EfInboxRecorder.cs:52,77-80); purged byOutboxCleanupServicewhen the inbox is enabled (OutboxCleanupService.cs:220-225, gated on_inboxEnabledatOutboxCleanupService.cs:53and called atOutboxCleanupService.cs:119-121); configured on every relational context byApplicationDbContext.ConfigureInbox(ApplicationDbContext.cs:977, called from line 441) (G07). - Caveats / not-in-source: the type itself has no first-party reference (it is a plain POCO),
so the links to
IInboxStore/IDomainEventabove are conceptual, not compile dependencies. The configuration is skipped by the Cosmos context, which overridesOnModelCreating(ApplicationDbContext.cs:973-975). There is also no tenant column: a tenant with its own database gets its ownInboxMessagestable instead (seeOutboxCleanupService).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
InboxSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/InboxSettings.cs:10· Level 0 · class (public sealed)
- What it is: the options class for the consumer-side inbox, bound from the optional
Inboxconfiguration section (InboxSettings.cs:5-9). It carries one setting, how long anInboxMessagerow is kept. - Depends on: nothing first-party;
System.ComponentModel.DataAnnotationsfor the[Range]attribute (InboxSettings.cs:1). Its doc refers toInboxMessageandInboxPosture, the type through which it is read. - Concept introduced, the inbox retention is the deduplication horizon.
[Rubric §6, CQRS & Event-Driven](idempotent consumers) and[Rubric §29, Resilience & Business Continuity]. An inbox row is the only proof that a handler already ran a message. Once the row is purged, a redelivery of that message would run its handlers again, so the retention period is also the window inside which redelivery is safe (InboxSettings.cs:15-21). The doc spells out that the horizon is enforced on both sides (InboxSettings.cs:22-27): the broker receive pipeline dead-letters, with a Warning and without running any handler, an event whoseDateOccurredis older than the horizon (the usual route is a resubmit from a broker dead-letter queue, which brokers keep indefinitely by default), andIOutboxAdministration.RepublishProcessedAsyncrefuses a republish window that starts before the horizon, since every event in it would meet that same refusal at the consumer. - Walkthrough: two members.
SectionName(InboxSettings.cs:13), astatic readonly stringset to"Inbox".RetentionDays(InboxSettings.cs:33), aninit-onlyintdefaulted to30and validated by[Range(0, 3650)](InboxSettings.cs:32). It is independent ofOutbox:RetentionDays, so the dedup window and the outbox table size are two separate decisions (InboxSettings.cs:19-20).0keeps inbox rows forever and turns both horizon checks off (InboxSettings.cs:29).
- Why it's built this way: separating the inbox window from the outbox retention keeps a
decision about table size from silently shortening the dedup guarantee. The doc gives the sizing
rule: set it at least as long as the longest delay after which a message can still be redelivered
or resubmitted (
InboxSettings.cs:28-29). The value is never read directly by the cleanup sweep, the republish guard or the receive pipeline; they read it throughInboxPosture, which zeroes it when the host has no inbox (InboxSettings.cs:7-8). - Where it's used: bound with
ValidateDataAnnotationsandValidateOnStartinAddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:162-165) and passed to the singletonInboxPostureregistered just below it (DependencyInjection.cs:169-171); read straight from configuration inAddBrokerMessaging, falling back to a default instance when the section is absent, to compute the receive pipeline's horizon (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:113-116). Exercised byInboxPostureTests,OutboxCleanupServiceTestsandOutboxAdministrationTests. - Caveats / not-in-source: the two registration paths read the section independently (options
binding in
AddInfrastructure, a directGet<InboxSettings>()inAddBrokerMessaging, which a host wiring the broker withoutAddInfrastructurestill honours,DependencyInjection.Messaging.cs:110-112); the direct read does not run the[Range]validation itself.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
Handle
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/InboxConsumeScope.cs:73· Level 1 · struct (internal readonly, nested)
- What it is: the disposable token
InboxConsumeScope.Enterreturns. Disposing it restores the consume marker that was current beforeEnterran (InboxConsumeScope.cs:72-77). - Depends on:
Entry(Level 0), the privateAsyncLocal<Entry?>of its enclosingInboxConsumeScope(InboxConsumeScope.cs:18), and BCLIDisposable. - Concept: the ambient consume marker is introduced at
InboxConsumeScope; this struct is the restore-on-dispose half of it, the same shape as a logging scope. - Walkthrough: a
readonly structwith a primary constructor that captures the previousEntry, possiblynull(InboxConsumeScope.cs:73). Its only member,Dispose()(InboxConsumeScope.cs:76), writes that captured value back into the async-local slot. - Why it's built this way: restoring the previous value rather than clearing the slot is what
keeps a nested consume from leaking its marker into the outer one (
InboxConsumeScope.cs:23-26). Areadonly structconsumed by ausingstatement adds no heap allocation for the handle on a path that runs once per handler invocation. - Where it's used: returned by
InboxConsumeScope.Enter(InboxConsumeScope.cs:31-36) and disposed by theusingblock around each handler invocation inInboxHandlerLoop(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/InboxHandlerLoop.cs:61-64).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
NoOpInboxStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/NoOpInboxStore.cs:7· Level 1 · class (internal sealed)
- What it is: the
IInboxStoreused when a broker host explicitly disables the inbox. It never dedups and records nothing, so every handler runs on every delivery, exactly as it would with no inbox at all (NoOpInboxStore.cs:3-6). - Depends on:
IInboxStore(the port it implements); BCLTask/Guidonly. - Concept reinforced, the Null Object pattern.
[Rubric §2, Design Patterns](assesses idiomatic use of patterns) and[Rubric §17, DevOps & Deployment].GetProcessedConsumersAsyncalways returns the same cached task over an empty ordinal set (NoOpInboxStore.cs:9-13) andRecordAsyncreturnsTask.CompletedTask(NoOpInboxStore.cs:15-16). The consumer pipeline is written againstIInboxStoreand runs identically whether or not dedup is enabled: the Null Object removes a runtimeif (inbox enabled)branch from every consumer. - Walkthrough: the class implements the port's two members plus one private static field,
Nothing, aTask<IReadOnlySet<string>>built once from an emptyHashSet<string>withStringComparer.Ordinal(NoOpInboxStore.cs:9-10), so the per-message read allocates nothing. Because the set is always empty, the per-handler check inInboxHandlerLoopnever skips (InboxHandlerLoop.cs:57-65), and theRecordAsyncafter each handler writes nothing (InboxHandlerLoop.cs:76). The handler-side half is off too:EfInboxRecorderis registered only on the enabled branch (DependencyInjection.Messaging.cs:149), soScopedIntegrationEventHandlerBase<TIntegrationEvent>resolves noIInboxRecorderand stages nothing (its optionalGetService<IInboxRecorder>()call,ScopedIntegrationEventHandlerBase.cs:81). - Why it's built this way: the inbox resolves ON for a broker transport
(
MessageBusSettings.IsInboxEnabled,MessageBusSettings.cs:148), so this store is the deliberate opt-out path for a host that cannot query theInboxMessagestable yet, not a quiet default. Note that it is registered as a singleton whileEfInboxStoreis scoped (DependencyInjection.Messaging.cs:143,157): a stateless no-op needs no per-request lifetime, an EF-backed store that reads and writes through the consume scope's context does. The sameelsebranch also registersInboxDisabledWarningService(DependencyInjection.Messaging.cs:162), so choosing the Null Object is never silent (ADR-021). - Where it's used: registered as
IInboxStoreinsideAddBrokerMessagingon theelsebranch ofsettings.IsInboxEnabled, that is whenMessageBus:EnableInbox=falseis set explicitly (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:141-163); consumed byIntegrationEventConsumer<TEvent>.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
OutboxMessage
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/OutboxMessage.cs:14· Level 2 · class (public sealed)
- What it is: a row in an
OutboxMessagestable: a JSON-serialized domain event persisted in the same database transaction as its aggregate, ready for reliable asynchronous dispatch, plus all the bookkeeping the processor needs (retry and dead-letter state, claim lease, trace context, ordering key). - Depends on:
IDomainEventandIHasOrderingKey(G02),EventNameResolver,OutboxOrigin; BCLSystem.Text.Json,System.Diagnostics.Activity(trace capture) andSystem.Collections.Concurrent(the type cache). - Concept introduced, the Transactional Outbox pattern.
[Rubric §6, CQRS & Event-Driven](reliable at-least-once delivery),[Rubric §8, Data Architecture](the event is written in the same transaction as the aggregate) and[Rubric §29, Resilience & Business Continuity](the delivery guarantee survives a crash). ADR-003 is the governing decision. The problem it solves: if you save an aggregate and then publish an event, a crash between the two loses the event. The fix is to write the event to anOutboxMessagesrow in the same database transaction as the aggregate change; theOutboxProcessorthen reads unprocessed rows and dispatches them, re-dispatching after a crash (at-least-once). Each service owns its own outbox table (ADR-006), so there is no cross-service race. - Walkthrough
- Static
SerializerOptions(OutboxMessage.cs:28) is a barenew(): the System.Text.Json defaults, deliberately. Its doc gives the reasoning (lines 17-25): an event is a contract another process deserializes by shape, so a reference cycle in it is a modelling error (in practice an entity graph put on the wire), and the default reference handling refuses it with aJsonExceptionat write time, inside the save that raised the event. Ignoring the cycle instead wrote the back-reference asnull, so the row looked healthy and the consumer silently received an event with data missing. TheIntegrationEventPayloadsHoldNoEntitiesarchitecture rule catches the usual cause at build time, and rows written under the old cycle-ignoring options carry no reference metadata, so they still read back. The field isinternal, not private, so the broker wire serializes with this same instance (BrokerWire.JsonOptions): one options object, so the outbox hop and the broker hop cannot drift (lines 25-26). The same instance is reused on the read side (line- so the read and the write can never disagree about the payload's shape.
- Static
EventTypeCache(OutboxMessage.cs:38), aConcurrentDictionary<string, Type?>keyed ordinally by the stored name, memoizing the reflection that deserialization would otherwise run per row. Only a successful resolution is cached (lines 30-37): an unresolvable name is re-scanned on its retry, so an assembly that loads late can still resolve it before the row dead-letters. - Identity and payload (
OutboxMessage.cs:40-54):Id(Guid, defaulted toGuid.NewGuid(), line 41);EventType(required, the stored identity, line 48);Payload(required, the JSON string, line 51);OccurredOn(the business timestamp copied fromIDomainEvent.DateOccurred, line 54). Allinit-only.EventTypeis documented as theEventNameAttributename when the event declares one and the assembly-qualified type name otherwise (lines 44-46). - Processing state (
OutboxMessage.cs:56-101), deliberately settable because the processor mutates it:ProcessedOn?(null until dispatched, line 57);RetryCount(line 60);LockedUntil?(line 68) andLockToken?(line 75);LastError?(line 78);DeadLetteredOn?(line 93) andDeadLetterReason?(line 101). - The claim lease is the part worth slowing down for.
LockedUntilis the UTC timestamp until which the row is leased to one processor replica, and its doc states the consequence plainly: rows with an unexpired lease are skipped by other replicas' polls, making scale-out safe by construction, where before the lease two replicas could drain the same rows and double-dispatch every event (lines 63-66).LockTokenis the claim token written together with the lease, so the claiming replica processes only rows carrying its own token, which is what stops a race between two claim updates from handing the same row to both (lines 71-73). - The dead-letter state is explicit.
DeadLetteredOnis the UTC instant the processor abandoned the row, null while it is still pending or once it is processed; a dead-lettered row is never claimed again until an operator replays it throughIOutboxAdministration.ReplayDeadLettersAsync, which clears this column andDeadLetterReason(lines 81-84). The doc names why it is a column rather than a reading ofRetryCountagainstOutbox:MaxRetries(lines 86-90): with the implicit rule, raising the setting silently replayed every dead letter the old value had produced, and lowering it silently abandoned rows that were still pending. Now the setting only decides WHEN a failing row is abandoned, whether it IS abandoned is recorded on the row, and the dead-letter retention window runs from this stamp.DeadLetterReasoncarries the same value theoutbox.dead_letter.countmetric is tagged with (retries_exhaustedortype_unresolvable), while the failure itself stays inLastError(lines 96-99). - Trace context (
OutboxMessage.cs:103-116):TraceId?/SpanId?(lines 104, 107), W3C ids captured at write time andinit-only, so a trace can be resumed across the asynchronous hop, plusTraceFlags?(byte?, line 116), the W3C trace flags of the activity current when the event was raised, which is the request's sampling decision. The processor rebuilds the parent context with those flags, so a parent-based sampler exports the delivery span only when the request itself was sampled, and a null (no ambient activity, or a row written before the column existed) reads as not sampled (lines 110-114, consumed atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:1289). - Ordering key (
OutboxMessage.cs:128):OrderingKey?, copied from an event implementingIHasOrderingKey. Its doc gives the invariant the processor enforces (lines 119-125): a row carrying a key is not claimed while an earlier unprocessed, non-dead-lettered row with the same key exists in the same data source, so events for one aggregate reach the bus in the order they were raised, across batches and across replicas, with the head-of-line blocking that implies. - The ambient-context capture (
OutboxMessage.cs:130-162):TenantId?(line 135),UserId?(UserIdentifierType?, line 142),UserRoles?(line 148),UserPermissions?(line 155, a JSON array of the raising user's permission claims, restored aspermissionclaims so a handler authorizing on a claim-only grant sees what the raising request saw; unbounded and never truncated) andCorrelationId?(line 162), allinit-only, copied from anOutboxOriginat write time and restored onto the delivery scope before a handler runs, so a poll-cycle-later dispatch sees the same tenant, principal, roles, permissions and correlation id the raising request did. Every one is null for a row written before these columns existed or for a tenant-less/system-raised event, which is deliberate: it is exactly the struct's own default. FromDomainEvent(IDomainEvent, OutboxOrigin)(OutboxMessage.cs:180-205), the static factory. It null-guards the event (line 182), capturesActivity.Current(line 185), resolves the stored name throughEventNameResolver.GetStorageName(line 188), serializes against the runtime type (line 189), copies the fiveOutboxOriginfields onto the row (lines 194-198,UserPermissionsat 197), and copies the ordering key with(domainEvent as IHasOrderingKey)?(line 203).origindefaults todefault(OutboxOrigin)(line 180), so a caller with nothing to capture keeps the single-argument call and every capture column stores null. The comment above the ordering key cast is the subtle bit (lines 200-202): the interface test cannot be replaced by a type-level flag, because an implementing event returningnullopts that one instance out of ordered delivery.DeserializeEvent()(OutboxMessage.cs:217-226) resolves the type (line 219), returnsnullrather than throwing when it cannot (lines 220-221) so the processor can dead-letter the row instead of crashing, and otherwise deserializes with the shared options (line 225).- Type resolution. The private
ResolveEventType()(OutboxMessage.cs:240) is a one-line forward tointernal static ResolveStoredEventType(string)(lines 250-272), which exists so a caller deciding something about a stored name sees exactly the type the processor would deliver: the republish window inOutboxAdministrationkeeps only names that resolve to integration events (doc, lines 242-249). It checks the cache withTryGetValuefirst (lines 252-255), then does a two-step lookup whose order the comment calls load-bearing (lines 257-259):Type.GetTyperuns first so a row storing an assembly-qualified name resolves by a direct lookup, and the attribute scan (EventNameResolver.FindTypeByDeclaredName) only runs for a stored name that is not a CLR name (line 260). Only an event type is a valid resolution (lines 262-268): a stored name that resolves to no type, or to a type not assignable toIDomainEvent(a tampered row, a restored foreign backup), returnsnull, so the payload is never materialized into an arbitrary type and the row dead-letters astype_unresolvable. The cache is written only after that check passes (line 270), so a failure is not cached and the one-shot retry the processor grants an unresolvable row really scans again.IsEventTypeCached(OutboxMessage.cs:231) is aninternaltest hook that exposes whether a stored name is in the cache.
- Static
- Why it's built this way: persisting events in the same transaction, not after it, is the only way
to guarantee no event is lost. JSON keeps rows human-readable for debugging, and the default
serializer options make a malformed payload fail loudly at the save rather than arrive incomplete;
the stored identity enables polymorphic deserialization; the per-name type cache keeps the hot poll
path off reflection;
TraceId/SpanIdlet traces span the asynchronous hop; theOutboxOrigincapture columns let a delivered handler run authorization checks and stamp audit fields against the same principal a synchronous dispatch would have seen instead of running anonymously; the lease pair moves scale-out safety from a deployment convention (minReplicas: 1) into the data model; and the explicit dead-letter pair makes abandonment a fact about the row rather than a function of a setting that can change. The EF configuration completes the picture (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:902-970): tabledbo.OutboxMessages(line 908), bounded columns forEventType(500, non-Unicode, line 910),LastError(4000, line 912),DeadLetterReason(256, non-Unicode, line 919) andOrderingKey(200, line 925), and three filtered indexes, each with its reason written above it:IX_OutboxMessages_Pending(line 950), filtered toProcessedOn IS NULL, whose includedDeadLetteredOnandLockedUntillet the poll's filter columns ride along without a key lookup (lines 941-949);IX_OutboxMessages_Processed(line 957) so the six-hourly retention sweep does not scan the largest partition of the table; andIX_OutboxMessages_Ordering(line 969) keyed on(OrderingKey, OccurredOn), carryingDeadLetteredOn(line 967) and filtered to keyed pending rows (line 968), so the claim's predecessor test is a seek and a host that never declares an ordering key carries an empty index. - Where it's used: written by the
SaveChangescapture inDomainEventSaveChangesInterceptor(DomainEventSaveChangesInterceptor.cs:293), byInProcessEventBus(InProcessEventBus.cs:139) and byBrokerEventBus(BrokerEventBus.cs:86); read, claimed and dispatched by theOutboxProcessor; dispatched in-process and handed back byInProcessDispatch; marked processed in bulk byOutboxFinalizer; listed, replayed and republished byOutboxAdministration; purged byOutboxCleanupService. - Caveats / not-in-source: an event that has not adopted
EventNameAttributestores its assembly-qualified name, so a rename or assembly move makesType.GetTypereturn null for rows already written, the failure is not cached (OutboxMessage.cs:265-270), and the row is dead-lettered with reasontype_unresolvableafter the processor's one retry, which re-scans the name. The same outcome applies to a stored name that resolves to a non-event type.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
InboxConsumeScope
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/InboxConsumeScope.cs:16· Level 2 · class (internal static)
- What it is: the ambient marker of the broker consume currently running on this async flow:
which message, and which handler. The broker consumers set it around each handler invocation and
EfInboxRecorderreads it, so a row is staged only for the handler and message actually being consumed (InboxConsumeScope.cs:3-6). - Depends on: its nested
EntryandHandle, and BCLAsyncLocal<T>. - Concept introduced, guarding the handler-side inbox write to the delivery it deduplicates.
[Rubric §6, CQRS & Event-Driven](idempotent consumers) and[Rubric §15, Best Practices & Code Quality]. The same handler classes also run outside a broker consume: the in-processDomainEventDispatcherdelivers an integration event raised as a domain event to itsIIntegrationEventHandlers, and a handler can raise further events whose handlers run nested inside it. A row staged there would record a message id no broker delivery ever checks, or, for a nested event, a different message under this one's consumer. Matching both the message id and the consumer name keeps staging to exactly the delivery the inbox is deduplicating (InboxConsumeScope.cs:7-14). - Walkthrough:
CurrentEntry(InboxConsumeScope.cs:18) is a private staticAsyncLocal<Entry?>, andCurrent(InboxConsumeScope.cs:21) reads it,nulloutside a consume.Enter(messageId, consumer)(InboxConsumeScope.cs:31-36) saves the current value, sets a newEntry, and returns aHandleholding the saved value, which puts it back on dispose so a nested consume never leaks its marker into the outer one (InboxConsumeScope.cs:23-26).HasStaged(messageId, consumer)(InboxConsumeScope.cs:46-47) answers whether the consume running right now is exactly this one and its handler staged its own inbox row: only then can the row already be committed by the handler's own save, so only then does recording read before it writes (InboxConsumeScope.cs:38-42). The two nested types follow atInboxConsumeScope.cs:52-70andInboxConsumeScope.cs:73-77. - Why it's built this way: an
AsyncLocalflows across everyawaitinto the handler's code without threading a message id and consumer name through theIIntegrationEventHandlersignature or the handler base. Because theEntryobject is shared by every scope on the flow, the marker also carries a signal back out: the recorder setsStagedinside the handler, and the store reads it after the handler returns, which spares a handler that never stages the extra read. The class isinternal static, so the marker is not public surface; its two readers,EfInboxRecorderandEfInboxStore, live in the same assembly (ADR-021). - Where it's used:
Enterwraps each handler invocation and itsRecordAsyncinInboxHandlerLoop(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/InboxHandlerLoop.cs:69-77), the loop bothIntegrationEventConsumer<TEvent>andUpcastingIntegrationEventConsumer<TEvent>run;Currentis read byEfInboxRecorder.StageandEfInboxRecorder.IsCurrentConsume(EfInboxRecorder.cs:41,84-85), andHasStagedbyEfInboxStore.RecordAsync(EfInboxStore.cs:76). Also referenced byEfInboxStoreTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Inbox/EfInboxStoreTests.cs:30).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
InboxPosture
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/InboxPosture.cs:13· Level 2 · class (public sealed)
- What it is: the consumer inbox as this host actually runs it: whether it is wired at all and,
if it is, how long its rows deduplicate (
InboxPosture.cs:5-12). It turns two settings into one resolved answer. - Depends on:
InboxSettings(Level 0) forRetentionDaysandMessageBusSettings(MessageBusSettings.IsInboxEnabled,MessageBusSettings.cs:148), both taken by the constructor (InboxPosture.cs:18); BCLTimeSpan. - Concept introduced, one rule for every reader of the dedup horizon.
[Rubric §6, CQRS & Event-Driven]and[Rubric §29, Resilience & Business Continuity]. Three places need the inbox horizon: the cleanup sweep (how old an inbox row may get), the republish guard (how far back a republish window may start) and the broker receive pipeline (how old an event may be and still run its handlers). If each readInbox:RetentionDaysdirectly, a host with no inbox would purge rows it does not have and refuse events against a horizon it does not enforce. The class doc states the rule (InboxPosture.cs:8-11): every reader resolves the horizon through this one type, so they cannot disagree, and a host with no inbox has no inbox rows to purge and no horizon to enforce, whateverInbox:RetentionDayssays. - Walkthrough
- The constructor (
InboxPosture.cs:18-25) null-guards both arguments, copiesmessageBus.IsInboxEnabledintoIsEnabled, and setsRetentionDaystoinbox.RetentionDayswhen enabled and0otherwise. IsEnabled(InboxPosture.cs:28): whether this host wires the consumer inbox.RetentionDays(InboxPosture.cs:34): the days inbox rows are kept,0meaning no inbox sweep runs (InboxPosture.cs:30-33).Horizon(InboxPosture.cs:41):TimeSpan.FromDays(RetentionDays)whenRetentionDays > 0, otherwisenull.nullcovers both "no inbox" and "an inbox that keeps its rows forever"; an event older than a non-null horizon may have had its inbox rows purged, so it cannot be proven not to have run (InboxPosture.cs:36-40).
- The constructor (
- Why it's built this way: computing the posture once, from immutable inputs, makes the three
consumers agree by construction rather than by each re-deriving the same condition. Returning a
nullable
TimeSpanlets every reader express "no horizon" as a single pattern match (_inboxHorizon is { } horizon) instead of two flag checks. - Where it's used: registered as a singleton by
AddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:169-171); taken byOutboxCleanupService, which readsRetentionDaysinto its inbox window (OutboxCleanupService.cs:54,74), and byOutboxAdministration, which readsIsEnabledandHorizon(OutboxAdministration.cs:44,86-87) and refuses a republish window that starts before the horizon (OutboxAdministration.cs:347).AddBrokerMessagingbuilds its own instance from configuration and passes itsHorizonto theBrokerReceivePipeline(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:113-117), which dead-letters an event older than the horizon with reasonpast-inbox-horizon, without running its handlers (BrokerReceivePipeline.cs:43,112-118). Covered byInboxPostureTests. - Caveats / not-in-source: the broker registration constructs a second, unregistered instance
rather than resolving the singleton, so that a host wiring the broker without
AddInfrastructurestill honours the horizon (DependencyInjection.Messaging.cs:110-112); both instances apply the same constructor rule.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
EfInboxRecorder
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/EfInboxRecorder.cs:29· Level 10 · class (internal sealed)
- What it is: the EF-backed
IInboxRecorder, the handler-side half of the inbox. It adds the handler'sInboxMessagerow to the CURRENT scope's context for the inbox data source, unsaved, and can revoke that row after a failure (EfInboxRecorder.cs:10-12). - Depends on:
IDbContextFactory,IDataSourceResolver,IOptions<OutboxSettings>and aTimeProvider, all via primary constructor (EfInboxRecorder.cs:29-33); the portIInboxRecorder(G05);InboxMessage;InboxConsumeScope; resolves anApplicationDbContext. - Concept introduced, staging the dedup row into the handler's transaction.
[Rubric §6, CQRS & Event-Driven](idempotent consumers),[Rubric §8, Data Architecture](transaction boundaries) and[Rubric §29, Resilience & Business Continuity]. A naive inbox writes its row after the handler commits, which leaves a window: crash in between and the handler runs again on redelivery. This recorder is resolved from the scopeScopedIntegrationEventHandlerBase<TIntegrationEvent>opens per delivery, so the context it stages into is the one the handler's own repositories and unit of work resolve: the handler'sSaveChangesAsynccommits the row in the same transaction as its writes, a rollback discards it with them, and a scope that never saves discards it on disposal (EfInboxRecorder.cs:13-17). The class comment states the limit (EfInboxRecorder.cs:18-22): atomicity holds only when the handler writes to the same physical source the inbox lives in (theOutbox:DataSource/Outbox:DatabaseNamepair, the single database of a monolith or of a service that owns one). A handler writing elsewhere is back to two transactions, andEfInboxStore's record after the handler returns covers it, so delivery stays at-least-once. - Walkthrough
Stage(messageId, eventType, consumer)(EfInboxRecorder.cs:36-59) null-guards its strings (lines 38-39) and returns without doing anything unlessInboxConsumeScope.Currentis set and itsEntryMatchesthis message and this handler (lines 41-44). Otherwise it first callscurrent.MarkStaged()(line 48), which tells the consumer'sRecordAsyncthat this handler's save may already have committed the row, so it reads before it writes, while a handler that never stages is recorded with one insert (lines 46-47). It then resolves the context (line 49) andAdds anInboxMessagewhoseProcessedOncomes from the injected clock,timeProvider.GetUtcNow().UtcDateTime(lines 52-58), so a test can pin the stamp. TheAddis synchronous on purpose, per the EF guidance comment (line 51). Nothing is saved here.RevokeAsync(messageId, consumer, cancellationToken)(EfInboxRecorder.cs:68-81) applies the same guard throughIsCurrentConsume(lines 72-75), then issues a set-basedExecuteDeleteAsyncfor that message and that consumer only (lines 77-80). The remarks explain both choices (EfInboxRecorder.cs:62-67): the instance is resolved from a scope opened for the revoke alone, so its context holds nothing of the failed handler's (a rejected insert, an aborted transaction, a half-cleared tracker), and a legacy message-wide row is never removed.IsCurrentConsume(EfInboxRecorder.cs:84-85) is the guard:InboxConsumeScope.Currentmust be set andEntry.Matchesmust hold, that is the same message id and an ordinally equal consumer name.ResolveContext(EfInboxRecorder.cs:87-91) resolvesOutboxSettings.DataSource/DatabaseNamethroughIDataSourceResolverand asks the factory for that context, the same routingEfInboxStoreuses.
- Why it's built this way: splitting the inbox into a recorder on the handler's scope and a store
on the consume scope is what lets the common case be atomic without the consumer knowing which
context a handler writes through. The
InboxConsumeScopeguard keeps the in-process dispatch path, where the same handler classes also run, from staging rows no broker delivery will ever check (ADR-021). - Where it's used: registered as the scoped
IInboxRecorderonly when the inbox is enabled (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:149);Stageis called byScopedIntegrationEventHandlerBase<TIntegrationEvent>through an optionalGetService<IInboxRecorder>()(MMCA.Common/Source/Core/MMCA.Common.Application/DomainEvents/ScopedIntegrationEventHandlerBase.cs:81), andRevokeAsyncfrom that base'sRevokeInboxRowAsync, inside a fresh scope and under a time budget (ScopedIntegrationEventHandlerBase.cs:152-165). Exercised byEfInboxStoreTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Inbox/EfInboxStoreTests.cs:30). - Caveats / not-in-source: whether a given handler's save lands on the same physical source as the resolved outbox data source is a per-host configuration question, not determinable from this file.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
EfInboxStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Inbox·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/EfInboxStore.cs:33· Level 10 · class (public sealed partial)
- What it is: the EF-backed inbox store. It records, per handler, which messages this service has
processed, in the consumer service's own database (the configured outbox data source), so a
redelivered message skips the handlers that already succeeded (
EfInboxStore.cs:12-15). - Depends on:
IDbContextFactory,IDataSourceResolver,IOptions<OutboxSettings>(to find the publish-target source),ICurrentUserService(the consume scope's user, used to stamp the save),ILogger<EfInboxStore>and aTimeProvider(the clock that stampsProcessedOn), all via primary constructor (EfInboxStore.cs:33-39); theInboxMessageentity;InboxConsumeScope(itsHasStagedsignal); resolves anApplicationDbContext; EF Core'sEntityStateto detach a rejected row. - Concept reinforced, the consume-scope half of the inbox.
[Rubric §6, CQRS & Event-Driven](idempotent consumers),[Rubric §8, Data Architecture]and[Rubric §29, Resilience & Business Continuity]. This store reads and writes on the CONSUME scope; the atomic half lives inEfInboxRecorder, through which aScopedIntegrationEventHandlerBase<TIntegrationEvent>handler stages its own row and commits it with its writes. By the timeRecordAsyncruns for that handler the row is usually already there and the store writes nothing. For a handler that never saved, or that writes to another physical source, the store writes the row after the handler returned, and a crash between the two redelivers the message to that handler, which is why handlers must be idempotent (EfInboxStore.cs:16-24). Concurrent duplicate deliveries are absorbed by the unique index on (MessageId,Consumer), whichever save hits it (EfInboxStore.cs:25-31). - Walkthrough
LegacyConsumer(EfInboxStore.cs:45) is the empty string: the consumer value of a row written before the inbox was keyed per handler, which answers "processed" for any consumer (EfInboxStore.cs:41-44).GetProcessedConsumersAsync(EfInboxStore.cs:49-59) is oneAsNoTrackingquery over the (MessageId, Consumer) index, whatever the number of handlers (line 48): it selects theConsumerof every row with the message id (lines 51-56) and returns them as aHashSet<string>withStringComparer.Ordinal(line 58). A legacy row contributesLegacyConsumer, which the caller treats as "every handler ran".RecordAsync(EfInboxStore.cs:69-115) null-guards its strings (lines 71-72) and resolves the context (line 74). It reads before it writes only when the handler staged its own row during this consume,InboxConsumeScope.HasStaged(messageId, consumer)(line 76): that is the one case where the handler's own save may already have committed the row, and checking first there avoids a rejected insert and a provider error log on every such consume; whenIsRecordedAsyncthen finds the row it returns (lines 76-80). Every other handler is recorded with a single insert, and a concurrent duplicate is still absorbed by the unique-index fallback (remarks, lines 62-68). The insertAdds anInboxMessagestamped from the injected clock (lines 83-89) and saves withcontext.SaveChangesAsync(currentUserService.UserId, ...)(line 97): the publisher's origin is restored onto this scope before the inbox is touched, and anything a handler left pending on this scope's context is flushed by the same save and must carry that user rather than the system (lines 93-96). Itscatch (DbUpdateException)(line 99) does three things in order. First it detaches the rejected entry (line 104), because the context is cached per data source for the whole scope and a survivingAddedrow would make every later save on it fail, the next handler's record included (lines 101-103). Second it re-queries throughIsRecordedAsyncand rethrows when the row is still absent (lines 110-111): only a concurrent duplicate delivery tripping the unique index is safe to absorb, re-querying holds for every engine where sniffing provider error codes would not, and swallowing any other failure would ack a message whose inbox row was never written (lines 106-109). Third, and only then, it logs the absorbed duplicate at Debug (line 113, source-generated at lines 139-140).IsRecordedAsync(EfInboxStore.cs:122-131) is oneAsNoTrackingAnyAsyncfor a row with the message id whoseConsumeris either the given consumer orLegacyConsumer(line 130), seeking the (MessageId, Consumer) index; it runs after a staged handler returns and after a rejected insert (lines 117-121). The no-tracking read never adds an entry to the change tracker.ResolveContext(EfInboxStore.cs:133-137) routes to the configured outbox data source by resolvingOutboxSettings.DataSource/DatabaseNamethroughIDataSourceResolver(line 135) and asking the factory for that context (line 136), so the inbox lands in the same database as the outbox.
- Why it's built this way: dedup by
MessageId(theIDomainEventmember introduced at Level 0) plus the handler's consumer name makes redelivery safe without distributed locks, and storing the row in the consumer's own database keeps it within the database-per-service boundary (ADR-006) while making the handler-side same-transaction commit possible at all. Relying on the unique index and confirming the violation by re-query avoids a read-then-write race between concurrent deliveries without hiding a genuine write failure: a handler's own save surfaces theDbUpdateExceptionso its mutations roll back and the broker redelivers into the skip path (EfInboxStore.cs:28-30). ADR-021 is the governing decision. - Where it's used: registered as the scoped
IInboxStorewheneverMessageBusSettings.IsInboxEnabledresolves true, which for a broker transport is the default (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:141-143;MessageBusSettings.cs:148); read once per message and recorded per handler byInboxHandlerLoop(InboxHandlerLoop.cs:58,76) for bothIntegrationEventConsumer<TEvent>andUpcastingIntegrationEventConsumer<TEvent>; its rows are purged byOutboxCleanupService(OutboxCleanupService.cs:220-225). Exercised directly byEfInboxStoreTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Inbox/EfInboxStoreTests.cs:30). - Caveats / not-in-source: the
eventTyperecorded on each row is the event's inbox name, resolved by the caller, not by this store (EventNameResolverGetInboxName, called atIntegrationEventConsumer.cs:81). Whether a given handler'sSaveChangesAsyncactually lands on the same physical source as the resolved outbox data source is a per-host configuration question that is not determinable from this file alone.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
IOutboxSignal
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/IOutboxSignal.cs:8· Level 0 · interface
- What it is: a wake-up signal between the producer (the code that has just committed outbox rows)
and the
OutboxProcessorbackground service, so the processor wakes the instant new rows exist instead of sleeping out a fixed polling interval. - Depends on: nothing first-party (BCL
TimeSpan/Task/CancellationToken). Implemented byOutboxSignal, aSemaphoreSlimwrapper. - Concept introduced, event-driven wake versus fixed polling.
[Rubric §12, Performance & Scalability]assesses whether latency is bounded by design rather than by a timer, and[Rubric §31, Cost Efficiency / FinOps]assesses idle resource burn. Without a signal the processor would poll on a fixed schedule, and the framework deliberately lets deployed environments set that fallback high to cut idle database chatter (the default is 2 seconds,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxSettings.cs:36, with the doc on lines 28-34 explicitly recommending 300 for a deployed host). The signal is what makes that safe: the producer callsSignal()right after committing outbox entries, and the processor, parked onWaitAsync(timeout, ct), returns at once. Dispatch latency collapses from "up to the polling interval" to near zero in the common case, while the timeout stays as a safety net. - Walkthrough:
Signal()(IOutboxSignal.cs:11) is synchronous and unblocks any waiter, so it is safe to call from the same thread that just finishedSaveChangesAsync.WaitAsync(TimeSpan timeout, CancellationToken cancellationToken)(IOutboxSignal.cs:20) is what the processor loop awaits at the bottom of every cycle, returning when either signalled or the timeout elapses; the doc names it as the replacement for polling delays (IOutboxSignal.cs:13-19). - Why it's built this way: keeping the wake-up an interface lets a test inject a controllable
signal and drive the processor deterministically without real timers, a
[Rubric §14, Testability]injection point, and it keeps theSemaphoreSlimdetail (including its one-permit cap) out of every call site. - Where it's used: registered as a singleton by
AddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:286).Signal()is called byDomainEventSaveChangesInterceptorat four call sites inMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs: the synchronousSavedChangespath when outbox rows or integration events were written (:153), and inFlushStateAsyncafter releasing the lease on undelivered rows (:421), when only integration events were written (:425), and in the catch path after a failed dispatch or finalize (:440); byBrokerEventBusafter writing its outbox batch (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerEventBus.cs:107), and byOutboxAdministrationafter a replay (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxAdministration.cs:207) and after a republish (OutboxAdministration.cs:292).WaitAsyncis handed by theOutboxProcessorto the sharedPollingLoop.RunAsyncas its wait delegate (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:150), which awaits it between cycles (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Polling/PollingLoop.cs:99), with the duration computed fromOutboxCycleResult.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
OutboxCycleResult
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxCycleResult.cs:19· Level 0 · record struct (internal readonly)
- What it is: the outcome of one outbox polling cycle, used by the
OutboxProcessorto decide how long to wait before the next one. - Depends on: nothing first-party (BCL
boolandDateTime?). Consumed by the processor, which feeds the computed wait toIOutboxSignal.WaitAsync. - Concept introduced, the smart-wait input.
[Rubric §12, Performance & Scalability],[Rubric §29, Resilience & Business Continuity], and[Rubric §31, Cost Efficiency]. Two members drive two distinct wait policies, and the XML doc spells both out (OutboxCycleResult.cs:7-18).HasMoreEligibleWorktriggers an immediate re-poll: it is set only when a full batch of eligible messages was fetched and at least one of them made progress (dispatched or dead-lettered), so more eligible rows are probably waiting. The progress requirement is what stops a batch stuck in a permanent error from hot-spinning the loop.EarliestPendingOccurredOnenables time-precise wake-up: it carries theOccurredOnof the oldest row that is not yet eligible (younger than the processing delay), so the processor sleeps until exactly that moment instead of the full polling interval;nullmeans nothing is pending and the full interval applies. - Walkthrough: declared as a
readonly record structwith two positional members on a single line (OutboxCycleResult.cs:19):HasMoreEligibleWork(bool) andEarliestPendingOccurredOn(DateTime?). The value-type, no-heap shape means the tight background loop allocates nothing per cycle, andinternalkeeps it out of the package's public API surface. - Why it's built this way: a record struct is the cheapest way to return two related values from a
loop that runs forever, and
internalvisibility keeps the outbox processing contract private to the Infrastructure layer where the only two participants live. - Where it's used: returned by
OutboxProcessor.ProcessPendingMessagesAsyncafter aggregating the per-target results (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:186), produced per source byProcessSourceAsync(OutboxProcessor.cs:242,253,270-274), and consumed byExecuteAsyncto either continue immediately (OutboxProcessor.cs:162-166) or wait for the durationComputeWaitTimederives from it (OutboxProcessor.cs:164-169).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
OutboxDisabledNoticeService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Administration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxDisabledNoticeService.cs:22· Level 0 · class (internal sealed partial,IHostedService)
- What it is: a hosted service whose entire job is to write one Information log line at startup when the host is running without the transactional outbox, so the changed delivery guarantee is stated out loud rather than inferred from an absent background service.
- Depends on:
ILogger<OutboxDisabledNoticeService>via primary constructor (OutboxDisabledNoticeService.cs:22) andIHostedService(line 22); nothing else first-party. - Concept introduced, announcing a posture instead of leaving it to be discovered.
[Rubric §13, Observability & Operability]assesses whether an operator can tell what mode a host is in without reading its source, and[Rubric §33, Developer Experience]assesses whether the framework's defaults explain themselves. Outbox registration is a transport decision, not a persistence one:MessageBusSettings.IsOutboxEnabledresolves tofalsefor the in-process provider unlessMessageBus:EnableOutboxsays otherwise (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:176), and in that mode neitherOutboxProcessornorOutboxCleanupServiceis registered (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:298-306). The delivery guarantee changes with it: events reach their handlers synchronously inside the raising process, and a crash between the commit and the dispatch loses them. The class doc states that this is the right trade for a single-process application and the wrong one to discover from an absent hosted service (OutboxDisabledNoticeService.cs:7-14). - Walkthrough:
StartAsynccalls the single generated log method and returnsTask.CompletedTask(OutboxDisabledNoticeService.cs:26-30);StopAsyncis a no-op (line 32). The message itself is the type's real content (OutboxDisabledNoticeService.cs:35-38): it names what is not happening (noOutboxMessagesrows, neither background service running, a failed handler is not retried, a crash between commit and dispatch loses the event), names the fix (MessageBus:EnableOutbox=true), and closes the obvious follow-up question by noting that theOutboxMessagestable is already part of the model, so flipping the flag is never a migration. - Why it's built this way: the level choice is the interesting part and the doc argues it
explicitly (
OutboxDisabledNoticeService.cs:15-19). This is Information, not the Warning that the inbox'sInboxDisabledWarningServiceuses, because a missing outbox is the default posture of an in-process host rather than an opt-out of a safety feature, and a warning on every small application's startup would train operators to ignore the category. - Where it's used: registered by
AddInfrastructurein theelsebranch of the outbox gate (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:303-306), so a host either gets the two outbox background services or gets this notice, never both and never neither.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
OutboxMetrics
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxMetrics.cs:16· Level 1 · class (internal static)
- What it is: the single OpenTelemetry
Meterand the five instruments that describe the health of the outbox pipeline: dead letters, successful dispatches, end-to-end delivery lag, observed backlog depth, and the age of the oldest row still waiting. - Depends on: nothing first-party; BCL
System.Diagnostics.Metrics(Meter,Counter<long>,Histogram<double>,ObservableGauge<long>,ObservableGauge<double>,Measurement<double>),Interlocked, andConcurrentDictionary. Emitted exclusively byOutboxProcessor. - Concept introduced, instrumenting an asynchronous pipeline no request trace can cover.
[Rubric §13, Observability & Operability]assesses whether operators can answer "is it healthy, and how far behind is it" without attaching a debugger, and[Rubric §29, Resilience]assesses whether degradation is visible before it becomes an outage. Everything the outbox does happens after the HTTP response has gone out, so no request trace ever covers it; these instruments are the substitute. A host exports them by registering theMeterNamemeter, and the Aspire service defaults (ConfigureOpenTelemetry) already do. The meter name is duplicated as a literal in MMCA.Common.Aspire because that package has no reference to Infrastructure (OutboxMetrics.cs:6-11), the same deliberate duplication used for theOutboxPollactivity name. - Walkthrough
MeterName(OutboxMetrics.cs:19) is the constant"MMCA.Common.Outbox", and the single staticMeteris created from it (line 21). The class doc is explicit that one meter serves every outbox instrument and that a secondMeterwith this name must never be created (lines 12-14).DeadLetterCounter(outbox.dead_letter.count,OutboxMetrics.cs:41-44) counts abandoned messages, tagged byevent_typeand byreason, which takes exactly two values,type_unresolvableorretries_exhausted(lines 37-40). That second tag is what lets an operator tell a deployment mistake (a renamed event type) apart from a genuine downstream outage.ProcessedCounter(outbox.processed.count,OutboxMetrics.cs:47-50) counts messages dispatched successfully and stamped processed, tagged byevent_type.DispatchLagHistogram(outbox.dispatch.lag, unit seconds,OutboxMetrics.cs:57-60) records the interval betweenOccurredOnandProcessedOn. The doc calls it the number that answers "how far behind is eventual consistency right now" (lines 52-56).PendingDepthGauge(outbox.pending.depth,OutboxMetrics.cs:75-79) is anObservableGaugereading the_pendingDepthfield (line 27) throughInterlocked.Read, published once per cycle bySetPendingDepth(line 108) viaInterlocked.Exchange. Itsremarks(lines 66-74) carry the operational caveat that matters most: the gauge reports what this instance last observed, not a cluster-wide depth, so with several replicas each publishes its own view and the values must be read per instance and never summed into a fleet total. The count uses the same predicate as the poll (unprocessed, retries not exhausted, not under an unexpired lease), so rows another replica currently holds are excluded, and a source whose database is unreachable contributes zero for that cycle rather than holding a stale value.OldestPendingAgeGauge(outbox.oldest_pending.age, unit seconds,OutboxMetrics.cs:98-102) is the alerting counterpart to the lag histogram, and the distinction in its doc is worth internalizing (lines 81-86):outbox.dispatch.lagreports how late the messages that did get delivered were, while this one reports how late the backlog already is while it is still stuck, which is the number an alert on a wedged outbox fires on. It is tagged perdata_source, backed by theOldestPendingAgeSecondsdictionary (lines 34-35), published bySetOldestPendingAge(lines 115-116), and projected into oneMeasurement<double>per source byObserveOldestPendingAge(lines 118-126). Itsremarks(lines 87-97) note that it costs no extra query at all (the poll already fetches pending rows ordered byOccurredOn, so the first row is the minimum and noMIN()is ever issued), that it excludes leased and dead-lettered rows so it measures deliverable backlog rather than table age, and that a drained source reports0rather than dropping out of the series, so "drained" stays distinguishable from "host stopped". Unlike the depth gauge, a source whose database was unreachable keeps its previous age until its next successful cycle (lines 96-97). The dead-letter counter's description names both reasons (OutboxMetrics.cs:44).
- Why it's built this way: static instruments on one shared meter is the idiomatic
System.Diagnostics.Metricsshape and costs nothing when no listener is attached.Interlockedon the depth field and aConcurrentDictionaryfor the per-source ages keep the observation callbacks lock-free while the processor writes them from its own loop. Making the depth a gauge fed by the cycle rather than an independent query means the steady state pays no extra database round-trip: seeCountPendingAsync, which derives the depth from the fetch itself unless the batch came back saturated (OutboxProcessor.cs:299-320). - Where it's used:
DeadLetterCounteron both dead-letter paths (OutboxProcessor.cs:1215-1218for an unresolvable type,:700-703for exhausted retries);ProcessedCounterandDispatchLagHistogramon the success path (OutboxProcessor.cs:1101,1106-1108);SetOldestPendingAgeper source right after its fetch (OutboxProcessor.cs:226-228); andSetPendingDepthonce per cycle after every target has been drained (OutboxProcessor.cs:184). - Caveats / not-in-source: the circuit-open signal the processor emits alongside these lives on a
different meter,
BrokerMetrics.CircuitOpenCounter, not onOutboxMetrics(OutboxProcessor.cs:783-785).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
EventNameResolver
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/EventNameResolver.cs:19· Level 1 · class (internal static)
- What it is: the one cached lookup of the name an event is stored under, shared by the two places a stored identity is written: the outbox row and the inbox dedup key. It is also the reverse lookup that turns a stored name back into a CLR type.
- Depends on:
EventNameAttribute(G02); BCLSystem.ReflectionandConcurrentDictionary. Consumed byOutboxMessage,IntegrationEventConsumer<TEvent>andUpcastingIntegrationEventConsumer<TEvent>. - Concept introduced, a serialization identity that outlives the CLR type name.
[Rubric §9, API & Contract Design]assesses whether a stored or on-the-wire contract can evolve without breaking what is already in flight, and[Rubric §15, Best Practices & Code Quality]assesses whether an ordinary refactoring (rename, namespace move, project split) is safe. The problem: an outbox row records the event's assembly-qualified CLR name, so renaming the class or moving it to another assembly orphans every row already written under the old name, and the processor eventually dead-letters them.EventNameAttributedeclares a stable identity instead, and this resolver is the single place that decides which of the two a given event uses. Crucially, adoption is opt-in and backward-compatible: an event without the attribute keeps exactly the identity it had before this type existed, the assembly-qualified name in the outbox and the short type name in the inbox (EventNameResolver.cs:7-18), so rows already in flight are unaffected. - Walkthrough
DeclaredNameCache(EventNameResolver.cs:26) is aConcurrentDictionary<Type, string?>. Cachingnullmatters as much as caching a hit: the common unannotated case then pays one reflection lookup per type per process rather than one per event instance (lines 21-25).GetDeclaredName(Type)(EventNameResolver.cs:35-38) reads the attribute withinherit: false, so a derived event never silently borrows its base's identity (lines 28-32).GetStorageName(Type)(EventNameResolver.cs:47-51) is the outbox side: the declared name when present, otherwiseAssemblyQualifiedName, falling back toFullNamethenNamefor the exotic types that have neither.GetInboxName(Type)(EventNameResolver.cs:59-60) is the inbox side: the declared name when present, otherwise the short type name, which is what every existing inbox row already holds.FindTypeByDeclaredName(string)(EventNameResolver.cs:76-82) is the reverse lookup for a stored name that is not a CLR name: it scans the loaded, non-dynamic assemblies for the type declaring that name. Two performance details are deliberate (lines 69-73): the LINQ query stays lazy so the scan stops at the first match instead of materializing every loaded type, andType.IsDefinedcomes first in the predicate because it answers without constructing the attribute, so only the handful of annotated types pay for construction. It is reached once per stored name that resolves, because the caller caches only a successful result; a name that matches nothing is scanned again on its retry (lines 62-68).GetLoadableTypes(Assembly)(EventNameResolver.cs:91-101) catchesReflectionTypeLoadExceptionand degrades toex.Types.OfType<Type>(), the subset that did load, so one unloadable type cannot stop a scan whose answer may live in a later assembly.
- Why it's built this way: putting the decision in one static class is what keeps the outbox and
the inbox from drifting into two different notions of "the event's name", which would silently break
dedup. The attribute is documented as a before-the-refactoring move
(
MMCA.Common/Source/Core/MMCA.Common.Domain/Attributes/EventNameAttribute.cs:14-19): it changes only what NEW rows store, so applying it while the outbox holds pending rows is a two-step operation, drain first, then rename. - Where it's used:
GetStorageNameinOutboxMessage.FromDomainEvent(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/OutboxMessage.cs:188);FindTypeByDeclaredNameinOutboxMessage.ResolveEventType(OutboxMessage.cs:260), as the fallback afterType.GetTypefails;GetDeclaredNamein the broker entity naming (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerNaming.cs:29);GetInboxNameinIntegrationEventConsumer<TEvent>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumer.cs:81) andUpcastingIntegrationEventConsumer<TEvent>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/UpcastingIntegrationEventConsumer.cs:73). - Caveats / not-in-source:
FindTypeByDeclaredNamesearches only loaded assemblies (EventNameResolver.cs:77), which is precisely why the processor treats the first unresolvable attempt as transient (seeHandleUnresolvableTypeunderOutboxProcessor). Uniqueness of a declared name across a host's events is a documented requirement of the attribute (EventNameAttribute.cs:20-24), not something this resolver enforces.
OutboxSignal
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxSignal.cs:10· Level 1 · class (public sealed)
- What it is: the
SemaphoreSlim-basedIOutboxSignalthat wakes theOutboxProcessorthe instant new outbox entries are written. - Depends on:
IOutboxSignal(the port it implements) andIDisposable(OutboxSignal.cs:10); the internalWakeUpSignal(MMCA.Common.Infrastructure.Persistence.Polling), the actualSemaphoreSlimwrapper it now delegates to (OutboxSignal.cs:12). - Concept reinforced, event-driven wake, plus a small cost lesson.
[Rubric §12, Performance & Scalability](introduced atIOutboxSignal) and[Rubric §31, Cost Efficiency / FinOps]. The one-permit cap that makes surplus signals free now lives onWakeUpSignal(new SemaphoreSlim(0, 1),WakeUpSignal.cs:18), and its doc explains exactly why (lines 6-14): each processor drains a whole batch per cycle, so one pending wake-up is all the information a burst of writes carries. With the default uncappedSemaphoreSlim(0)the class accumulated one permit perSignal()call, so N writes in a burst madeWaitAsyncreturn immediately N times, and each of those cycles issued a candidate-fetch query per relational data source that returned nothing. The surplus signals were harmless for correctness but not for cost; with the cap, the surplus is absorbed. Moving the primitive intoWakeUpSignalalso meansInternalCommandSignal(the internal-command queue's own wake-up) shares this exact cap-and-swallow behavior instead of re-implementing it. - Walkthrough:
OutboxSignalis now three one-line forwards to a privateWakeUpSignal _signal = new()field (OutboxSignal.cs:12):Signal()calls_signal.Signal()(line 15),WaitAsynccalls_signal.WaitAsync(timeout, cancellationToken)(lines 18-19), andDispose()calls_signal.Dispose()(line 22).WakeUpSignalholds the mechanics this section previously described directly:Signal()(WakeUpSignal.cs:21-31) calls_semaphore.Release()inside atryand swallows theSemaphoreFullExceptionthe cap makes routine, so repeated signals never throw and callers never need to coordinate;WaitAsync(WakeUpSignal.cs:37-47) awaits_semaphore.WaitAsync(timeout, cancellationToken)and rethrowsOperationCanceledExceptiononly when the token really was cancelled, propagating shutdown;Dispose()(line 50) disposes the semaphore. - Why it's built this way: a counting semaphore is still the lightest primitive that both parks the
processor loop and is releasable from the commit path. Extracting it into
WakeUpSignalis what letsInternalCommandSignalreuse the identical cap-and-swallow behavior instead of duplicating it, keeping the "at-least-once is fine, duplicates are absorbed" instinct that runs through this whole group in one place rather than two. - Where it's used: registered as the singleton
IOutboxSignalbyAddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:286). Its callers are listed underIOutboxSignal. Note the registration is unconditional, above the outbox gate, so the producers can signal without checking whether a processor exists.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
OutboxSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Administration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxSettings.cs:10· Level 2 · class (public sealed)
What it is: the
Outboxconfiguration section, tuning the outbox background processor and its cleanup companion. Every property carries a default (OutboxSettings.cs:16-130), so the section is optional and a host with noOutboxconfiguration still runs a working outbox. Note the division of labour withMessageBusSettings: that class decides WHETHER the outbox runs, this one decides HOW.Depends on:
DataSource(the engine enum) andDataSourceKey(for itsDefaultNameconstant), both imported throughMMCA.Common.Application.Interfaces.Infrastructure(OutboxSettings.cs:58,:67). Externals:System.ComponentModel.DataAnnotationsfor the[Range]attributes.Concept introduced, options binding with a static
SectionName. Note the convention that runs through every settings class in the framework:public static readonly string SectionName = "Outbox";(OutboxSettings.cs:13) is the single source of truth for the section name, referenced at the bind call instead of duplicating the literal (DependencyInjection.cs:157). The properties areinit-only, so once materialized from configuration they are immutable for the process lifetime.[Rubric §6, CQRS & Event-Driven]assesses how reliably state changes turn into dispatched events. This is the knob set for the at-least-once outbox (ADR-003):MaxRetries(:26) caps delivery attempts, andProcessingDelaySeconds(:50) is the eligibility delay after message creation. It defaults to 0, so an integration event is published as soon as the post-save signal wakes the processor (tens of milliseconds) instead of several seconds later (:40-41). The delay does not bound the duplicate-dispatch window: on the async save path, local domain-event rows are inserted under theLeaseSecondslease, so the in-process pipeline (save, dispatch, mark processed) races the processor only once that lease expires, and sync-path rows never dispatch in-process. Handlers must be idempotent regardless, and the doc reserves a value above 0 for holding rows back deliberately, for example to give a failed in-process local dispatch a pause before the processor retries it (:41-47).[Rubric §29, Resilience & Business Continuity]assesses behavior under replication and repeated failure. Four properties carry the weight.MaxRetriesdecides only WHEN a failing row is abandoned: the abandonment itself is recorded on the row (OutboxMessage.DeadLetteredOn), so changing the value neither replays existing dead letters nor abandons rows that are still pending (:19-24).LeaseSeconds(:100) claims a batch for a replica so concurrent replicas never double-dispatch, and expires so a dead replica's rows become claimable again (:90-93, applied atOutboxProcessor.cs:227). The lease is checked before each row is dispatched and renewed for the rows not yet dispatched only once less than half of it remains, so half the lease must comfortably exceed the time to dispatch one message, not a whole batch; local domain-event rows, and the rowsInProcessEventBuspublishes, are also inserted under it while their in-process dispatch runs (:93-97).RetryBackoffBaseSeconds(:117) makes the retry cadence explicit: attemptnwaitsbase * 2^(n-1), multiplied by a jitter factor in [0.8, 1.2] so rows that failed together do not retry in lockstep, then capped atLeaseSeconds(:102-106, implemented atOutboxProcessor.cs:1244-1245). The remark is worth reading as a design lesson: before this setting existed the claim was simply never cleared on failure, so the real retry cadence was an accident of the lease (300s) rather than a decision (:108-115).[Rubric §30, Compliance, Privacy & Data Governance]assesses bounded retention. The two outbox retention windows are independent:RetentionDaysset to0keeps processed rows forever but switches off only that sweep, not the dead-letter or inbox sweeps, which run on their own windows (:71-74);DeadLetterRetentionDaysfalls back toRetentionDayswhen it is0, so dead letters are kept forever only when both are0, and it is honoured even whenRetentionDaysis0(:121-125). The inbox window is not here at all: it isInbox:RetentionDays, onInboxSettings.[Rubric §31, Cost & FinOps]assesses cost-relevant defaults.PollingIntervalSeconds(:36) is a fallback, not a hot loop (:28-34): with signal-based wakeup the processor wakes immediately on new entries and otherwise smart-waits until the earliest pending message becomes eligible, so deployed environments set it high (300 in this workspace) to cut idle SQL polling without adding latency for real traffic.[Rubric §8, Data Architecture]assesses how deliberately data is routed. TheDataSource/DatabaseNamepair (:58,:67) names where integration events published viaIEventBusare written, defaulting to the top-level connection strings so single-database behavior is preserved. It is a per-write target, not a global switch: the doc is explicit that the PROCESSOR still drains the outbox table of every relational physical source in use (:64-65, and seeOutboxProcessor.cs:153-161).Walkthrough: one static field then eleven
initproperties, nine of them[Range]-validated.SectionName(OutboxSettings.cs:13): static readonly"Outbox", the bind key.BatchSize(:16-17):[Range(1, 1000)], default50; messages per cycle, used both to size the fetch (OutboxProcessor.cs:340, cut byTakeat:404) and to decide whether more eligible work remains or a backlog count is needed (OutboxProcessor.cs:253,:306).MaxRetries(:25-26):[Range(1, 20)], default5; delivery attempts before a failing message is dead-lettered, which the processor does by stampingDeadLetteredOnwhenRetryCountreaches it (OutboxProcessor.cs:795-801); the poll then excludes the row by that stamp, not by comparing against this setting. The first unresolvable-type failure is only re-scheduled whenMaxRetries > 1, so1is honored as "the host asked for no retries at all" (OutboxProcessor.cs:1202).PollingIntervalSeconds(:35-36):[Range(1, 3600)], default2; the fallback interval.ProcessingDelaySeconds(:49-50):[Range(0, 600)], default0(no initializer, so theintdefault); the eligibility delay, applied as a cutoff on the message timestamp (OutboxProcessor.cs:206,:214).DataSource(:58): defaultDataSource.SQLServer; must be a relational provider that supports the outbox table (SQL Server, PostgreSQL or SQLite,:54-55), since the outbox is a table.DatabaseName(:67): defaultDataSourceKey.DefaultName; the logical source name paired withDataSource.RetentionDays(:76-77):[Range(0, 3650)], default7; days a PROCESSED message is kept before purge.0keeps processed rows forever and turns off only the processed sweep (OutboxCleanupService.cs:133, cutoff fromCutoffForat:247).CleanupIntervalHours(:86-87):[Range(1, 168)], default6; the cadence of all three purge sweeps (OutboxCleanupService.cs:88). It is ignored only when every retention window is off (RetentionDays, the dead-letter window and, where the host has an inbox,Inbox:RetentionDays), because the service then does not run (:81-83, checked atOutboxCleanupService.cs:101).LeaseSeconds(:99-100):[Range(10, 3600)], default300; the claim window, renewed for the remaining rows once less than half of it is left.RetryBackoffBaseSeconds(:116-117):[Range(1, 3600)], default10; the exponential-backoff base described above.DeadLetterRetentionDays(:129-130):[Range(0, 3650)], default0, which falls back toRetentionDays. Set it higher to keep failed payloads around for diagnosis and manual replay; the cleanup service resolves the fallback once, at construction (OutboxCleanupService.cs:69-71). The window runs from the row'sDeadLetteredOnstamp, which a replay clears and the next dead-lettering stamps again (:125-127), and that is the column the sweep keys on (OutboxCleanupService.cs:189-192).
Why it's built this way: the defaults encode the framework's out-of-the-box posture (ADR-003 outbox, ADR-006 database-per-service): a host with no
Outboxsection that has the outbox switched on gets a working at-least-once processor writing to its single default database, while a multi-service deployment overridesPollingIntervalSeconds,DataSourceandDatabaseNameto tune cost and routing. Keeping each retention window independent means turning one off never silently turns another off with it. The[Range]guards give fail-fast validation at bind time rather than a bad value surfacing mid-cycle (ADR-070).Where it's used: bound with
.ValidateDataAnnotations().ValidateOnStart()inAddInfrastructure(DependencyInjection.cs:156-159). Consumed byOutboxProcessor(OutboxProcessor.cs:64,:69) andOutboxCleanupService(OutboxCleanupService.cs:53,:60, its two outbox windows at:63and:69-71) for batching, retry pacing and retention; byOutboxAdministrationfor its target selection (OutboxAdministration.cs:366); by both event buses to pick the write target when publishing an integration event (InProcessEventBusInProcessEventBus.cs:55,:78;BrokerEventBusBrokerEventBus.cs:36,:67); and byEfInboxStore, which deliberately reuses the sameDataSource/DatabaseNamepair so the inbox lands in the consumer's own database (EfInboxStore.cs:36,:217).Caveats:
BrokerEventBusthrows when the resolved target does not support the outbox table, naming both configuration keys in the message (BrokerEventBus.cs:77), so an outbox pointed at Cosmos fails on first publish rather than at bind time; the[Range]attributes cannot express "relational engines only".CleanupIntervalHoursis one cadence for all three sweeps; there is no per-sweep interval.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
ClaimedBatch
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:1361· Level 10 · class (private sealed, nested inOutboxProcessor)
- What it is: the per-batch state object
OutboxProcessorthreads through dispatch. It holds one claimed batch's progress: the claimed rows in dispatch order, the lock token every renewal and stamp is guarded by, this replica's current lease expiry, the delivered rows waiting for their batched stamp, and the rows a lease renewal found under another token (type doc,OutboxProcessor.cs:1355-1360). - Depends on:
OutboxMessage(this group) only. It is a primary-constructor classClaimedBatch(List<OutboxMessage> messages, Guid lockToken, DateTime leaseUntil)(OutboxProcessor.cs:1361) with no behavior of its own. - Concept introduced, batch state as one mutable carrier instead of loose locals.
[Rubric §29, Resilience](lease-guarded, crash-tolerant delivery) and[Rubric §12, Performance & Scalability](set-based stamping). Five members carry the whole protocol:Messages(get-only list of the claimed rows, line 1174),LockToken(get-only, line 1176),LeaseUntil(the only settable member, line 1178, advanced each time a renewal succeeds),PendingStamps(the delivered rows buffered for one set-basedProcessedOnupdate, line 1180) andLostIds(aHashSet<Guid>of rows a renewal found re-claimed by another replica, line 1182, so they are skipped rather than dispatched twice). - Walkthrough:
DispatchMessagesAsyncbuilds it from the claimed rows, the batch'slockTokenand theclaimLeaseUntilthe claim wrote (OutboxProcessor.cs:618), then hands it toDispatchRowsAsyncandFlushDeliveredAsync.RenewLeaseIfDueAsyncreadsLeaseUntilagainst the injected clock and reports a row lost when its id is inLostIds(lines 677-684);RecordOutcomeAsyncappends a delivered row toPendingStamps(line 704);RenewRemainingLeasesAsyncwrites the newLeaseUntiland unions intoLostIds(lines 839-842);FlushDeliveredAsyncdrainsPendingStampschunk by chunk (lines 862-896). - Why it's built this way: delivered rows are no longer stamped one UPDATE per row, so something has to remember them between the delivery and the flush, and the flush has to run from several places (end of batch, before a renewal, early exit). One object passed by reference keeps those paths reading the same buffer and the same lease expiry instead of each re-deriving them.
- Where it's used: only inside
OutboxProcessor.cs; it is private to the processor, so nothing else constructs one.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
InProcessDispatch
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/InProcessDispatch.cs:14· Level 8 · class (internal static partial)
- What it is: the shared helper both in-process dispatch paths call once a save has committed. It
dispatches the save's events one at a time with per-event failure isolation, in two flavours (events
an outbox row backs, and events none backs), and it hands undelivered rows back to the
OutboxProcessorearly by releasing their lease. - Depends on:
IDomainEventDispatcher,IDomainEvent,IHasOrderingKey(G02, read throughOutboxMessage.OrderingKey),OutboxMessage,ApplicationDbContextandOutboxFinalizer.ReleaseLeaseAsync;ILoggerthrough three source-generated[LoggerMessage]methods. - Concept introduced, per-event failure isolation after commit.
[Rubric §6, CQRS & Event-Driven](in-process delivery that does not let one event's handler take the others down) and[Rubric §29, Resilience & Business Continuity](a failure is handed to the durable retry path instead of being lost or re-running work that already succeeded). The class doc for the backed path states the problem it fixed (InProcessDispatch.cs:16-21): dispatching the whole set in one call stopped at the first throwing event with nothing marked processed, so the outbox processor re-ran the handlers of every event BEFORE the failure, and the events after it waited for a poll they did not need. - Walkthrough
DispatchBackedAsync(InProcessDispatch.cs:36-74) takes the events and their backing outbox rows as parallel lists, one row per event in the same order (parameter docs, lines 30-35), and returns a(Delivered, Undelivered)tuple of rows so the caller finalizes exactly the events that succeeded. For each event it dispatches that one event alone (line 60) and adds its row toDelivered(line 61). A failure is caught by an exception filter that lets a requested cancellation propagate (line 63), logs a Warning naming the event type (line 65,LogLocalEventDispatchFailedat 144-145, "the outbox processor will retry it") and adds the row toUndelivered(line 66). Ordering is preserved: when the failed row carries an ordering key, the key joins an ordinalfailedKeysset (lines 68-69), and every later row with that key is handed over unattempted, behind its predecessor (lines 52-56), because running it now would deliver the key out of order. Unkeyed events and other keys carry on (doc, lines 22-27).DispatchUnbackedAsync(InProcessDispatch.cs:90-109) is the path for events no outbox row backs (the outbox is off, or the engine is not relational). Nothing retries such an event, so each failure is logged at Error naming the event type (line 106,LogUnbackedDispatchFailedat 147-148, whose message says the event is not retried) and the next event still dispatches; the catch-all carries an inlineCA1031justification (lines 102-104). The doc draws the boundary (lines 76-83): the isolation is per event, not per handler, and a host whose handlers must all run, or run again, enables the outbox.ReleaseLeaseAsync(InProcessDispatch.cs:123-142) clears the lease on the given rows, guarded by the token they were inserted under, so the processor can take them once the processing delay has elapsed rather than after the full lease (doc, lines 111-116). It returns at once when the rows were inserted unleased or there are none (lines 129-130), callsOutboxFinalizer.ReleaseLeaseAsyncwithCancellationToken.Noneon purpose, because a dispatch that failed by cancellation still has to hand its rows back (line 134), and treats a failure as best effort: logged as a Warning (LogLeaseReleaseFailed, line 140 and 150-151), never thrown, since the lease expires on its own and a failure here must not escape work that already committed (lines 136-141).
- Why it's built this way: one dispatch per event is what makes a failure cost only that event (and
its key-mates), so the rows of events that did succeed can be finalized and the processor re-runs
nothing that already ran. Holding back a failed key's successors keeps the in-process path consistent
with the ordered delivery the processor's claim enforces, and releasing the lease turns "retry after
LeaseSeconds" into "retry on the processor's next cycle". Sharing one helper keeps the two callers from drifting. - Where it's used: by
InProcessEventBus(DispatchUnbackedAsyncatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/InProcessEventBus.cs:126,DispatchBackedAsyncat:144,ReleaseLeaseAsyncat:152and:159) and byDomainEventSaveChangesInterceptor(DispatchUnbackedAsyncatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:414,DispatchBackedAsyncat:405,ReleaseLeaseAsyncat:420and:437). - Caveats / not-in-source: the isolation is per event, not per handler: the dispatcher runs one
event's handlers in sequence, so a throwing handler still skips the handlers registered after it for
that same event (
InProcessDispatch.cs:80-82). The type isinternal, so it is not a consumer extension point.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
OutboxFinalizer
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxFinalizer.cs:13· Level 11 · class (internal static)
- What it is: the helper that marks a batch of just-dispatched
OutboxMessagerows processed with a single set-based SQLUPDATE, then re-syncs the EF change tracker so a later save does not re-issue the same statement. It is the finalize step on the low-latency in-process happy path, not the background processor's path. A second method,ReleaseLeaseAsync, clears the lease on those same entries when the in-process dispatch fails. - Depends on:
OutboxMessage(this group) andApplicationDbContext(G07); EF Core (ExecuteUpdateAsync) and BCLTimeProvider. - Concept introduced, set-based finalize off the hot write path.
[Rubric §12, Performance & Scalability]assesses keeping the hottest write path cheap, and[Rubric §8, Data Architecture]assesses efficient set-based mutation. Every event-raising command reaches this the moment its transaction commits and its local events are dispatched in-process. The naive approach, settingProcessedOnon each tracked entity and callingSaveChangesagain, would run a second full save (change detection, audit stamping, the whole interceptor pipeline) on the busiest write path in the system. Instead the doc states the design (OutboxFinalizer.cs:6-12): one asynchronousExecuteUpdatestatement that bypasses the change tracker and theSaveChangesinterceptor pipeline entirely. - Walkthrough:
MarkProcessedAsync(ApplicationDbContext, IReadOnlyList<OutboxMessage>, TimeProvider, CancellationToken)(OutboxFinalizer.cs:27-55) short-circuits on an empty batch (lines 32-33), computesnowonce from the injectedtimeProvider(line 35), collects the row ids (line 36), and issues oneExecuteUpdateAsyncthat setsProcessedOnoverWhere(m => ids.Contains(m.Id))(lines 38-41). BecauseExecuteUpdatedoes not touch tracked instances, it then loops the entries and, for each, sets the trackedProcessedOn, writes the property'sOriginalValue, and clearsIsModified(lines 47-53). The ordering inside that loop is load-bearing and the comment says why (lines 43-46): clearingIsModifiedreverts the current value to the original, so the original must already hold the new value first. TheTimeProvideris a parameter rather than aTimeProvider.Systemread (its doc, lines 20-24) so a test driving aFakeTimeProvidersees this stamp move with the same clock as the processor's lease, backoff and retention arithmetic, a[Rubric §14, Testability]point.ReleaseLeaseAsync(ApplicationDbContext, IReadOnlyList<OutboxMessage>, Guid lockToken, CancellationToken)(OutboxFinalizer.cs:67-98) is the failure-path twin: it short-circuits on an empty batch (lines 73-74), then issues oneExecuteUpdateAsyncthat setsLockedUntilandLockTokento null overids.Contains(m.Id) && m.LockToken == lockToken(lines 78-84). The token guard means a row a processor has since claimed under its own token is left alone. It then re-syncs each tracked entry the same wayMarkProcessedAsyncdoes, nulling both properties, writing theirOriginalValueand clearingIsModified(lines 86-97). The type doc now says it also releases the lease when the in-process dispatch fails (OutboxFinalizer.cs:11). - Why it's built this way:
ExecuteUpdateis a single round-trip that never materializes entities, and re-syncing the tracker afterwards keeps a laterSaveChangesfrom queueing a redundantUPDATEfor rows that are already processed. This is how ADR-003's in-process dispatch stays cheap; the durability net is the backgroundOutboxProcessor, which deliberately does not use this helper (it writes each row's outcome as the row completes, through its ownStampAsyncupdate guarded by the batch's lock token,OutboxProcessor.cs:1156-1177, because it must persistRetryCount,LastErrorand lease changes and drop an outcome whose lease another replica has taken). - Where it's used:
MarkProcessedAsyncis called byDomainEventSaveChangesInterceptorright after the local dispatch (DomainEventSaveChangesInterceptor.cs:428), andReleaseLeaseAsyncbyInProcessDispatch's ownReleaseLeaseAsynchelper, which passesCancellationToken.None(InProcessDispatch.cs:134); the interceptor reaches that helper on its failure paths (DomainEventSaveChangesInterceptor.cs:435,452).MarkProcessedAsyncis also called byInProcessEventBusafter writing and dispatching an integration-event batch (InProcessEventBus.cs:180).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
OutboxProcessor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:61· Level 13 · class (public sealed partial,BackgroundService)
- What it is: the background service that drains every outbox table the host owns, claims rows under
a lease, and dispatches the
OutboxMessages. It is the engine of at-least-once delivery (ADR-003) and the most intricate type in this group. - Depends on:
IServiceScopeFactory,ILogger<OutboxProcessor>,IOptions<OutboxSettings>,IOutboxSignal,FrameworkTableTargets(registered once as a singleton byAddInfrastructure,DependencyInjection.cs:98) and a requiredTimeProvider(resolved from theTryAddSingleton(TimeProvider.System)registration,DependencyInjection.cs:416, rather than defaulted in the constructor) (OutboxProcessor.cs:61-67); the sharedPollingLoop(MMCA.Common.Infrastructure.Persistence.Polling), the loop, smart-wait and per-source drain engine this processor andInternalCommandProcessorboth run on; per cycle scopeIDbContextFactory(line 202), and per row scopeIMessageBusorIDomainEventDispatcher(lines 930, 945), both scopes opened throughCreateTenantScope(TenantDataSourceTargets,TenantDataSourceTargets.cs:100); theOutboxMessageentity,OutboxMetrics,OutboxCycleResult, its nested per-batch stateClaimedBatch(OutboxProcessor.cs:1361),TenantDataSourceTarget,ColumnWidth,ExceptionChain(line 761),BrokerResilienceDefaults,BrokerMetricsandAmbientOrigin; externally Polly (ResiliencePipeline,BrokenCircuitException). - Concept introduced, the outbox drain loop: smart wait, claim leases, ordered delivery,
explicit dead-lettering, a broker circuit breaker, jittered backoff and trace continuity.
[Rubric §6, CQRS & Event-Driven](reliable delivery),[Rubric §29, Resilience],[Rubric §13, Observability & Operability]and[Rubric §31, Cost Efficiency](idle-poll suppression), plus[Rubric §12, Performance & Scalability](batched stamping and the key-aware fetch). The class doc sets the delivery contract up front (OutboxProcessor.cs:37-49): delivery is at-least-once; a failed row's retry or dead-letter state is written as soon as the row is done, while delivered rows are buffered and stamped together by one set-based update per flush (end of batch, before a lease renewal, every early exit); every write is guarded on the lease token; and the lease is renewed for the rest of the batch, in one statement, once less than half of it remains. A delivered message not yet flushed after a crash is redelivered only once its claim lease expires (Outbox:LeaseSeconds, 300s by default), not immediately on restart, because the claim is persisted before dispatch and the poll skips leased rows. Take the rest a layer at a time. - Walkthrough
- The loop, extracted.
ExecuteAsync(OutboxProcessor.cs:137-151) contains no loop body: it is a one-expression call intoPollingLoop.RunAsync(Persistence/Polling/PollingLoop.cs:48-101), passing_timeProvider, whether this host owns any target (GetOutboxTargets().Count > 0),LogOutboxDisabledfor the no-target case, a cycle delegate that callsProcessPendingMessagesAsyncand projects its result to(HasMoreWork, EarliestUpcoming)(line 145),LogProcessingError, the configured delay and interval seconds (lines 148-149), andoutboxSignal.WaitAsyncitself as the wait function (line 150).PollingLoop.RunAsyncruns the mechanics: it waitsStartupDelay(a shared 5-second constant,PollingLoop.cs:18, matching the internal command processor's own delay) so the application finishes initializing, returns immediately whenhasTargets()is false, and otherwise loops until cancelled, treating a cancellation as a clean stop and any other cycle exception as a reported, non-fatal error (PollingLoop.cs:59-84). A cycle with more work re-polls immediately; otherwise it awaits the injectedwaitForSignalfor whichever comes first of a signal, the smart wait, or the fallback interval (PollingLoop.cs:86-99). The remark onExecuteAsyncsays this in one line (OutboxProcessor.cs:136): the loop, startup delay and smart wait are the sharedPollingLoop. - The smart wait. The processor keeps no wait computation of its own: it hands the loop the
earliest upcoming timestamp from each cycle plus the delay and interval, and the wait is
PollingLoop.ComputeWaitTime(PollingLoop.cs:117-134). It returns the full polling interval when nothing is upcoming; otherwise it waits until just after the earliest upcoming row becomes ready, itsOccurredOnplusProcessingDelaySeconds(default 0,OutboxSettings.cs:50) plus a 50-millisecondReadinessMargin(PollingLoop.cs:29), capped at the polling interval. The margin exists because eligibility is a strict< cutoffcomparison and the signal wait truncates to whole milliseconds, so waking at the exact instant could still find the row ineligible (doc,PollingLoop.cs:23-28). A row that is already due waits theMinimumWaitof 1 second (PollingLoop.cs:21, applied at lines 129-131) so it cannot hot-loop the processor, while a row not yet due is never pushed past its due instant by that floor. Its doc keeps the subtle rule (PollingLoop.cs:109-110): failed-but-already-ready rows never shorten the wait, which throttles a permanently failing message instead of letting it drive the loop. This is why a deployed host can set a long poll interval without adding latency: real messages wake it by signal or smart wait, and the slow fallback only cuts idle database chatter and telemetry cost. - Which databases.
GetOutboxTargets(OutboxProcessor.cs:160-161) asks the injectedFrameworkTableTargetsone question,tableTargets.Relational(_settings.DataSource, _settings.DatabaseName), the overload that adds the caller's configured home source to every relational source in use and then expands per tenant (FrameworkTableTargets.cs:54-64). That type exists so the outbox processor, the internal-command processor, both cleanup services, both operator surfaces and the audit-trail sweep all share one answer rather than each re-deriving it from the registry, the resolver and the tenancy settings (FrameworkTableTargets.cs:16-18). The method's own doc states the contract (OutboxProcessor.cs:153-159): every relational source this host owns (every source backing a registered entity plus the configured publish target; Cosmos has no outbox table) against the shared database, plus one extra unit per tenant that keeps its own copy of a source, because a tenant database has its ownOutboxMessagestable that nothing else would drain (ADR-006; ADR-073). A host therefore only touches its own databases, never racing another service for its rows. - Aggregating a cycle.
ProcessPendingMessagesAsync(OutboxProcessor.cs:169-187) delegates toPollingLoop.DrainAllAsync(PollingLoop.cs:147-185), passingGetOutboxTargets(), a delegate that callsProcessSourceAsyncper target and projects its tuple to(HasMoreWork, EarliestUpcoming, PendingDepth), andLogSourceProcessingError.DrainAllAsyncORs theHasMoreWorkflags, keeps the earliest upcoming timestamp across all targets, and sums the observed backlog; one unreachable database must not starve the others, so a per-target failure is reported and skipped while a real cancellation propagates (PollingLoop.cs:159-181). Back inProcessPendingMessagesAsync, the summed depth is published throughOutboxMetrics.SetPendingDepth(OutboxProcessor.cs:184), so a target that threw contributes zero and an outage reads as a drop rather than a stale plateau (comment,OutboxProcessor.cs:182-183). - Draining one target.
ProcessSourceAsync(OutboxProcessor.cs:193-258) opens the cycle scope throughscopeFactory.CreateTenantScope(target)(line 200; the comment at line 199 notes the tenant is set before the context is asked for) and gets the context for that source (lines 202-203). It resolves no dispatcher or message bus: delivery happens on a separate scope per row (see below). It asksFetchWorkAsyncfor the cycle's rows, whether that fetch was key-aware, and the backlog depth (lines 208-209). Then it splits the ordered batch: the eligible prefix is everything withOccurredOnbefore theProcessingDelaySecondscutoff (lines 206, 213-217), and the first row past it becomesearliestPending(line 219). Nothing eligible means an early return carrying only the wait information (lines 221-224). Otherwise it mints this batch'slockToken(line 226), computes the batch'sleaseUntilas now plusLeaseSeconds(line 227; the caller owns the expiry so the claim and the dispatch share one value) and claims the prefix, receiving the claimed rows plus adeferredKeyMatesflag (lines 228-229), returns early if another replica claimed all of it between fetch and claim (lines 231-235), and hands the batch toDispatchMessagesAsynctogether with the cycle context, the target, the token and thatleaseUntil(lines 243-244). There is no batch-endSaveChangesAsync: the comment (lines 239-242) says every outcome is persisted byDispatchMessagesAsyncitself, failures per row and deliveries per flush, through guarded set-based updates, so a cancellation partway through still flushes the rows already delivered to the database rather than leaving them only in the change tracker. The re-poll decision (lines 252-255) requires progress plus one of three reasons: a full eligible batch, key-mates this cycle deferred behind their key's head row, or, after a key-aware fetch, a pending key-mate of a row just processed. Those successors become claimable the moment the head row is delivered, so waiting out the polling interval (300s deployed) per successor would serialize a key at one row per poll; a key-aware fetch never returns them, so there the table is asked instead (comment, lines 246-251). The progress requirement still stops a fully-failing batch from hot-spinning. It returns a(OutboxCycleResult, long PendingDepth)tuple (line 257) so the caller can sum the depth. - Fetching, plain then key-aware.
FetchWorkAsync(OutboxProcessor.cs:268-289, doc 260-266) runs the plain fetch,FetchCandidatesAsync(lines 331-343), derives the backlog depth from it (lines 275-276) and publishes the oldest-pending age from the batch's own first row, which costs no extra query because the fetch is ordered byOccurredOnover exactly the pending predicate (lines 278-282). The plain fetch isPendingCandidates(lines 374-377, doc 365-369): rows that are unprocessed, not dead-lettered (DeadLetteredOn == null), and not under another replica's unexpired lease, ordered byOccurredOnthenIdand capped atBatchSizeby the sharedOrderedhelper (lines 403-404; default 50,OutboxSettings.cs:17). Dead letters leave the poll by their own state, not by comparingRetryCountagainstMaxRetries, so changing the setting neither revives nor abandons a row. There is deliberately noOccurredOncutoff in SQL (doc, lines 326-329): pending rows are fetched too so the caller can smart-wait, and ordering byOccurredOnguarantees eligible rows sort before pending ones, which is what stops a full batch from starving eligible work. When that window holds no keyed row,FetchWorkAsyncreturns it as-is (lines 284-285), so a host that never declares an ordering key runs exactly one statement. When it does, the window is fetched again byFetchUnblockedCandidatesAsync(lines 351-363, called at 287-288) throughUnblockedCandidates(lines 394-401, doc 379-389): the same predicate with the claim's ordering guard applied BEFORE the window is cut, so a keyed row whose key still has an earlier unprocessed, non-dead-lettered row (a head under backoff, a head another replica holds, or simply the head of a burst) cannot take one of theBatchSizeslots. Each key contributes at most its head row, and unkeyed rows and other keys behind a large backlog are reached on the same poll. The doc is careful about what this does not do: ordering still rests on the claim, which re-checks the same guard atomically at update time, so this filter changes which rows are fetched, never which are delivered out of turn (lines 386-388). Each fetch query runs inside an explicitOutboxPollactivity (lines 337, 357; the name constantPollActivityNameis at line 78) that the AspireOutboxPollFilterProcessorsuppresses from telemetry export along with its SqlClient child span; the string is deliberately duplicated there because Aspire has no project reference back to Infrastructure (comment, lines 72-77).HasPendingKeyMatesAsync(lines 423-442, doc 418-422) is the key-aware fetch's re-poll probe: oneAnyAsyncfor a pending, non-dead-lettered row sharing a key with the rows just processed, and no query at all when none of them was keyed (lines 428-430). - Backlog depth almost for free.
CountPendingAsync(OutboxProcessor.cs:299-320) returns the fetched count directly whenever the plain batch came back short, because a short batch is the whole backlog (lines 306-309, doc 291-297). Only a saturated batch, exactly the state an operator alerts on, pays for aLongCountAsync, and that query runs inside its ownOutboxPollactivity so it is suppressed like the poll itself (lines 311-312). The predicate mirrors the plain fetch (lines 315-317), so the gauge counts the rows this processor considers workable, blocked key-mates included. - Claiming: how scale-out is made safe.
ClaimEligibleAsync(OutboxProcessor.cs:467-515, astaticmethod, since nothing it does reads the settings) takes both the batch'sleaseUntiland itslockTokenfrom the caller (lines 472-473), because the same token later guards every renewal and outcome write and the same expiry seeds the batch's lease tracking. It narrows the prefix (line 476), and recordsdeferredKeyMatesascandidates.Count < eligibleCount(line 480), the rowsSelectOrderedCandidatesdropped to keep one row per key. It then issues one conditionalExecuteUpdateAsyncsettingLockedUntil(default lease 300s,OutboxSettings.cs:100) andLockToken(lines 494-498). A claim of zero rows means another replica took the whole prefix (lines 500-501); a full claim returns the candidates as-is (lines 503-504); a partial claim re-queries which ids carry this replica's token and processes only those (lines 506-514). Every return is a(Claimed, DeferredKeyMates)tuple. The doc states the property this buys (lines 445-450): two replicas can never dispatch the same message, and a replica that dies mid-batch releases its rows implicitly when the lease expires. That is scale-out safety by construction rather than by aminReplicas: 1deployment convention. - Ordered delivery, enforced inside the claim. This is the piece that is easy to get wrong, and
the doc explains why it lives here rather than after the fetch (lines 452-458): enforcing it in the
claim is what makes it survive batching and scale-out. Four pieces cooperate.
SelectOrderedCandidates(OutboxProcessor.cs:524-540) narrows the eligible prefix to every unkeyed row plus the first row of each ordering key, which is what stops one cycle from dispatching two events of a key in parallel.FilterClaimable(lines 546-553) is the shared predicate (these ids, still unprocessed, not dead-lettered, not leased).WhereNotBlocked(lines 411-416, doc 406-410) is the ordering guard itself, shared by the claim and the key-aware fetch: a correlatedNOT EXISTSthat refuses a keyed row while any earlier unprocessed, non-dead-lettered (DeadLetteredOn == null, line 415) row shares its key, seekable on the(OrderingKey, OccurredOn)index.FilterUnblocked(lines 562-566) composes it overFilterClaimable, so it is evaluated by the database at the instant of the update and a second replica racing the same key loses on the row rather than on a check it made before the race started (doc, lines 555-561). Which claim runs is decided per batch (lines 487-492): a batch with no keyed row runs exactly the query it always ran, so hosts that never declare an ordering key pay nothing for the feature, not even a subquery the optimizer has to prove away. Two documented consequences: a predecessor still blocks while it is retrying, which is the head-of-line blockingIHasOrderingKeydocuments, but once it is dead-lettered it stops blocking, so a poison event cannot freeze its key forever (lines 456-458); and the predecessor test is onOccurredOnalone, so two rows sharing a key and an exact timestamp are ordered byIdwithin a cycle but neither blocks the other in SQL, becauseGuidhas no order that .NET and every provider agree on (remarks, lines 462-465). - A fresh scope per row, and the request's identity restored onto it.
DispatchMessagesAsync(OutboxProcessor.cs:610-635) wraps the claimed rows, the batch'slockTokenand the claim's lease expiry in aClaimedBatch(line 618) and callsDispatchRowsAsync(lines 643-732), which receives the cycle context, that batch and the batch'sTenantDataSourceTarget. For each row it opens its ownrowScopethroughscopeFactory.CreateTenantScope(target)(line 675): a tenant-owned target keeps its tenant, while the shared target starts unresolved so the restore can set this row's tenant or leave it unset (comment, lines 671-674). The scope only carries the delivery, so it is disposed before the outcome is recorded through the cycle context. The doc gives the reason (remarks, lines 577-580): the tenant context refuses a change once resolved, so on one shared scope every later row of a shared-target batch ran under the first row's tenant. Before anything else runs,Context.AmbientOrigin.Restorewrites that row's capturedUserId,UserRoles,UserPermissions,TenantIdandCorrelationIdontorowScope.ServiceProvider, tagged with the authentication typeOutboxPrincipalAuthenticationType("Outbox", line 84) so the rebuilt identity readsIsAuthenticatedtrue and names the hop it came back from (lines 682-689). The message bus and the dispatcher are resolved from that row scope too (DeliverAsync, lines 930, 945), soBrokerMessageBusreads the restored values when it stamps its publish headers, and the in-process path (InProcessMessageBustoIDomainEventDispatcher) gets the right ambient context for free, without either transport reaching back into the row. Only delivery moves to the row scope: the cycle scope's context holds the claimed rows and writes the lease renewals and outcomes (lines 583-584). - Lease renewal, once per batch when due, and guarded outcomes. The claim lease covers the whole
batch, so a slow batch could outlive it and let another replica claim a later row while this one is
still busy (remarks, lines 586-593). Renewal is not a statement per row.
RenewLeaseIfDueAsync(OutboxProcessor.cs:823-837) runs before each row is dispatched (line 661), subtracts the clock from the batch'sLeaseUntil(line 829) and writes nothing while at least half ofLeaseSecondsremains (line 830). Once less remains it flushes the buffered stamps and callsRenewRemainingLeasesAsync(lines 832-833; lines 958-997). That method pushesLockedUntilout to now plusLeaseSeconds(line 964) for every not-yet-dispatched, not-known-lost row of the batch (lines 969-972), in oneExecuteUpdateAsyncper chunk ofMaxIdsPerStatementids (500, line 93, well under SQL Server's 2100-parameter limit), each filtered onIdand this batch'sLockToken(lines 974-979). When fewer rows renewed than asked for, one query finds the ids still carrying the token and the rest joinLostIds(lines 986-993), and the batch'sLeaseUntilis advanced (line 996). A row found inLostIdsis skipped with a Warning (LogLeaseLostBeforeDispatch, lines 661-665), so a lease that lapsed during one long dispatch is caught by the next check before another row goes out. A failed row's outcome is written the same guarded way as soon as the row is done:StampAsync(OutboxProcessor.cs:1156-1177) runs the update againstId == message.Id && LockToken == lockToken(lines 1162-1163), so a replica that lost the row mid-dispatch matches nothing, logsLogLeaseLost, detaches the tracked row and drops its stale outcome instead of overwriting the new owner's (lines 1168-1173). A match syncs the tracked row's original values to the current ones and marks itUnchanged, so nothing later writes the outcome through the change tracker without the guard (lines 1175-1176). An expired lease nobody re-claimed still carries this token, so its outcome is stamped (doc, lines 1143-1150). - Dispatching, and delivered rows stamped in batches.
DispatchRowsAsync(OutboxProcessor.cs:643-732) walks the claimed batch by index and opens a per-message activity (line 667). A row whose payload will not deserialize goes toHandleUnresolvableType(lines 691-695). OtherwiseDeliverAsync(lines 926-948, called at line 698) publishes anIIntegrationEventthroughIMessageBusand sends a pure domain event toIDomainEventDispatcher. After each row,RecordOutcomeAsync(called at line 724; lines 844-858; the comment at lines 718-722 notes this sits outside the try on purpose, so a database failure while recording is not charged to the row as a retry) does one of two things. A failed row goes toRecordFailureOutcomeAsyncand its retry state is written now (line 853). A delivered row only joinsbatch.PendingStamps(line 856).FlushDeliveredAsync(lines 1011-1051) later stamps the buffer: per chunk ofMaxIdsPerStatementit takes oneProcessedOnvalue from the flush time (line 1024) and issues one guardedExecuteUpdateAsyncfiltered on the ids and the batch'sLockToken(lines 1026-1029). When fewer rows were stamped than buffered, one query finds the rows that carry the token (lines 1033-1042).SyncDelivered(lines 1086-1111) then handles each row: an unmatched row logsLogLeaseLostand is detached (lines 1089-1094), while a stamped row is accepted asUnchanged(lines 1096-1098), incrementsProcessedCounter(line 1101), recordsDispatchLagHistogramas the seconds betweenOccurredOnandProcessedOn, clamped at zero because the two timestamps come from different hosts and clock skew must not publish a negative duration (lines 1103-1108), and writes the success log. Each chunk leaves the buffer once synced, so a retried flush never stamps or counts a row twice (line 1049; doc 999-1009). Flushes happen at three points: the end of the batch (line 624), before a lease renewal (line 832), and on any early exit (see Graceful shutdown). The per-message success log is deliberately Debug, not Information, and the comment prices the difference: it would otherwise be the single noisiest line in steady state, a real telemetry-ingestion cost, while failures stay loud (lines 1316-1318). - Dead-lettering is an explicit state. Both terminal paths go through
DeadLetter(lines 1232-1237), which stampsDeadLetteredOnfrom the processor's clock, records the reason, and clearsLockedUntil, because a dead letter is excluded from the poll by its own state and has nothing left to wait out (doc, lines 1223-1228). The two reasons areinternal conststrings shared with the dead-letter metric'sreasontag:RetriesExhaustedReason("retries_exhausted", line 99) andTypeUnresolvableReason("type_unresolvable", line 105).RecordFailureAsync(lines 1118-1141) persists the failure handling's in-memory state,RetryCount,LastError,LockedUntil,DeadLetteredOnandDeadLetterReason, through the token-guardedStampAsyncupdate (lines 1130-1140). - Dead-lettering an unresolvable type, with one grace attempt.
HandleUnresolvableType(OutboxProcessor.cs:1196-1221) recordsLastError(line 1198) and treats the first failure to resolve as transient, retrying it through the normal backoff path (lines 1202-1209), because the assembly declaring the type may simply not be loaded yet, a module assembly resolved lazily or a host still coming up, and a name that resolves one cycle later was never a dead letter (doc, lines 1180-1184). Only the second attempt is terminal, which is also the point at which an operator has already had a Warning naming the row (LogTypeUnresolvableRetryat 1328-1329, whose message names the fix: give the event anEventName). A host that setMaxRetriesto 1 asked for no retries at all, so the first attempt is already the terminal one (comment, lines 1200-1201). The terminal path counts the attempt like any other, soRetryCountstays the number of attempts actually made (lines 1211-1213), then callsDeadLetter(message, TypeUnresolvableReason)(line 1214), increments the dead-letter counter with that reason and logs at Error (lines 1215-1219). The doc names the effect (lines 1185-1189): the row leaves the poll but stays listed and replayable by the outbox administration and is kept for the dead-letter retention window, instead of being purged as delivered. - The circuit breaker around the message-bus publish. Only the integration-event publish is
wrapped, and the doc states precisely what that hop is.
_brokerPublishPipeline(OutboxProcessor.cs:133) is a PollyResiliencePipelinebuilt byBuildBrokerPublishPipeline(timeProvider)(lines 1255-1266) fromBrokerResilienceDefaults(failure ratio, minimum throughput, sampling and break durations, lines 1259-1262), on aResiliencePipelineBuilderwhoseTimeProvideris the processor's own clock (line 1256), so a test driving the clock drives the break duration too (doc, lines 1252-1253). The integration-event branch ofDeliverAsyncexecutes the publish through it (lines 937-941). The guarded call is theIMessageBuspublish: the broker hop on a host that registers broker messaging, but on a monolith the defaultInProcessMessageBusruns the integration-event handlers in-process inside the breaker, so failing handlers can open it too (field doc, lines 118-132; comment, lines 932-936). Three deliberate choices sit in the doc comments. It never guards the database calls, because a breaker on those would open exactly when the processor most needs to persist retry state (lines 122-123). It carries no retry strategy, because the outbox already owns retry throughRetryCountandComputeRetryBackoffSeconds(lines 124-125). And it is an instance field rather than a static one, so breaker state cannot leak across the many processors a test assembly constructs in parallel (lines 127-130).OperationCanceledExceptionis excluded from the handled set (lines 1263-1264), because a host shutdown cancelling a batch is not evidence that the broker is unhealthy (doc, lines 1249-1252). The pure domain-event branch is left unwrapped on purpose: it is a direct method call into this same process with no transport to be dead (comment, lines 935-936). - Failure handling. A cancellation during dispatch is rethrown rather than treated as a delivery
failure, and the comment explains the bug that guard prevents (lines 702-708): falling into the
generic handler would increment
RetryCountand stampLastErroron this message and, since every laterawaitfails the same way, on the whole remainder of the batch, so a graceful restart could dead-letter messages that were never attempted. Any other exception is caught (with an inlineCA1031justification, lines 710-712) and handed toApplyDeliveryFailure(line 714; lines 743-814), which writes the retry state onto the row in memory and returns the batch's circuit-open log latch. A genuine failure bumpsRetryCount(line 758), recordsLastErrorasExceptionChain.Describe(ex)truncated to the 4000-character column width (MaxErrorLength, line 87, throughColumnWidth.Truncate, lines 761-762) and re-leases the row for an explicit backoff (lines 772-775); the comment notes that simply keeping the original claim made every retry wait the fullLeaseSecondsno matter what the polling interval or a signal said, turning the retry cadence into an accident of the lease (lines 764-771). ABrokenCircuitExceptionis treated differently: an open circuit is a rejection, not a delivery attempt, so it does not consume a retry and cannot dead-letter the row, which would otherwise walk every undelivered row through its whole retry budget during a long outage without one real attempt; real publish failures, and the failure of the single half-open probe, keep counting (comment and check, lines 750-759). The rejected row is re-leased for the break instead of a count-keyed backoff, throughPollingLoop.ComputeCircuitOpenBackoffSeconds(line 774;PollingLoop.cs:211-220): the break duration plus up to a quarter of it as jitter, capped atLeaseSeconds, so a whole batch does not become claimable in the same instant the circuit half-opens, and the lease keeps it from hot-spinning. It is counted onBrokerMetrics.CircuitOpenCounter(lines 783-785) and logged once per batch through a local latch (lines 655, 787-790), because an open circuit rejects every remaining row in the same instant, and "the broker refused 50 messages" and "we did not try, the broker is known-dead" are different operational facts (comment, lines 781-782); the method then returns before the exhaustion check (line 792). The log is a Warning because nothing is lost, only deferred (comment, lines 1337-1339). When a genuine failure bringsRetryCounttoMaxRetries(5 by default,OutboxSettings.cs:26) the row is dead-lettered explicitly withDeadLetter(message, RetriesExhaustedReason)(line 801), the dead-letter counter is incremented with that reason and it logs at Error (lines 802-806), otherwise it logs a retry Warning (lines 808-811). The comment gives the consequence (lines 797-800): from here the row leaves the poll through theDeadLetteredOnfilter whateverMaxRetriesis later changed to, and is eventually purged byOutboxCleanupServiceonce the dead-letter retention window has run from that stamp, unless an operator replays it first throughOutboxAdministration. - Backoff.
OutboxProcessor.ComputeRetryBackoffSeconds(OutboxProcessor.cs:1244-1245) is a one-line forward toPollingLoop.ComputeRetryBackoffSeconds(PollingLoop.cs:197-209), passing_settings.RetryBackoffBaseSecondsand_settings.LeaseSecondsas the base and cap. The shared implementation isRetryBackoffBaseSeconds * 2^(retryCount - 1)(default base 10,OutboxSettings.cs:117) with the exponent clamped to at most 16 before it reachesMath.Pow(PollingLoop.cs:202), multiplied by a random jitter factor in[0.8, 1.2](PollingLoop.cs:206) and capped atLeaseSeconds, the cap this processor passes in (PollingLoop.cs:208). Jitter is applied before the cap so a capped backoff sits exactly at the lease bound (comment,PollingLoop.cs:205). The doc names the reason for the jitter (PollingLoop.cs:188-191): a batch that failed together, one dependency outage failing all 50 rows in the same instant, would otherwise retry in lockstep and re-hammer that dependency on a single shared schedule. TheCA5394suppression on the sharedNextJitterhelper (PollingLoop.cs:222-223) is justified inline: the randomness feeds no security, token, key or cryptographic decision. - Graceful shutdown. Delivered rows are buffered, so shutdown handling covers two writes: the
failed row in flight and the buffered stamps.
DispatchMessagesAsynctracks abatchCompletedflag (line 619) and, if the batch ends any way but normally, callsFlushDeliveredOnExitAsyncfrom afinally(lines 628-634). That method flushes the buffer under its own 5-second budget (ShutdownStampTimeout, line 114; theCancellationTokenSourceis built on the injectedTimeProvider, line 1067) rather thanCancellationToken.None, so an uncancellable write against a dead connection cannot hold host shutdown open until the command timeout (lines 1060-1078, doc 1053-1059). A flush failure is logged, never thrown (LogExitStampFailed, line 1076 and 1352-1353: delivered messages will be redelivered when their lease expires), so it cannot replace the exception already propagating, which the polling loop uses to recognize shutdown. For a failed row,RecordFailureOutcomeAsync(lines 873-894) writes normally while the batch token is live; if the token is already cancelled, or the shutdown lands during the write itself (the guarded update is idempotent, so it is simply written again, lines 886-890), it falls toRecordFailureOnShutdownAsync(lines 900-919), which writes under the same budget (line 906), logs a failure asLogShutdownStampFailed(lines 915 and 1349-1350) and ends by rethrowing the cancellation (line 918). After each recorded row the loop also callscancellationToken.ThrowIfCancellationRequested()(line 728), stopping the batch after the row's outcome is safe, so thefinallystamps the rows already delivered. Without a shutdown, a database failure propagates and fails the source for the cycle (comment, lines 718-722). - Trace continuity.
StartOutboxActivity(OutboxProcessor.cs:1279-1302) rebuilds the original request'sActivityContextfrom the row'sTraceId/SpanId, carrying the stored trace flags (null reads as none) and marked remote (lines 1286-1290), so a parent-based sampler records the delivery span exactly when the raising request was sampled instead of exporting an orphan span for a request the sampler dropped (doc, lines 1272-1277). It starts aConsumer-kindOutboxProcessactivity tagged with the message id, event type and data source (lines 1292-1299), returning null when no trace context was captured (lines 1281-1284), so traces span the asynchronous hop.
- The loop, extracted.
- Why it's built this way:
ADR-003 makes the outbox the
durability guarantee behind every integration event; the per-source design follows from
ADR-006 and the per-tenant
expansion from ADR-073. The smart
wait, the derived backlog count and the suppressed poll activity are all cost and latency work: an
idle fleet polling around the clock would otherwise dominate telemetry ingestion. Dead-lettering
unresolvable types stops one poison message from blocking the queue, and recording dead-lettering on
the row keeps a later
MaxRetrieschange from silently replaying or abandoning rows; the progress requirement on re-poll (seeOutboxCycleResult) prevents a fully-failing batch from hot-spinning, the circuit breaker keeps a known-dead broker from being hammered once per row per cycle (and, by not charging its rejections as retries, keeps an outage from dead-lettering rows that were never attempted), the lease-plus-token pair is what makes running more than one replica safe, the ordering guard inside the claim is what makes ordered delivery survive both batching and scale-out, the same guard applied to the fetch keeps one blocked or bursty key from filling the whole fetch window, and the per-row scope is what lets one batch deliver rows belonging to different tenants. - Where it's used: registered as a hosted service by
AddInfrastructurewhenever the transport enables the outbox (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:298-302), so every broker-backed service host runs exactly one. The producer side is the twoIEventBusimplementations (InProcessEventBusandBrokerEventBus) plus theSaveChangescapture inDomainEventSaveChangesInterceptor; rows whose in-process dispatch failed are handed to it early byInProcessDispatch; its companion sweeper isOutboxCleanupServiceand its operator surface isOutboxAdministration. - Caveats / not-in-source: the
outbox.pending.depthgauge is per instance by design (seeOutboxMetrics); the lease makes multiple replicas correct, but the gauge still must not be summed across them. A host that declares ordering keys pays a second fetch query on every cycle whose plain window holds a keyed row, and one extraAnyAsyncon a cycle that processed keyed rows without another re-poll reason.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
OutboxAdministration
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Administration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxAdministration.cs:38· Level 13 · class (public sealed partial)
- What it is: the EF-backed operator surface over the outbox tables this host owns. It lists dead
letters, replays them back into the pending pool, republishes processed integration events inside a
window, and counts the pending backlog, over exactly the same targets the
OutboxProcessordrains and theOutboxCleanupServicesweeps. - Depends on:
IServiceScopeFactory,ILogger<OutboxAdministration>,IOptions<OutboxSettings>,FrameworkTableTargets,IOutboxSignal,InboxPosture(the resolved inbox posture: is the inbox on, and how far back its horizon reaches) andTimeProvider(the clock that horizon is measured against), all via primary constructor (OutboxAdministration.cs:38-45); implementsIOutboxAdministrationand projectsOutboxDeadLetter; resolves anIDbContextFactoryand, for a tenant target, anITenantContextper visited target; returnsResult/Error. - Concept introduced, a supported way BACK into delivery for an abandoned event.
[Rubric §13, Observability & Operability]assesses whether operators have first-class tooling for the failure modes a system actually has, and[Rubric §29, Resilience & Business Continuity]assesses recovery, not just detection. The interface doc states the gap it closes: without it the only terminal states for an undelivered event are "eventually deleted by the retention sweep" and "edited by hand in production SQL" (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IOutboxAdministration.cs:5-14). Every method returns aResult, because an unknown or unreachable source is an expected failure an operator screen renders, not an exception. Note also whatOutboxDeadLetterdoes not carry: the event payload is deliberately not projected, because it can contain personal data (ADR-005) and nothing an operator decides about a replay depends on reading it (IOutboxAdministration.cs:108-112), a[Rubric §30, Compliance, Privacy & Data Governance]choice. - Walkthrough
- Guards and paging.
MaxPageSizeis 500 (OutboxAdministration.cs:48), so an admin call cannot ask for the whole table at once, andMaxSkipis 10,000 (line 55): paging is merged across every source, so each source returns up toskip + takerows into memory, and an unbounded skip would let one call materialize a whole dead-letter table (kept forever when retention is off) per source (doc, lines 50-54). The two paging validation errors are preallocatedError.Validationvalues (lines 57-61). ListDeadLettersAsync(OutboxAdministration.cs:90-150) validatesskipagainst[0, MaxSkip]andtakeagainst[1, MaxPageSize](lines 96-100), resolves its targets and fails with aNotFound-shaped error when a named source is not owned by this host (lines 102-104, 355-358), then queries each target for unprocessed rows whoseDeadLetteredOnis set (line 123), ordered byOccurredOnthenId, projected straight intoOutboxDeadLetterunderAsNoTracking, the projection carrying the row'sDeadLetteredOnandDeadLetterReason(lines 122-136). The selection reads the row's own dead-letter state, notRetryCountagainstMaxRetries, so the list does not change when the setting does. Two details are commented in place: the source name is materialized outside the query because inside the projection it would be a method call EF has to translate (lines 113-115), and each target returns at mostskip + takerows because paging is applied across the merged result, so "skip 50" means the same thing whether the host owns one database or four (lines 117-119, merged at lines 144-147). The per-target row cap is plainperTarget = skip + take(line 107, used at.Take(perTarget), line 126): both bounds are capped above, so the sum is small and cannot wrap (comment, line 106).ReplayDeadLettersAsync(OutboxAdministration.cs:153-211) is expressed as one set-basedExecuteUpdateAsyncper target rather than as loaded entities, because an operator replaying a backlog is replaying thousands of rows and none of the values written depend on the row's current state. It selects unprocessed rows withDeadLetteredOnset (line 172), optionally narrowed by an id filter (lines 162, 174-177). The update clearsDeadLetteredOnandDeadLetterReason, which is what returns the row to the poll's predicate, resetsRetryCountto zero to give it the full retry budget again, and clearsLockedUntilandLockTokenso it is claimable on the very next cycle instead of afterLeaseSeconds(lines 184-191, comment 179-183).LastErrorsurvives on purpose: the comment calls it the record of why this row needed replaying, and a replay that erased it would destroy the only evidence. Each non-empty target logs at Warning (lines 195-198,LogReplayedat 386-387), and when anything was replayed it callsIOutboxSignal.Signal()rather than leaving the work to a polling interval deployed environments set as high as 300 seconds (lines 203-208).RepublishProcessedAsync(OutboxAdministration.cs:223-296) is the recovery for a broker-side loss after a successful publish, or a transport cutover where the old revision published to entities nothing consumes any more: it returns the INTEGRATION-event rows processed inside[fromUtc, toUtc)to the pending pool across every owned source (IOutboxAdministration.cs:59-94). It is refused with theError.ConflictOutbox.RepublishRequiresInboxbefore anything is touched unless the consumer inbox is enabled (lines 232-233, error at 75-78), read once at construction from the injectedInboxPosture(OutboxAdministration.cs:44,_inboxEnabledat line 86), because the inbox is what turns a republished event into a harmless duplicate; the comment notes the in-process bus counts as no inbox whateverMessageBus:EnableInboxsays (lines 228-231). The window then passes two checks, chained (lines 235-236).ValidateRepublishWindow(lines 327-336) bounds its shape: both bounds UTC, a non-empty range and a width of at mostMaxRepublishWindow, seven days (line 64), each failure a preallocatedError.Validation(lines 66-73).ValidateRepublishAge(lines 346-349, doc 338-344) bounds its AGE: a window starting before now minus the inbox horizon (_inboxHorizon, line 87, this host's ownInbox:RetentionDays) is refused withOutbox.RepublishWindowPastInboxHorizon(lines 80-83), because consumers dead-letter an event older than their horizon without running its handlers, its inbox rows possibly already purged. No horizon (0, inbox rows kept forever) means no age bound, and a consumer with a shorter horizon still refuses the older events itself. The table stores no event kind, so each source is first asked for the DISTINCT stored names processed in the window (lines 252-259), each name is resolved byIsIntegrationEventthroughOutboxMessage.ResolveStoredEventType, the same cache and lookup order the processor uses, and kept only when it is assignable toIIntegrationEvent(lines 261, 351-353). Domain-event rows are never reset, because their handlers run in-process with no inbox and already ran (IOutboxAdministration.cs:68-69), and a name this host cannot resolve is left alone (remarks, lines 214-222). One set-basedExecuteUpdateAsyncper source then clearsProcessedOn,RetryCount,LockedUntilandLockToken, leavingLastErrorandOccurredOnuntouched so ordering keys hold (lines 267-279). Every source logs at Warning, a zero included, because the republish is an operator action whose record should show which sources had nothing (lines 283-286,LogRepublishedat 389-390), and the processor is signalled when anything moved (lines 290-293).CountPendingAsync(OutboxAdministration.cs:299-319) sumsLongCountAsyncover unprocessed rows that are not dead-lettered (DeadLetteredOn == null, line 312) across every selected target. Its interface doc draws the line against the gauge (IOutboxAdministration.cs:96-101): this counts the tables at the moment of the call and includes rows currently under a claim lease, whereoutbox.pending.depthreports what the processor last observed.- Target selection and scoping.
SelectTargets(OutboxAdministration.cs:365-366) is a one-line call to the injectedFrameworkTableTargets.Named, passing the outbox's ownDataSource/DatabaseNameand the optional operator-supplied name. That shared type answers the target question once for every framework-table sweeper: every relational physical source in use (Cosmos skipped), plus the configured publish target when its engine is relational, expanded per tenant that keeps its own copy (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:54-64), then optionally narrowed to one target matched case-insensitively against its display name (FrameworkTableTargets.cs:75-82). It is recomputed per call for the same reason the processor recomputes it per cycle: module assemblies can register entities after startup (doc, lines 360-364).VisitAsync<T>(lines 373-384) runs the work for one target in its own DI scope, created through the sharedscopeFactory.CreateTenantScope(target)extension (TenantDataSourceTargets) that sets the tenant before the context is asked for, because the tenant is what routes the scoped factory to that tenant's database and is also what the query filter reads (line 380, doc 368-372).
- Guards and paging.
- Why it's built this way: reusing the processor's exact target expansion means an operator screen
can never show a different set of databases than the one being drained, including per-tenant copies
(ADR-073). Keying every query on
the row's
DeadLetteredOnrather than onMaxRetriesmeans the dead-letter list, the replay scope and the pending count agree with the processor whatever the setting is changed to. Replay is intentionally not a delete-and-reinsert:OccurredOnis untouched, so a replayed row keeps its place in its ordering key (IOutboxAdministration.cs:39-44), which is what makes replay safe for events that declare anIHasOrderingKey. The republish refuses up front what the consumers would refuse anyway (no inbox, or a window older than the inbox horizon), so an operator learns of it from the call'sResultrather than from a pile of consumer-side dead letters. - Where it's used: registered scoped as
IOutboxAdministrationbyAddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:308-311), with the comment explaining the lifetime: scoped, because it creates one child scope per data source it visits and holds no state of its own. ItsFrameworkTableTargetsdependency is registered withTryAddSingleton(DependencyInjection.cs:98), and itsInboxPostureis a singleton registered there too (DependencyInjection.cs:169). The framework ships no endpoint for it; a host exposes it from an admin endpoint, a support command or a scheduled job (IOutboxAdministration.cs:10-14).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
OutboxCleanupService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Outbox.Administration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxCleanupService.cs:50· Level 13 · class (public sealed partial,PeriodicBackgroundService)
- What it is: the periodic sweeper that purges spent outbox rows (both processed rows and
dead-lettered rows) and, where the host has an inbox, inbox rows, past their retention windows,
from every relational target the host owns, including each tenant database that keeps its own copy
of a source. It runs three sweeps, each on its OWN window, so turning one off never silently turns
another off with it (class doc,
OutboxCleanupService.cs:18-20). - Depends on:
IServiceScopeFactory,ILogger<OutboxCleanupService>,IOptions<OutboxSettings>(the two outbox windows and the sweep interval),InboxPosture(the inbox window),FrameworkTableTargets(which decides the databases, including per-tenant copies, that hold the tables it sweeps), a requiredTimeProvider(forwarded straight to thePeriodicBackgroundServicebase it extends) and an optionalIDistributedLockcycleLock(OutboxCleanupService.cs:50-58); resolves anIDbContextFactoryand, for a tenant target, anITenantContextper sweep, both through the sharedscopeFactory.CreateTenantScope(target)helper (TenantDataSourceTargets); its work list is a list ofTenantDataSourceTargetvalues; operates on theOutboxMessageandInboxMessageentities. - Concept introduced, retention as a privacy and storage control (plus a clock injection point).
[Rubric §30, Compliance, Privacy & Data Governance]assesses bounded retention of data that may contain PII,[Rubric §8, Data Architecture]assesses lifecycle management of operational tables,[Rubric §31, Cost Efficiency]assesses storage growth, and[Rubric §14, Testability]assesses whether time-driven code can be tested. TheOutboxProcessoronly ever setsProcessedOn, and a dead-lettered message keepsProcessedOnnull forever, so without this sweep the outbox, which stores serialized event payloads that may contain personal data, grows without bound and dead rows linger in the pending index every poll re-scans (class doc, citing ADR-003 and ADR-005). The three windows are captured once at construction:_processedDaysfromRetentionDays(line 63),_deadLetterDaysfromDeadLetterRetentionDaysfalling back toRetentionDayswhen it is 0 (lines 69-71), and_inboxDaysfromInboxPosture.RetentionDays, which is 0 when the host has no inbox or keeps its rows forever (line 74). TheTimeProvideris a required constructor parameter rather than an optional one defaulting toTimeProvider.System, because the basePeriodicBackgroundServiceowns the clock all its waits go through; a private_timeProviderfield (line 78) re-reads the same value under this type's own name only because capturing the base constructor's own parameter into this type's state would be a compiler error, CS9107 (comment,OutboxCleanupService.cs:76-77). A test can drive the hour-scale sweep loop deterministically instead of waiting real hours, through the base's injected clock. - Walkthrough
- The fixed-interval loop itself (delay, cycle, retry-on-failure, log-and-continue) lives in the
shared
PeriodicBackgroundServicebase; this type supplies only the hooks the base calls.CycleLockreturns the injected lock (line 85): the purge is idempotent, so it runs on one replica per interval when the host registers a lock, which the remark saysAddInfrastructurealways does, rather than once per replica (remarks, lines 81-84).IntervalreturnsCleanupIntervalHourshours (OutboxCleanupService.cs:88, default 6,OutboxSettings.cs:87) andStartupDelayreuses it verbatim (line 94, doc 90-93), so the first sweep waits one full interval before running, which keeps cleanup off the critical path of startup or migration work.IsEnabled(lines 97-109) is the off switch: it returnsfalse, and logs (LogCleanupDisabled, 249-250, whose message names all three settings), only when all three windows are<= 0(line 101).ExecuteCycleAsyncdelegates straight toPurgeAsync(line 112), andLogCycleFailureoverrides the base's generic message with this service's own event id (line 115,LogCleanupErrorat 261-262). PurgeAsync(OutboxCleanupService.cs:117-160) reads the clock once per cycle, so the three windows are measured from the same instant (line 120, comment 119), each cutoff beingnowminus the window's days (CutoffFor, line 247). It walksGetRelationalTargets()(line 122). For each target it opens a scope through the sharedscopeFactory.CreateTenantScope(target)helper (line 128), which sets the tenant on the scope before the context is asked for, because the tenant is what routes the scoped factory to that tenant's database. It then runs each sweep whose window is above zero (lines 133-146). The processed sweep,PurgeProcessedAsync(lines 202-218), deletes processed rows older than the cutoff withBatchedDelete.DeleteAsyncordered byProcessedOn(lines 209-210), which reads ids and deletes by id at mostBatchSize= 1000 rows per statement, so a first sweep over a long-neglected table is not one enormous delete with one lock footprint and one transaction, and observes cancellation between batches (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Retention/BatchedDelete.cs:8-23). Its callback reports the rows actually removed exactly once, even when a later batch throws (BatchedDelete.cs:32-35), and logs at Information when anything went (LogPurged, 252-253). The dead-letter sweep and the inbox purge go through the same helper, and the per-targetcatchcarries a scopedCA1031suppression (lines 152-154).- The dead-letter sweep (
SweepDeadLettersAsync,OutboxCleanupService.cs:180-200) is the second, separate pass, and its doc is worth reading in full (lines 162-179): dead-lettered rows keepProcessedOnnull forever, so the processor's poll excludes them (DeadLetteredOn IS NULL) but the processed sweep never reaches them either, and they accumulate inside the pending index. They are purged on their own window,DeadLetterRetentionDaysfalling back toRetentionDays(resolved at lines 69-71, and 0 is the default,OutboxSettings.cs:130), which runs even whenRetentionDaysis 0 and only processed rows are kept forever (doc, lines 168-169). The window runs from the moment the row was dead-lettered: the filter keys onProcessedOn == null && DeadLetteredOn != null && DeadLetteredOn < deadLetterCutoffand orders the batches byDeadLetteredOn(lines 189-192). The processor stampsDeadLetteredOnon both dead-letter paths (retries exhausted, unresolvable type), a replay clears it and the next dead-lettering re-stamps it, so a replayed row gets a full window again, and a row is never judged by aMaxRetriesvalue that has since changed (doc, lines 170-174). This permanently abandons an undelivered event, which is why the deletion logs at Warning (line 197,LogDeadLetterPurgedat 255-256, whose message names both reasons) while the processed purge logs at Information, and why the doc points atOutboxAdministrationas the thing to use before the window closes (lines 175-177). - Inbox rows are purged on the inbox's own window,
Inbox:RetentionDaystaken from theInboxPosture(line 74), and only when it is above zero (lines 143-146), which it never is on a host without an inbox.PurgeInboxAsync(lines 220-236) deletesInboxMessagerows withProcessedOn < cutoff(line 227,LogInboxPurgedat 258-259). - A single unreachable database does not stop the others: the per-target
catchlogs and moves on (lines 152-158,LogSourcePurgeErrorat 264-265), while a real cancellation is rethrown (lines 148-151).GetRelationalTargets(lines 244-245) is a one-line call to the injectedFrameworkTableTargets.Relationalwith the outbox's ownDataSource/DatabaseName: every relational source backing a registered entity plus the configured publish target, against the shared database, plus one extra unit per tenant that keeps its own copy (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:54-64). That per-tenant expansion is the only reason a per-tenant database's outbox and inbox tables ever get swept (ADR-073), and because the processor, both operator surfaces and the other cleanup services ask the same type, the sweep cannot visit a different set of databases than the one being drained (FrameworkTableTargets.cs:16-18).
- The fixed-interval loop itself (delay, cycle, retry-on-failure, log-and-continue) lives in the
shared
- Why it's built this way: bounded retention keeps both storage cost and PII exposure in check;
doing it as a batched
DELETErather than load-then-remove is the efficient path; independent windows mean that keeping processed rows forever does not also keep dead letters or inbox rows forever; per-target error isolation keeps one bad database from blocking the sweep; and the cycle lock keeps N replicas from running the same idempotent purge N times per interval. ADR-021 has the inbox reuse this same sweep, on its own window, rather than adding a second housekeeping service. - Where it's used: registered as a hosted service alongside the
OutboxProcessor, inside the sameIsOutboxEnabledgate (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:298-302), so a host with the outbox disabled runs neither and getsOutboxDisabledNoticeServiceinstead. - Caveats / not-in-source: the inbox window is this host's own
Inbox:RetentionDays; shortening it shortens the dedup memory the inbox gives this host's consumers. All three sweeps share one cadence,CleanupIntervalHours. Without a registeredIDistributedLockthecycleLockparameter is null and every replica sweeps; that is safe because the purge is idempotent, only wasteful.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
CreateWebhookSubscriptionRequest
MMCA.Common.Shared ·
MMCA.Common.Shared.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Shared/Webhooks/CreateWebhookSubscriptionRequest.cs:17· Level 0 · record
- What it is: the wire body of "create a webhook subscription for the caller's tenant": a target
Url, an optionalDescriptionand the list ofEventTypesto subscribe to (CreateWebhookSubscriptionRequest.cs:5-8,17). - Depends on: nothing first-party;
System.Diagnostics.CodeAnalysisfor the suppressions. - Concept: a contract DTO in the Shared layer, so the API controller and any typed client share one
shape.
[Rubric §9, API & Contract Design]assesses whether request contracts are explicit and stable; this one documents its own limits in the XML doc rather than in a separate spec: the URL must be an absolute https target (http and local targets only in Development when the host allows them), the description is up to 200 characters, and the event list holds 1 to 20 registered types or"*"for every one (CreateWebhookSubscriptionRequest.cs:6-8). - Walkthrough: a single positional
sealed record(CreateWebhookSubscriptionRequest.cs:17). The twoSuppressMessageattributes (CreateWebhookSubscriptionRequest.cs:9-16) keepUrlastringagainst CA1054/CA1056, with the justification that the URL is untrusted operator input validated as text before anything parses it, and thatSystem.Uriwould re-normalize it. - Why it's built this way: carrying the raw string means the validator judges exactly what the
operator sent; the address policy itself runs later in
DnsWebhookTargetValidator. The design is recorded in ADR-142. - Where it's used:
IWebhookSubscriptionService.CreateAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/IWebhookSubscriptionService.cs:28, seeIWebhookSubscriptionService) and the[FromBody]parameter ofCreateAsynconWebhookSubscriptionsControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Webhooks/WebhookSubscriptionsControllerBase.cs:87-88). The answer is aWebhookSubscriptionSecretResponse.
IWebhookDnsResolver
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/IWebhookDnsResolver.cs:9· Level 0 · interface
- What it is: the internal abstraction that resolves a webhook target's host name to its IP
addresses, used both when a subscription is validated and when a delivery connects
(
IWebhookDnsResolver.cs:5-8). - Depends on: BCL
System.Net.IPAddress. Implemented bySystemWebhookDnsResolver. - Concept: a test injection point over a static BCL call.
[Rubric §14, Testability]assesses whether nondeterministic dependencies can be replaced; DNS is exactly that, and the doc says tests register a stub first (IWebhookDnsResolver.cs:6-7), which works because the default registration is aTryAddSingleton(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:86). - Walkthrough: one member,
ResolveAsync(string host, CancellationToken)returningTask<IPAddress[]>, "possibly none" (IWebhookDnsResolver.cs:15). An empty array is a legal answer and both callers handle it explicitly. - Why it's built this way: one resolver feeds both the early check and the authoritative connect-time
check, so a test can model a DNS answer that changes between them (the rebinding case the connect
callback exists for). The interface is
internal: hosts do not replace DNS resolution. - Where it's used:
DnsWebhookTargetValidator(DnsWebhookTargetValidator.cs:21,45) andWebhookConnectCallback(WebhookConnectCallback.cs:23,40); tests inMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Webhooks/(DnsWebhookTargetValidatorTests.cs,WebhookConnectCallbackTests.cs,AddWebhooksTests.cs) supply stubs.
UpdateWebhookSubscriptionRequest
MMCA.Common.Shared ·
MMCA.Common.Shared.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Shared/Webhooks/UpdateWebhookSubscriptionRequest.cs:17· Level 0 · record
- What it is: the wire body that replaces an existing subscription's target URL, description and
event types (
UpdateWebhookSubscriptionRequest.cs:5). - Depends on: nothing first-party.
- Concept: same shape, limits and CA1054/CA1056 suppressions as
CreateWebhookSubscriptionRequest(UpdateWebhookSubscriptionRequest.cs:6-17); see that section. It is a full replacement, not a patch: every field is required positionally, with onlyDescriptionnullable. - Walkthrough:
sealed record UpdateWebhookSubscriptionRequest(string Url, string? Description, IReadOnlyList<string> EventTypes)(UpdateWebhookSubscriptionRequest.cs:17). - Why it's built this way: a separate type from the create request keeps the two operations free to
diverge without a breaking change, while today they carry identical fields. The update does not issue
a secret, which is why its answer is the plain
WebhookSubscriptionResponse. - Where it's used:
IWebhookSubscriptionService.UpdateAsync(Guid id, UpdateWebhookSubscriptionRequest request, ...)(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/IWebhookSubscriptionService.cs:35) and the controller'sUpdateAsync(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Webhooks/WebhookSubscriptionsControllerBase.cs:112-114).
WebhookSubscriptionResponse
MMCA.Common.Shared ·
MMCA.Common.Shared.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Shared/Webhooks/WebhookSubscriptionResponse.cs:26· Level 0 · record
- What it is: one subscription as the administration surface lists it, without its signing secret
(
WebhookSubscriptionResponse.cs:5-8). - Depends on: nothing first-party.
- Concept: a read model that deliberately omits a sensitive field.
[Rubric §11, Security]assesses whether secrets leak through read paths; here the secret is simply not a member, and the doc points toWebhookSubscriptionSecretResponseas the only carrier, at create or rotate time (WebhookSubscriptionResponse.cs:6-7). - Walkthrough: nine positional members (
WebhookSubscriptionResponse.cs:26-35):Id,Url,Description,EventTypes(ordinal-sorted,"*"for all, line 12),IsEnabled,CreatedOn, and the delivery health fieldsLastDeliveredOn,LastFailedOnandLastFailure(lines 15-17), all UTC. The same CA1054/CA1056 suppressions as the request records apply (lines 18-25). - Why it's built this way: surfacing the last-success and last-failure stamps on the list lets an
operator see a broken receiver without reading logs, a small
[Rubric §13, Observability & Operability]touch. - Where it's used: built by
WebhookSubscriptionService, returned byListAsync,UpdateAsync,DisableAsyncandEnableAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/IWebhookSubscriptionService.cs:22,35,47,53) and by the matching controller actions (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Webhooks/WebhookSubscriptionsControllerBase.cs:54,112,161,182); wrapped byWebhookSubscriptionSecretResponse.
WebhookTargetRefusedException
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookTargetRefusedException.cs:7· Level 0 · class
- What it is: the exception the webhook client's connect callback throws, before any socket opens,
when a target host resolves to a non-public address; the sender maps it to
TargetRefused(WebhookTargetRefusedException.cs:3-6). - Depends on: BCL
HttpRequestException(its base, line 7). - Concept: a typed refusal distinct from a transport failure.
[Rubric §10, Messaging & Integration]assesses whether delivery failures are classified so retries are spent sensibly; a generic socket error is retryable, while a refused target is a policy outcome, and this type is what letsHttpWebhookSendertell them apart. - Walkthrough: the three conventional constructors (parameterless, message, message plus inner
exception) at
WebhookTargetRefusedException.cs:10,16,24; no extra state. - Why it's built this way: deriving from
HttpRequestExceptionmeans a throw from insideSocketsHttpHandler.ConnectCallbacktravels throughHttpClientthe way any connect failure does. The sender then catches it both directly and as theInnerExceptionof a wrappingHttpRequestException(HttpWebhookSender.cs:82,86), so the classification holds either way. - Where it's used: thrown by
WebhookConnectCallback(WebhookConnectCallback.cs:51), caught byHttpWebhookSender(HttpWebhookSender.cs:82-89); exercised byHttpWebhookSenderTests.cs,WebhookConnectCallbackTests.csandMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Webhooks/DeliverWebhookInternalCommandHandlerTests.cs. - Caveats / not-in-source: whether
HttpClientsurfaces the callback's exception wrapped or bare is runtime behavior of the BCL, not visible here; the double catch exists so the code does not depend on it.
SystemWebhookDnsResolver
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/SystemWebhookDnsResolver.cs:6· Level 1 · class
- What it is: the default
IWebhookDnsResolver, a one-line pass-through toDns.GetHostAddressesAsync(host, cancellationToken)(SystemWebhookDnsResolver.cs:9-10). - Depends on:
IWebhookDnsResolver; BCLSystem.Net.Dns. - Concept: see
IWebhookDnsResolverfor why DNS sits behind an interface. - Walkthrough:
ResolveAsyncis an expression-bodied forward (SystemWebhookDnsResolver.cs:9-10); no caching, so every validation and every connect resolves afresh, which is what the connect-time check relies on. - Why it's built this way: keeping the production implementation trivial leaves all policy in the
callers (
DnsWebhookTargetValidatorandWebhookConnectCallback). - Where it's used: registered as a singleton by
WebhookServiceCollectionExtensions(WebhookServiceCollectionExtensions.cs:86).
WebhookConnectCallback
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookConnectCallback.cs:16· Level 1 · class (static)
- What it is: the
SocketsHttpHandler.ConnectCallbackof theMMCA.Webhooksclient. It resolves the host itself, refuses before opening a socket when any resolved address is not public, then dials only the addresses it checked (WebhookConnectCallback.cs:7-15). - Depends on:
IWebhookDnsResolver,WebhookTargetRefusedException,OutboundAddressPolicy; BCLSocketsHttpHandler,Socket,NetworkStream. - Concept introduced, connect-time SSRF defense.
[Rubric §11, Security]assesses whether server-side request forgery is closed, not just discouraged. A webhook target is operator-supplied, so a check at subscription time alone is defeated by DNS rebinding (the name resolves publicly when validated and privately when delivered) or by any handler that rewrites the request URI. Doing the resolution inside the connect callback means the address that is checked is the address that is dialled, on every delivery (WebhookConnectCallback.cs:11-14). - Walkthrough:
Create(resolver, allowInsecure)(WebhookConnectCallback.cs:22-29) returns a closure overcontext.DnsEndPoint.ConnectAsync(WebhookConnectCallback.cs:31-71): an IP literal is used as-is, otherwise the resolver is asked (lines 38-40). An empty answer throwsSocketException(HostNotFound), commented as not a refusal because it may be transient and so is retried (lines 42-46). UnlessallowInsecure, the first address failingOutboundAddressPolicy.IsPublicAddressthrowsWebhookTargetRefusedExceptionnaming host and address (lines 48-53). Then each checked address is tried in resolver order; the first that connects wins, and when none does the lastSocketExceptionsurfaces (lines 55-70).ConnectToAsync(WebhookConnectCallback.cs:73-87) opens aNoDelayTCP socket, wraps it in aNetworkStreamwithownsSocket: true, and nulls the local so thefinallydisposes only on failure (lines 75-85).
- Why it's built this way: dialling the checked addresses itself, rather than letting the handler resolve again, removes the window between check and use. The refusal versus transport-failure split decides whether the internal-command queue retries. See ADR-142.
- Where it's used: wired as the primary handler's
ConnectCallbackinWebhookServiceCollectionExtensions(WebhookServiceCollectionExtensions.cs:100-104); covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Webhooks/WebhookConnectCallbackTests.cs. - Caveats / not-in-source:
allowInsecureis fixed when the primary handler is built (it is read atWebhookServiceCollectionExtensions.cs:102-104); how long that handler lives is governed byIHttpClientFactoryhandler rotation, which is not configured in this code.
WebhookInsecureTargets
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookInsecureTargets.cs:11· Level 1 · class (static)
- What it is: the single decision behind
Webhooks:AllowInsecureTargetsInDevelopment: the flag is honoured only when a registeredIHostEnvironmentreports Development (WebhookInsecureTargets.cs:6-10). - Depends on:
WebhookSettings;Microsoft.Extensions.Hosting.IHostEnvironment. - Concept introduced, a dev-only relaxation that fails closed.
[Rubric §11, Security]assesses whether convenience switches can leak into production.AreAllowedreturns true only when the flag is set AND an environment is registered AND it is Development (WebhookInsecureTargets.cs:17-18); a host with no registered environment reads as production, the rule of ADR-122. - Walkthrough: one method,
AreAllowed(WebhookSettings settings, IHostEnvironment? environment)(WebhookInsecureTargets.cs:17-18). - Why it's built this way: four call sites must agree on the same switch (validator, sender, connect callback wiring, startup notice); one helper means a production host cannot accept an http target at validation while refusing it at send, or the reverse.
- Where it's used:
DnsWebhookTargetValidator(DnsWebhookTargetValidator.cs:30),HttpWebhookSender(HttpWebhookSender.cs:45),InsecureWebhookTargetsNoticeService(InsecureWebhookTargetsNoticeService.cs:27) and the connect callback wiring (WebhookServiceCollectionExtensions.cs:102-104).
WebhookSubscriptionSecretResponse
MMCA.Common.Shared ·
MMCA.Common.Shared.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Shared/Webhooks/WebhookSubscriptionSecretResponse.cs:13· Level 1 · record
- What it is: a
WebhookSubscriptionResponseplus the plaintext signingSecretjust issued for it, the answer to a create or a rotate (WebhookSubscriptionSecretResponse.cs:3-5,13). - Depends on:
WebhookSubscriptionResponse. - Concept: show-once secret delivery.
[Rubric §11, Security]: only the protected secret is stored, so this response is the only place the plaintext ever appears, and a receiver that loses it rotates (WebhookSubscriptionSecretResponse.cs:6-9). The secret iswhsec_followed by the Base64 key (line 12), the formatWebhookSignaturedecodes. - Walkthrough:
sealed record WebhookSubscriptionSecretResponse(WebhookSubscriptionResponse Subscription, string Secret)(WebhookSubscriptionSecretResponse.cs:13). - Why it's built this way: composing the plain response instead of adding a nullable
Secretto it keeps the secret out of every list and update payload by construction. - Where it's used:
CreateAsyncandRotateSecretAsynconIWebhookSubscriptionService(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/IWebhookSubscriptionService.cs:28,41) and the controller actions (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Webhooks/WebhookSubscriptionsControllerBase.cs:87,140).
InsecureWebhookTargetsNoticeService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/InsecureWebhookTargetsNoticeService.cs:18· Level 2 · class
- What it is: an
IHostedServicethat logs one startup Warning whenWebhooks:AllowInsecureTargetsInDevelopmentis set in a host that is not Development, so the operator learns the flag is ignored at startup rather than from refused subscriptions (InsecureWebhookTargetsNoticeService.cs:9-14). - Depends on:
WebhookSettings,WebhookInsecureTargets;IOptions<T>,IHostedService,ILoggerwith[LoggerMessage]source generation. - Concept: the observable half of a fail-closed relaxation.
[Rubric §13, Observability & Operability]assesses whether misconfiguration is surfaced; ignoring the flag silently would be safe but confusing, and this service makes the ignored state visible once (ADR-122). - Walkthrough:
StartAsync(InsecureWebhookTargetsNoticeService.cs:24-33) reads the optional environment throughIServiceProvider.GetService(line 26), and logs when the flag is set butWebhookInsecureTargets.AreAllowedis false (lines 27-30), naming the environment or"(none registered)".StopAsyncis a no-op (line 36). The Warning text, generated at lines 38-41, states that targets must be https and resolve to public addresses only. - Why it's built this way: resolving the environment optionally rather than as a constructor dependency lets the service run in a host that registers none, which is exactly the production case the rule must cover.
- Where it's used: registered with
TryAddEnumerableas a singletonIHostedService(WebhookServiceCollectionExtensions.cs:109); covered byDnsWebhookTargetValidatorTests.csandAddWebhooksTests.csinMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Webhooks/.
DataProtectionWebhookSecretProtector
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/DataProtectionWebhookSecretProtector.cs:16· Level 4 · class
- What it is: the default
IWebhookSecretProtector, encrypting signing secrets at rest with the host's ASP.NET Core data-protection key ring under the purposeMMCA.Common.Webhooks.Secret.v1(DataProtectionWebhookSecretProtector.cs:9-14). - Depends on:
IWebhookSecretProtector,Result,Error,WebhookErrorCodes;Microsoft.AspNetCore.DataProtection. - Concept: secrets encrypted at rest, with an unreadable secret as a value rather than an exception.
[Rubric §11, Security]assesses secret storage;[Rubric §29, Resilience & Business Continuity]assesses graceful degradation. A replica without the shared key ring (ADR-069) cannot read another replica's secret, and that surfaces asWebhooks.SecretUnreadable, never as a throw (DataProtectionWebhookSecretProtector.cs:11-13). - Walkthrough: the
Purposeconstant is part of the stored format and never changes (DataProtectionWebhookSecretProtector.cs:18-19); the protector is created once from it (line 21).Protectrejects null or empty and forwards (lines 24-28).Unprotectreturns the failure for blank input (lines 33-36), otherwiseResult.Successof the plaintext (line 40), mappingCryptographicExceptionandFormatExceptionto the same failure (lines 42-49).Unreadable()builds anError.Unexpected(ErrorType.Unexpected,MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:140) with codeWebhookErrorCodes.SecretUnreadable(lines 52-56): a missing key ring is a host fault, not a caller mistake. - Why it's built this way: returning
ResultletsHttpWebhookSenderrefuse to send unsigned instead of crashing a delivery; see ADR-142. - Where it's used: registered as a singleton (
WebhookServiceCollectionExtensions.cs:85, withAddDataProtection()at line 90); consumed byHttpWebhookSender.ReadKeys(HttpWebhookSender.cs:123); covered byDataProtectionWebhookSecretProtectorTests.cs.
DnsWebhookTargetValidator
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/DnsWebhookTargetValidator.cs:20· Level 4 · class
- What it is: the default
IWebhookTargetValidator, the early answer to "may this URL be a webhook target?". The connect-time check stays authoritative; this one tells the operator at subscribe time (DnsWebhookTargetValidator.cs:11-16). - Depends on:
IWebhookDnsResolver,WebhookSettings,WebhookInsecureTargets,OutboundAddressPolicy,Result,Error,WebhookErrorCodes. - Concept: defense in depth against SSRF, the early layer in front of
WebhookConnectCallback.[Rubric §11, Security]. - Walkthrough:
ValidateAsync(DnsWebhookTargetValidator.cs:26-55) computesallowInsecure(line 30), then refuses any URI failingOutboundAddressPolicy.IsAcceptableTargetUri(lines 31-34). With insecure targets allowed, or an IP-literal host already judged by the policy, it succeeds without resolving (lines 36-40). Otherwise it resolves the host; any non-cancellation exception becomes a refusal (lines 42-50). It succeeds only when the answer is non-empty and every address is public (lines 52-54).Refusedis anError.Validationwith codeWebhookErrorCodes.TargetNotAllowedon theUrlfield (lines 57-58). - Why it's built this way: a validation error tied to
Urlbecomes a field-level 400 for the operator, where a connect-time refusal would only show later as a failed delivery. Requiring ALL addresses public matches the connect callback, which refuses on any non-public address. See ADR-122 and ADR-142. - Where it's used: registered scoped (
WebhookServiceCollectionExtensions.cs:83) and called fromWebhookSubscriptionServicethrough its injectedIWebhookTargetValidator(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/WebhookSubscriptionService.cs:26,250); covered byDnsWebhookTargetValidatorTests.cs.
HttpWebhookSender
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/HttpWebhookSender.cs:25· Level 4 · class
- What it is: the default
IWebhookSender: one Standard Webhooks POST through theMMCA.Webhooksclient, signed once per readable secret, mapped to aWebhookSendOutcomefrom the status code or the exception alone; the response body is never read (HttpWebhookSender.cs:14-19). - Depends on:
IWebhookSecretProtector,WebhookSignature,WebhookDeliveryRequest,WebhookSendStatus,WebhookInsecureTargets,WebhookTargetRefusedException,OutboundAddressPolicy;IHttpClientFactory,TimeProvider. - Concept: outcome classification for an at-least-once delivery.
[Rubric §10, Messaging & Integration]assesses whether a sender tells retryable from terminal failures; this class turns every path into one ofDelivered,Gone,Rejected,TransportFailed,TargetRefusedorSecretUnreadable, and never throws for a receiver's behavior. - Walkthrough:
- Constants:
ClientName = "MMCA.Webhooks",UserAgent = "MMCA-Webhooks/1", JSON media type (HttpWebhookSender.cs:33-36). SendAsync(HttpWebhookSender.cs:39-99): re-applies the scheme rule with the same switch as the connect callback, so a storedhttp://row reaching a production host is refused, never sent in plaintext (lines 43-52). Reads the keys; none readable meansSecretUnreadable, because an unsigned delivery is never sent (lines 54-59). Stamps a Unix timestamp fromTimeProviderand joins one signature per key with spaces (lines 61-62). Builds the POST with the id, timestamp and signature headers and the user agent (lines 64-71), sends withResponseHeadersRead(lines 75-78) and classifies (line 80). Catches map a refusal (bare or as inner exception) toTargetRefused, any otherHttpRequestExceptiontoTransportFailed, and a client timeout (anOperationCanceledExceptionwhile the caller's token is still live) toTransportFailed(lines 82-98).Classify(HttpWebhookSender.cs:102-110): 410 isGone, 2xx isDelivered, anything else, redirects included, isRejected.ReadKeys(HttpWebhookSender.cs:118-136): current secret first, then any readable previous one; an unreadable current secret yields no keys, an unreadable previous one is dropped.
- Constants:
- Why it's built this way: signing with every readable secret lets a receiver verify across a secret rotation; never reading the body keeps a hostile receiver from streaming data into the host. The dev-only switch is shared with the validator and the callback (ADR-122, ADR-142).
- Where it's used: registered scoped (
WebhookServiceCollectionExtensions.cs:84), its named client configured at lines 87-102; called byDeliverWebhookInternalCommandHandler(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/DeliverWebhookInternalCommandHandler.cs:26,66); covered byHttpWebhookSenderTests.cs.
WebhookDeliveryLane
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookDeliveryLane.cs:20· Level 15 · class (static)
- What it is: the dedicated internal-command lane that drains webhook delivery rows
(
DeliverWebhookInternalCommand) with its ownInternalCommandLaneProcessor, never the shared loop, so a slow or failing receiver cannot delay the other internal commands (WebhookDeliveryLane.cs:14-19). - Depends on:
InternalCommandLane,InternalCommandLanes,InternalCommandLaneProcessor,InternalCommandProcessor,InternalCommandNameResolver,InternalCommandsSettings,IInternalCommandSignal,FrameworkTableTargets,WebhookSettings. - Concept introduced, bulkhead lane over the durable job queue.
[Rubric §29, Resilience & Business Continuity]assesses failure isolation; webhook receivers are third-party and can be slow for minutes, so they get their own processor (a bulkhead) on top of the internal-command queue of ADR-114. Keying rows by subscription means a failing subscription is cooled down on its own and two deliveries to one subscription never run at once (WebhookDeliveryLane.cs:17-18). - Walkthrough:
LaneName = "webhooks", thelanemetric tag and log value (WebhookDeliveryLane.cs:23);CommandTypeis the stored command name computed from the type (lines 26-27).Create(settings)(WebhookDeliveryLane.cs:36-49): cooldown fromReceiverCooldownSeconds(line 43), receiver key =SubscriptionId.ToString("N")(lines 44-46),MaxConcurrencyfromDeliveryConcurrency(line 47), andBatchStartBudgetfromTimeoutSeconds(line 48).Register(services, configuration)(WebhookDeliveryLane.cs:58-81): reads both settings sections straight from configuration (lines 60-62) and returns unlessWebhooks:EnabledandInternalCommands:Enabledare both true; an existingInternalCommandLanesdescriptor makes a second call a no-op (line 64). It registers the lane registry (line 69) and the processor as a plain factory singletonIHostedService, commented as needed becauseAddHostedServiceusesTryAddEnumerable, which refuses a factory registration (lines 71-80).
- Why it's built this way: reading configuration directly at registration mirrors how the queue reads
its own flag (
WebhookDeliveryLane.cs:53-55), so a disabled feature registers no hosted service at all. See ADR-142. - Where it's used: called from
AddWebhooks(WebhookServiceCollectionExtensions.cs:111); covered byWebhookDeliveryLaneTests.cs,MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.SQLServer.Tests/Webhooks/WebhookDeliveryLaneSqlServerTests.csandMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.PostgreSQL.Tests/InternalCommandLanePostgreSqlTests.cs.
WebhookServiceCollectionExtensions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Webhooks·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:20· Level 16 · class (static, extension block)
- What it is: the public DI entry point
services.AddWebhooks(configuration), registering settings, the subscription store and service, the target validator, the signed sender and its client, the secret protector, the DNS resolver, the event catalog and the startup notice (WebhookServiceCollectionExtensions.cs:24-29,68). - Depends on: every type in this part plus
EFWebhookSubscriptionStore,WebhookSubscriptionService,WebhookEventCatalogandWebhookSettings;IHttpClientFactory,SocketsHttpHandler,Microsoft.AspNetCore.DataProtection. - Concept: an
extension(IServiceCollection)block as the public DI surface (C#extension(T)types, ADR-106).[Rubric §11, Security]: the client is locked down in one place.[Rubric §33, Developer Experience]: the remarks are an adoption checklist. - Walkthrough:
- Settings bound, data-annotation validated and validated on start (
WebhookServiceCollectionExtensions.cs:72-75, ADR-070). - The table's model contributor:
WebhookSubscriptionModelContributoradded as a singletonIModelContributorthroughTryAddEnumerable, inert untilWebhooks:Enabledand then mapped only on the sourceWebhooks:DataSourceNamenames (lines 77-79, ADR-148). TryAddregistrations, so a host or test can pre-register a replacement: scoped store, service, validator and sender; singleton protector, resolver, catalog andTimeProvider.System(lines 81-88);AddDataProtection()(line 90).- The
MMCA.Webhooksclient (lines 92-107):TimeoutfromTimeoutSeconds; aSocketsHttpHandlerwith no redirects, no proxy, no cookies,ActivityHeadersPropagator = nulland theWebhookConnectCallback(lines 94-105); every additional handler cleared (line 106) and all loggers removed (line 107). - The notice hosted service (line 109) and
WebhookDeliveryLane.Register(line 111).
- Settings bound, data-annotation validated and validated on start (
- Why it's built this way: the remarks (
WebhookServiceCollectionExtensions.cs:32-67) give the reasons. Calling this alone turns nothing on: withWebhooks:Enabledfalse the fan-out is inert, every administration endpoint answers 404 and no context maps theWebhookSubscriptionstable; turning it on also needspipeline.AddWebhookDelivery(), oneAddWebhookEvent<TEvent>(name)per event, the migration on theWebhooks:DataSourceNamedatabase (DesignTimeDbContextOptions.EnableWebhooks), and a controller deriving fromWebhookSubscriptionsControllerBasegrantedwebhooks:manage(lines 34-40). Clearing host-default handlers makes the internal-command queue the only retry and failure policy, removing loggers keeps target URLs (often carrying a receiver token) out of logs, and notraceparent/tracestate/baggagereaches the receiver (lines 49-55, ADR-009). A multi-replica host needs the shared key ring (ADR-069, lines 43-46). Lane defaults, includingWebhooks:DeliveryConcurrency(default 4) per replica, are documented at lines 58-65 (ADR-142). - Where it's used: no call site outside the defining file in
MMCA.Common/Source, and none inMMCA.ADC/Source(noAddWebhooks(orWebhookSubscriptionsControllerBasematch); exercised byAddWebhooksTests.csandDependencyInjectionModelContributorTests.cs. - Caveats / not-in-source: the default of 4 stated in the remarks (line 60) matches its declaration
on
WebhookSettings(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/WebhookSettings.cs:41). The remark notes the HTTP client trace still records the URL path, so a host exporting traces to a shared backend must filterMMCA.Webhooksspans itself (lines 54-55).
IDomainEventDispatcher
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Events·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Events/IDomainEventDispatcher.cs:8· Level 1 · interface
- What it is: the dispatch port for in-process domain-event delivery. A single method,
DispatchAsync(IEnumerable<IDomainEvent>, CancellationToken)(IDomainEventDispatcher.cs:16), takes a batch of events and routes each to its registered handlers after an aggregate persists changes (doc comment, lines 5-7). - Depends on:
IDomainEvent(Level 0). - Concept introduced, the dispatcher/handler split for domain events.
[Rubric §6, CQRS & Event-Driven]assesses whether events are dispatched after persistence rather than from inside aggregates, and whether handlers are discoverable. The dispatcher is the port half of the pair; the handler half isIDomainEventHandler<in TDomainEvent>.[Rubric §1, SOLID]: the dispatcher depends only on the abstract handler contract (dependency inversion), so adding a reaction never edits the dispatcher. - Walkthrough: a one-method port taking a batch rather than a single event, which lets the
implementation resolve handlers once per event type for a whole save. The only implementation is
DomainEventDispatcher(Level 3), which fans each event out to every registeredIDomainEventHandler<T>and, for integration events, additionally to everyIIntegrationEventHandler<in TIntegrationEvent>. - Why it's built this way: keeping the contract in
Application(a port) and the implementation behind it follows the Clean Architecture ports-and-adapters split, and the outbox (ADR-003) reuses the same dispatcher for both the synchronous in-process copy and the background re-dispatch of persisted events, so a handler cannot behave differently depending on which path delivered its event. - Where it's used: the
DomainEventSaveChangesInterceptorcollects domain events from aggregates, writes them asOutboxMessagerows, then callsDispatchAsyncfor the immediate in-process reactions, one event at a time through the shared internalInProcessDispatchhelper (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:414-422, which callsDispatchAsyncatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/InProcessDispatch.cs:60,100); the backgroundOutboxProcessorroutes non-integration events through it (OutboxProcessor.cs:830), as doInProcessMessageBus(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/InProcessMessageBus.cs:24,31) andInProcessEventBus(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/InProcessEventBus.cs:126,177-178, through the sameInProcessDispatchhelper).
IDomainEventHandler<in TDomainEvent>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Events·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Events/IDomainEventHandler.cs:10· Level 1 · interface
- What it is: the contract a domain-event reaction implements, with a single
HandleAsync(TDomainEvent, CancellationToken)(IDomainEventHandler.cs:19). - Depends on:
IDomainEvent(Level 0). - Concept: the handler half of the dispatcher/handler split introduced by
IDomainEventDispatcher.IDomainEventHandler<in TDomainEvent>is contravariant onTDomainEvent(theinkeyword,IDomainEventHandler.cs:10), constrainedwhere TDomainEvent : IDomainEvent(line 11); contravariance means a handler written against a base event type is usable where a handler for a more derived event is required. Per the doc comment (lines 5-8), implementations are auto-discovered by Scrutor assembly scanning and resolved from DI during dispatch, which the framework wires throughScanModuleApplicationServices<T>.[Rubric §6, CQRS & Event-Driven]and[Rubric §5, Vertical Slice]: a new reaction is a new file in the owning module, never an edit to shared dispatch code. - Walkthrough: a one-method port. Handlers that must succeed atomically with the primary
transaction (a read model in the same database, say) implement it directly and let exceptions
propagate; handlers that want their own failure context logged first extend
SafeDomainEventHandler<TDomainEvent>, which logs and then lets the exception continue so the outbox can redeliver. - Where it's used: resolved and invoked by
DomainEventDispatcher(Level 3) for every dispatched event; the dispatcher closes this open generic over the concrete runtime event type to find the right handlers.
BaseDomainEvent
MMCA.Common.Domain ·
MMCA.Common.Domain.DomainEvents·MMCA.Common.Domain/DomainEvents/BaseDomainEvent.cs:26· Level 1 · record class (abstract)
- What it is: the abstract base record for every domain event, supplying default values for both
IDomainEventproperties so a concrete event type is a one-liner. - Depends on:
IDomainEvent(Level 0). No externals beyondDateTimeandGuid. - Concept introduced, record semantics for domain events.
[Rubric §6, CQRS & Event-Driven]assesses whether events carry enough context and whether consumers can stay idempotent. Declaring the base as arecord class(MMCA.Common.Domain/DomainEvents/BaseDomainEvent.cs:26) gives structural equality, which is useful for value-based assertions in tests. Two properties are initialized inline at construction.DateOccurred = DateTime.UtcNow(MMCA.Common.Domain/DomainEvents/BaseDomainEvent.cs:28) captures when the business action happened, not when the event was dispatched, a distinction the summary comment draws explicitly (BaseDomainEvent.cs:5-8).MessageId = Guid.NewGuid()(BaseDomainEvent.cs:35) mints a unique per-instance id at construction time. BecauseMessageIdis serialized with the payload it survives the outbox to broker to consumer round trip, which is what makes consumer-side deduplication through theInboxMessagetable reliable (property doc,BaseDomainEvent.cs:30-34). - Walkthrough: two
initproperties with inline defaults, and nothing else. The type isabstract, so a consumer must declare a concrete event; derived events add whatever domain payload they carry (entity id, state change, and so on) as positional orinitmembers. The first<remarks>block (BaseDomainEvent.cs:9-17) exists to head off a trap: structural equality is not a deduplication mechanism here. BothMessageIdandDateOccurreddefault to a fresh value per instance, so two logically identical events raised separately are never equal, and anything relying on that comparison to spot a duplicate would silently never match. Deduplication is the inbox's job (ADR-021), keyed onMessageId. - Why it's built this way: inline defaults mean a concrete event record needs zero boilerplate,
public sealed record SessionCreated(SessionIdentifierType SessionId) : BaseDomainEvent;is the complete type. MintingMessageIdat construction rather than at serialization keeps the id stable even if the event is serialized more than once, which is the consumer-idempotency half of the at-least-once story in ADR-003. The creation-time default onDateOccurredis documented as a deliberate domain-modelling choice rather than an oversight (second<remarks>block,BaseDomainEvent.cs:18-25): a domain event's occurrence instant is by definition the moment the aggregate raises it, so stamping it at construction is the correct event-sourcing and audit semantic, and it is intentionally distinct from infrastructure timestamps that must be deterministically testable (audit fields, notification read-time), which are stamped from an injectedTimeProvider.[Rubric §14, Testability]is the tension being resolved here, and the comment records that resolving it the other way (threading a clock through every aggregate) would not improve the model. - Where it's used: the base of every domain event across MMCA.Common, MMCA.ADC, and MMCA.Store;
subclassed by
BaseIntegrationEventand byEntityChangedEvent<TIdentifierType>; it is the generic constraint onSafeDomainEventHandler<TDomainEvent>(MMCA.Common.Application/DomainEvents/SafeDomainEventHandler.cs:37); instances are captured intoOutboxMessagerows and routed byDomainEventDispatcher.
IEventBus
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Events·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Events/IEventBus.cs:13· Level 2 · interface
- What it is: the abstraction application code publishes
IIntegrationEvents through. TwoPublishAsyncoverloads (IEventBus.cs:20and:25): a single event and a batch. - Depends on:
IIntegrationEvent(Level 1). - Concept introduced, integration events versus domain events at the publish call site.
[Rubric §6, CQRS & Event-Driven]assesses reliable events, at-least-once delivery and idempotent consumers. A domain event is raised inside an aggregate, captured by the save-changes interceptor and dispatched after that save; an integration event is an intentional signal to other bounded contexts that may cross a service boundary.IEventBusis where that distinction shows up in a caller's code: you publish anIIntegrationEventand the infrastructure decides how to route it. The doc comment (lines 5-10) is precise: the default implementation dispatches in-process throughIDomainEventDispatcherwith outbox persistence for at-least-once delivery, while alternative implementations (Azure Service Bus, RabbitMQ) can be substituted via DI. The "persist first, then act" guarantee lives in the concrete implementations, not in this interface. - Why it's built this way: two overloads rather than one keeps the batch case a single save and a
single signal in the implementations, which is exactly the atomicity argument
BrokerEventBusdocuments; a loop over the single-event overload would produce one transaction and one wake-up per event. - Where it's used: implemented by
InProcessEventBus(the monolith default) andBrokerEventBus(the extracted-service path), both Level 13. Contrast it with the transport-agnosticIMessageBusthat theOutboxProcessordrains through:IEventBusis the producer's API and writes the outbox row,IMessageBusis the transport's API and moves the row's payload onward.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
IIntegrationEventHandler<in TIntegrationEvent>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Events·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Events/IIntegrationEventHandler.cs:17· Level 2 · interface
- What it is: the handler contract for receiving integration events. One method,
HandleAsync(TIntegrationEvent, CancellationToken)(IIntegrationEventHandler.cs:26). - Depends on:
IIntegrationEvent(Level 1). - Concept: mirrors
IDomainEventHandler<in TDomainEvent>(Level 1) but for cross-module notifications, and the doc comment contrasts the two directly (IIntegrationEventHandler.cs:5-15): a domain-event handler reacts to intra-module events, an integration-event handler reacts to cross-module ones, for example a Sales module handlingUserRegisteredfrom the Identity module. It is contravariant (in, line 15), constrainedwhere TIntegrationEvent : IIntegrationEvent(line 16). Implementations are auto-discovered by Scrutor at singleton lifetime, and the doc states the consequence plainly: handlers create their own DI scopes internally (lines 9-12), which is whatScopedIntegrationEventHandlerBase<TIntegrationEvent>exists to do for you.[Rubric §6, CQRS & Event-Driven]and[Rubric §7, Microservices Readiness]: a handler written against this contract does not know whether its event arrived in-process or off a broker. - Where it's used: implemented by the framework's own
OutputCacheEvictionHandlerand by application handlers in ADC and Store; invoked in-process byDomainEventDispatcher(Level 3) and, on the extracted-service path, byIntegrationEventConsumer<TEvent>, which resolves every registered handler for the delivered event and invokes them in order.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
BaseIntegrationEvent
MMCA.Common.Domain ·
MMCA.Common.Domain.DomainEvents·MMCA.Common.Domain/DomainEvents/BaseIntegrationEvent.cs:11· Level 2 · record class (abstract)
- What it is: the abstract base for integration events, the events meant to cross module or
service boundaries. It inherits
BaseDomainEventfor outbox-pipeline compatibility and implementsIIntegrationEventso the dispatcher additionally routes it to integration-event handlers (MMCA.Common.Domain/DomainEvents/BaseIntegrationEvent.cs:11). - Depends on:
BaseDomainEvent(Level 1),IIntegrationEvent(Level 1). - Concept introduced, explicit integration-event schema versioning. This base adds exactly one
member beyond what it inherits:
public virtual int SchemaVersion => 1;(MMCA.Common.Domain/DomainEvents/BaseIntegrationEvent.cs:32).[Rubric §9, API & Contract Design]assesses whether contracts evolve without silently breaking consumers, and an integration event is a wire contract the moment it crosses a service boundary. The version is serialized with the payload, so a consumer has an explicit signal to branch or upcast on. The doc comment (BaseIntegrationEvent.cs:13-20) states the discipline precisely: additive or optional field changes keep the same version, while a breaking change (a renamed, removed, or retyped field) requires a new event type (for exampleFooV2) plus a consumer-side upcaster, never a silent reshape of an existing type. Concrete events bump it by overriding (public override int SchemaVersion => 2;).[Rubric §6, CQRS & Event-Driven]: the dual inheritance is the routing mechanism.BaseDomainEventsuppliesDateOccurredandMessageId, so the outbox and inbox machinery (which operates onIDomainEvent) treats integration events uniformly, while theIIntegrationEventmarker is what makesDomainEventDispatcherfan the event out toIIntegrationEventHandler<T>as well. - Concept introduced, the upcaster is a registration, not a convention. The second doc paragraph
(
BaseIntegrationEvent.cs:21-30) spells out the migration mechanics from ADR-090. The owning module registersservices.AddEventUpcaster<FooV1, FooV2, FooUpcaster>(), and a host that also still receives the retired contract over a broker addsx.RegisterUpcastedIntegrationEventConsumer<FooV1>()(IntegrationEventConsumerExtensions,MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumerExtensions.cs:123) beside its plainx.RegisterIntegrationEventConsumer<FooV2>(). Handlers are then written once, against the newest contract only. The framework preservesMessageIdandDateOccurredacross every hop, so inbox deduplication is unaffected by an upcast, and a fitness function requires the upcast target to declare a strictly higherSchemaVersionthan its source. That last rule is what keeps the version number from being decorative.[Rubric §15, Best Practices & Code Quality]: the handler set never has to grow a branch per historical contract shape. - Why it's built this way: declaring
SchemaVersionvirtual with a default keeps adding the member a non-breaking change, so every pre-existing event implicitly stays v1 with no edits (BaseIntegrationEvent.cs:19-20). See ADR-010 for the versioning policy, ADR-090 for the upcaster registration contract, and ADR-003 for why integration events ride the same outbox as ordinary domain events. - Where it's used: base of the framework's own
OutputCacheEvictionRequestedand of every cross-module event in the apps (for example ADC'sSpeakerLinkedToUser,SpeakerUnlinkedFromUser,UserRegistered, and Store'sProductVariantChanged).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
EntityChangedEvent<TIdentifierType>
MMCA.Common.Domain ·
MMCA.Common.Domain.DomainEvents·MMCA.Common.Domain/DomainEvents/EntityChangedEvent.cs:24· Level 2 · record (abstract)
- What it is: the standardized CRUD lifecycle event base. Instead of separate
Created,Updated, andDeletedevents per entity, one event type carries theState(DomainEntityState) and the affectedEntityId. Handlers filter onStateto decide which transitions they care about. - Depends on:
BaseDomainEvent(Level 1),DomainEntityState(Level 0). - Concept introduced, consolidated lifecycle events.
[Rubric §6, CQRS & Event-Driven]: one event type per entity avoids a proliferation of near-identical event classes while still carrying enough context to act on. The doc comment (MMCA.Common.Domain/DomainEvents/EntityChangedEvent.cs:5-20) draws the boundary clearly: derive one record per entity and raise it withDomainEntityState.Addedfrom factory methods,DomainEntityState.Updatedfrom mutation methods, andDomainEntityState.DeletedfromDelete(); reserve a named event (for exampleOrderPaid,ShoppingCartCheckedOut), inheritingBaseDomainEventdirectly, for business state-machine transitions with unique payloads (EntityChangedEvent.cs:15-19).[Rubric §15, Best Practices & Code Quality]assesses change-amplification cost: collapsing three CRUD events into one keeps the event surface small, so adding an entity adds one record rather than three. - Walkthrough: a primary-constructor record (
EntityChangedEvent.cs:24) with two positional parameters,Stateof typeDomainEntityState(EntityChangedEvent.cs:25) andEntityIdof typeTIdentifierType(EntityChangedEvent.cs:26). Thewhere TIdentifierType : notnullconstraint (EntityChangedEvent.cs:27) prevents a nullable identifier from reaching the outbox payload. Theabstractmodifier forces consumers to derive a concrete record (for exampleCategoryChanged : EntityChangedEvent<ConferenceCategoryIdentifierType>), which may add extra payload of its own. The identifier types themselves come from the module-levelglobal usingalias convention (see the primer's conventions section). - Where it's used: the base of the generic CRUD events in MMCA.ADC such as
CategoryChanged,EventChanged,QuestionChanged,SessionChanged, andSpeakerChanged.
IMessageBus
MMCA.Common.Application ·
MMCA.Common.Application.Messaging·MMCA.Common.Application/Messaging/IMessageBus.cs:29· Level 2 · interface
- What it is: the transport-agnostic abstraction for publishing integration events across
module or service boundaries. Two
PublishAsyncoverloads, single event (MMCA.Common.Application/Messaging/IMessageBus.cs:36) and batch (IMessageBus.cs:43). - Depends on:
IIntegrationEvent(Level 1). Nothing else, which is the point: this file has oneusingand it is a Domain namespace (IMessageBus.cs:1). - Concept introduced, a transport-agnostic message bus for microservices readiness.
[Rubric §7, Microservices Readiness]assesses whether the transport is a swappable boundary and whether the business layers stay free of transport coupling. The doc comment (IMessageBus.cs:5-28) enumerates both implementations explicitly:InProcessMessageBusdispatches synchronously through the existingIDomainEventDispatcherpath for the modular-monolith deployment (IMessageBus.cs:14-18), andBrokerMessageBuspublishes through the selected framework broker transport (anIBrokerTransport,MMCA.Common.Infrastructure/Messaging/Transports/IBrokerTransport.cs:22), RabbitMQ in development and Azure Service Bus in production, for the extracted-service mode (IMessageBus.cs:19-25,MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs:46). The same comment records why transactional-outbox semantics survive the swap:OutboxProcessordrainsOutboxMessagerows through this bus instead of dispatching in-process (IMessageBus.cs:21-23). It is also explicit that application code that publishes cross-cutting events should depend onIMessageBusrather than onIEventBusor on a transport-specific client (IMessageBus.cs:6-9).[Rubric §3, Clean Architecture]: the interface lives inApplicationand both implementations live inInfrastructure, so the dependency arrow points inward. - Why it's built this way: transport belongs at the edge
(ADR-007,
ADR-008). The same
application code that called
IMessageBus.PublishAsyncin the monolith keeps working when the module is extracted andBrokerMessageBusis swapped in; only configuration (MessageBus:Provider,MessageBusSettings) changes.Application,Domain, andSharedmust never reference a broker client directly (RabbitMQ, Azure Service Bus, Amazon SQS and SNS, and MassTransit, which is banned outright), and the architecture transport-boundary rule enforces exactly that (MMCA.Common.Testing.Architecture/Rules/Layering/ArchitectureRules.Transport.cs:14-20, run byMMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Layering/MicroserviceExtractionTests.cs:12). The MassTransit ban is a separate constraint enforced by the dependency-version fitness test, which fails the build on anyMassTransit*PackageVersion (MMCA.Common.Testing.Architecture/Bases/Governance/DependencyVersionTestsBase.cs:13-18, ADR-118). - Where it's used: implemented by
InProcessMessageBus, the default scoped registration (MMCA.Common.Infrastructure/DependencyInjection.cs:409, with the rationale comment atDependencyInjection.cs:551-555), and byBrokerMessageBus, whichReplaces that registration insideAddBrokerMessaging(MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:128). At runtime it is resolved per cycle by the backgroundOutboxProcessor(MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:278) and invoked for every integration-event row it drains (OutboxProcessor.cs:590-600).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
IWebhookSecretProtector
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Subscriptions·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/IWebhookSecretProtector.cs:9· Level 3 · interface
- What it is: the port that protects a webhook signing secret at rest and recovers it for
signing. Two members:
string Protect(string secret)(IWebhookSecretProtector.cs:14) andResult<string> Unprotect(string protectedSecret)(IWebhookSecretProtector.cs:19). - Depends on: the Result pattern from
MMCA.Common.Shared.Abstractions(IWebhookSecretProtector.cs:1); nothing else. - Concept introduced, a secret that is stored protected and recovered without throwing.
[Rubric §11, Security]assesses how secrets are held at rest and whether a key failure degrades safely. Here the subscription row only ever stores the protected form, and the read side is aResult, not an exception: the doc onUnprotectsays it "never throws" and answersWebhooks.SecretUnreadableinstead (IWebhookSecretProtector.cs:16-18). The interface doc names the operational consequence (IWebhookSecretProtector.cs:5-8): the default sits on the host's data-protection key ring, so a multi-replica host needs the shared key ring of ADR-069, or one replica cannot read a secret another replica wrote. - Walkthrough:
Protectis synchronous and returns the stored form.Unprotectreturns the plaintext on success. The defaultDataProtectionWebhookSecretProtector(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/DataProtectionWebhookSecretProtector.cs:16) creates oneIDataProtectorunder the fixed purposeMMCA.Common.Webhooks.Secret.v1, which its comment marks as part of the stored format, so it never changes, and answers a blank input as unreadable before trying to decrypt. - Why it's built this way: an unreadable secret is an expected runtime condition (a replica
without the shared key ring, a rotated-out key), so modelling it as a
Resultlets the sender fail one delivery cleanly rather than crash the delivery pipeline. ADR-142 records the split: an unreadable current secret means nothing is sent, an unreadable previous secret is dropped from the signature set. - Where it's used: registered as a singleton by
AddWebhooks(configuration)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:85,WebhookServiceCollectionExtensions);Protectis called byWebhookSubscriptionServiceat create and rotate, andUnprotectbyHttpWebhookSenderfor each stored secret it signs with (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/HttpWebhookSender.cs:123).
IWebhookSubscriptionService
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Subscriptions·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/IWebhookSubscriptionService.cs:11· Level 3 · interface
- What it is: the administration API behind the webhook-subscription endpoints: two read-only
properties and seven
Result-returning operations, always scoped to the caller's tenant. - Depends on: the Result pattern (
MMCA.Common.Shared.Abstractions), and the wire contracts inMMCA.Common.Shared.Webhooks(IWebhookSubscriptionService.cs:1-2):CreateWebhookSubscriptionRequest,UpdateWebhookSubscriptionRequest,WebhookSubscriptionResponse, andWebhookSubscriptionSecretResponse. - Concept introduced, a show-once secret in the contract shape.
[Rubric §9, API & Contract Design]assesses whether a contract makes misuse hard. The return types do that here: onlyCreateAsync(IWebhookSubscriptionService.cs:28) andRotateSecretAsync(IWebhookSubscriptionService.cs:41) return aWebhookSubscriptionSecretResponse; every other operation returns the secretlessWebhookSubscriptionResponse, so no read path can leak the signing secret (interface doc,IWebhookSubscriptionService.cs:6-10).[Rubric §11, Security]: the same doc fixes the tenancy rule, an id belonging to another tenant or to a deleted row answersWebhooks.NotFound, so a caller cannot probe for another tenant's subscriptions. - Walkthrough
IsEnabled(IWebhookSubscriptionService.cs:14) reports whether outbound webhooks are on in this host;EventTypes(IWebhookSubscriptionService.cs:17) lists the event types the host publishes.ListAsync(IWebhookSubscriptionService.cs:22) returns the caller's subscriptions without secrets.CreateAsync(IWebhookSubscriptionService.cs:28) andUpdateAsync(IWebhookSubscriptionService.cs:35) take the request records; update replaces target, description and event types.RotateSecretAsync(IWebhookSubscriptionService.cs:41) issues a new secret while the previous one keeps signing for the configured grace period (doc, line 37).DisableAsync,EnableAsync, andDeleteAsync(IWebhookSubscriptionService.cs:47,:53,:59); delete is a soft delete and returns a bareResult.
- Why it's built this way: keeping the operations behind an Application port lets the API layer
stay a thin adapter (
[Rubric §3, Clean Architecture]), and theIsEnabledflag lets one controller base ship in every host and simply answer not-found where webhooks are off (ADR-142). - Where it's used: implemented by
WebhookSubscriptionService, registered scoped (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:82); consumed byWebhookSubscriptionsControllerBase, which resolves it optionally from the request services and treats it as absent unlessIsEnabledis true (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Webhooks/WebhookSubscriptionsControllerBase.cs:43-44).
IWebhookTargetValidator
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Subscriptions·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/IWebhookTargetValidator.cs:10· Level 3 · interface
- What it is: the port that decides whether a webhook target URL may be stored. One method,
Task<Result> ValidateAsync(Uri target, CancellationToken)(IWebhookTargetValidator.cs:16), which answers success orWebhooks.TargetNotAllowed(doc, line 15). - Depends on: the Result pattern (
MMCA.Common.Shared.Abstractions,IWebhookTargetValidator.cs:1);System.Uri. - Concept introduced, save-time SSRF feedback versus the connect-time guarantee.
[Rubric §11, Security]assesses defences against server-side request forgery, where a stored URL makes the server call into its own network. The interface doc states the policy and its limit (IWebhookTargetValidator.cs:5-9): https only, no local host, every address the host resolves to must be public (unless insecure targets are allowed in Development), and the connect-time check of the delivery client "stays authoritative". This validator is early feedback for the person registering the target; it cannot be the guarantee, because DNS can answer differently at delivery time. The connect-time half isWebhookConnectCallback. - Walkthrough: a one-method async port. It is async because the default
DnsWebhookTargetValidator(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/DnsWebhookTargetValidator.cs:20) resolves the host throughIWebhookDnsResolverbefore judging the addresses. - Why it's built this way: putting the check behind a port keeps DNS out of the Application layer
(
[Rubric §3, Clean Architecture]) and lets tests substitute a fixed answer ([Rubric §14, Testability]). See ADR-142 for why the policy is checked where the socket opens as well. - Where it's used: registered scoped
(
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:83); called byWebhookSubscriptionServiceon create and update (MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/WebhookSubscriptionService.cs:249-250).
OutputCacheEvictionRequested
MMCA.Common.Domain ·
MMCA.Common.Domain.IntegrationEvents·MMCA.Common.Domain/IntegrationEvents/OutputCacheEvictionRequested.cs:29· Level 3 · record class (public sealed)
- What it is: the framework's own integration event, a cross-service request to evict output-cache
entries carrying the given tags. It is published by the service that owns the data, through the
outbox like any other integration event, and consumed by every host that serves output-cached
responses built from that data
(
MMCA.Common.Domain/IntegrationEvents/OutputCacheEvictionRequested.cs:6-9). - Depends on:
BaseIntegrationEvent(Level 2), and through itIIntegrationEventandIDomainEvent;EventNameAttribute(Level 0). The only BCL type in its payload isIReadOnlyList<string>. - Concept introduced, a framework-shipped event contract, and why a per-host cache needs a
fan-out.
[Rubric §12, Performance & Scalability](cache correctness under scale-out),[Rubric §9, API & Contract Design](wire contracts and their versioning), and[Rubric §6, CQRS & Event-Driven]. The doc comment states the problem precisely (OutputCacheEvictionRequested.cs:10-15): ASP.NET Core's output cache is per host, becauseIOutputCacheStoreis a local store, so a write in the owning service leaves a stale cached response sitting in front of every OTHER replica and every other service until its TTL expires. Broadcasting the eviction turns a per-process concern into a fan-out one message wide. Note that this is a framework event, not an application one: the events fitness rule records that framework-shipped integration events are the framework's own contract, gated by its conventions and public API baseline, so consumer residency rules and frozen snapshots neither police nor churn on them (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Contracts/ArchitectureRules.Events.cs:300-307). - Walkthrough: the type carries one member and one attribute.
[EventName("Common.OutputCacheEvictionRequested.v1")](OutputCacheEvictionRequested.cs:28) pins the stable wire and storage identity, which is what the outbox writes and whatEventNameResolverreverse-resolves, so the CLR type can be renamed without orphaning rows or inbox keys.Tags(OutputCacheEvictionRequested.cs:37) is anIReadOnlyList<string>defaulted to[], holding the output-cache tags to evict exactly as the producing host spelled them in its[OutputCache(Tags = ...)]or policy registration. Defaulting rather than marking itrequiredis deliberate and documented (OutputCacheEvictionRequested.cs:31-36): a message that arrives without the field deserializes into a harmless no-op instead of faulting the consumer and dead-lettering.SchemaVersionis inherited at1fromBaseIntegrationEvent. - Why it's built this way: the doc calls it a frozen-contract candidate
(
OutputCacheEvictionRequested.cs:16-26). The wire shape is deliberately minimal, a tag list and nothing else, because every host that consumes it must be able to deserialize it forever. Any change is therefore a versioning decision (ADR-010): additive optional fields keepSchemaVersionat 1, while a rename, removal, or retype requires a new event type plus a registered upcaster (services.AddEventUpcaster<OutputCacheEvictionRequested, OutputCacheEvictionRequestedV2, ...>()) and aRegisterUpcastedIntegrationEventConsumer<OutputCacheEvictionRequested>()on every host still receiving the old contract until the queues drain (ADR-090). Riding the ordinary outbox path (ADR-003) means the eviction inherits the same at-least-once guarantee as any business event, and a duplicate eviction is harmless by nature, which is why this event needs no special idempotency handling. - Where it's used: consumed by
OutputCacheEvictionHandler(MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheEvictionHandler.cs:32), registered byAddOutputCacheEvictionHandler(MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheEvictionExtensions.cs:111); its broker consumer is wired by the named shorthandRegisterOutputCacheEvictionConsumeronIntegrationEventConsumerExtensions(MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumerExtensions.cs:158-160). It is published in ADC byBookmarkCacheEvictionProcessor(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Caching/BookmarkCacheEvictionProcessor.cs:71), which paces the evictions thatUserSessionBookmarkCacheEvictionHandleronly flags (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/UserSessionBookmarks/DomainEventHandlers/UserSessionBookmarkCacheEvictionHandler.cs:58).
IWebhookSubscriptionStore
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Subscriptions·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/IWebhookSubscriptionStore.cs:10· Level 5 · interface
- What it is: the persistence port for
WebhookSubscriptionrows, with four reads and three writes, every read filtered by tenant. - Depends on:
WebhookSubscription(Level 4,MMCA.Common.Domain.Webhooks,IWebhookSubscriptionStore.cs:1). - Concept introduced, an explicit tenant argument instead of an ambient filter.
[Rubric §11, Security]and[Rubric §8, Data Architecture]both look at how tenant isolation is enforced. Every read takesstring? tenantId, and the interface doc fixes the semantics (IWebhookSubscriptionStore.cs:5-9): reads filter by tenant, anulltenant matches only untenanted rows, and a soft-deleted row is never returned. Passing the tenant explicitly, rather than relying on the tenant-entity marker, is what lets webhooks work in a host that never resolves a tenant (ADR-142). - Walkthrough
ListAsync(IWebhookSubscriptionStore.cs:16) lists the tenant's subscriptions for the admin API;ListEnabledAsync(IWebhookSubscriptionStore.cs:22) lists only enabled ones, for the fan-out.FindAsync(IWebhookSubscriptionStore.cs:29) returns one row tracked for an update, ornull.CountAsync(IWebhookSubscriptionStore.cs:35) counts non-deleted rows, which backs the per-tenant limit.AddAsync(IWebhookSubscriptionStore.cs:41) adds and saves;SaveAsync(IWebhookSubscriptionStore.cs:47) saves an administrative change to a row fromFindAsync.RecordOutcomeAsync(IWebhookSubscriptionStore.cs:56) saves a delivery's last-outcome columns and swallows a concurrency conflict, because a concurrent admin change or another delivery outcome has already moved the row (doc,IWebhookSubscriptionStore.cs:49-52).[Rubric §29, Resilience & Business Continuity]: a lost last-outcome write is cosmetic, so it is not allowed to fail a delivery that already happened.
- Why it's built this way: separating
SaveAsyncfromRecordOutcomeAsyncgives the two writers different conflict policies, strict for an operator's change, best-effort for delivery bookkeeping. - Where it's used: implemented by
EFWebhookSubscriptionStore(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Webhooks/EFWebhookSubscriptionStore.cs:30), registered scoped (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:81). Consumed byWebhookSubscriptionService, byWebhookFanOutHandler<TEvent>throughListEnabledAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/WebhookFanOutHandler.cs:70-71), and byDeliverWebhookInternalCommandHandlerthroughFindAsyncandRecordOutcomeAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Delivery/DeliverWebhookInternalCommandHandler.cs:52,:69).WebhookRegistrationValidatorfails startup when delivery is registered without a store (MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/WebhookRegistrationValidator.cs:18-21), the fail-fast contract of ADR-070.
WebhookSubscriptionService
MMCA.Common.Application ·
MMCA.Common.Application.Webhooks.Subscriptions·MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/Subscriptions/WebhookSubscriptionService.cs:24· Level 6 · class (public sealed)
- What it is: the default
IWebhookSubscriptionService. It validates a subscription definition, enforces the per-tenant limit, checks the target, generates and protects the signing secret, and drives theWebhookSubscriptionaggregate's own methods for every change. - Depends on:
IWebhookSubscriptionStore,IWebhookTargetValidator,IWebhookSecretProtector,WebhookEventCatalog,ITenantContext,IOptions<WebhookSettings>, andTimeProvider, all through the primary constructor (WebhookSubscriptionService.cs:24-31); alsoWebhookSignatureandWebhookErrorCodes. - Concept, cheap checks before expensive ones, domain rules in the aggregate. The class doc
(
WebhookSubscriptionService.cs:10-16) lists the contract: caller's tenant only, event types are"*"or registered in the catalog, targets pass the validator, and a new secret is generated, stored only protected, and returned once.[Rubric §4, DDD]: the service owns cross-cutting checks (catalog, tenant limit, DNS) while the aggregate'sCreate,Update,RotateSecret,Disable,Enable, andDeleteown the entity invariants.[Rubric §11, Security]: the plaintext secret exists only in the returned response; the row receivessecretProtector.Protect(secret). - Walkthrough
IsEnabledmapssettings.Value.Enabled(WebhookSubscriptionService.cs:34);EventTypesmaps the catalog (WebhookSubscriptionService.cs:37).UtcNowreads the injectedTimeProvider(WebhookSubscriptionService.cs:39), so disable and rotation instants are testable ([Rubric §14, Testability]).ListAsync(WebhookSubscriptionService.cs:42) reads the tenant's rows and maps each throughToResponse(WebhookSubscriptionService.cs:179), which never copies a secret.CreateAsync(WebhookSubscriptionService.cs:50) runs in a fixed order. A missingeventTypesmember bindsnulland is treated as empty so the domain answersEventTypesRequired(WebhookSubscriptionService.cs:58-59).CheckDefinitionruns first (line 60), then the tenant count againstMaxSubscriptionsPerTenantwith aWebhooks.LimitReachedconflict (WebhookSubscriptionService.cs:66-73; default 25, range 1 to 500,MMCA.Common/Source/Core/MMCA.Common.Application/Webhooks/WebhookSettings.cs:66-67), then the DNS target check (line 75), so the network call runs last. The secret comes fromWebhookSignature.GenerateSecret()(line 81), the aggregate is built with the protected form (WebhookSubscriptionService.cs:82-87), saved (line 93), and returned with the plaintext once (line 94).UpdateAsync(WebhookSubscriptionService.cs:98) finds the caller's own row, re-runs the definition and target checks, callssubscription.Update(line 124) and saves (line 130). It does not re-check the limit, because an update does not add a row.RotateSecretAsync(WebhookSubscriptionService.cs:135) protects a fresh secret and hands the aggregate the previous-secret expiryUtcNow.AddHours(PreviousSecretGraceHours)(WebhookSubscriptionService.cs:144-146; default 24, range 0 to 168,WebhookSettings.cs:59-60).DisableAsyncandEnableAsync(WebhookSubscriptionService.cs:153-158) go through the sharedChangeAsynchelper (WebhookSubscriptionService.cs:194);DeleteAsync(WebhookSubscriptionService.cs:161) returns the aggregate's ownDelete()failure unchanged (line 169).FindOwnAsync(WebhookSubscriptionService.cs:211) passes the caller'sTenantIdto the store and also drops a soft-deleted row (WebhookSubscriptionService.cs:214), so every not-found case, including another tenant's id, collapses to the oneWebhooks.NotFounderror built atWebhookSubscriptionService.cs:191.CheckDefinition(WebhookSubscriptionService.cs:218) collects errors rather than stopping at the first: a URL that is blank or not absolute givesUrlInvalid(line 222), and every event type that is neitherWebhookSubscription.AllEventTypesnor in the catalog is reported, de-duplicated, in oneEventTypeUnknownerror (WebhookSubscriptionService.cs:231-244).ValidateTargetAsync(WebhookSubscriptionService.cs:249-250) builds the absoluteUrionly afterCheckDefinitionhas proved it parses.
- Why it's built this way: running the database count and the DNS lookup only after the pure checks keeps a malformed request from costing a query or a network call, and collapsing every ownership miss into one error keeps tenant boundaries opaque. ADR-142 covers the rotation window and the show-once secret.
- Where it's used: registered scoped as
IWebhookSubscriptionService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:82) and reached throughWebhookSubscriptionsControllerBase. - Caveats / not-in-source: the tenant limit is a count followed by an insert with no lock between
them (
WebhookSubscriptionService.cs:66and:93), so concurrent creates can exceed it; ADR-142 records it as a soft limit.
InProcessMessageBus
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging·MMCA.Common.Infrastructure/Messaging/InProcessMessageBus.cs:18· Level 3 · class (public sealed)
- What it is: the
IMessageBusimplementation for the modular-monolith and integration-test case. It dispatches integration events synchronously through the in-processIDomainEventDispatcher, and it is the default registration when no broker is configured (MMCA.Common.Infrastructure/Messaging/InProcessMessageBus.cs:7-10). - Depends on:
IDomainEventDispatcher(Level 1),IMessageBus(Level 2),IIntegrationEvent(Level 1). No externals at all. - Concept reinforced, same interface, different transport.
[Rubric §7, Microservices Readiness]: application code injectsIMessageBusand never learns whether the events leave the process. Swapping the registration from this class toBrokerMessageBusis the entire "go distributed" change for the publish path. - Walkthrough: both overloads (
InProcessMessageBus.cs:21andInProcessMessageBus.cs:28) null-guard and then forward straight todomainEventDispatcher.DispatchAsync([integrationEvent], ...)(InProcessMessageBus.cs:24) andDispatchAsync(integrationEvents, ...)(InProcessMessageBus.cs:31). Neither returns an awaited task; both return the dispatcher's task directly, so there is no extra state machine on this path. No outbox write happens here: the doc comment (InProcessMessageBus.cs:11-16) is explicit that this bus is meant to be invoked by theOutboxProcessorwhen draining already-persisted entries, or by application paths that have already taken responsibility for outbox persistence elsewhere. It is the in-process counterpart ofBrokerMessageBus, not a "persist and dispatch" bus. Code that wants persist-and-dispatch semantics usesIEventBusinstead (InProcessMessageBus.cs:15-16). - Why it's built this way: keeping the monolith path a single synchronous dispatcher call means
integration tests need no broker container and the common (monolith) deployment pays no broker
latency. When the outbox is enabled, the
OutboxProcessorstill supplies the at-least-once safety net around this bus, because the processor is what invokes it. - Where it's used: registered as the default scoped
IMessageBusinAddServices(MMCA.Common.Infrastructure/DependencyInjection.cs:409, with the rationale comment atDependencyInjection.cs:551-555), and therefore the bus resolved byOutboxProcessorin monolith mode (MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:278). It is replaced byBrokerMessageBusin broker-mode service hosts (MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:128).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
IntegrationEventConsumerExtensions
MMCA.Common.Infrastructure |
MMCA.Common.Infrastructure.Messaging.Consumers|MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumerExtensions.cs:11| Level 4 | class (public static)
- What it is: a C#
extension(IBrokerConsumerBuilder)block (MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumerExtensions.cs:13) that adds one named registration shorthand,RegisterOutputCacheEvictionConsumer(), toIBrokerConsumerBuilder, the builder theconfigureConsumerscallback ofAddBrokerMessagingreceives (class doc,IntegrationEventConsumerExtensions.cs:6-10). The genericRegisterIntegrationEventConsumer<TEvent>()andRegisterUpcastedIntegrationEventConsumer<TEvent>()are members of that interface itself (MMCA.Common.Infrastructure/Messaging/Broker/IBrokerConsumerBuilder.cs:26,IBrokerConsumerBuilder.cs:40), not of this class. - Depends on:
IBrokerConsumerBuilder,OutputCacheEvictionRequested. No external messaging library. - Concept reinforced,
extension(T)members as registration sugar. Theextension(T)syntax is the workspace-wide DI-registration idiom (see the primer's conventions section).[Rubric S7, Microservices Readiness]: a host declares what it consumes by event type and never names the consumer class the receive pipeline resolves, so the registration call site stays decoupled from the concrete consumer. - Walkthrough:
RegisterOutputCacheEvictionConsumer()(IntegrationEventConsumerExtensions.cs:28) null-guards the builder (IntegrationEventConsumerExtensions.cs:30) and returnsbuilder.RegisterIntegrationEventConsumer<OutputCacheEvictionRequested>()(IntegrationEventConsumerExtensions.cs:32), so it chains like the interface members. It exists purely so the wiring reads as an intention rather than a type argument, and its doc pairs it withservices.AddOutputCacheEvictionHandler()from MMCA.Common.API: subscribing without the handler is harmless but pointless, because the messages complete with a "no handler registered" log and nothing is evicted (IntegrationEventConsumerExtensions.cs:15-26). - Why it's built this way: there is one queue per host and no per-consumer endpoint configuration,
and a consumer that exhausts its retries is dead-lettered, logged and counted (
broker.fault.count) by the framework's receive pipeline, so no separate fault consumer and no fault opt-out parameter exist to register (IBrokerConsumerBuilder.cs:9-14). That leaves this class with nothing to hide but a type argument. The transport-boundary fitness rule keeps Application and Domain off any messaging library (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Layering/MicroserviceExtractionTests.cs:7; ADR-007, ADR-008). - Where it's used: inside a host's
configureConsumerscallback (MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:65, invoked atDependencyInjection.Messaging.cs:92); the ADC Conference service passesConferenceBrokerConsumers.Register(MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:363) and its comments nameRegisterOutputCacheEvictionConsumeras the broker half of output-cache eviction (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:257-258).
[Rubric S10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
WebhookSubscription
MMCA.Common.Domain |
MMCA.Common.Domain.Webhooks|MMCA.Common.Domain/Webhooks/WebhookSubscription.cs:38| Level 4 | class (public sealed)
- What it is: one outbound webhook subscription, an auditable entity keyed by
Guidthat names a target URL receiving a signed POST for every published integration event whose webhook type it lists, or every type throughAllEventTypes = "*"(class doc,MMCA.Common.Domain/Webhooks/WebhookSubscription.cs:7-9; constant,WebhookSubscription.cs:62). - Depends on:
AuditableBaseEntity<TIdentifierType>(WebhookSubscription.cs:38),ResultandErrorfor the factory and update; BCLUrifor URL validation. - Concept reinforced, the entity factory returns
Result<T>and guards its own invariants. The Result pattern is taught in the primer.[Rubric S4, DDD]assesses whether invariants live on the entity: here every property has a private setter (WebhookSubscription.cs:71-101), the constructor is private (WebhookSubscription.cs:66), and bothCreateandUpdaterun the sameValidateDefinitionso a subscription can never hold an invalid URL or event list.[Rubric S11, Security]: the signing secret is only ever held protected (ProtectedSecret,WebhookSubscription.cs:83); the plaintext is returned once, at create or rotate (class doc,WebhookSubscription.cs:15-19). - Walkthrough
- Column widths and limits as public constants (
WebhookSubscription.cs:41-59):UrlMaxLength2048,DescriptionMaxLength200,EventTypesMaxLength2048,MaxEventTypes20,ProtectedSecretMaxLength1024,TenantIdMaxLength64,LastFailureMaxLength500. The EF mapping reads these rather than repeating the numbers (seeWebhookSubscriptionModelBuilderExtensions). Create(url, description, eventTypes, tenantId, protectedSecret)(WebhookSubscription.cs:110) collects the definition errors (WebhookSubscription.cs:117), addsWebhooks.SecretRequiredfor a blank secret (WebhookSubscription.cs:118-122), returns every error at once (WebhookSubscription.cs:124-127), and otherwise builds the entity withId = Guid.NewGuid()(WebhookSubscription.cs:129-137).Update(url, description, eventTypes)(WebhookSubscription.cs:145) re-validates and replaces only the URL, description and event types; a failure leaves the subscription unchanged, and secrets and outcome columns are kept.ValidateDefinition(WebhookSubscription.cs:221):Webhooks.UrlInvalidunlessIsValidUrlholds (WebhookSubscription.cs:231-238), which demands an absolutehttpsorhttpURL of at most 2048 characters with no user info and no fragment (WebhookSubscription.cs:273-281); the description is trimmed, blank becomingnull, and over 200 characters yieldsWebhooks.DescriptionTooLong(WebhookSubscription.cs:240-245); an empty or blank-containing event list yieldsWebhooks.EventTypesRequired(WebhookSubscription.cs:248-253); the types are trimmed, de-duplicated and ordinal-sorted before joining with,(WebhookSubscription.cs:255-260), and more than 20 types or a joined string over 2048 characters yieldsWebhooks.TooManyEventTypes(WebhookSubscription.cs:262-267). The normalization makes the stored column canonical, so two subscriptions listing the same types store the same string.- Reads:
IsEnabled()isDisabledOn is null(WebhookSubscription.cs:161);GetEventTypes()splits the column (WebhookSubscription.cs:165-166);Subscribes(eventType)matches the type or"*"ordinally (WebhookSubscription.cs:171-175). - Secret rotation:
RotateSecretmoves the current secret toPreviousProtectedSecret, records its expiry and installs the new one (WebhookSubscription.cs:183-190);GetSigningSecrets(utcNow)returns the current secret first, then the previous one whileutcNowis before its expiry (WebhookSubscription.cs:195-198), so a receiver can switch without dropping deliveries. - State and outcome:
Disablekeeps the first disable instant (DisabledOn ??= utcNow,WebhookSubscription.cs:202),Enableclears it (WebhookSubscription.cs:205),RecordDeliveredstampsLastDeliveredOn(WebhookSubscription.cs:209), andRecordFailedstampsLastFailedOnand truncates the reason to 500 characters (WebhookSubscription.cs:214-219).
- Column widths and limits as public constants (
- Why it's built this way: the table is opt-in, mapped only where a host calls
AddWebhookswithWebhooks:Enabled, so a host that never opts in builds an unchanged model (class doc,WebhookSubscription.cs:10-14).TenantIdis a plain column stamped at create rather thanITenantEntity, and the store filters it explicitly,nullmatching onlynull(class doc,WebhookSubscription.cs:20-23).Urland the comma-joinedEventTypesstay strings by design; the three suppressions say why (WebhookSubscription.cs:25-36): the URL is untrusted input validated as text and stored verbatim, andEventTypesis the mapped column whileGetEventTypes()is its parsed view. See ADR-142. - Where it's used: persisted by
EFWebhookSubscriptionStorebehindIWebhookSubscriptionStore, managed byWebhookSubscriptionService, and read on delivery byDeliverWebhookInternalCommandHandler.
WebhookSubscriptionModelBuilderExtensions
MMCA.Common.Infrastructure |
MMCA.Common.Infrastructure.Persistence.Webhooks|MMCA.Common.Infrastructure/Persistence/Webhooks/WebhookSubscriptionModelBuilderExtensions.cs:17| Level 5 | class (public static)
- What it is: the EF Core mapping for
WebhookSubscription, exposed as oneModelBuilderextension method,ApplyWebhookSubscriptionConfiguration(MMCA.Common.Infrastructure/Persistence/Webhooks/WebhookSubscriptionModelBuilderExtensions.cs:33). - Depends on:
WebhookSubscriptionfor its width constants; externally EF Core'sModelBuilder. - Concept: the opt-in table mapping. It is applied by
ApplicationDbContextonly to the one context whose sourceWebhooks:DataSourceNamenames and only whileWebhooks:Enabledis true, so a host that never opts in keeps a byte-identical model (class doc,WebhookSubscriptionModelBuilderExtensions.cs:11-16; the call is made by the internal model contributorWebhookSubscriptionModelContributor, whichAddWebhooksregisters and whoseAppliesTochecks both settings,WebhookSubscriptionModelBuilderExtensions.cs:74-86; the context keeps only the contributors whoseAppliesTopasses and runs them while building the model,MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:550-554,MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:675-682).[Rubric S8, Data Architecture]: an optional feature adds no table, no migration and no model-cache churn to hosts that do not use it. - Walkthrough: the public constants
TableName = "WebhookSubscriptions"andTenantIndexName = "IX_WebhookSubscriptions_TenantId_IsDeleted"(WebhookSubscriptionModelBuilderExtensions.cs:20,WebhookSubscriptionModelBuilderExtensions.cs:23). The method null-guards (WebhookSubscriptionModelBuilderExtensions.cs:35), maps the table underschema, defaultdbo(WebhookSubscriptionModelBuilderExtensions.cs:33,WebhookSubscriptionModelBuilderExtensions.cs:39), keys onIdwithValueGeneratedNever()because the factory assigns theGuid(WebhookSubscriptionModelBuilderExtensions.cs:40-41), sets every column width from the entity's constants, withEventTypesandTenantIdnon-Unicode (WebhookSubscriptionModelBuilderExtensions.cs:43-53), and adds the composite(TenantId, IsDeleted)index every tenant-filtered read uses (WebhookSubscriptionModelBuilderExtensions.cs:55-56). It returns the builder for chaining (WebhookSubscriptionModelBuilderExtensions.cs:59). - Why it's built this way: the doc asks for it to run BEFORE the soft-delete, tenant and
concurrency-token passes, so the subscription is treated like any other auditable entity
(
WebhookSubscriptionModelBuilderExtensions.cs:25-29), which is also what givesEFWebhookSubscriptionStoreits soft-delete filter and the row version its concurrency catch relies on. - Where it's used:
ApplicationDbContext(ApplicationDbContext.cs:551); exercised byWebhookSubscriptionModelGateTestsand the SQL ServerWebhookSubscriptionSqlServerTests.
WebhookSubscriptionsControllerBase
MMCA.Common.API |
MMCA.Common.API.Controllers.Webhooks|MMCA.Common.API/Controllers/Webhooks/WebhookSubscriptionsControllerBase.cs:40| Level 6 | class (public abstract)
- What it is: the abstract base controller for the outbound webhook administration endpoints: list,
list the publishable event types, create, update, rotate the secret, disable, enable and delete, each
scoped to the caller's tenant (class doc,
MMCA.Common.API/Controllers/Webhooks/WebhookSubscriptionsControllerBase.cs:12-16). A derived controller supplies only the route and API version (WebhookSubscriptionsControllerBase.cs:19-25). - Depends on:
ApiControllerBase(WebhookSubscriptionsControllerBase.cs:40),IWebhookSubscriptionService,AdministrationPermissionsthrough[HasPermission](WebhookSubscriptionsControllerBase.cs:39),IdempotentAttributeandNonIdempotentAttribute, and the request and response recordsCreateWebhookSubscriptionRequest,UpdateWebhookSubscriptionRequest,WebhookSubscriptionResponseandWebhookSubscriptionSecretResponse. - Concept introduced, "off means no routes". Every action answers 404 unless the host called
AddWebhooksAND setWebhooks:Enabled(class doc,WebhookSubscriptionsControllerBase.cs:27-30). The service is therefore resolved per action fromHttpContext.RequestServicesrather than injected, since a host withoutAddWebhookshas none to inject; the privateEnabledWebhooksproperty returns it only whenIsEnabledis true (WebhookSubscriptionsControllerBase.cs:43-44).[Rubric S11, Security]: a disabled feature is indistinguishable from an absent one, and the whole controller sits behindManageWebhooks(WebhookSubscriptionsControllerBase.cs:39).[Rubric S9, API & Contract Design]: the class doc lists the refusal codes a client must expect, 400 for the validation codes, 404Webhooks.NotFound(also for another tenant's id) and 409Webhooks.LimitReached(WebhookSubscriptionsControllerBase.cs:32-37). - Walkthrough: every action follows one shape: return
NotFound()whenEnabledWebhooksis null, call the service, and map a failure throughHandleFailureor the value throughOk.GetAllAsynconGET(WebhookSubscriptionsControllerBase.cs:49,WebhookSubscriptionsControllerBase.cs:54) lists subscriptions, disabled ones included, never their secrets;GetEventTypesonGET event-types(WebhookSubscriptionsControllerBase.cs:67,WebhookSubscriptionsControllerBase.cs:72-73) is synchronous and returns the service'sEventTypes.CreateAsynconPOST(WebhookSubscriptionsControllerBase.cs:79,WebhookSubscriptionsControllerBase.cs:87) andRotateSecretAsynconPOST {id}/rotate-secret(WebhookSubscriptionsControllerBase.cs:134,WebhookSubscriptionsControllerBase.cs:140) are marked[NonIdempotent]because the response carries the only copy of the secret (WebhookSubscriptionsControllerBase.cs:80,WebhookSubscriptionsControllerBase.cs:135). After a rotation the previous secret keeps signing forWebhooks:PreviousSecretGraceHours(WebhookSubscriptionsControllerBase.cs:127-130).UpdateAsynconPUT {id}(WebhookSubscriptionsControllerBase.cs:106,WebhookSubscriptionsControllerBase.cs:112) replaces URL, description and event types.DisableAsyncandEnableAsynconPOST {id}/disableandPOST {id}/enableare[Idempotent](WebhookSubscriptionsControllerBase.cs:155-161,WebhookSubscriptionsControllerBase.cs:176-182).DeleteAsynconDELETE {id}(WebhookSubscriptionsControllerBase.cs:197,WebhookSubscriptionsControllerBase.cs:202) soft-deletes and returnsNoContent()(WebhookSubscriptionsControllerBase.cs:210); deliveries already queued complete without sending.- Every action is
public virtual, so a derived controller can override one without copying the rest.
- Why it's built this way: the base-controller-plus-thin-derived shape lets each host mount the endpoints under its own route and version while Common owns the behavior; see ADR-142.
- Where it's used: exercised by
WebhookSubscriptionsControllerTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Webhooks/WebhookSubscriptionsControllerTests.cs). - Caveats / not-in-source: no derived controller exists in
MMCA.ADC/Source; whether Store or Helpdesk mounts one is not determinable from the sources checked for this section.
BrokerMessageBus
MMCA.Common.Infrastructure |
MMCA.Common.Infrastructure.Messaging|MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs:46| Level 9 | class (public sealed)
- What it is: the
IMessageBusimplementation that publishes integration events to the brokerMessageBus:Providerselects (RabbitMQ and PostgreSQL built in; an adapter such as MMCA.Common.Azure or MMCA.Common.Aws registers its own transport) through the transport'sIBrokerPublisher. Extracted microservices use it in place ofInProcessMessageBus(MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs:14-18). - Depends on:
IMessageBus(Level 2),IIntegrationEvent(Level 1),IBrokerPublisherandBrokerTopology, taken through the primary constructor along with three optional context accessors,ICurrentUserService?,ITenantContext?andICorrelationContext?, each defaulted tonull(BrokerMessageBus.cs:46-51). It also usesBrokerHeaders,BrokerWire,OutgoingBrokerMessageandMessageHeaders; externallySystem.Text.JsonandSystem.Diagnostics.Activity. - Concept introduced, the transport kept at the edge.
[Rubric S7, Microservices Readiness]assesses whether a module can be lifted out of the monolith without rewriting application code, and[Rubric S6, CQRS & Event-Driven]assesses at-least-once delivery of integration events. TheIMessageBusinterface is defined up inMMCA.Common.Application, andApplication,Domain, andSharedmust never reference a messaging library directly, which the transport-boundary fitness rule enforces (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Layering/MicroserviceExtractionTests.cs:7).BrokerMessageBuslives in Infrastructure and talks only to the framework's ownIBrokerPublisher, so the wire format, topic naming and header set are owned by Common and each transport adapter only moves bytes. - Concept introduced, everything a consumer needs travels as headers. The doc comment
(
BrokerMessageBus.cs:27-35) lists them: theBrokerHeaderstransport headers (event name, message id, content type), the W3Ctraceparent/tracestateof a Producer span on theMMCA.Common.Messagingsource, and the request context asMessageHeadersorigin headers (who raised the event, their roles, the tenant, the correlation id), read back on the other side byIntegrationEventConsumer<TEvent>. The outbox processor restores each row's captured context onto this bus's scope before it publishes, so the headers describe the original request rather than the background poll.[Rubric S29, Resilience & Business Continuity]: this is what lets a request's identity, tenant and roles survive the hop between processes. - Walkthrough
PublishAsync(IIntegrationEvent, CancellationToken)(BrokerMessageBus.cs:54): null-guards (BrokerMessageBus.cs:56), then derives everything from the runtime type, notIIntegrationEvent, because the topic, the wire name and the body all describe the concrete class consumers subscribe to (comment,BrokerMessageBus.cs:58-59):eventType, the wire name fromBrokerNaming.EventName, the topic fromtopology.TopicFor, and theMessageId(BrokerMessageBus.cs:60-63).- It calls
CaptureHeaders()(BrokerMessageBus.cs:65) and adds the event-name, message-id ("D"format, invariant culture) and JSON content-type headers (BrokerMessageBus.cs:66-68). - It starts a Producer activity named
"{topic} publish"onBrokerWire.ActivitySourceand, when a listener created one, tags it with the messaging system, operationsend, destination and message id (BrokerMessageBus.cs:70-77).InjectTraceContext(activity ?? Activity.Current, headers)(BrokerMessageBus.cs:81) falls back to the ambient activity (the outbox row's), so a publish with no listener still carries the trace (comment,BrokerMessageBus.cs:79-80),[Rubric S13, Observability & Operability]. - It serializes the event as its runtime type with
BrokerWire.JsonOptions(BrokerMessageBus.cs:83) and hands anOutgoingBrokerMessage(topic, eventName, messageId, body, headers)topublisher.PublishAsync(BrokerMessageBus.cs:85-87). PublishAsync(IEnumerable<IIntegrationEvent>, CancellationToken)(BrokerMessageBus.cs:91): null-guards (BrokerMessageBus.cs:93), then awaits each single publish in turn (BrokerMessageBus.cs:95-98). There is no transactional grouping across the batch here; batch atomicity is the outbox's concern, not the publisher's.InjectTraceContext(BrokerMessageBus.cs:106-118) writestraceparentonly for a W3C id, andtracestateonly when non-empty: a hierarchical id has notraceparentform (doc,BrokerMessageBus.cs:101-105).CaptureHeaders()(BrokerMessageBus.cs:126-145) builds an ordinal-keyed dictionary (BrokerMessageBus.cs:128) holding only the values actually present, each routed throughAddIfPresent(BrokerMessageBus.cs:148-154):MessageHeaders.TenantId(BrokerMessageBus.cs:130),MessageHeaders.UserIdformatted with the invariant culture (BrokerMessageBus.cs:131-134), then, when a current-user service is present,MessageHeaders.UserRolesfromContext.AmbientOrigin.FlattenRolesandMessageHeaders.UserPermissionsfromContext.AmbientOrigin.FlattenPermissions(BrokerMessageBus.cs:138-139), and finallyMessageHeaders.CorrelationId(BrokerMessageBus.cs:142). The doc (BrokerMessageBus.cs:120-125) explains why absence is not written as an empty header: an absent header reads as "the publisher had nothing to say", and an empty one would turn a non-answer into a false answer.
- Why it's built this way: this bus does not itself write to the outbox. Transactional-outbox
semantics are preserved by the
OutboxProcessor: events are persisted toOutboxMessagein the same database transaction as the aggregate change, then the processor drains them by calling this bus (ADR-003; doc comment,BrokerMessageBus.cs:19-25). KeepingBrokerMessageBusa thin publish adapter, with no outbox knowledge, is what lets one set of outbox machinery serve both monolith and broker modes (ADR-007, ADR-008). The context accessors default tonull, so a host or test that constructs this bus without them publishes no identity headers (parameter doc,BrokerMessageBus.cs:40-43). - Where it's used: swapped in for the default in-process registration by
AddBrokerMessagingthroughservices.Replace(MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:128), which returns early without touching the container whenMessageBus:Provideris in-process (MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:72-75; seeMessageBusSettings). It is driven at runtime by theOutboxProcessor, which resolvesIMessageBusper cycle (MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:278) and calls it inside a resilience pipeline that wraps only the broker hop (OutboxProcessor.cs:590-600).
[Rubric S10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
WebhookSubscriptionModelContributor
MMCA.Common.Infrastructure |
MMCA.Common.Infrastructure.Persistence.Webhooks|MMCA.Common.Infrastructure/Persistence/Webhooks/WebhookSubscriptionModelBuilderExtensions.cs:74| Level 9 | class (internal sealed)
- What it is: the
IModelContributorthatAddWebhooksregisters to put theWebhookSubscriptionstable into a model, and only into the right one (class doc,MMCA.Common.Infrastructure/Persistence/Webhooks/WebhookSubscriptionModelBuilderExtensions.cs:63-67). It lives in the same file asWebhookSubscriptionModelBuilderExtensions, whose mapping it applies. - Depends on:
IModelContributor,ModelContributorPhase,PhysicalDataSource,IOptions<WebhookSettings>through the primary constructor (WebhookSubscriptionModelBuilderExtensions.cs:74), andWebhookSubscriptionModelBuilderExtensions; externally EF Core'sModelBuilder. - Concept, an opt-in table gated per data source. The table belongs in a model only while
Webhooks:Enabledis true and the context targets the sourceWebhooks:DataSourceNamenames, so a host that never opts in sees no migration (class doc,WebhookSubscriptionModelBuilderExtensions.cs:64-67; ADR-148 per that doc).[Rubric S8, Data Architecture]: an optional feature adds no table and no model churn to a host or a database that does not use it. - Walkthrough: three members.
PhasereturnsModelContributorPhase.BeforeEntityPasses(WebhookSubscriptionModelBuilderExtensions.cs:77), because a subscription is an auditable entity and the soft-delete filter and concurrency token passes must see it (class doc,WebhookSubscriptionModelBuilderExtensions.cs:68-71).AppliesTo(PhysicalDataSource)is true only whensettings.Value.Enabledand the source'sKey.Nameequalssettings.Value.DataSourceNameunder an ordinal comparison (WebhookSubscriptionModelBuilderExtensions.cs:80-82).Configure(ModelBuilder, DataSource)callsmodelBuilder.ApplyWebhookSubscriptionConfiguration()and ignores the engine (WebhookSubscriptionModelBuilderExtensions.cs:85-86).
- Why it's built this way: expressing the gate as a contributor keeps the decision beside the
mapping and the settings it reads, so turning the table on for a host is one
AddWebhooksregistration (WebhookServiceCollectionExtensions.cs:79) rather than an edit to a context class. - Where it's used: registered as a singleton
IModelContributorwithTryAddEnumerablebyAddWebhooks(MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:79); added at design time when the design options enable webhooks (MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:208); exercised byWebhookSubscriptionModelGateTests,ModelCacheKeyGateTestsandDependencyInjectionModelContributorTests.
BrokerEventBus
MMCA.Common.Infrastructure |
MMCA.Common.Infrastructure.Messaging|MMCA.Common.Infrastructure/Messaging/BrokerEventBus.cs:32| Level 10 | class (public sealed)
- What it is: the
IEventBusimplementation for microservice (broker) deployments. It persists integration events to the outbox and signals theOutboxProcessorto drain them, but it deliberately does not dispatch in-process, because the consumers live in other processes (MMCA.Common.Infrastructure/Messaging/BrokerEventBus.cs:13-18). - Depends on:
IEventBus(Level 2),IDbContextFactory,IOutboxSignal,IDataSourceResolver, andIOptions<OutboxSettings>, all through the primary constructor (BrokerEventBus.cs:32-36); it producesOutboxMessagerows fromIIntegrationEventinstances, and inside an open transaction it defers its wake-up through the internalDeferUntilCommithook ofDomainEventSaveChangesInterceptor(BrokerEventBus.cs:99). - Concept introduced, the broker half of dual-mode event publishing.
[Rubric S6, CQRS & Event-Driven],[Rubric S8, Data Architecture](the transactional outbox), and[Rubric S29, Resilience & Business Continuity]. The doc comment (BrokerEventBus.cs:19-30) is explicit that this class differs fromInProcessEventBusonly in whether it dispatches synchronously after persistence: in-process mode writes the outbox, dispatches, then marks processed (BrokerEventBus.cs:24), while broker mode writes the outbox, signals the processor, and returns (BrokerEventBus.cs:25). In broker mode an in-process dispatch would be incorrect, since no consumer is present locally, so the processor's broker-publish path is the only correct delivery channel (BrokerEventBus.cs:27-29). - Walkthrough: both public overloads funnel into the private
PublishBatchAsync, and neither isasync: each returns the batch task directly. The single-event overload (BrokerEventBus.cs:39) null-guards and returnsPublishBatchAsyncover a one-element array (BrokerEventBus.cs:43); the batch overload (BrokerEventBus.cs:47) null-guards, coerces the sequence to an array exactly once (BrokerEventBus.cs:51), and returnsTask.CompletedTaskearly when it is empty (BrokerEventBus.cs:52-53).PublishBatchAsync(BrokerEventBus.cs:66-108) resolves the outbox's logical data source throughIDataSourceResolver(BrokerEventBus.cs:68) and gets its context (BrokerEventBus.cs:69). The outbox gate is the context's engine capability,!context.Engine.Capabilities.IsRelational(BrokerEventBus.cs:71): when the resolved engine is not relational (Cosmos for example) it throws anInvalidOperationExceptionnaming the misconfiguredOutbox:DataSourceandOutbox:DatabaseName, and tells the operator to configure SQL Server, PostgreSQL or SQLite (or fall back toInProcessEventBus), rather than silently dropping the events (BrokerEventBus.cs:76-77, with the rationale atBrokerEventBus.cs:73-75). Otherwise it reads the scope's ambientOutboxOriginonce for the whole batch,context.CurrentOutboxOrigin(BrokerEventBus.cs:80-82), because the batch is one caller's work so one origin describes all of it, then builds oneOutboxMessageper event throughFromDomainEvent(integrationEvent, origin)(BrokerEventBus.cs:84-86),AddRanges them (BrokerEventBus.cs:89; EF's synchronousAddRangeis intentional here, as the comment atBrokerEventBus.cs:88notes, sinceAddRangeAsyncexists only for special value generators), saves once (BrokerEventBus.cs:90), then wakes the processor so the broker publish does not wait for the next poll. How it wakes depends on whether the context has an open transaction (anITransactionalcommand),context.Database.CurrentTransaction is not null(BrokerEventBus.cs:97): inside one the new rows are not visible to the processor until the commit, so theoutboxSignal.Signal()call is queued onDomainEventSaveChangesInterceptor.DeferUntilCommit(BrokerEventBus.cs:99-103), the same post-commit hook the save interceptor uses, which runs it after a successful commit and drops it on rollback (comment,BrokerEventBus.cs:92-96; hook doc,MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:177-188), and the method returns (BrokerEventBus.cs:104). With no transaction open it callsoutboxSignal.Signal()directly (BrokerEventBus.cs:107). Either way the rows themselves are already saved: the deferral only stops a wake-up being spent on a query that cannot yet see them. - Why it's built this way: the one-save shape is the load-bearing detail, and the method's own doc
explains it (
BrokerEventBus.cs:58-65). A per-event save-and-signal loop cost a round trip per event and, worse, was not atomic: a failure partway through a batch left the earlier events committed and the rest unwritten, so a caller that saw a failure could not tell what had already been published. One save makes the batch all-or-nothing, and one signal is all the processor can consume anyway, becauseIOutboxSignalcaps at a single permit and discards the surplus (seeOutboxSignal). Beyond that, it enforces the transactional-outbox invariant of ADR-003 (persist atomically, publish later), while ADR-007 and ADR-008 motivate keeping delivery entirely on the asynchronous broker path once a module is extracted. Throwing on a non-outbox data source makes the "broker mode needs an outbox-enabled store" constraint fail loudly at the first publish rather than lose events quietly, and the same constraint is checked once at startup as well:EnsureOutboxAvailableForProviderrejectsMessageBus:EnableOutbox=falseunder a broker transport with a message that names this class as the reason (MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:80,DependencyInjection.Messaging.cs:251,DependencyInjection.Messaging.cs:263-268). - Where it's used: registered as the scoped
IEventBuswhenAddBrokerMessagingruns, replacingInProcessEventBus(MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:134, with the explanatory comment atDependencyInjection.Messaging.cs:130-133). EveryIEventBusinjection in application code resolves this implementation in broker mode.
[Rubric S10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
InProcessEventBus
MMCA.Common.Infrastructure |
MMCA.Common.Infrastructure.Messaging|MMCA.Common.Infrastructure/Messaging/InProcessEventBus.cs:51| Level 10 | class (public sealed partial)
- What it is: the default
IEventBusimplementation. When the outbox is on it persists integration events to the outbox under a lease, dispatches them in-process one event at a time throughIDomainEventDispatcher, and settles each row on its event's outcome; when the outbox is off it dispatches only (MMCA.Common.Infrastructure/Messaging/InProcessEventBus.cs:15-23). Dispatch is synchronous, or, when the call runs inside an open transaction (anITransactionalcommand), right after that transaction commits and never if it rolls back (InProcessEventBus.cs:17-19). - Depends on:
IEventBus(Level 2),IDbContextFactory,IDomainEventDispatcher,IDataSourceResolver,IOptions<OutboxSettings>, a requiredTimeProviderresolved from whateverAddServicesregisters it as, anILogger<InProcessEventBus>, and an optionalIOptions<MessageBusSettings>, all through the primary constructor (InProcessEventBus.cs:51-58); it also usesOutboxMessage,InProcessDispatch,OutboxFinalizer, and the internalDeferUntilCommithook ofDomainEventSaveChangesInterceptor(InProcessEventBus.cs:121,InProcessEventBus.cs:154). - Concept, the monolith half of dual-mode event publishing, and an explicit outbox opt-out.
[Rubric S6, CQRS & Event-Driven]and[Rubric S8, Data Architecture]: the "persist to outbox in the same save, then dispatch, then settle" sequence is the dual dispatch of ADR-003. The rows are saved under a lease so no replica'sOutboxProcessordelivers them while this call is still dispatching; afterward delivered rows are marked processed in one set-based update and the rest have their lease released, so the processor's next poll retries them (method doc,InProcessEventBus.cs:84-91). The bus does not wake the processor for those rows: retrying a failed handler is not latency-critical, and the poll interval bounds the wait (InProcessEventBus.cs:89-91). A handler failure does not surface to the caller, exactly as it does not from the save that raised a local event; only a failure to persist the rows still throws (class doc,InProcessEventBus.cs:25-33). The second half of the method doc (InProcessEventBus.cs:92-97) is the part to read carefully: with the outbox turned off (MessageBus:EnableOutboxresolving to false: set to false, or left unset, which is the in-process default) the direct-dispatch branch is taken instead, which means no rows, no save, and no processor to retry. That is the in-process default:MessageBusSettings.IsOutboxEnabledresolves an unsetEnableOutboxfrom the provider, ON for a broker and OFF forInProcess(MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:186,MessageBusSettings.cs:151), on the reasoning that a single-process application dispatches every event in the same process anyway. A monolith that wants at-least-once delivery across a crash setsMessageBus:EnableOutbox=trueexplicitly (MessageBusSettings.cs:160).[Rubric S31, Cost/FinOps]is the quiet counterpart here: store-and-forward that nothing needs still costs a table, a save, and a poller. The third paragraph of the method doc (InProcessEventBus.cs:98-103) adds the transactional rule: when the outbox target's context has an open transaction, both branches defer the dispatch until that transaction commits (the outbox branch still writes its rows now, inside the transaction), exactly as the save interceptor defers a transactional save's events, so handlers only ever see committed state and a rollback runs none of them. - Walkthrough
- Two readonly fields resolve the constructor's clock and posture:
_timeProvideris assignedtimeProviderdirectly with no fallback (InProcessEventBus.cs:60), so the caller (AddServices, or a test constructing this type directly) must supply one;_outboxEnabledfalls back totruewhen noMessageBusSettingsoptions are registered (InProcessEventBus.cs:62). The outbox default is documented as a compatibility choice (InProcessEventBus.cs:48-50): a host that resolves noMessageBusSettingsoptions keeps the outbox path, so the opt-out is only ever taken because configuration asked for it. - Both public overloads funnel into the private
PublishBatchAsync(InProcessEventBus.cs:105) and are non-async, returning its task directly: the single overload wraps one event (InProcessEventBus.cs:69), and the batch overload coerces the sequence to an array once and returnsTask.CompletedTaskearly when empty (InProcessEventBus.cs:77-79). PublishBatchAsyncresolves the outbox target (InProcessEventBus.cs:107) and its context (InProcessEventBus.cs:108), then records once whether that context has an open transaction,deferToCommit = context.Database.CurrentTransaction is not null(InProcessEventBus.cs:115). The comment gives the reason (InProcessEventBus.cs:110-114): a rollback would leave the handlers' side effects behind for state that never committed, and a handler that opens its own scope could not even see the uncommitted rows. If the resolved engine is not relational or the outbox is off,!context.Engine.Capabilities.IsRelational || !_outboxEnabled(InProcessEventBus.cs:117), it dispatches throughInProcessDispatch.DispatchUnbackedAsyncwith no outbox persistence: underdeferToCommitthat call is queued onDomainEventSaveChangesInterceptor.DeferUntilCommitand the method returns (InProcessEventBus.cs:119-124), otherwise it runs now and returns (InProcessEventBus.cs:126-127); nothing can retry an event on that path, so a failing event is logged at Error and the next one runs (class doc,InProcessEventBus.cs:30-32).- Otherwise it reads the scope's ambient
OutboxOriginonce for the whole batch,context.CurrentOutboxOrigin(InProcessEventBus.cs:130-132), because the batch is one caller's work so one origin describes all of it, mints one lease token and a lease expiry ofOutboxSettings.LeaseSecondsfrom now (InProcessEventBus.cs:133-134; default 300,MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxSettings.cs:100), then builds oneOutboxMessageper event throughFromDomainEvent(integrationEvent, origin)stamped withLockedUntilandLockToken(InProcessEventBus.cs:136-143),AddRanges them (InProcessEventBus.cs:146, synchronously by intent, as the comment atInProcessEventBus.cs:145notes), and saves data plus outbox in one call (InProcessEventBus.cs:147). UnderdeferToCommitit queuesDispatchAndSettleAsynconDeferUntilCommitand returns (InProcessEventBus.cs:149-157): the rows are written inside the transaction and commit or roll back with the caller's change, and their lease keeps every processor off them until the deferred dispatch settles them, or until it expires if the flush never runs (comment,InProcessEventBus.cs:151-153). Otherwise it hands the saved batch toDispatchAndSettleAsyncat once (InProcessEventBus.cs:159). DispatchAndSettleAsync(InProcessEventBus.cs:168-194) dispatches throughInProcessDispatch.DispatchBackedAsync, which splits the rows intodeliveredandundelivered(InProcessEventBus.cs:177-178). The delivered rows are marked processed with a single set-based update throughOutboxFinalizer.MarkProcessedAsync(InProcessEventBus.cs:180), passing the injectedTimeProviderso theProcessedOnstamp is testable; any undelivered rows get their lease released throughInProcessDispatch.ReleaseLeaseAsync(InProcessEventBus.cs:182-185). Any exception there, a cancellation or a failed finalize, is caught under a scopedCA1031suppression (InProcessEventBus.cs:187-189), logged by the source-generatedLogDispatchErrorat Warning (InProcessEventBus.cs:191,InProcessEventBus.cs:196-197), and every row of the batch has its lease released (InProcessEventBus.cs:192): a row already stamped processed is unaffected by the release, and its handlers do not run again (method doc,InProcessEventBus.cs:162-166).
- Two readonly fields resolve the constructor's clock and posture:
- Why it's built this way: writing the outbox row and the aggregate change in one
SaveChangesAsynccloses the dual-write gap, and dispatching immediately afterward gives synchronous in-process reactions without giving up the durable retry path. Settling per event through the same loop the save interceptor uses means one failing event settles only itself (and the later events sharing its ordering key) instead of the whole batch (class doc,InProcessEventBus.cs:25-27), and the lease keeps another replica's processor from double-delivering the batch mid-dispatch. Finishing throughOutboxFinalizerrather than a second full save keeps the hottest write path down to one extra statement,[Rubric S12, Performance & Scalability]. Deferring through the one post-commit hook the save interceptor also uses means a transactional unit's integration events and its local domain events both wait for the commit, so the two paths cannot disagree on when a transactional unit's events reach their handlers (hook doc,MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:177-185). The non-relational (Engine.Capabilities.IsRelational) fast path keeps the framework usable on a store without an outbox table (dispatch-only) rather than failing, which is the deliberate opposite of the choiceBrokerEventBusmakes: with no local consumers, a silent dispatch-only fallback in broker mode would drop the event entirely, so that class throws instead. - Where it's used: the default scoped
IEventBusregistration (MMCA.Common.Infrastructure/DependencyInjection.cs:408), superseded byBrokerEventBusonceAddBrokerMessagingis called (MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:134).
[Rubric S10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
IntegrationEventConsumer<TEvent>
MMCA.Common.Infrastructure |
MMCA.Common.Infrastructure.Messaging.Consumers|MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumer.cs:40| Level 12 | class (public sealed partial)
- What it is: a single generic broker consumer that bridges a delivered event to the existing
IIntegrationEventHandler<in TIntegrationEvent>contract, invoking every handler registered in the per-attempt DI scope and adding consumer-side inbox idempotency, keyed per handler, throughIInboxStore(class doc,MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumer.cs:9-12; parameter doc,IntegrationEventConsumer.cs:30). It implements the framework's ownIBrokerMessageConsumer(IntegrationEventConsumer.cs:44); no external messaging library is involved. - Depends on:
IInboxStore,IIntegrationEventHandler<in TIntegrationEvent>,IIntegrationEvent,EventNameResolver,InboxHandlerLoop,ConsumerOriginRestore; externallyILogger<T>with a source-generated[LoggerMessage]method and a requiredIServiceProvider. The four dependencies arrive through the primary constructor (IntegrationEventConsumer.cs:40-44), constrainedwhere TEvent : class, IIntegrationEvent(IntegrationEventConsumer.cs:45). The provider has no default (IntegrationEventConsumer.cs:44): a consumer built without it would run every handler anonymously, with no origin restored and nothing logged (parameter doc,IntegrationEventConsumer.cs:32-39). It is taken as the provider rather than as the restore services themselves because one of them (ScopedUserOverride) is internal and this consumer is public (same parameter doc). - Concept introduced, the per-handler consumer-side inbox for broker idempotency.
[Rubric S29, Resilience & Business Continuity]assesses at-least-once delivery paired with idempotent consumers, and[Rubric S6, CQRS & Event-Driven]assesses idempotent integration-event handling. Broker delivery is at-least-once: the same message can arrive twice after a consumer crash or a redelivery. The inbox makes that safe, and it is keyed per handler, not per message. The consumer does not touch the inbox itself: it hands its handlers toInboxHandlerLoop.RunAsync(IntegrationEventConsumer.cs:83-90), the loop it shares withUpcastingIntegrationEventConsumer<TEvent>so the inbox rule lives once (MMCA.Common.Infrastructure/Messaging/Consumers/InboxHandlerLoop.cs:8-9). For each handler, in registration order, the loop names the consumer withInboxConsumer.NameOf(handler.GetType())(InboxHandlerLoop.cs:48, seeInboxConsumer), skips a handler thatinbox.IsProcessedAsync(messageId, consumer, ct)already records for this message (InboxHandlerLoop.cs:53-57), otherwise runs it inside anInboxConsumeScopemarker so aScopedIntegrationEventHandlerBase<TIntegrationEvent>handler can stage its own row atomically with its writes (InboxHandlerLoop.cs:61-64, class docInboxHandlerLoop.cs:11-14), and once it returns records it withinbox.RecordAsync(messageId, eventTypeName, consumer, ct)(InboxHandlerLoop.cs:79), which absorbs a row the handler's own save already committed (comment,InboxHandlerLoop.cs:76-77). The store contract is that pair (MMCA.Common.Infrastructure/Persistence/Inbox/IInboxStore.cs:27,IInboxStore.cs:40). The payoff is in the class doc (InboxHandlerLoop.cs:15-18): a throwing handler rethrows at once while the handlers before it stay recorded, so the retry or redelivery runs only the failed handler and the ones after it. A crash between a handler's commit and its record redelivers the message to that handler, which is why handlers must still be idempotent (comment,InboxHandlerLoop.cs:77-78). - Concept introduced, the recorded event name is the declared name, not the CLR name. It is
computed by
EventNameResolver.GetInboxName(typeof(TEvent))(IntegrationEventConsumer.cs:81), which returns the event'sEventNameAttributename when it declares one and its short type name otherwise (MMCA.Common.Infrastructure/Persistence/Outbox/Processing/EventNameResolver.cs:59-60). The comment (IntegrationEventConsumer.cs:78-80) is explicit that this name is only the event half of every row the consume writes, kept for diagnostics: the dedup key is the pair (message id, consumer).[Rubric S9, API & Contract Design]: what an operator reads in the inbox is the stable wire identity, not a CLR name that a refactor can change. - Walkthrough
- Entry point:
ConsumeAsync(TEvent integrationEvent, IReadOnlyDictionary<string, string> headers, CancellationToken)(IntegrationEventConsumer.cs:62-65) null-guards both the event and the headers (IntegrationEventConsumer.cs:67-68). The explicitIBrokerMessageConsumer.ConsumeAsync(IIntegrationEvent, ...)implementation casts toTEventand forwards (IntegrationEventConsumer.cs:101-106), which is how the non-generic receive pipeline calls a generic consumer. - Context restore (
IntegrationEventConsumer.cs:70-76): on every consume,ConsumerOriginRestore.Apply(headers, serviceProvider, PrincipalAuthenticationType)(IntegrationEventConsumer.cs:76) runs before the inbox is touched, held in ausing var originso the handle stays open for the whole consume and a handler that opens its own scope from the root factory still runs as the publisher's origin (comment,IntegrationEventConsumer.cs:74-75), because the inbox store resolves its context through the scoped factory, and under database-per-tenant that routing is decided by the tenant this restores (ADR-073). A message published with no origin headers restores nothing, and the scope keeps the defaults it already had (comment,IntegrationEventConsumer.cs:70-73). The stampedPrincipalAuthenticationType = "IntegrationEvent"(IntegrationEventConsumer.cs:51) is what makes the rebuilt identityIsAuthenticatedand names the hop it came back from. - Per-handler loop (
IntegrationEventConsumer.cs:83-90): passes the inbox, the event'sMessageId, the inbox name, the resolved handlers and the invocation(handler, ct) => handler.HandleAsync(integrationEvent, ct)(IntegrationEventConsumer.cs:88) toInboxHandlerLoop.RunAsync. A handler the inbox already records is skipped withLogHandlerSkippedat Debug (InboxHandlerLoop.cs:55,InboxHandlerLoop.cs:85), so a full duplicate runs nothing and completes the message rather than dead-lettering it. On any non-OperationCanceledException(InboxHandlerLoop.cs:66) the loop logsLogHandlerFailurenaming the failing handler's full type name (InboxHandlerLoop.cs:72) and rethrows (InboxHandlerLoop.cs:73) with nothing recorded for that handler, so the receive pipeline retries it in a fresh scope with exponential backoff (MessageBusSettings.RetryLimit, default 5,MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:94), then redelivers or dead-letters (comment,InboxHandlerLoop.cs:68-71). The loop returns how many handlers are registered, run or skipped (InboxHandlerLoop.cs:32,InboxHandlerLoop.cs:82). - No-handler case (
IntegrationEventConsumer.cs:92-98): if zero handlers were registered for the event in this process,LogNoHandlersfires at Information and the method returns normally, so the message completes with no retry storm while the misconfigured service host stays visible in telemetry. - One
[LoggerMessage]partial remains on the consumer,LogNoHandlers(IntegrationEventConsumer.cs:108-109); the skip and failure partials live on the shared loop (InboxHandlerLoop.cs:85-89). All are source-generated, allocation-free log methods,[Rubric S13, Observability & Operability].
- Entry point:
- Why it's built this way: application code keeps writing plain
IIntegrationEventHandler<in TIntegrationEvent>implementations, which the module scan already auto-discovers; there is no broker-specific consumer class to write per event type (class doc,IntegrationEventConsumer.cs:14-17). The receive pipeline deserializes the message, opens a fresh scope per attempt, resolves this consumer from it and callsConsumeAsync, and a throw from here drives its retry, redelivery and dead-letter decisions (class doc,IntegrationEventConsumer.cs:19-26). That keeps the transport out of the handlers and out of the Application layer (ADR-021 for the inbox guarantee, ADR-003 for the outbox half, ADR-007 and ADR-008 for the extraction boundary). - Where it's used: chosen per subscription by
BrokerConsumerBuilderfor a current contract registered throughRegisterIntegrationEventConsumer<TEvent>()(MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:20; closed type atBrokerConsumerBuilder.cs:41-42), registered scoped once per subscription byAddBrokerMessaging(MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:105), and resolved per attempt byBrokerReceivePipeline. A retired contract getsUpcastingIntegrationEventConsumer<TEvent>instead. - Caveats / not-in-source: whether the inbox actually dedups depends on which
IInboxStoreis registered.AddBrokerMessagingregistersEfInboxStorewhenMessageBusSettings.IsInboxEnabledresolves true, which it does by default for a broker transport (MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:141-143,MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:142); an explicitMessageBus:EnableInbox=falseopts down toNoOpInboxStore(DependencyInjection.Messaging.cs:157), where the inbox records nothing and every redelivery re-runs the handlers, a posture announced once at startup byInboxDisabledWarningService.
[Rubric S10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
EFWebhookSubscriptionStore
MMCA.Common.Infrastructure |
MMCA.Common.Infrastructure.Persistence.Webhooks|MMCA.Common.Infrastructure/Persistence/Webhooks/EFWebhookSubscriptionStore.cs:30| Level 13 | class (internal sealed)
- What it is: the EF Core
IWebhookSubscriptionStoreover the databaseWebhooks:DataSourceNamenames (MMCA.Common.Infrastructure/Persistence/Webhooks/EFWebhookSubscriptionStore.cs:13-14). - Depends on:
IDbContextFactory,IEntityDataSourceRegistry,IDataSourceResolver,IOptions<WebhookSettings>andIConcurrencyConflictDetector, all through the primary constructor (EFWebhookSubscriptionStore.cs:30-35); it reads and writesWebhookSubscriptionthroughApplicationDbContextandDataSourceKey, and locates its table throughFrameworkTableTargets(EFWebhookSubscriptionStore.cs:107). - Concept, explicit tenant filtering on a plain column.
[Rubric S11, Security]and[Rubric S8, Data Architecture]: the subscription is deliberately not anITenantEntity, so this store filtersTenantId == tenantIdon every read, anulltenant matching only untenanted rows, while the soft-delete filter hides deleted rows (class doc,EFWebhookSubscriptionStore.cs:19-23). Writes go through the unit of work so the audit interceptor stamps who created or changed a subscription. - Walkthrough
Contextresolves the context forResolveDataSourceKey()on each access, andSubscriptionsis itsDbSet<WebhookSubscription>(EFWebhookSubscriptionStore.cs:37,EFWebhookSubscriptionStore.cs:39).ListAsyncandListEnabledAsyncareAsNoTracking, tenant-filtered and ordered byCreatedOnthenId; the enabled variant addsDisabledOn == null(EFWebhookSubscriptionStore.cs:42-49,EFWebhookSubscriptionStore.cs:52-59).FindAsync(id, tenantId)is tracked, matching on both id and tenant so another tenant's id is simply not found (EFWebhookSubscriptionStore.cs:62-63);CountAsynccounts the tenant's rows (EFWebhookSubscriptionStore.cs:66-67).AddAsyncadds and saves through the factory (EFWebhookSubscriptionStore.cs:70-76);SaveAsynconly saves, because the row came from the trackedFindAsync(comment,EFWebhookSubscriptionStore.cs:83-84).RecordOutcomeAsyncsaves and swallows a concurrency conflict recognized byIConcurrencyConflictDetector(EFWebhookSubscriptionStore.cs:89-103): the delivery already happened, so a lost last-outcome stamp is dropped rather than failing the row into a retry (comment,EFWebhookSubscriptionStore.cs:99-101).ResolveDataSourceKey()delegates toFrameworkTableTargets.ResolveHome<WebhookSubscription>(registry, dataSourceResolver, settings.Value.DataSourceName)(EFWebhookSubscriptionStore.cs:106-107), the one resolution every store and sweep over this table shares (comment,EFWebhookSubscriptionStore.cs:105). That helper takes the registry's key forWebhookSubscriptionwhen an entity configuration registered one, and otherwise the configured source name verbatim on the engine the resolver answers for the default source (MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:105-113).
- Why it's built this way: the store is
internalso hosts depend on theIWebhookSubscriptionStoreabstraction, and the data-source resolution is not the store's own rule: every store and every sweep over an opt-in framework table with a configured home goes throughResolveHome, so a sweep can never visit a different database than its store reads (FrameworkTableTargets.cs:85-91). Only the engine goes through the resolver, so a host that configures no SQL Server connection string gets the engine it does configure rather than a context over an empty connection string (FrameworkTableTargets.cs:94-96). See ADR-142. - Where it's used: registered as the scoped
IWebhookSubscriptionStorebyAddWebhooks(MMCA.Common.Infrastructure/Webhooks/WebhookServiceCollectionExtensions.cs:81), consumed byWebhookSubscriptionServiceandDeliverWebhookInternalCommandHandler.
⬅ Querying: Specifications, Filtering & the Entity Query Service • Index • CQRS: Commands, Queries & the Decorator Pipeline ➡