Onboarding guide
10. Notifications (Push + In-App Inbox + Email)
What this group covers. This is the notification subsystem, the machinery that turns "an
organizer wants to tell every attendee something" into messages that actually reach people across
several transports at once. It spans all five layers and both repositories: the framework
(MMCA.Common) owns the aggregates, the transport abstractions, the SignalR hub, the REST
controllers, and the CQRS handlers, while MMCA.ADC supplies the thin
NotificationModule host, the app-specific recipient rule, and the gRPC
edges that let an extracted service still deliver over the one WebSocket. The design principle is
the same one that runs through the whole codebase: application and domain code talk to
abstractions (IPushNotificationSender,
ILiveChannelPublisher,
INotificationRecipientProvider,
IEmailSender); the concrete transport (SignalR, SMTP, a native push hub, a gRPC
forwarder) is chosen at the composition root, and every transport has a registered default so
nothing has to be configured for DI to resolve.
NullPushNotificationSender and
NullLiveChannelPublisher are no-ops
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:418-419), and
IEmailSender defaults to the real SmtpEmailSender
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:417). The one deliberate
exception is INotificationRecipientProvider: there is no default, and a host that registers the
notification services without a provider fails at startup instead of failing every send
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:91-94).
There are really four delivery channels here, and it is worth separating them up front because they have different durability guarantees:
- The durable in-app inbox. Every send writes one
UserNotificationrow per recipient, page by page, so a user who was offline at send time still sees the message when they next open their inbox (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:140-143). This is the persistent half of the two-channel model (ADR-024). - The transient SignalR push.
IPushNotificationSenderfans the same message out to any connections the recipient has open right now via theNotificationHub; clients not connected at send time simply never see this copy (the inbox is their catch-up). This is the real-time half of ADR-024. - The OS-level native push (ADR-044). A separate best-effort channel reaches devices the
SignalR hub cannot (app backgrounded or killed), through
INativePushSenderand the device registrations managed byDevicesController. The sender itself and its Azure Notification Hubs implementation live in Group 07; this chapter covers only the request record and the registration endpoint. - Ephemeral live-channel events (ADR-039). A distinct, never-persisted fan-out to a group
of subscribed connections (for example
event:1orsession:123), used by the ADC Engagement live layer for poll and question updates. This rides the same hub but throughILiveChannelPublisherand the hub'sJoinChannel/LeaveChannelgroup membership rather than per-user targeting (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationHub.cs:142-206).
A fifth transport, plain email, is present as IEmailSender /
SmtpEmailSender (MailDev locally, real SMTP in production) but is a
lower-traffic, fire-one-message helper rather than part of the broadcast pipeline: it builds and
disposes an SmtpClient per call and offers a "send to the configured default recipient" overload
for system mail
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Mail/SmtpEmailSender.cs:40-65). Two safety
decisions ride on that per-call client: TLS is resolved once at construction by
SmtpTransportSecurity from the settings, the configuration, and the host environment, rather than
left to a caller (SmtpEmailSender.cs:28-37), and the client's timeout is set explicitly from
SmtpSettings.TimeoutSeconds instead of inheriting SmtpClient's 100-second default, which is
longer than the callers sitting in front of it (SmtpEmailSender.cs:76-86,
ADR-070). The same
client uses SmtpDeliveryFormat.International, so an address with a non-ASCII local part can be sent
when the relay advertises SMTPUTF8 instead of throwing under the 7-bit default
(SmtpEmailSender.cs:88-92).
The layering, and why the pieces sit where they do
The dependency flow of the group mirrors the framework's Clean Architecture story
([Rubric §3, Clean Architecture]). The Domain layer holds the two aggregates,
PushNotification (the audit record of a broadcast: title, body, sender,
recipient count, an optional deduplication key, an optional scope key, and a
PushNotificationStatus of Pending/Sent/Failed, plus the
per-platform native-push counts and the provider's delivery unit, all null when that leg recorded
nothing,
MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:26-78)
and UserNotification (one per-recipient inbox row with read/unread state),
plus the PushNotificationInvariants guards. PushNotification.Create
raises no domain event: nothing consumes one, and the id is not known until the first save
(MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:106,121).
(The invariants: title max 200 chars, body max
2000, both non-empty:
MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/Invariants/PushNotificationInvariants.cs:13-26).
Both aggregates are [IdValueGenerated], so the database assigns their ids
(MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:14,
MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/UserNotifications/UserNotification.cs:11).
The Application layer defines the four transport contracts, the CQRS use cases, and
NotificationSettings, the optional Notifications configuration section
whose every property has a default: 500 recipients per delivery page, the retention sweep on, rows
kept 90 days, a sweep every 24 hours
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/NotificationSettings.cs:13,21-22,29,36-37,40-41).
AddNotificationInfrastructure(configuration) binds it with data-annotation validation on start and
registers the retention sweep,
NotificationCleanupService,
unless RetentionEnabled is false
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:29,36-48). The
Shared layer carries the wire types (PushNotificationDTO,
UserNotificationDTO,
SendPushNotificationRequest,
DeviceInstallationRequest) and three constant holders:
NotificationFeatures (the Notification.PushNotifications flag, declared
[FeatureFlag(FeatureFlagLifetime.Permanent, Owner = "MMCA.Common")] so the flag inventory knows it
is a permanent capability switch and not a cleanup candidate,
MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationFeatures.cs:11-12),
NotificationPermissions (the single notifications:manage capability,
MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationPermissions.cs:10), and
NotificationScopeKey (the event:{id} / session:{id} formatter and its
guard pattern,
MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationScopeKey.cs:20-36,48-55). The
Infrastructure layer supplies the SignalR-backed implementations
(SignalRPushNotificationSender,
SignalRLiveChannelPublisher), the SMTP email sender, and the
NotificationHub itself, plus the no-op fallbacks
(NullPushNotificationSender,
NullLiveChannelPublisher). The API layer exposes
three controllers (NotificationsController,
InboxController, DevicesController).
The critical placement decision is that the four transport interfaces live in Application
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/IPushNotificationSender.cs:8,
ILiveChannelPublisher.cs:9, INotificationRecipientProvider.cs:25, IEmailSender.cs:6), not
Infrastructure. That keeps the send handler and the Engagement live layer depending on an
abstraction the way IMessageBus and the gRPC service interfaces do (the microservices-extraction
discipline in ADR-007 and
ADR-008): the same
application code runs unchanged whether the concrete sender is an in-process SignalR call or a gRPC
forward to another service.
The broadcast send flow, end to end
Sending a notification is a command-side vertical slice ([Rubric §5, Vertical Slice],
[Rubric §6, CQRS & Event-Driven]). An organizer POSTs to
NotificationsController, which is gated three ways at the class level
(API versioning, [FeatureGate(NotificationFeatures.PushNotifications)], and
[HasPermission(NotificationPermissions.Manage)]) and a
fourth on the POST action itself,
[Idempotent]
(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationsController.cs:25-29,43-44).
The authorization is stated as a capability, never a role: the endpoint asks for
notifications:manage, and the consuming host decides who holds it. ADC declares that binding once,
in NotificationPermissionGrants, whose single Apply grants
NotificationPermissions.Manage to the Organizer role and to no other
(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Shared/Authorization/NotificationPermissionGrants.cs:34-39),
and the module registration applies it as AddPermissions(NotificationPermissionGrants.Apply)
(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:45). The map
is a named type rather than a lambda inside that registration because two hosts apply it: the
Notification host gates the framework's endpoints with it, and the token-minting Identity host
applies the same map so the issued access token carries the permission claim, which is what the
framework's push-notifications navigation entry is gated on
(MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Authorization/TokenPermissionGrants.cs:58,
NotificationPermissionGrants.cs:11-18). It sits in the module's Shared (contracts) project, and the
RoleNames members it names are const, so they leave no reference in the compiled contract
assembly and the Shared-layer fitness test stays green (NotificationPermissionGrants.cs:19-24).
That is what lets an attendee never broadcast and an administrator hold no notification capability it
was not explicitly given ([Rubric §11, Security]). The controller then reads the authenticated id from
ICurrentUserService and refuses the call with an Error.Unauthorized when there is none
(NotificationsController.cs:52-56), reads the raw Idempotency-Key header and carries it into the
domain as the command's DedupKey, treating a whitespace-only header as absent
(NotificationsController.cs:60-67). Header binding is done by hand rather than with [FromHeader]
precisely so the key stays protocol plumbing and does not leak into the generated OpenAPI contract
(NotificationsController.cs:61). The request is wrapped in a
SendPushNotificationCommand and handed to
SendPushNotificationHandler (NotificationsController.cs:69-74).
Those two idempotency mechanisms are deliberately stacked (ADR-017). The filter replays the
original HTTP response for a repeated key; the DedupKey protects delivery even when the
filter's cache is cold, evicted, or degraded (NotificationsController.cs:37-41). The key the
handler stores is not the client's raw header: it is a hex SHA-256 of {SentByUserId}:{key}, so two
senders reusing one client key never collide and the stored value is always 64 characters, inside
the column
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationCommand.cs:25-36,
MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationHandler.cs:124-133).
The command is also ITransactional
(SendPushNotificationCommand.cs:23), which is what keeps the dedup short-circuit honest: the
handler writes the audit row and schedules the first delivery page on the same unit of work, so
without a transaction a fault between the two would leave a committed row carrying the key that
nothing ever delivers, and every retry of that key would then report success forever
(SendPushNotificationCommand.cs:11-19). No sender call runs inside this request at all. The
handler runs a deliberate ordering (SendPushNotificationHandler.cs:55-122):
- Dedup lookup first (lines 65-76). A whitespace-only key counts as absent; otherwise the
handler derives the sender-scoped key, requeries for an existing
PushNotificationcarrying it and, on a hit, returns it mapped to a DTO without sending anything again. The lookup goes throughunitOfWork.GetReadRepository<...>()rather than an injected repository, so it reads the same data source the write below targets (SendPushNotificationHandler.cs:140-149). - Count recipients through
INotificationRecipientProvider.CountRecipientsAsync, failing early with aPushNotification.NoRecipientsvalidation error when the count is zero, before anything is written (lines 78-89). The count feeds the audit row and that answer only; the delivery pages read the recipients again, one keyset page at a time. - Create and save the audit aggregate (lines 91-108), stamping the dedup key and the caller's
optional scope key onto it (lines 96-97). Because the dedup lookup is a check-then-act, two
concurrent sends of one key can both pass it, and the loser fails this first save against the
filtered unique index on
DedupKey. The handler does not try to recover in place: the failure propagates as the persistence exception (a 409 throughDbUpdateExceptionHandler), the transactional decorator rolls the attempt back, and the client's retry is answered by the dedup lookup with the winner's notification. In-place recovery is impossible from the Application layer, because the failed insert stays tracked and on PostgreSQL the unique violation has already aborted the transaction a requery would run in (lines 32-40, 106-108). The index itself is the arbiter: unique, filtered to a non-nullDedupKeyand to live rows, so the many keyless sends coexist and a soft-deleted row does not occupy a key slot forever (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/Notifications/PushNotificationConfiguration.cs:73-83). - Schedule the first delivery page, a
DeliverPushNotificationPageInternalCommandwith no cursor, throughIInternalCommandScheduleron this request's own unit of work (ADR-114). A failed schedule fails the command, so the audit row rolls back with it and the client's retry re-runs the whole send (lines 110-118). - Map and return the aggregate, still
Pending, as aPushNotificationDTOviaPushNotificationDTOMapper(lines 51, 120-121).
The fan-out then runs off the request path, one page at a time.
DeliverPushNotificationPageInternalCommand carries
two integers, the notification id and a keyset cursor AfterUserId (null for the first page), under
the stable queue name MMCA.Notifications.DeliverPushNotificationPage.v1, and is itself
ITransactional, so a page's inbox rows, its outcome on the notification row and the next page's
schedule commit together or not at all
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommand.cs:12-25).
Its handler is registered beside the other handlers so the decorators wrap it and the
internal-command processor finds it
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:81-84).
DeliverPushNotificationPageInternalCommandHandler
runs each page in this order
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:58-104):
- Load the notification tracked, and complete without work when it is gone (deleted, or past retention, before its delivery finished) (lines 62-71).
- Detect a re-run. An inbox row for this notification past the page's cursor (soft-deleted rows included) can only exist if this page already committed, and every page commit also commits the next page's schedule, so the re-run completes without writing, sending or scheduling anything (lines 24-30, 73-77, 106-118).
- Read the page. The handler asks the provider's
GetRecipientPageAsyncfor the nextDeliveryPageSizeids after the cursor, a keyset read, so no page ever loads the whole audience, and normalizes the answer defensively (distinct, after the cursor, ascending, at most one page) so a provider that breaks the ordering contract cannot move the cursor backwards (lines 79-80, 120-135;NotificationSettings.cs:21-22). The provider owes exactlytakeids unless the audience is exhausted, because a short page is read as the last one; an implementation that filters rows after reading them must keep reading until the page is full (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/INotificationRecipientProvider.cs:15-23). A recipient added after the send is delivered when the walk reaches it and one removed is skipped, whileRecipientCountstays the send-time count (lines 33-37). - Write the page's inbox rows, one
UserNotificationper recipient, and save (lines 140-143). - Attempt SignalR delivery to the page via
IPushNotificationSender, passing the scope key as live metadata so a client viewing another scope can leave it out of its toast and badge; any exception marks the notificationFailedand does not stop the page, since delivery failure is non-fatal (lines 145, 155-178, 233-240). - Attempt the native-push leg through
INativePushSender(ADR-044). ANativePushOutcomecarrying per-platform counts or a failure is added onto the row throughPushNotification.AddNativePushOutcome, which accumulates the Android and Apple sent/failed counts across pages, and a failure is logged at Warning with the exception; the leg never throws and never changes the audit status, which stays the SignalR leg's (lines 150, 180-220;MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:169-199). - Continue or finish. A full page schedules the next one with its last recipient as the cursor
(a failed schedule rolls the page back, so the retry delivers it again); a short page ends the walk
and moves a still-
Pendingnotification toSent(lines 86-100, 222-231).
A page the internal-command processor dead-letters is the one way the walk can stop short: no later page is scheduled,
so the recipients past its cursor are not delivered. That case has its own handler.
DeliverPushNotificationPageDeadLetterHandler, an
IInternalCommandDeadLetterHandler<DeliverPushNotificationPageInternalCommand>
the internal-command processor runs after it stamps the dead letter, marks the notification Failed
and logs one Warning carrying the
InternalCommandDeadLetterNotice's
reason and attempt count, so the organizer's history shows the failure instead of a notification
left Pending forever. It is idempotent (an already failed or since-deleted notification is left
alone), and requeuing the dead page resumes the walk from its cursor while the status stays Failed,
as it does after a failed live leg
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageDeadLetterHandler.cs:8-25,28-57).
It is registered with TryAddEnumerable beside the page handler
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:86-89).
The durable inbox write happening before the transient channels on every page is the
load-bearing choice: the record of who should have been reached survives even when nobody is
connected, the status records whether any page's SignalR leg failed, and the native counts record
what the OS leg did. Execution is at-least-once (a host can die after a page commits and before the
processor stamps its queue row), and the re-run check turns that second run into a no-op, so
delivery is at-least-once for the live channels and exactly-once for the inbox rows
(DeliverPushNotificationPageInternalCommandHandler.cs:24-30)
([Rubric §29, Resilience & Business Continuity]). Paging is also what bounds the work: the
organizer's POST returns after one insert and one queue row whatever the audience size, and each
page's transaction and provider calls stay short (NotificationSettings.cs:15-20)
([Rubric §12, Performance & Scalability]).
Who counts as a recipient is deliberately left to the consuming app.
INotificationRecipientProvider is the extension point, and the
framework registers no default. Instead
NotificationRecipientProviderValidator, an
IValidateOptions<NotificationSettings> run by ValidateOnStart, asks
IServiceProviderIsService whether a provider is registered (without resolving one) and fails
startup with a message naming the registration, so a host that forgot it fails at boot rather than
answering every send with NoRecipients
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/NotificationRecipientProviderValidator.cs:14-23,
MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:91-94). ADC
supplies AttendeeNotificationRecipientProvider, which
bridges the Identity module's
IAttendeeQueryService (over gRPC across
service boundaries) so a broadcast targets every conference attendee. Both of its members map one to
one onto Identity: GetRecipientPageAsync onto GetAttendeeUserIdPageAsync, which already honours
the page-full contract by reading past the synthetic load-test accounts it leaves out, and
CountRecipientsAsync onto CountAttendeesAsync, which applies the same rule
(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/AttendeeNotificationRecipientProvider.cs:10-27).
Because the check runs at start rather than at registration, ordering does not matter: ADC registers
its provider with TryAddScoped and then calls AddNotificationApplicationServices(), and either
order would pass
(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/DependencyInjection.cs:22,29).
Scope keys: one string that narrows a broadcast, an inbox, and a live channel
NotificationScopeKey is the small type that ties three otherwise unrelated
paths together. It owns the format (event:{id} via ForEvent, session:{id} via ForSession,
both rendered under InvariantCulture so a culture with non-ASCII digits cannot produce a key the
guard rejects) and, in the same file, the regular expression that validates one:
^(event|session):[0-9]+\z, anchored with \z rather than $ because $ also matches before a
final newline and would let event:1\n pass
(MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationScopeKey.cs:32-36,48-55,62-63),
compiled once through a source-generated [GeneratedRegex] with a one-second match timeout
(NotificationScopeKey.cs:68-69). That constant is also the default of
PushNotificationSettings.ChannelKeyPattern
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:37), which
is what NotificationHub enforces before a client may join a group. Producer and
guard therefore cannot drift apart: keeping the format and its pattern in one type is the whole point
of the class ([Rubric §15, Best Practices & Code Quality]).
On the send side the key is optional and opaque. It arrives as an init property on
SendPushNotificationRequest rather than a positional parameter, so
every pre-existing caller keeps compiling and an omitted key means "unscoped"
(MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/PushNotifications/SendPushNotificationRequest.cs:23-28);
SendPushNotificationRequestValidator caps its length at
128 and, when one is present, requires NotificationScopeKey.IsValid, because a key of any other
shape would reach no scoped reader; the domain re-checks the length bound in
PushNotification.Create
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationRequestValidator.cs:27-37,
MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:21,139-145).
On the read side the scope is a view filter, not a security boundary, and the code says so in as
many words: a read that supplies a scope sees the notifications carrying that scope plus every
unscoped one, and a read that supplies none still sees everything
(PushNotification.cs:49-55). Ownership is enforced separately, by the un.UserId == query.UserId
predicate that every inbox read carries. ADC's Engagement UI is the producer of the key in practice:
CurrentEventNotificationScopeProvider
resolves event:{EventId} for the conference currently in focus, caches it for five minutes, and
deliberately answers event:0 (a well-formed key no row carries, hence an empty inbox) rather than
null when it cannot resolve one, because on that contract null means unscoped and would widen an
attendee's inbox to every event
(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Notifications/CurrentEventNotificationScopeProvider.cs:35-48,67).
The inbox side
Reading and acknowledging notifications is the query/command counterpart, served by
InboxController under the same feature gate and a plain [Authorize], so any
authenticated user reaches only their own inbox
(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationInboxController.cs:24-28);
every action re-reads ICurrentUserService.UserId and builds the message from it rather than
trusting a client-supplied id ([Rubric §11, Security]). It exposes four use cases, three of which
accept the optional scope query parameter, length-checked against
PushNotification.ScopeKeyMaxLength at the boundary
(NotificationInboxController.cs:46,70,113):
- The paged inbox (
GetMyNotificationsQuery/GetMyNotificationsHandler), which joins the per-userUserNotificationrows to theirPushNotificationcontent newest-first, applies the scope predicate to thePushNotificationside only when one was supplied, and clamps paging throughPagingMathwith a 500-row page ceiling (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/GetInbox/GetMyNotificationsHandler.cs:21,32,39-66). - The unread count (
GetUnreadNotificationCountQuery/GetUnreadNotificationCountHandler), served[ResponseCache(NoStore = true)]so the bell badge is never stale (NotificationInboxController.cs:66-68). Its join toPushNotificationis introduced only for a scoped count, because an unconditional join would dragPushNotification's soft-delete global query filter into the unscoped count and change a number no caller asked to change (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/GetUnreadCount/GetUnreadNotificationCountHandler.cs:27-40). - A single mark-read (
MarkNotificationReadCommand/MarkNotificationReadHandler), which matches on both the notification id and the requesting user id, returningUserNotification.NotFoundrather than a forbidden when the row belongs to somebody else (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/MarkRead/MarkNotificationReadHandler.cs:24-36). - A mark-all-read (
MarkAllNotificationsReadCommand/MarkAllNotificationsReadHandler), which issues one set-basedExecuteUpdateAsyncthat setsIsReadandReadOndirectly rather than loading and tracking every unread row: an inbox can hold an unbounded number of them, andMarkAsReadonly sets those two columns and raises no domain event, so bypassing the change tracker loses nothing (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/MarkAllRead/MarkAllNotificationsReadHandler.cs:13-17,48-55). Its condition is the unread count's: a scoped command adds anEXISTSsubquery over thePushNotificationset (matching the scope or unscoped rows), so a scoped client never marks rows it cannot see, and that subquery takesPushNotification's soft-delete filter exactly as the count's join does, while a no-scope command keeps the plain per-user predicate (lines 29-46) ([Rubric §8, Data Architecture]).
UserNotification.MarkAsRead is idempotent and takes the read timestamp
as a parameter (from an injected TimeProvider, MarkNotificationReadHandler.cs:15,38) so the
domain stays free of ambient clock access and the transition is deterministically testable
(MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/UserNotifications/UserNotification.cs:58-67).
The organizer-facing history read is the fifth use case and lives on the other controller:
GetNotificationHistoryQuery /
GetNotificationHistoryHandler pages the
PushNotification audit rows newest-first under the same 500-row clamp and maps
them through PushNotificationDTOMapper
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/GetHistory/GetNotificationHistoryHandler.cs:21,30-43).
List reads that go through the generic query service take a different path again:
PushNotificationDTOProjector is itself a Mapperly [Mapper]
whose generated ProjectTo returns the DTO's columns instead of whole rows, inlining the
status enum-to-string mapping as a conditional the database can translate (a SQL CASE) because the
mapper's custom status method cannot run inside an expression tree; its equivalence with
PushNotificationDTOMapper is pinned by a test
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/DTOs/PushNotificationDTOProjector.cs:8-28).
Merely registering it switches those reads onto server-side projection
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:55-60)
([Rubric §12, Performance & Scalability]).
The SignalR transport, and how it survives extraction
NotificationHub is intentionally thin
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationHub.cs:34-39): it is
[Authorize]d, and beyond ASP.NET's built-in per-user connection mapping it does three things.
It caps concurrent connections per user on the replica it runs on, counting them in a static
dictionary and refusing the surplus with a HubException, then handing the slot straight back so the
refused connections cannot lock the account out once aborted ones drain (the cap is
PushNotificationSettings.MaxConnectionsPerUser, 20 by default:
NotificationHub.cs:64-73,76-96,114-133,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:50).
It manages channel (SignalR group) membership through JoinChannel/LeaveChannel, validating
each channel key against the configured pattern with a cached, one-second-timeout Regex so a bad
key throws HubException rather than opening an injection or ReDoS hole
(NotificationHub.cs:59-62,229-239). Joins are also bounded per connection on two axes: at most
MaxChannelsPerConnection memberships (32 by default), and a token bucket of
ChannelJoinsPerMinute (60) with a ChannelJoinBurst of 32. The join budget is spent before any
other check, so a refused join costs the same as an accepted one and a loop of refused joins cannot
drive the entitlement check without bound; the membership slot is reserved before that check and
released again if the join does not complete. Both live in the connection's Context.Items bag and
end with it (NotificationHub.cs:27-33,142-178,248-319,
PushNotificationSettings.cs:63,76,85). And before it creates the group membership it consults an
entitlement check (NotificationHub.cs:163-171,211-227) ([Rubric §11, Security]).
That check is IChannelJoinAuthorizer
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/IChannelJoinAuthorizer.cs:15),
an optional constructor dependency defaulted to null (NotificationHub.cs:38), and the reason
it exists is that shape is not entitlement: the pattern proves a key is well formed, not that the
caller may read what is published to it, and the keys are consecutive integers, so enumerating them
costs nothing. Without one the hub fails closed: every join is refused with a HubException
and a Warning per refusal (NotificationHub.cs:208-217,241-242), and AddPushNotifications adds
ChannelJoinAuthorizerMissingWarningService
to name the missing interface once at startup
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:104-107).
A host that wants channel joins at all therefore registers one. ADC does, per connection in the Notification host
(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:132), and the implementation is
LiveChannelJoinAuthorizer: it refuses an unauthenticated principal,
admits the privileged read audience without a lookup (ConferenceReadAudience.PrivilegedRoles, the
same Organizer / ContentEditor pair that reads the unfiltered catalog through REST), and otherwise
asks Conference's IEventLiveValidationService whether the event behind an event:{id} key is
published, or whether the session behind a session:{id} key is live-eligible and its owning event
published
(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Live/LiveChannelJoinAuthorizer.cs:61-80,105-128).
Reusing Conference's answer rather than inventing a second rule is the point: the same service
already gates opening a poll and submitting a question. Every other outcome, a failed lookup
included, is a refusal logged at Information (LiveChannelJoinAuthorizer.cs:73-80,164-168), because
a join is not a request the user is waiting on data for, so failing closed costs a retry while
failing open would restore exactly the exposure the gate closes. It also parses the key with its own
TryParseChannelKey instead of trusting the hub's match, so the gate cannot be widened by a host
that widens ChannelKeyPattern in configuration (LiveChannelJoinAuthorizer.cs:130-162).
The Conference lookup is not repeated for every attendee join. The authorizer reads and writes
LiveChannelVisibilityCache, a host-wide singleton the Notification
host registers beside it (Program.cs:131), keyed by channel key: a parsed key's answer is served
from the cache when present and stored after a lookup, while a malformed key is refused before any
lookup and never cached (LiveChannelJoinAuthorizer.cs:41-44,87-102). The answer depends only on the
channel, never on the caller (a privileged reader is admitted before the lookup), so one entry serves
every attendee joining that channel, and refusals are cached as well as admissions, because a refused
join is the cheap one to repeat and leaving it uncached would keep the very load the cache removes.
The cache owns its own MemoryCache capped at MaxEntries (4,096), so enumerating keys cannot grow
it without bound (past the cap an answer is simply not remembered, costing a lookup, never a wrong
answer), and each answer lives EntryLifetime (30 seconds), which is how long a change of visibility
can take to reach new joins; an existing membership is not re-checked either way. Each value is an
Entry, a private record of the answer and an expiry stamped from the injected
TimeProvider and checked on read, so the lifetime holds under a test clock while the
MemoryCache expiration only evicts eventually
(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Live/LiveChannelVisibilityCache.cs:10-35,50-71,76-78)
([Rubric §12, Performance & Scalability]).
Actual delivery does not run inside the hub:
SignalRPushNotificationSender and
SignalRLiveChannelPublisher both use IHubContext<NotificationHub>
so they can be called from any handler without a live connection. The push sender targets
Clients.User / Clients.Users / Clients.All and batches large user lists in chunks of 100
to avoid overwhelming the connection manager
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/SignalRPushNotificationSender.cs:14,39-56)
([Rubric §12, Performance & Scalability]); the live publisher does a single Clients.Group send
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Live/SignalRLiveChannelPublisher.cs:14-18).
Both are wired by AddPushNotifications(configuration), which also attaches a Redis backplane when
a redis connection string is present, so the fan-out crosses replicas
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:62-110).
The live channel is where the extracted-service topology shows through
([Rubric §7, Microservices Readiness]). In a monolith the default
NullLiveChannelPublisher is registered, and a host that maps the hub
swaps in the real SignalRLiveChannelPublisher
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:419,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:98). In extracted ADC, Engagement is a different process from the
one that owns the WebSocket, so Engagement's live layer depends on
ILiveChannelPublisher as usual but the composition root Replaces the
registration with LiveChannelPublisherGrpcAdapter
(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:49-58). That
adapter forwards each event over gRPC with a tight 2-second deadline to the Notification service's
LiveChannelGrpcService, which then delegates to the local
SignalRLiveChannelPublisher, the only host whose IHubContext can
reach connected clients
(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/LiveChannelGrpcService.cs:31-63).
The live path is best-effort by contract (ADR-039),
but the adapter is not where that is enforced: a transport, resolution or broken-circuit failure
propagates from it. Its one caller, Engagement's
LiveChannelPublishProcessor, runs each
publish inside BestEffort.ExecuteAsync off the
request path, which swallows the failure, logs one Warning and counts it on
besteffort.dispatch.failed
(ADR-096); swallowing in the
adapter as well would hide every push failure from that metric. A publishing command never awaits
the adapter, so a slow or down Notification service still cannot fail it. The caller's own
cancellation, which the gRPC client reports as an RpcException with StatusCode.Cancelled, is
rethrown as an OperationCanceledException so a host shutdown is not counted as a failed push
(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/LiveChannelPublisherGrpcAdapter.cs:14-26,35,42-55)
([Rubric §29, Resilience & Business Continuity]).
Serving both a WebSocket and an h2c gRPC ingress from one host is the mixed-endpoint profile of
ADR-012, and it is why the Notification host keeps its default endpoints on
Http1AndHttp2 (the WebSocket Upgrade needs HTTP/1.1) while a second, Http2-only Kestrel endpoint
named grpc (8081 in the container, 5996 locally) is declared in the Kestrel:Endpoints config
section and resolved by peers as _grpc.notification through the
services__notification__grpc__0 entry
(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:72-80). The host maps the hub
itself at /hubs/notifications via MapNotificationHub() (Program.cs:154-157, the path coming
from PushNotificationSettings.HubPath,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:25) and both
gRPC services on that dedicated endpoint (Program.cs:167,175). Both are authorized, but against
different callers, and the difference is deliberate. The live-channel ingress WRITES (it fans poll
results and approved questions out to every connected client), so it is never left to internal-only
reach; its one caller, Engagement's
LiveChannelPublishProcessor background
drain, has no HttpContext and so no user bearer, and instead presents its own service token
(WithServiceToken,
MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:51). The edge is
therefore mapped under the service-only ServiceTokenDefaults.ServiceCallerPolicy, which refuses a
signed-in user's bearer (Program.cs:134-139,159-167), and the service still applies its
bounded-payload checks to every admitted call
(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/LiveChannelGrpcService.cs:16-29).
The export rpc is mapped with .RequireAuthorization() and takes the end user's forwarded JWT,
because its response carries personal data keyed by a raw user id (Program.cs:169-175).
The module host, native-device registration, and the privacy export
On the ADC side the whole capability is packaged by NotificationModule
(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/NotificationModule.cs:14), an
IModule that declares a hard dependency on
Identity (Dependencies => ["Identity"], RequiresDependencies => true, since it needs attendee
data, NotificationModule.cs:20-23) and whose Register calls AddNotificationModule
(NotificationModule.cs:26-30) to wire the
application handlers, the EF configurations, the SignalR push registration, the native-push channel,
the one role-to-permission grant (NotificationPermissionGrants),
and the Common controllers
(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:30-51). It
is a deliberately thin module (API + Application only, no Infrastructure project of its own). The
framework's own registration
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:43-97) uses
TryAddScoped throughout so a consuming app can override any handler or the recipient provider, and
the API-layer registration
(MMCA.Common/Source/Presentation/MMCA.Common.API/Notifications/DependencyInjection.cs:24-28) adds
the Common controllers as an MVC application part, because they ship in a NuGet assembly that
ASP.NET does not scan by default ([Rubric §15, Best Practices & Code Quality]).
Native-device management is the third channel's control plane.
DevicesController (ADR-044) lets an authenticated user upsert
(PUT, after login and on token rotation) or delete (DELETE, before logout) a device
installation, described by DeviceInstallationRequest (a
client-generated stable installation id, a platform of fcmv1 or apns, and the platform push
handle,
MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/PushNotifications/DeviceInstallationRequest.cs:14-33).
Both verbs scope ownership the same way: each reads currentUserService.UserId and passes it to the
registrar, so a PUT can only register the caller's own installation and a DELETE only removes one
the caller owns
(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/DevicesController.cs:43-50,67-74).
The ownership check itself lives in the registrar
(IPushDeviceRegistrar, Group 07): an id
that does not exist and an id belonging to another user both answer 204 without deleting anything,
so the response cannot be used as an existence oracle for other users' installation ids
(DevicesController.cs:53-59) ([Rubric §11, Security]).
Finally, the module carries the Notification half of the cross-service data-subject export
(PRIVACY.md section 12), UserNotificationExportService,
published across modules as IUserNotificationExportService and
reachable from the Identity aggregator over gRPC via
UserNotificationExportGrpcService and its client-side
UserNotificationExportServiceGrpcAdapter. Beyond the
endpoint's authorization, the gRPC service answers only for the caller's own user id or an
Organizer (the export privilege), and refuses anything else with PermissionDenied; the edge takes
the default policy, which authenticates only the user bearer, so a service token never reaches that
check. It emits timestamps as round-trip UTC strings, stamping the Utc kind that SQL Server drops
so the Z marker the wire contract promises is present, and carries an unscoped notification as the
empty string, since proto3 has no null string
(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/UserNotificationExportGrpcService.cs:17-30,43-47,58-64).
The export produces
UserNotificationExportItemDTO rows (id, title, sent/read dates,
and the scope the notification was sent under, but never the body) scoped strictly to the requesting
user through a where un.UserId == userId filter on an unpaged, newest-first join
(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/UserNotificationExportService.cs:27-42,
MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Shared/UserNotifications/UserNotificationExportItemDTO.cs:8-29).
The module's application registration binds the interface to that service with TryAddScoped,
beside the recipient provider
(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/DependencyInjection.cs:24-26)
([Rubric §30, Compliance, Privacy & Data Governance]).
Where this group sits
Upstream, this group depends on the domain building blocks of
Group 02 (both aggregates derive from
AuditableAggregateRootEntity<TIdentifierType>),
the Result pattern of
Group 01, the CQRS pipeline of
Group 05 and
IUnitOfWork of persistence
(Group 07), the permission attribute of
Group 08, the idempotency filter of
Group 12, and the module system and
internal-command queue of
Group 14. Downstream, the Blazor UI of
Group 15 consumes it: the
NotificationBell, inbox, and send pages call
these REST endpoints, ask an
INotificationScopeProvider for the
scope to pass, and the UI's SignalR client listens on the hub's ReceiveNotification /
ReceiveChannelEvent methods (NotificationHub.cs:42-45). The ADC Engagement live layer
(Group 23) is the busiest producer of live-channel events, and
recipients are resolved through the Identity module.
Read this chapter as the answer to one question: how does a single "notify everyone" intent become a
durable inbox row, a real-time toast, an OS push, and (for the live layer) an ephemeral group event,
without any of the four ever taking the others down, and without a retried request doing it twice.
Entry
MMCA.ADC.Notification.Service ·
MMCA.ADC.Notification.Service.Live·MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Live/LiveChannelVisibilityCache.cs:78· Level 0 · record (private sealed, nested)
- What it is: one remembered visibility answer inside
LiveChannelVisibilityCache: whether a live channel's subject is on the
public agenda (
IsVisible) and the instant the answer stops being reused (ExpiresAt) (LiveChannelVisibilityCache.cs:78). - Depends on: nothing first-party (BCL
boolandDateTimeOffset). Nested in, and only constructed by, LiveChannelVisibilityCache. - Concept: the per-channel answer cache is introduced at
LiveChannelVisibilityCache; this record is its value.
[Rubric §12, Performance & Scalability]applies through that type. - Walkthrough: a positional record with two members.
Setbuilds it with the injected clock's current time plusEntryLifetime(LiveChannelVisibilityCache.cs:70), andTryGetreturnsIsVisibleonly whileExpiresAtis still after that clock's current time (LiveChannelVisibilityCache.cs:52-57). - Why it's built this way: the expiry travels with the value so the lifetime holds under a test
clock; the
MemoryCacheexpiration set alongside it only evicts the entry eventually (the comment atLiveChannelVisibilityCache.cs:76-77).privatekeeps it out of every caller's view: the cache exposes a plainbool. - Where it's used: only inside LiveChannelVisibilityCache, written by
Set(line 70) and read byTryGet(line 52). - Caveats / not-in-source: the simple name collides with unrelated nested
Entrytypes elsewhere (for example the inbox consume marker inInboxConsumeScope, G04); they share nothing but the name.
GetMyNotificationsQuery
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.UserNotifications.UseCases.GetInbox·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/GetInbox/GetMyNotificationsQuery.cs:11· Level 0 · record
- What it is: the read request that backs a user's in-app notification inbox, "give me page N of my
notifications". A
sealed recordcarrying the caller'sUserId, paging arguments, and an optional scope key. - Depends on: the solution-wide
UserIdentifierTypealias (see primer §2); BCL only otherwise. Handled by GetMyNotificationsHandler through the query side of the CQRS pipeline (IQueryHandler<in TQuery, TResult>). - Concept introduced: the paged-query record shape. This is the first notification query, so note
the convention it shares with every read in the codebase: an immutable positional
recordwith defaulted paging (PageNumber = 1,PageSize = 20,GetMyNotificationsQuery.cs:13-14) is the message, a matching handler is the behavior, and the two are joined by a closed generic registration rather than a direct call (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:73-74). It also introduces the scope key as an optional view filter:ScopeKeydefaults tonull, and the XML doc states what that default means (GetMyNotificationsQuery.cs:7-10), namely that a null scope is the legacy read returning every notification, while a supplied scope narrows the inbox to notifications carrying that scope plus the unscoped ones. Making the narrowing opt-in is what keeps an existing caller's result set unchanged (ADR-024 records the scope key on the sent artifact).[Rubric §6, CQRS & Event-Driven]assesses whether reads and writes are modeled as distinct, single-purpose messages; this record is a pure read with no side effects.[Rubric §12, Performance & Scalability]assesses guarding against unbounded work: the XML doc pinsPageSizeat "max 500" (GetMyNotificationsQuery.cs:6) and GetMyNotificationsHandler enforces that ceiling as aconst, so a client cannot request an unbounded page. - Walkthrough: four positional members,
UserId(the authenticated user, line 12),PageNumberdefaulting to 1 (line 13),PageSizedefaulting to 20 (line 14), and the nullableScopeKey(line 15). No factory, no validation here: it is a plain carrier, and the page ceiling, the negative-offset guard and the scope join are all applied downstream in the handler. - Why it's built this way: a positional record gives value equality and immutability for free, which
is exactly what a query message wants (it is data in flight, never mutated). The default page size
keeps the common "just show my inbox" call one-argument-simple, and the defaulted
ScopeKeymeans adding scoping did not break a single existing construction site. - Where it's used: constructed by InboxController from the resolved caller id, the
query-string paging values and the optional
scopeargument (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationInboxController.cs:55), then handled by GetMyNotificationsHandler. The controller bounds the scope string with[StringLength(PushNotification.ScopeKeyMaxLength)](NotificationInboxController.cs:46), the same 128-character constant the entity publishes (MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:21).
GetNotificationHistoryQuery
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.UseCases.GetHistory·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/GetHistory/GetNotificationHistoryQuery.cs:6· Level 0 · record
- What it is: the read request for the push-notification sent history (the admin-facing "what did
we broadcast" list), as opposed to a single user's inbox. A
sealed recordof paging arguments only. - Depends on: BCL only. Handled by GetNotificationHistoryHandler.
- Concept introduced: none new; this is the same paged-query shape
GetMyNotificationsQuery introduced, minus a user filter and minus the scope
key. History is global (it lists PushNotification rows, the sent artifacts), so
there is no
UserIdmember and no per-reader narrowing.[Rubric §6, CQRS & Event-Driven]: a second read model (sent history) distinct from the inbox read model, each with its own query, handler and DI entry (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:71-72). - Walkthrough: two positional members,
PageNumber = 1(line 7) andPageSize = 10(line 8). Note the default page size is 10 here versus 20 for the inbox; both are capped at 500 by their handlers, and both XML docs state the ceiling (GetNotificationHistoryQuery.cs:5). - Where it's used: constructed by NotificationsController
(
MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationsController.cs:85), handled by GetNotificationHistoryHandler.
IEmailSender
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Mail·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Mail/IEmailSender.cs:6· Level 0 · interface
- What it is: the Application-layer port for sending email. Two
SendAsyncoverloads: one to an explicit recipient, one to a default/system recipient (admin notifications). Infrastructure supplies the concrete transport. - Depends on: BCL only (
Task,CancellationToken). Implemented by SmtpEmailSender (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Mail/SmtpEmailSender.cs:12). - Concept introduced: the port/adapter split for outbound side effects. Application code that
needs to send mail depends on this interface, never on an SMTP client; the XML doc names SMTP or
SendGrid as interchangeable backings (
IEmailSender.cs:4).[Rubric §3, Clean Architecture]assesses whether the core depends inward on abstractions rather than outward on I/O libraries, and this interface is a textbook outbound port: the dependency arrow points from Infrastructure's SmtpEmailSender into Application, so the transport is swappable without touching a handler.[Rubric §1, SOLID](Dependency Inversion): the high-level policy owns the contract, the low-level detail implements it. - Walkthrough:
SendAsync(string to, string subject, string body, bool isHtml = false, CancellationToken cancellationToken = default)(line 15): explicit recipient, HTML flag defaulting to plain text.SendAsync(string subject, string body, bool isHtml = false, CancellationToken cancellationToken = default)(line 23): the same message routed to the implementation's configured default/system recipient, so callers that always mail the operators do not repeat the address. In the SMTP implementation that address isSmtpSettings.To, reached through a settings field captured once fromIOptions(SmtpEmailSender.cs:14) and forwarded to the explicit-recipient overload (SmtpEmailSender.cs:65). - Why it's built this way: keeping the interface in Application (and the SMTP dependency in
Infrastructure) is what lets a test host register a no-op sender and production register
SmtpEmailSender. Registration is
TryAddTransient<IEmailSender, SmtpEmailSender>()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:417), so theTryAddlets a host pre-register its own sender and win. - Where it's used: the framework's own consumer is the password-reset flow:
ForgotPasswordHandlerBase<TUser, TCommand>
takes it as a primary-constructor dependency
(
MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:66), and MMCA.ADC's concrete ForgotPasswordHandler passes its own sender through (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandler.cs:24). MMCA.Store uses it twice more, resolving it from a scope insideOrderPaidHandlerandOrderPaymentFailedSagaHandler(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Orders/DomainEventHandlers/OrderPaidHandler.cs:41,MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Orders/Saga/OrderPaymentFailedSagaHandler.cs:31), the arrangement ADR-024 describes. - Caveats / not-in-source: the "default/system recipient" of the second overload is not defined by this interface; it is whatever the implementation's settings configure.
ILiveChannelPublisher
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/ILiveChannelPublisher.cs:9· Level 0 · interface
- What it is: the port for publishing ephemeral live events to a channel of currently-connected
clients (for example
event:1orsession:123). Its defining property, stated in the XML doc (ILiveChannelPublisher.cs:4-6): channel events are not persisted, so a client that is not connected and subscribed at publish time never sees them. - Depends on: BCL only. Contrast with IPushNotificationSender (which
persists a PushNotification plus per-user UserNotification
inbox rows), a contrast the XML doc draws explicitly via
<see cref="IPushNotificationSender"/>(line 5). Implemented by SignalRLiveChannelPublisher, the NullLiveChannelPublisher no-op, and in MMCA.ADC by the out-of-process LiveChannelPublisherGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/LiveChannelPublisherGrpcAdapter.cs:22). - Concept introduced: ephemeral fan-out versus durable notification. This is the distinction that
splits the whole group in two: live channel events (poll-results-changed, a new session question) are
fire-and-forget to whoever is watching right now, while push notifications are durable and land in an
inbox (ADR-039). The interface
deliberately speaks in strings (a
channelKey, an application-definedeventName, apayloadJsonstring) so it stays transport-agnostic; the XML doc names SignalR groups or a message fan-out service as candidate backings (line 7).[Rubric §7, Microservices Readiness]assesses whether cross-boundary calls go through abstractions that can be re-homed onto a network transport: in MMCA.ADC this exact interface is served over gRPC by the Notification host's LiveChannelGrpcService (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/LiveChannelGrpcService.cs:31) and consumed through a scoped adapter thatReplaces the local registration in publishing services (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:55), so the boundary already survives extraction (ADR-007, ADR-008). - Walkthrough: one method,
PublishAsync(string channelKey, string eventName, string payloadJson, CancellationToken cancellationToken = default)(line 17): publish an event to every client currently subscribed tochannelKey. No return value beyond theTask, because there is no delivery guarantee to report. - Why it's built this way: a JSON-string payload plus a free-form event name keeps the framework out
of the business of knowing each live event's schema; the presentation and UI layers agree on the
contract. Non-delivery to absent clients is the intended semantics, not a gap. The default registration
is the inert NullLiveChannelPublisher
(
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:419), replaced by SignalRLiveChannelPublisher when a host opts into the SignalR wiring (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:98). - Where it's used: ADC's conference-day live layer does not inject it into command handlers.
Handlers enqueue a work item and a single-reader hosted drain,
LiveChannelPublishProcessor, resolves the
publisher from a fresh scope per work item and calls
PublishAsyncin FIFO order (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Live/LiveChannelPublishProcessor.cs:138-144).[Rubric §29, Resilience & Business Continuity]assesses whether a degraded dependency stays contained: the drain wraps each publish in BestEffort (LiveChannelPublishProcessor.cs:47-60), which turns any non-cancellation failure into one Warning log plus one metric increment instead of an exception (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Resilience/BestEffort.cs:66-73), and it returns quietly when host shutdown is the reason a publish stopped (LiveChannelPublishProcessor.cs:62-66, the rethrow-on-cancellation half ofBestEffortatBestEffort.cs:59-64). A down Notification peer can therefore never fail an Engagement command. The other consumer is the Notification host's gRPC ingress, which forwards a wire call onto the local SignalR publisher. - Caveats / not-in-source: the interface itself makes no delivery or ordering guarantee; those are properties of the concrete SignalR, queue and gRPC wiring, not visible here.
INotificationRecipientProvider
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/INotificationRecipientProvider.cs:25· Level 0 · interface
- What it is: the port that answers who receives a broadcast push notification, read one keyset
page at a time, plus a count of the whole audience. The framework knows how to send; the consuming
app implements this to answer who (the XML doc's examples,
INotificationRecipientProvider.cs:5-6: all users, users in a role, subscribers to a topic). - Depends on: the
UserIdentifierTypealias; BCL only otherwise. Works alongside IPushNotificationSender. The framework registers no default (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:91-92); MMCA.ADC supplies AttendeeNotificationRecipientProvider (MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/DependencyInjection.cs:22). - Concept introduced: separating recipient policy from delivery mechanism. "Who to notify" is
app-specific domain knowledge; "how to notify" is framework infrastructure. Splitting them means the
push pipeline never needs to understand ADC's attendee model. The second idea is the audience as a
keyset walk: each delivery page asks for the next
takeids after the last id it delivered, so no page ever loads the whole audience, and an implementation reads the page from its store (WHERE Id > @after ORDER BY Idwith a row limit) rather than filtering a full list in memory (INotificationRecipientProvider.cs:9-14).[Rubric §7, Microservices Readiness]assesses whether a shared component can be re-homed without its consumers changing; this is an inversion point that lets the shared framework host an app-defined audience query.[Rubric §1, SOLID](Interface Segregation and Dependency Inversion): two focused methods, and both handlers depend on the abstraction rather than on a concrete audience source.[Rubric §12, Performance & Scalability]: the paged read keeps the memory and transaction size of a send bounded by the page, not by the audience. - Walkthrough:
GetRecipientPageAsync(UserIdentifierType? afterUserId, int take, CancellationToken cancellationToken = default)(lines 35-38): the next page of recipient ids afterafterUserId, from the start when it isnull. The page contract (lines 15-23) is strict: distinct ids, ascending, every one greater thanafterUserId, and EXACTLYtakeof them unless the walk has reached the end, because the delivery handler reads a shorter page as the last one and completes the notification. An implementation that filters rows after reading them must keep reading until the page is full or the store is exhausted, or the walk ends early and silently skips everyone after the thinned page.CountRecipientsAsync(CancellationToken cancellationToken = default)(line 46): every eligible recipient, under the same filter as the pages, read once per send for the notification's recipient count and the no-recipients answer (lines 40-43).
- Why it's built this way: the framework deliberately binds no default provider.
AddNotificationApplicationServices()leaves the slot empty and instead arms NotificationRecipientProviderValidator throughAddOptions<NotificationSettings>().ValidateOnStart()(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:91-94), so a host that registers none fails at startup with a message naming the registration rather than sending to nobody. ADC registers its own withTryAddScopedbefore callingAddNotificationApplicationServices()(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/DependencyInjection.cs:22,29), which satisfies that check; the host may equally register it after the call. Splitting the count from the pages lets the send answer "no recipients" and stamp the audit count without walking the audience. - Where it's used: SendPushNotificationHandler takes it as a primary
constructor dependency
(
MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationHandler.cs:49) and callsCountRecipientsAsyncfor the audit row and the no-recipients answer (SendPushNotificationHandler.cs:80-89). DeliverPushNotificationPageInternalCommandHandler takes it too (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:49) and reads one page per delivery throughGetRecipientPageAsync, normalizing it defensively (distinct, after the cursor, ascending, at most one page) so a provider that breaks the ordering contract cannot move the cursor backwards (DeliverPushNotificationPageInternalCommandHandler.cs:120-135), before handing the page to IPushNotificationSender.
IPushNotificationSender
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/IPushNotificationSender.cs:8· Level 0 · interface
- What it is: the Application-layer port for real-time push delivery, with three targeting shapes:
one user, a set of users, or a broadcast to everyone connected. The XML doc names SignalR or Firebase
Cloud Messaging as interchangeable backings (
IPushNotificationSender.cs:4-5). - Depends on: the
UserIdentifierTypealias; BCLDictionaryfor the optional metadata. Implemented by SignalRPushNotificationSender (real delivery) and NullPushNotificationSender (the inert default). Paired with INotificationRecipientProvider for audience resolution. - Concept introduced: the metadata dictionary as an open payload. All three methods share
title,body, and an optionalDictionary<string, string>? metadata(lines 16, 25, 33). That dictionary carries typed extras (a deep-link URL, a notification type, per the XML doc on line 13) without a bespoke strongly-typed payload per notification kind, so a new notification variety needs no interface change.[Rubric §6, CQRS & Event-Driven Design]assesses whether a capability like push is factored once and reused broadly, and this single port serves every push-emitting feature. This is the durable counterpart to ILiveChannelPublisher's ephemeral fan-out (ADR-024). - Walkthrough:
SendToUserAsync(UserIdentifierType userId, string title, string body, Dictionary<string, string>? metadata = null, CancellationToken cancellationToken = default)(line 16): one user.SendToUsersAsync(IEnumerable<UserIdentifierType> userIds, ...)(line 25): an explicit set.BroadcastAsync(string title, string body, ...)(line 33): all connected clients. The three methods differ only in targeting; body and metadata are identical. - Why it's built this way: three targeting methods rather than one "audience" parameter keeps each
call site's intent explicit and lets the SignalR implementation map user-targeting to hub groups
directly. The default registration is the no-op
(
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:418) so a host with no real-time transport still resolves the port; the SignalR wiring replaces it withAddTransient(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:97), a deliberate override rather than aTryAdd. - Where it's used: SendPushNotificationHandler no longer calls this
port; it persists the PushNotification record and schedules the first delivery
page (
SendPushNotificationHandler.cs:103-112). Each page of DeliverPushNotificationPageInternalCommandHandler writes its per-user UserNotification rows and fans the message out through this port withSendToUsersAsync(DeliverPushNotificationPageInternalCommandHandler.cs:164-169). That handler also carries a second, separate delivery leg,INativePushSender(DeliverPushNotificationPageInternalCommandHandler.cs:51), which is the OS-level channel of ADR-044 rather than part of this port.
NotificationSettings
MMCA.Common.Application ·
MMCA.Common.Application.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/NotificationSettings.cs:10· Level 0 · class
- What it is: the options class for the notification subsystem, bound from the
Notificationsconfiguration section (SectionName,NotificationSettings.cs:13). It carries two concerns: how a send is paged into delivery batches, and how long sent notifications and inbox rows are kept. - Depends on: BCL only, plus
System.ComponentModel.DataAnnotationsfor the[Range]attributes. Read by DeliverPushNotificationPageInternalCommandHandler and by the retention sweep NotificationCleanupService; it is also the options type that NotificationRecipientProviderValidator hooks to fail startup. - Concept introduced: one options class sizing both the write fan-out and the data lifetime.
DeliveryPageSize(line 22, default 500,[Range(1, 10000)]on line 21) is the number of recipients one delivery page covers: a send schedules its first page as an internal command (ADR-114), and each page writes its recipients' inbox rows, runs the live and native legs and commits on its own before scheduling the next (the XML doc, lines 15-20).[Rubric §12, Performance & Scalability]: smaller pages keep each transaction and each provider call short, larger pages mean fewer queue rows per send. The retention trio isRetentionEnabled(line 29, defaulttrue),RetentionDays(line 37, default 90,[Range(1, 3650)]) andCleanupIntervalHours(line 41, default 24,[Range(1, 168)]): past the cutoff the sweep soft-deletes the UserNotification rows and their PushNotification, which then leave every inbox, unread count and history read (lines 31-35).[Rubric §30, Compliance/Privacy/Data Governance]assesses bounded retention of personal data, and this is the notification subsystem's bound. - Walkthrough: a
sealed classofinit-only properties with defaults, so an unconfigured host gets 500-recipient pages and a daily 90-day sweep. The sweep readsCleanupIntervalHoursas its interval andRetentionDaysas the cutoff (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationCleanupService.cs:71,109); the delivery handler readssettings.Value.DeliveryPageSizeper page (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:79). - Why it's built this way: binding and range validation live in the Infrastructure registration,
AddNotificationInfrastructure, which binds the section, callsValidateDataAnnotations()andValidateOnStart()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:36-40), and registers the sweep only whenRetentionEnabledreads true at registration time (lines 45-48 of the same file). The XML doc onRetentionEnabled(lines 24-28) records that the switch only matters on a host that maps the notification tables, which is the host that calls that method. - Where it's used: the Application registration also adds
AddOptions<NotificationSettings>().ValidateOnStart()(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:93), which is what gives the recipient-provider check a startup hook even on a host that never binds the section. - Caveats / not-in-source: on a host that calls only
AddNotificationApplicationServices()and notAddNotificationInfrastructure, nothing binds the section, so the defaults apply; whether any shipped host runs in that shape is not determinable from these files.
UserNotificationExportItemDTO
MMCA.ADC.Notification.Shared ·
MMCA.ADC.Notification.Shared.UserNotifications·MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Shared/UserNotifications/UserNotificationExportItemDTO.cs:8· Level 0 · record
- What it is: one notification-inbox row inside a user's personal-data export (the data-subject
access artifact the XML doc ties to PRIVACY.md §7,
UserNotificationExportItemDTO.cs:4): the notification id, title, sent/read timestamps, and the scope it was sent under. This is an MMCA.ADC-specific contract, not a framework type. - Depends on: the ADC
UserNotificationIdentifierTypealias; BCLstringandDateTime. Returned by IUserNotificationExportService; consumed by the Identity module's NotificationUserDataExportSection and projected into UserDataExportNotificationDTO. - Concept introduced: export DTOs deliberately omit content. The XML doc (lines 5-6) records that
the notification body is left out of the summary by design; the export carries the metadata a data
subject is owed (that they were notified, when, whether they read it, under which scope) without
duplicating message bodies.
[Rubric §30, Compliance/Privacy/Data Governance]assesses whether the codebase has concrete data-subject access and portability paths, and this DTO is the Notification module's contribution to that per-user export. - Walkthrough: a
sealed record classwithrequired NotificationId(line 11),required Title(line 14),required SentOn(line 17, UTC), then three optional members:IsRead(line 20), nullableReadOn(line 23, null when unread) and nullableScopeKey(line 29, null for an unscoped notification, documented with theevent:1example at lines 25-28). Therequiredmembers force every export row to carry an identity, a title and a send time; the optional members model "never read" and "unscoped" without sentinel values. - Why it's built this way: a flat immutable record is the right shape for a serialized export line:
value semantics, no behavior, self-describing timestamps in UTC. Being
init-only means an export row cannot be edited after assembly. CarryingScopeKeykeeps the export self-describing: two rows with the same title are distinguishable by the event they belonged to. - Where it's used: assembled by the in-process
UserNotificationExportService, which projects all six members
server-side out of the inbox join
(
MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/UserNotificationExportService.cs:31-39), and returned across the export boundary to Identity; the out-of-process path is UserNotificationExportServiceGrpcAdapter.
IUserNotificationExportService
MMCA.ADC.Notification.Shared ·
MMCA.ADC.Notification.Shared.UserNotifications·MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Shared/UserNotifications/IUserNotificationExportService.cs:14· Level 1 · interface
- What it is: the cross-module service contract for exporting the personal data the Notification module holds for one user: their inbox rows (ids, titles, sent and read dates). It is how the Identity module reaches into Notification-owned data to build a complete cross-service export.
- Depends on: UserNotificationExportItemDTO (its return element),
the ADC
UserIdentifierTypealias, and the[ServiceContract]marker fromMMCA.Common.Shared.Abstractions(applied atIUserNotificationExportService.cs:13, imported at line 1). Implemented in-process by UserNotificationExportService inside the Notification module (MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/UserNotificationExportService.cs:15) and, per the XML doc (IUserNotificationExportService.cs:10-11), by a gRPC adapter inMMCA.ADC.Notification.Contractseverywhere else (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:90); there is no disabled-module stub. - Concept introduced: the "one interface, in-process or gRPC" extraction pattern. The XML doc
calls out that this mirrors Engagement's
IUserEngagementExportService: a single
interface the caller depends on, satisfied by an in-process implementation when the module is co-hosted
(
MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/DependencyInjection.cs:25) and by a gRPC adapter thatReplaces that registration when it is not (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:90). The[ServiceContract]attribute is the machine-readable half of the same idea: it marks the interface as a cross-module boundary that architecture fitness tests can find and police.[Rubric §7, Microservices Readiness]assesses exactly this: whether a module boundary is expressed as an interface that can be re-homed onto a network transport without changing the caller (ADR-007 for gRPC extraction, ADR-008 for topology).[Rubric §30, Compliance/Privacy/Data Governance]: it is one leg of the data-subject-access aggregation.[Rubric §9, API & Contract Design]: the contract is a plain async method over DTOs, so the same shape serves both the in-process and the wire binding (the.protomirror lives atMMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/Protos/user_notification_export.proto:17-19, whose comments record that identifier aliases areinton the wire and dates travel as round-trip ISO 8601 strings,user_notification_export.proto:14-16). - Walkthrough: one method,
GetUserNotificationExportAsync(UserIdentifierType userId, CancellationToken cancellationToken)(line 23), returningIReadOnlyList<UserNotificationExportItemDTO>newest-first. Note the token has no default value here, so every caller must pass one explicitly. The XML doc (lines 17-18) states the implementation joins the framework UserNotification rows with their PushNotification content, which is the same join the inbox read performs. - Where it's used: the Identity module wraps it in a per-section adapter,
NotificationUserDataExportSection,
which takes it as its single constructor dependency
(
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/NotificationUserDataExportSection.cs:18), calls it (NotificationUserDataExportSection.cs:29-31) and projects the rows into the export document (NotificationUserDataExportSection.cs:33-44), unaware of which of the three implementations it received.[Rubric §29, Resilience & Business Continuity]: that section deliberately does not catch transport failures (NotificationUserDataExportSection.cs:11-15), because the export handler wraps every section and degrades an unreachable peer to one unavailable section rather than failing the whole export.
LiveChannelVisibilityCache
MMCA.ADC.Notification.Service ·
MMCA.ADC.Notification.Service.Live·MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Live/LiveChannelVisibilityCache.cs:27· Level 1 · class (sealed,IDisposable)
- What it is: a short-lived, size-bounded memory of whether the event or session behind a live
channel key is on the public agenda, so
LiveChannelJoinAuthorizer does not make a Conference gRPC call for every
attendee join (the XML doc,
LiveChannelVisibilityCache.cs:5-9, tracking item NTF-102). - Depends on: BCL
TimeProvider(the constructor argument that ages the answers, line 40) andMicrosoft.Extensions.Caching.Memory(MemoryCache, line 35). Its value type is the nested Entry record (line 78). - Concept introduced, a caller-independent answer cache that remembers refusals too. The answer
depends only on the channel, never on the caller (a privileged reader is admitted before the lookup),
so one entry serves every attendee joining the same channel (lines 12-13). Refusals are cached as well
as admissions: a refused join is the cheap thing to repeat, so leaving refusals uncached would keep
exactly the load the cache exists to remove, an attendee looping over unpublished or missing ids
(lines 13-16).
[Rubric §12, Performance & Scalability]assesses bounding per-request remote calls and memory: the cache owns its ownMemoryCachecapped atMaxEntries, so a caller enumerating channel keys cannot grow it without bound; past the cap a new answer is simply not remembered, which costs a lookup and never a wrong answer (lines 19-21).[Rubric §11, Security]: an answer can be stale for at mostEntryLifetime, which the doc names as how long a visibility change (an event published or unpublished, a session moved off the agenda) can take to reach new joins; an existing membership is not re-checked either way (lines 21-24). - Walkthrough
MaxEntries = 4_096(line 30) andEntryLifetime = TimeSpan.FromSeconds(30)(line 33) are the two public knobs, both fixed in code rather than bound from configuration.- The private
MemoryCacheis built withSizeLimit = MaxEntries(line 35); the constructor null-checks and stores theTimeProvider(lines 40-44). TryGet(string channelKey, out bool isVisible)(line 50) returnstruewith the remembered answer only when an entry exists and itsExpiresAtis still after_timeProvider.GetUtcNow()(lines 52-57); otherwiseisVisibleisfalseand the method returnsfalse(lines 60-61).Set(string channelKey, bool isVisible)(line 67) stores a new Entry stamped with the injected clock plusEntryLifetime(line 70), withSize = 1and the same lifetime as an absoluteMemoryCacheexpiration (line 71).Dispose()(line 74) disposes the ownedMemoryCache.
- Why it's built this way: the expiry is stamped from the injected clock and checked on read, so the
30-second lifetime holds under a test clock, while the
MemoryCacheexpiration only evicts the entry eventually (the comment at lines 76-77). Owning a dedicatedMemoryCacherather than sharing the host's keeps the size cap meaningful: the 4,096 slots belong to channel answers alone. - Where it's used: registered as a host-wide singleton by the Notification service, built over the
registered
TimeProviderorTimeProvider.System(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:131), and injected into LiveChannelJoinAuthorizer (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Live/LiveChannelJoinAuthorizer.cs:52), which reads it before and writes it after each Conference lookup. Covered byLiveChannelJoinAuthorizerTests(MMCA.ADC/Tests/Services/MMCA.ADC.Services.Tests/Live/LiveChannelJoinAuthorizerTests.cs). - Caveats / not-in-source: the cache is per process, so each Notification replica holds its own answers; how many replicas production runs is not determinable from these files.
NotificationRecipientProviderValidator
MMCA.Common.Application ·
MMCA.Common.Application.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/NotificationRecipientProviderValidator.cs:14· Level 1 · class
- What it is: an
internal sealedstartup check that fails the host whenAddNotificationApplicationServices()was called but nothing registered an INotificationRecipientProvider. Without it, every send would fail with no recipients (the XML doc,NotificationRecipientProviderValidator.cs:7-12). - Depends on:
IServiceProviderIsService(primary constructor, line 14), which answers whether a service is registered without resolving it (line 13); implementsIValidateOptions<NotificationSettings>(line 15). Externals:Microsoft.Extensions.OptionsandMicrosoft.Extensions.DependencyInjection. - Concept introduced: an options validator used as a startup hook for a registration check. The
validator ignores the options instance it is handed. It rides on
IValidateOptions<NotificationSettings>only becauseValidateOnStart()runs every registered validator for that type while the host starts, which gives a registration check a fail-fast moment that is neither registration time nor the first send. Checking at start rather than at registration is what lets the host register its provider before or after the notification services (lines 10-11).[Rubric §15, Best Practices & Code Quality]assesses fail-fast configuration; this follows the contract of ADR-070: a missing provider surfaces once, at startup, with a message that names the fix, instead of as a failure on every send. - Walkthrough: one expression-bodied
Validate(string? name, NotificationSettings options)(lines 18-23):serviceProviderIsService.IsService(typeof(INotificationRecipientProvider))returnsValidateOptionsResult.Success; otherwiseValidateOptionsResult.Failwith a message naming the missing registration and the exampleservices.AddScoped<INotificationRecipientProvider, MyRecipientProvider>()(lines 21-23). - Why it's built this way:
IsServiceinspects the service collection rather than resolving the provider, so the check builds no scoped provider at startup and runs none of its constructor dependencies.internalkeeps it out of the public surface: a consumer only ever meets it through the error message. - Where it's used: registered by the Application-layer DependencyInjection
as a singleton through
TryAddEnumerable, right afterAddOptions<NotificationSettings>().ValidateOnStart()(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:93-94), so a second call adds no second validator.
LiveChannelJoinAuthorizer
MMCA.ADC.Notification.Service ·
MMCA.ADC.Notification.Service.Live·MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Live/LiveChannelJoinAuthorizer.cs:50· Level 4 · class (sealed, partial)
- What it is: the SignalR hub-join gate for the standalone Notification service's live channels. It
implements IChannelJoinAuthorizer and decides
whether an authenticated caller may join a given
event:{id}orsession:{id}channel key. - Depends on: IChannelJoinAuthorizer (its
interface); IEventLiveValidationService
(primary-constructor parameter, line 51); LiveChannelVisibilityCache
(primary-constructor parameter, line 52); ConferenceReadAudience
(
PrivilegedRoles, line 68); NotificationScopeKey (EventPrefixandSessionPrefix, lines 107 and 116); Result (theTryGetValueread of each lookup, lines 113 and 124). Externals:System.Security.Claims(ClaimsPrincipal),Microsoft.Extensions.Logging([LoggerMessage], source-generated), andSystem.Globalization(CultureInfo.InvariantCulturefor the id parse). - Concept introduced, authorization by re-deriving public visibility, not by re-checking a role. A
privileged caller (a role in
ConferenceReadAudience.PrivilegedRoles) is admitted outright (lines 68-71). Everyone else is admitted only if the channel's subject is already something an ordinary attendee sees on the public agenda:IsPubliclyVisibleChannelAsync(line 87) parses the channel key and asks IEventLiveValidationService, through the privateLookUpVisibilityAsync(line 105), whether the event or session is published, and any failed lookup is a refusal (lines 113 and 124, and the doc comment at lines 82-86). The method never re-derives a role check: it re-derives the same published/unpublished question the public agenda already answers, so the live channel cannot show a caller more than the REST reads already would.[Rubric §11, Security]assesses whether a boundary check fails closed: an unparseable key or an unknown scope returnsfalse(lines 91, 127), and a failed lookup yields no value fromTryGetValue, so the join is refused rather than admitted.[Rubric §12, Performance & Scalability]: the lookup's answer, admission or refusal, is remembered per channel key in the host-wide LiveChannelVisibilityCache, so repeated joins of one channel, refused ones included, cost one Conference call per entry lifetime rather than one each (the remarks at lines 40-45, NTF-102). - Walkthrough
CanJoinAsync(ClaimsPrincipal? user, string channelKey, CancellationToken)(line 56): an unauthenticated user is refused immediately (lines 61-64). A privileged role short-circuits totrue(lines 68-71). Otherwise it awaitsIsPubliclyVisibleChannelAsync(line 73), logs a refusal via the source-generatedChannelJoinRefused(line 76; event id 5301, line 165) when admission fails, and returns the result (line 79).IsPubliclyVisibleChannelAsync(line 87): calls the privateTryParseChannelKey(line 89); an unparseable key returnsfalse(line 91) before any lookup, so a malformed key is never cached. A parsed key first triesvisibilityCache.TryGetand returns a remembered answer (lines 94-97); otherwise it awaitsLookUpVisibilityAsync, stores the answer withvisibilityCache.Setwhether it is an admission or a refusal, and returns it (lines 99-101).LookUpVisibilityAsync(string scope, int id, CancellationToken)(line 105): forNotificationScopeKey.EventPrefixit awaitsGetEventLiveInfoAsyncand returnseventInfo.TryGetValue(out var eventLive) && eventLive.IsPublished(lines 107-113). ForNotificationScopeKey.SessionPrefixit awaitsGetSessionLiveInfoAsyncand returns the sameTryGetValueshape (lines 116-124); the comment at lines 118-119 notes this single check already covers "no such session", "service session" (BR-91), and a status that keeps a session off the public agenda (BR-49), because the published flag covers the owning event.TryGetValuebinds the value only on success, so there is no null-forgivingValue!read. Any other scope prefix returnsfalse(line 127).TryParseChannelKey(string? channelKey, out string scope, out int id)(line 135): a null or empty key returnsfalse(lines 140-143); otherwise it splits on the first:(line 145), and a missing or leading separator (lines 146-149) or a non-integer suffix parsed withNumberStyles.NoneunderCultureInfo.InvariantCulture(lines 151-158) returnsfalse. The doc comment (lines 130-134) states this re-parses rather than trusts the hub's own pattern match, so the gate does not depend on a pattern a host configuration could widen.
- Why it's built this way: re-deriving public visibility from the same live-validation service the REST agenda reads keeps the live channel and the public agenda from disagreeing about what is visible, instead of maintaining a second, parallel visibility rule inside the hub. Caching the answer by channel key (not by caller) is sound because the privileged short-circuit runs before the cache is consulted, so every cached answer is the ordinary attendee's answer.
- Where it's used: registered as a scoped
IChannelJoinAuthorizerby the Notification service (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:132), right after the singleton LiveChannelVisibilityCache it depends on (Program.cs:131). Covered byLiveChannelJoinAuthorizerTests(MMCA.ADC/Tests/Services/MMCA.ADC.Services.Tests/Live/LiveChannelJoinAuthorizerTests.cs).
GetMyNotificationsHandler
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.UserNotifications.UseCases.GetInbox·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/GetInbox/GetMyNotificationsHandler.cs:16· Level 8 · class
- What it is: the query handler that materializes a user's inbox page. It joins the per-user UserNotification rows with their shared PushNotification content, optionally narrows that join by scope, and projects the pair into a single flat UserNotificationDTO.
- Depends on: IUnitOfWork, resolved as
IReadRepository<TEntity, TIdentifierType>
via
GetReadRepositoryfor both entities (lines 33-34), and IQueryableExecutor (EF terminal operations kept out of Application), injected via primary constructor (lines 16-18), plus PagingMath. Implements IQueryHandler<in TQuery, TResult><GetMyNotificationsQuery, Result<PagedCollectionResult<UserNotificationDTO>>>. Returns Result, PagedCollectionResult<T> and PaginationMetadata. - Concept introduced: the two-table inbox join and why the model is split. A push notification is
stored once (the PushNotification: title, body, created time, scope key) and fanned
out into one lightweight UserNotification per recipient (which carries only
per-user state:
IsRead,ReadOn). The read side rejoins them.[Rubric §8, Data Architecture]assesses normalization and read/write model fit: the shared content is not duplicated per recipient, and the handler pays a join at read time to reassemble the inbox view.[Rubric §3, Clean Architecture]: the handler expresses the join as a LINQIQueryablebut never calls EF'sToListAsyncorCountAsyncdirectly, delegating those to IQueryableExecutor so Application stays EF-free.[Rubric §11, Security]: thewhere un.UserId == query.UserIdclause (line 50) is the entire tenancy boundary for an inbox, and the value comes from the resolved caller rather than from client input (NotificationInboxController.cs:49,55). The scope filter is explicitly not part of that boundary: the comment above it (lines 36-38) calls scope "a view filter, not a security boundary". - Walkthrough: a
const int MaxPageSize = 500states the ceiling on the type (line 21), matching the query's documented "max 500".PagingMath.Clamp(query.PageNumber, query.PageSize, MaxPageSize)(line 32) turns the requested page into a PageWindow namedwindow, carrying the servedPageNumberandPageSizebeside a safeSkip/Takepair (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/PageWindow.cs:23); the comment above it (lines 28-31) records why: the offset is computed in 64-bit because a 32-bit(PageNumber - 1) * PageSizewraps negative nearint.MaxValue, and SQL Server rejects a negativeOFFSEToutright (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/PagingMath.cs:33-46). Then: grab the two read-only repositories from the unit of work viaGetReadRepository, each typed by entity and identifier alias (lines 33-34); build the push-notification source, which isTableNoTrackingunchanged for an unscoped read and gains apn.ScopeKey == null || pn.ScopeKey == scopeKeypredicate when a scope is supplied (lines 39-44, the localstring scopeKeyon line 42 giving the expression tree a non-nullable capture); build the LINQ query-syntax join ofUserNotificationto that source onun.PushNotificationId equals pn.Id, filtered toquery.UserId, ordered bypn.CreatedOndescending thenun.Iddescending (line 51), projected intoUserNotificationDTO(lines 48-61, mapping id, push id, title, body,IsRead,ReadOn, andSentOn = pn.CreatedOn); count the joined set (line 63); page it withSkip(window.Skip).Take(window.Take)and materialize (lines 65-67); wrap total,window.PageSizeandwindow.PageNumberinto PaginationMetadata (line 72) and return a successful PagedCollectionResult<T> (line 73). - Why it's built this way: both repositories are read through
TableNoTracking, which is correct for a read (no change-tracking overhead since nothing is saved). Server-side projection into the DTO means only the needed columns cross the wire, and the count runs against the same joined expression so the total is consistent with the page. Note the count and the page are two round trips against one composedIQueryable, the standard cost of a paged read. The scope predicate is applied to the push-notification side before the join rather than after it, so an unscoped read composes exactly the query it always did. Theun.Idtie-break afterCreatedOnmakes the sort a total order: without it, two notifications created in the same instant have no defined relative order, so they could swap places between twoOFFSETpages and one would repeat while the other vanished (the comment on lines 46-47 states exactly that). The metadata reports the window actually served (line 72), so a sub-1 page number cannot throw. Its page size is the clamped request (window.PageSize) rather thanwindow.Take: a page past the 32-bit offset range reads nothing (Take0), and a zero page size would report zero pages for a non-empty inbox (the comment on lines 69-71 says so). It matters because the[Range]attributes at the API boundary (NotificationInboxController.cs:44-45) do not protect a direct in-process caller. - Where it's used: injected as a closed
IQueryHandlerinto InboxController (NotificationInboxController.cs:30), which is how it reaches the CQRS decorator pipeline described in Group 05.
GetNotificationHistoryHandler
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.UseCases.GetHistory·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/GetHistory/GetNotificationHistoryHandler.cs:15· Level 9 · class
- What it is: the query handler for the push sent history: a reverse-chronological page of PushNotification rows (no per-user join), mapped to PushNotificationDTO.
- Depends on: IUnitOfWork, resolved as
IReadRepository<TEntity, TIdentifierType>
via
GetReadRepository(line 31), IQueryableExecutor and PushNotificationDTOMapper (primary constructor, lines 15-18), plus PagingMath. Implements IQueryHandler<in TQuery, TResult><GetNotificationHistoryQuery, Result<PagedCollectionResult<PushNotificationDTO>>>. - Concept introduced: none new; note the contrast with the inbox handler. History reads a single
table (the sent artifacts) with no
UserIdfilter and no scope narrowing, and maps entities to DTOs with an explicit PushNotificationDTOMapper rather than an inline LINQ projection, which means it materializes whole entities before mapping.[Rubric §6, CQRS & Event-Driven]: a separate read model and handler for the admin history view, sharing nothing with the inbox read but the underlying table.[Rubric §15, Best Practices & Code Quality]: the paging arithmetic that both this handler and the inbox handler once open-coded now lives once in PagingMath, whose own remarks record that duplication as the reason it was extracted (PagingMath.cs:14-18). - Walkthrough:
const int MaxPageSize = 500(line 21) thenPagingMath.Clamp(query.PageNumber, query.PageSize, MaxPageSize)(line 30), which yields a PageWindow namedwindow; get the PushNotification read-only repository viaGetReadRepository(line 31); ask the repository itself for the total viarepository.CountAsync(line 33, note this one goes through the repository, not the queryable executor, because there is no composed predicate to count); pageTableNoTrackingordered byCreatedOndescending thenIddescending withSkip(window.Skip)/Take(window.Take)and materialize the entities through the executor (lines 35-41); run them throughdtoMapper.MapToDTOs(line 43); build PaginationMetadata from the total,window.PageSize(the clamped request, notwindow.Take, so a page past the offset range that reads nothing still reports a non-zero size) andwindow.PageNumber(line 48, the comment on lines 45-47 giving that reason); return a successful PagedCollectionResult<T> (line 50). - Why it's built this way: the
ThenByDescending(n => n.Id)tie-break (line 38) makes the order total, so two notifications sent in the same instant cannot repeat or skip acrossOFFSETpages, the same guarantee the inbox handler gets from itsun.Idtie-break. History has no per-user state, so there is nothing to join; a dedicated mapper (versus an inline projection) is used because PushNotificationDTO is a richer contract reused across the push endpoints, and centralizing that mapping keeps the shape consistent (see ADR-001 on manual/Mapperly mapping). - Where it's used: injected into NotificationsController's history
endpoint (
NotificationsController.cs:32), which builds the query from its route arguments (NotificationsController.cs:85).
DependencyInjection
MMCA.Common.Application ·
MMCA.Common.Application.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:28· Level 10 · class (static)
(Application-layer notification DI. Distinct from the API-layer DependencyInjection documented
earlier in this group; both keep the raw type name as their heading.)
- What it is: the Application-layer composition helper for the notification subsystem. Its single
extension(IServiceCollection)member,AddNotificationApplicationServices, registers every notification command and query handler (the paged delivery internal command included), the delivery dead-letter handler, the DTO mapper, the DTO projector, the entity query service and the validators, and arms the startup check that a host registered its own recipient provider. - Depends on: PushNotification;
IEntityQueryService<TEntity, TEntityDTO, TIdentifierType>andEntityQueryService<TEntity, TEntityDTO, TIdentifierType>;IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>and PushNotificationDTOMapper;IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>and PushNotificationDTOProjector; the handler contractsICommandHandler<in TCommand, TResult>andIQueryHandler<in TQuery, TResult>with the seven concrete handlers named below;IInternalCommandDeadLetterHandler<in TCommand>and DeliverPushNotificationPageDeadLetterHandler; SendPushNotificationRequestValidator; INotificationRecipientProvider (documented in the remarks, not registered), NotificationSettings and NotificationRecipientProviderValidator; Result andPagedCollectionResult<T>. Externals:Microsoft.Extensions.DependencyInjection.Extensions(TryAddScoped,TryAddEnumerable),Microsoft.Extensions.Options(IValidateOptions<T>) andFluentValidation(AddValidatorsFromAssemblyContaining). - Concept introduced, hand-registration with
TryAddfor a module that lives inside the framework assembly. Application modules are normally auto-registered by a scan over the module's own assembly. The notification types have no module assembly of their own: they live inMMCA.Common.Application, so they are wired explicitly here (line 43). Every handler, mapper, projector and query-service registration usesTryAddScoped(lines 47-76 and 83-84), which is the override contract: a consuming app that registers its own handler, mapper or projector before calling this helper keeps its own registration, becauseTryAddnever replaces an existing service descriptor. The class documentation states that rule at lines 24-27, though four registrations are notTryAddScoped: the validator scan, theTryAddEnumerabledead-letter handler, theAddOptionscall and theTryAddEnumerablevalidator.[Rubric §1, SOLID]assesses dependency inversion: the notification send path depends on INotificationRecipientProvider, and this helper deliberately binds no default for it. The remarks (lines 36-41) state that the host must register its own, before or after this call, and that a host registering none fails at startup with a message naming the registration instead of failing every send.[Rubric §3, Clean Architecture]assesses whether wiring stays out of the domain: all of it is one static class in the Application layer, and nothing below Application knows these types exist. - Walkthrough:
AddNotificationApplicationServices()(line 43), insideextension(IServiceCollection services)(line 30), registers in reading order:- The PushNotification aggregate's
EntityQueryService<TEntity, TEntityDTO, TIdentifierType>closed overPushNotification/PushNotificationDTO/PushNotificationIdentifierType(lines 47-48). No navigation populator is registered here: the comment at lines 45-46 records that the aggregate's populator is the open-genericNullNavigationPopulator<TEntity>every host registers throughAddApplication(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:58), which is what states that this aggregate has no navigations to batch-load. - The PushNotificationDTOMapper twice, as the concrete type and as the
IEntityDTOMapper<...>interface (lines 51-53), so both the query service (which resolves the interface) and any direct consumer get the same scoped instance shape. - The PushNotificationDTOProjector twice, as the concrete type
(line 58) and as the
IEntityDTOProjector<...>interface (lines 59-60). The comment at lines 55-57 records why this pair matters: registering it is what switches notification list reads onto the server-side projection path, because the query service resolves it through its longer constructor, and the projected values are pinned equal to the mapper's by test. - Three command handlers: SendPushNotificationHandler (lines 63-64), MarkNotificationReadHandler (lines 65-66), and MarkAllNotificationsReadHandler (lines 67-68).
- Three query handlers: GetNotificationHistoryHandler (lines 71-72), GetMyNotificationsHandler (lines 73-74), and GetUnreadNotificationCountHandler (lines 75-76). These six registrations are exactly the closures the two controllers above inject.
- The FluentValidation validators discovered from the
SendPushNotificationRequestValidator assembly with
includeInternalTypes: true(line 79). Note this one is a plainAddValidatorsFromAssemblyContaining, not aTryAdd. - The paged delivery handler, DeliverPushNotificationPageInternalCommandHandler for DeliverPushNotificationPageInternalCommand (lines 83-84). The comment at lines 81-82 records why it is registered here with the other handlers: so the decorators wrap it and the internal-command processor finds it (ADR-114).
- DeliverPushNotificationPageDeadLetterHandler as a
scoped
IInternalCommandDeadLetterHandler<DeliverPushNotificationPageInternalCommand>throughTryAddEnumerable(lines 88-89). The comment at lines 86-87 records its job: a dead-lettered page ends the delivery walk, so this handler, run by the internal-command processor after the dead-letter stamp, marks the notification failed instead of leaving it pending forever. AddOptions<NotificationSettings>().ValidateOnStart()(line 93) and the NotificationRecipientProviderValidator as a singletonIValidateOptions<NotificationSettings>throughTryAddEnumerable(line 94), thenreturn servicesfor chaining (line 96).
- The PushNotification aggregate's
- Why it's built this way: hand-registration keeps the notification subsystem self-contained inside
the framework package while still honoring the framework-wide override contract, and the
extension(IServiceCollection)preview syntax lets it read as a first-classservices.AddNotificationApplicationServices()call (see primer §4). Making the recipient provider a required registration checked at startup, rather than a silent empty default, means a host that forgot it learns so on the first start, not when a broadcast reaches nobody. - Where it's used: called from a consuming host's Application composition root. Ordering matters in
one direction only: it must run before
AddApplicationDecorators(), because decoration can only wrap handlers that are already registered. The recipient provider is the exception: the host may register it before or after this call (lines 91-92). - Caveats / not-in-source: the infrastructure side of the subsystem (the SignalR sender, the device registrar, the email sender, the section binding of NotificationSettings and the retention sweep) is not registered here; those live in the Infrastructure-layer registration, which this file does not reference.
DeviceInstallationRequest
MMCA.Common.Shared ·
MMCA.Common.Shared.Notifications.PushNotifications·MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/PushNotifications/DeviceInstallationRequest.cs:12· Level 0 · record (sealed)
- What it is: the client request a native app sends to register or refresh this device for
platform push delivery. It carries three strings: a client-generated stable
InstallationId, aPlatformdiscriminator, and thePushChannelplatform handle (the FCM registration token or the APNs device token). - Depends on: nothing first-party. It uses
System.ComponentModel.DataAnnotations([Required],[MaxLength]) from the BCL to bound the wire shape. - Concept introduced, the annotated request record. This is the first push-side inbound contract in
the chapter, and it shows the framework's convention for a client-supplied DTO: a
sealed recordwithrequired initmembers plus DataAnnotations that ASP.NET model binding validates before a handler ever runs. Twoconst stringplatform values are published on the type itself,FcmV1Platform = "fcmv1"(DeviceInstallationRequest.cs:15) andApnsPlatform = "apns"(DeviceInstallationRequest.cs:18), so the accepted platform tokens have one source of truth rather than being sprinkled around as magic strings.[Rubric §9, API & Contract Design]assesses whether request contracts are explicit, bounded, and self-describing: the[MaxLength(128)],[MaxLength(16)], and[MaxLength(1024)]caps (DeviceInstallationRequest.cs:22,27,32) pin the payload and column sizes right on the contract.[Rubric §11, Security]shows in the design rule the doc comment states (DeviceInstallationRequest.cs:5-11): ownership is stamped server-side from the authenticated user and is deliberately not a field on this request, so a client cannot register a device against someone else's account. - Walkthrough: two platform constants (lines 15, 18), then three
required stringinit members,InstallationId(line 23),Platform(line 28), andPushChannel(line 33), each with[Required]and a[MaxLength]cap. TheInstallationIdis client-stable by design so that re-registering after a token rotation updates the same installation rather than creating a duplicate (DeviceInstallationRequest.cs:6-9). - Why it's built this way: the doc comment attributes the shape to ADR-044 (native push delivery). A stable client id plus a rotating platform channel is the installation model both FCM v1 and APNs expect, and keeping ownership server-stamped keeps the trust boundary at the authenticated request.
- Where it's used: bound as the
[FromBody]parameter of the registration action on DevicesController (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/DevicesController.cs:40), which is routed atNotifications/Devices(.../DevicesController.cs:21) and gated by the NotificationFeatures.PushNotificationsflag (.../DevicesController.cs:23).
MarkNotificationReadCommand
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.UserNotifications.UseCases.MarkRead·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/MarkRead/MarkNotificationReadCommand.cs:6· Level 0 · record (sealed)
- What it is: the CQRS command to mark a single inbox notification as read for the current user. A
two-parameter positional record: the
NotificationIdto mark and theUserIdthat must own it (MarkNotificationReadCommand.cs:6-8). - Depends on: nothing first-party. It uses the
UserNotificationIdentifierTypeandUserIdentifierTypealiases (MarkNotificationReadCommand.cs:7-8), which are solution-wideglobal using ... = int;aliases linked viaDirectory.Build.props, so there is no first-party type edge here. - Concept, a command carrying its own authorization key. Unlike a request DTO, a command is the
input to a handler in the CQRS pipeline (see
primer §2). The load-bearing detail
is that
UserIdis part of the command rather than looked up loosely later: the handler filters on it to enforce ownership.[Rubric §6, CQRS & Event-Driven]assesses whether writes flow through explicit command messages; this is the minimal shape of one. - Walkthrough: two positional parameters (
MarkNotificationReadCommand.cs:6-8). No decorator marker interfaces are declared on the type (noITransactional, no cache-invalidation marker), so it rides the default command pipeline unadorned. - Where it's used: handled by MarkNotificationReadHandler; the
authenticated
UserIdis supplied by the inbox controller from the token claim, never by the client body.
MarkAllNotificationsReadCommand
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.UserNotifications.UseCases.MarkAllRead·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/MarkAllRead/MarkAllNotificationsReadCommand.cs:10· Level 0 · record
- What it is: the only bulk write in the inbox, "clear my unread badge". A two-member
sealed recordwrapping the authenticatedUserIdand the same optionalScopeKeythe two inbox reads accept. - Depends on: the
UserIdentifierTypealias; BCL only otherwise. Handled by MarkAllNotificationsReadHandler via ICommandHandler<in TCommand, TResult>. Its single-row sibling is MarkNotificationReadCommand. - Concept introduced: commands opt into pipeline behavior through marker interfaces. This record
declares no base list at all (line 10), and neither does its single-row sibling
(
MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/MarkRead/MarkNotificationReadCommand.cs:6-8). That is a decision, not an omission: the Transactional decorator only opens a transaction for a command that implements ITransactional and otherwise passes it straight through (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TransactionalCommandDecorator.cs:29-31), so marking notifications read runs on the handler's own singleSaveChangesAsyncrather than an ambient transaction.[Rubric §6, CQRS & Event-Driven]assesses whether the write path is modeled as explicit messages with explicit cross-cutting opt-ins; the decorator pipeline is described in Group 05. - Walkthrough: two positional members,
UserId(line 11) and the nullableScopeKey(line 12). The scope of the write is entirely implied by those two values; there is no id list to validate. The XML doc (MarkAllNotificationsReadCommand.cs:5-9) states the rule that motivates the second member: a scoped caller marks only the notifications it could see, "so a scoped client never silently clears rows it could not see".[Rubric §11, Security]: read and write narrow by the identical predicate, which is what keeps a scoped client from mutating rows outside its view. - Why it's built this way: taking the user id as data rather than reading an ambient identity keeps the handler pure and testable; the controller is the one place that resolves "who is calling".
- Where it's used: constructed by InboxController's
PUT read-allaction from the current user id and the optional scope (NotificationInboxController.cs:113,122), and dispatched through the injectedICommandHandler<MarkAllNotificationsReadCommand, Result>(NotificationInboxController.cs:33). Registered in DI atMMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:67-68.
GetUnreadNotificationCountQuery
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.UserNotifications.UseCases.GetUnreadCount·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/GetUnreadCount/GetUnreadNotificationCountQuery.cs:9· Level 0 · record
- What it is: the tiniest read in the group, "how many unread notifications does this user have?". A
two-member
sealed recordwrappingUserIdplus the same optionalScopeKeythe inbox read takes. Its XML doc (GetUnreadNotificationCountQuery.cs:3) names the unread badge as the reason it exists. - Depends on: the
UserIdentifierTypealias; BCL only otherwise. Handled by GetUnreadNotificationCountHandler. - Concept introduced: none new; a purpose-built count query rather than fetching a page and counting
client-side. The scope member exists for one reason, stated in its XML doc
(
GetUnreadNotificationCountQuery.cs:5-8): the badge must count exactly what the list will show, so both reads narrow by the same rule.[Rubric §12, Performance & Scalability]: a dedicatedCOUNTquery avoids materializing rows just to size a badge, so the bell can poll cheaply. - Walkthrough: two positional members,
UserId(line 10) and the nullableScopeKey(line 11). No paging: the answer is a single integer. - Where it's used: constructed by InboxController's unread-count action
(
NotificationInboxController.cs:79, scope bound atNotificationInboxController.cs:70) behind the NotificationBell badge; handled by GetUnreadNotificationCountHandler. That action is also marked[ResponseCache(NoStore = true)](NotificationInboxController.cs:67), so a badge poll is never served from a stale cache.
NotificationFeatures
MMCA.Common.Shared ·
MMCA.Common.Shared.Notifications·MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationFeatures.cs:8· Level 1 · class (static)
- What it is: the feature-flag key constants for the Notification module. It holds exactly one:
PushNotifications = "Notification.PushNotifications"(NotificationFeatures.cs:12), declared[FeatureFlag(FeatureFlagLifetime.Permanent, Owner = "MMCA.Common")](NotificationFeatures.cs:11). - Depends on:
MMCA.Common.Shared.FeatureFlags.FeatureFlagAttributeandFeatureFlagLifetime(Level 0types this one now sits above). - Concept, feature flags as named constants with a declared lifecycle.
[Rubric §6, CQRS & Event-Driven Design]assesses whether cross-cutting configuration lives in one place rather than as copy-pasted string literals. Defining the flag key once as aconst stringkeeps every gate that references it typo-free; the value is resolved at runtime by the feature-management layer that the feature-gate decorators and the[FeatureGate]attribute consult (see primer §2). The[FeatureFlag]attribute is ADR-031's dead-toggle detector:Permanentmarks a flag with no end date (a capability a host chooses to run with or without), as opposed toTemporary, which must carry a removal date and fails the build once that date passes (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagLifetime.cs:9-22). - Walkthrough: one
public const stringon astaticclass, carrying the[FeatureFlag]attribute (NotificationFeatures.cs:8-13). - Where it's used: the constant is applied as
[FeatureGate(NotificationFeatures.PushNotifications)]on all three notification controllers, NotificationsController (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationsController.cs:28),NotificationInboxController(.../NotificationInboxController.cs:27), and DevicesController (.../DevicesController.cs:23), so turning the flag off removes the whole push surface at once. The[FeatureFlag]declaration itself is asserted byFeatureFlagLifecycleTestsand inventoried byFeatureFlagRegistryTests(MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/FeatureFlags/FeatureFlagRegistryTests.cs).
NotificationPermissions
MMCA.Common.Shared ·
MMCA.Common.Shared.Notifications·MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationPermissions.cs:7· Level 0 · class (static)
- What it is: the permission-key constants for the Notification module. It holds exactly one:
Manage = "notifications:manage"(NotificationPermissions.cs:10), covering both sending push notifications and reading the send history. - Depends on: nothing first-party.
- Concept, capability-named permissions instead of roles. The doc comment states the rule
(
NotificationPermissions.cs:3-6): a host grants these constants to whichever roles it wants to hold them throughAddPermissions(...), and the endpoints state the capability, never a role.[Rubric §11, Security]assesses whether authorization is expressed as fine-grained capabilities that can be re-granted without touching endpoint code: because the controller carries[HasPermission(NotificationPermissions.Manage)](MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationsController.cs:29) rather than a role name, moving the capability from one role to another is a single line in the host's DI. The permission machinery itself (HasPermissionAttribute, PermissionRegistry) is taught in Group 08.[Rubric §15, Best Practices & Code Quality]: aconst stringmeans the grant site and the check site cannot drift apart by a typo. - Walkthrough: one
public const stringon astaticclass (NotificationPermissions.cs:7-11). - Where it's used: granted to RoleNames
.Organizerand to no other role by ADC's Notification module wiring (MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:37, see DependencyInjection); enforced on the framework's NotificationsController.
NotificationScopeKey
MMCA.Common.Shared ·
MMCA.Common.Shared.Notifications·MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationScopeKey.cs:20· Level 0 · class (static partial)
- What it is: the canonical formatter and validator for a notification scope key (called a
channel key on the SignalR join path): the
event:{id}/session:{id}string that narrows a push notification, or a live channel, to one subject. - Depends on: nothing first-party. It uses
System.Globalization.CultureInfoand the source-generatedSystem.Text.RegularExpressions.Regexfrom the BCL. - Concept introduced, keeping a format and its guard in one type. A string format that is written in
one place and validated in another is a latent bug: change either half and the other silently
strands. This type collapses both halves onto one static class (
NotificationScopeKey.cs:11-19). ThePatternconstant (NotificationScopeKey.cs:36) is literally the default value ofPushNotificationSettings.ChannelKeyPattern(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:37), the regex NotificationHub enforces before a client may join a group (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationHub.cs:232), so every key the factories produce is a key the hub accepts by construction.[Rubric §15, Best Practices & Code Quality]assesses whether shared literals are centralized: the alternative here was a hand-written interpolation at each call site, which is what this replaced.[Rubric §12, Performance & Scalability]shows in[GeneratedRegex](NotificationScopeKey.cs:68): the regex is compiled at build time by the source generator rather than parsed at runtime, and it carries a 1000 ms match timeout.[Rubric §27, i18n]is the subtle one:ForEventandForSessionformat the identifier underCultureInfo.InvariantCulture(NotificationScopeKey.cs:49,55) so a thread culture with non-ASCII digits cannot produce a key that its ownPatternwould reject. - Walkthrough: four constants first,
EventPrefix = "event"(line 23),SessionPrefix = "session"(line 26),Pattern = "^(event|session):[0-9]+\\z"(line 36), andMetadataKey = "scopeKey"(line 43). The pattern ends in the regex anchor\z, not$, and its remarks (lines 32-35) say why:$also matches just before a trailing newline, soevent:1\nwould pass a$-anchored check; the remarks also note the pattern is only ever evaluated by .NET regular expressions.MetadataKeyis the key under which a live (SignalR) notification's metadata carries its scope key so a client can leave a notification for another scope out of its toast and badge; each delivery page writes it (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:237-240) and an unscoped send carries no metadata at all. Then two factories,ForEvent(long)(lines 48-49) andForSession(long)(lines 54-55), both built withstring.Create(CultureInfo.InvariantCulture, $"..."), which formats into a stack buffer without an intermediate allocation.IsValid(string?)(lines 62-63) short-circuits on null or empty before running the generated matcher. The matcher itself is the private partial propertyScopeKeyRegex(lines 68-69), declared[GeneratedRegex(Pattern, RegexOptions.ExplicitCapture, matchTimeoutMilliseconds: 1000)]; the comment above it (lines 65-67) records whyExplicitCaptureis safe, it only suppresses the unused capture group of the alternation and leaves the pattern text andIsMatchsemantics identical. - Why it's built this way: a scope key crosses three subsystems (the send request, the persisted aggregate, and the SignalR group name), so its shape is a contract. Putting the format, the prefixes, and the regex on one type makes a change to any of them a compile-time coordinated edit.
- Where it's used: ADC's Engagement module builds every live-channel and points-subject key through
it, LivePollChannel
(
MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/LivePolls/LivePollChannel.cs:25,30), PointsSubjectKeys (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/Points/PointsSubjectKeys.cs:20,26), and CurrentEventNotificationScopeProvider, which even builds its unresolved-state sentinel fromEventPrefix(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Notifications/CurrentEventNotificationScopeProvider.cs:39) so the hub guard still accepts it. ThePatternconstant is consumed as a settings default by PushNotificationSettings.
PushNotificationStatus
MMCA.Common.Domain ·
MMCA.Common.Domain.Notifications.PushNotifications·MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotificationStatus.cs:6· Level 0 · enum
- What it is: the delivery lifecycle status of a push notification:
Pending,Sent,Failed. - Depends on: nothing first-party.
- Concept: a domain lifecycle enum owned by the PushNotification aggregate.
Its members are unnumbered (
PushNotificationStatus.cs:9-15), so the ordinal is implicit (Pending= 0); the value is written and read within a single store, so a pinned numeric contract is not required here.[Rubric §4, DDD]assesses whether state is modeled explicitly rather than as loose booleans; a three-state enum captures the send outcome precisely. - Walkthrough: three members with the obvious transition,
Pendingmoves to eitherSentorFailed, driven by the aggregate'sMarkAsSent/MarkAsFailedmethods (PushNotification.cs:162,167). - Where it's used: the
private setStatusproperty on PushNotification (PushNotification.cs:39); surfaced as its string name on PushNotificationDTO.
SendPushNotificationRequest
MMCA.Common.Shared ·
MMCA.Common.Shared.Notifications.PushNotifications·MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/PushNotifications/SendPushNotificationRequest.cs:6· Level 0 · record (sealed)
- What it is: the broadcast request to push a notification to every recipient. A two-parameter
positional record,
sealed record SendPushNotificationRequest(string Title, string Body)(SendPushNotificationRequest.cs:6), plus an optionalScopeKeyinit property and the two length limits both sides of the wire share. - Depends on: nothing first-party.
- Concept, publishing an invariant's number on the contract.
TitleMaxLength = 200(SendPushNotificationRequest.cs:15) andBodyMaxLength = 2000(SendPushNotificationRequest.cs:21) mirror the domain invariantsPushNotificationInvariants.TitleMaxLength/.BodyMaxLength(MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/Invariants/PushNotificationInvariants.cs:13,16), which the server enforces. The doc comment (SendPushNotificationRequest.cs:8-14) gives the reason: the contract is the one type both sides of the wire share, so a compose form can cap its input and draw its character counter from the same number the server rejects on, instead of restating it.[Rubric §9, API & Contract Design]assesses whether the contract is self-describing; publishing the bound is exactly that.[Rubric §24, Forms/Validation/UX Safety]: the UI validation and the server validation cannot disagree because they read the same constant, and the framework's send page test exercises the boundary through it (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Notifications/NotificationSendTests.cs:139). - Walkthrough: two positional parameters (line 6); two
public const intlimits (lines 15, 21); andScopeKeyas a nullableinitproperty (line 28) rather than a third positional parameter, which the comment (lines 23-27) notes was deliberate so every existing caller keeps compiling. Null, the default, sends an unscoped notification that every read sees. No validation attributes live on this record: the content invariants are enforced server-side by the request validator and by the PushNotification aggregate'sCreatefactory. - Why it's built this way: mirroring rather than importing the domain constant keeps
MMCA.Common.Sharedfree of a dependency onMMCA.Common.Domain, which is what lets a client project reference the contracts assembly alone[Rubric §3, Clean Architecture]. - Where it's used: bound as the
[FromBody]parameter of the send action on NotificationsController (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationsController.cs:49), which also reads theIdempotency-Keyheader and passes it on as the dedup key (.../NotificationsController.cs:62); consumed client-side by PushNotificationService.
UserNotificationDTO
MMCA.Common.Shared ·
MMCA.Common.Shared.Notifications.UserNotifications·MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/UserNotifications/UserNotificationDTO.cs:7· Level 0 · record (sealed)
- What it is: the read DTO for one item in a user's notification inbox. It merges the user's
read-tracking (
IsRead,ReadOn) with the underlying push content (Title,Body,SentOn) into the single shape the inbox UI renders. - Depends on: nothing first-party. It uses the
UserNotificationIdentifierTypeandPushNotificationIdentifierTypealiases (UserNotificationDTO.cs:10,13), which areglobal using ... = int;aliases, so there is no first-party edge. - Concept, identifier-type aliases in a DTO.
[Rubric §4, DDD]assesses avoiding primitive obsession: theIdis typedUserNotificationIdentifierTypeand the foreign keyPushNotificationIdis typedPushNotificationIdentifierType, so the names carry intent even though both currently resolve toint. Change the alias in one file and every usage updates (see primer §2). - Walkthrough: a
sealed record classwithrequired initvalues that must always be present,Id,PushNotificationId,Title,Body, andIsRead(UserNotificationDTO.cs:10-22), plus plaininitmembers for the nullableReadOn(line 25) and the always-presentSentOn(line 28).requiredplusinitgives set-once, non-null-where-it-matters immutability without a hand-written constructor. - Why it's built this way: the DTO flattens two persistence concepts (the per-user read row and the
shared push content) into the one row the inbox needs
[Rubric §9], mirroring the two-table join the read handler performs. - Where it's used: returned by the inbox query GetMyNotificationsHandler. Note that the ADC privacy export uses a separate UserNotificationExportItemDTO shape instead, because it carries the scope key and omits the body.
PushNotificationDTO
MMCA.Common.Shared ·
MMCA.Common.Shared.Notifications.PushNotifications·MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/PushNotifications/PushNotificationDTO.cs:8· Level 1 · record class
- What it is: the read DTO for a persisted PushNotification: id, title, body, the sender, the recipient count, a delivery-status string, the optional scope key, the per-platform native push counts with their delivery unit, and the creation timestamp.
- Depends on: IBaseDTO<TIdentifierType>
(implements
IBaseDTO<PushNotificationIdentifierType>,PushNotificationDTO.cs:8). - Concept: the standard
IBaseDTOread-model shape (see IBaseDTO<TIdentifierType>). Note thatStatusis astring(PushNotificationDTO.cs:26) even though the domain uses the PushNotificationStatus enum: the DTO carries the serialized form so the API surface can evolve independently of the domain enum and stays readable in responses without a separate enum-to-string step at the client.[Rubric §9, API & Contract Design]. - Walkthrough:
required initmembers forId,Title,Body,SentByUserId,RecipientCount, andStatus(PushNotificationDTO.cs:11-26), then plaininitmembers: the nullableScopeKey(line 29), the four nullable native push countsAndroidSent,AndroidFailed,AppleSentandAppleFailed(lines 32-41), the nullableNativeDeliveryUnitstring naming the unit those counts are in (Batch,EndpointorMessage, line 47), andCreatedOn(line 50).ScopeKeyis optional rather than required precisely because unscoped notifications are the default (see PushNotification). The native fields are nullable because a null pair means that platform was not attempted or not recorded (doc comments, lines 31-46); likeStatus, the unit travels as a string rather than an enum.DedupKeyis deliberately absent from the DTO: it is internal idempotency plumbing, not something a reader needs. - Where it's used: returned by the notification-history query and rendered on the organizer's
push-notification admin view, where the notification list turns the native counts into per-platform
phone delivery lines
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationList.razor.cs:70-72).
PushNotification
MMCA.Common.Domain ·
MMCA.Common.Domain.Notifications.PushNotifications·MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:15· Level 7 · class (sealed)
- What it is: the framework-level aggregate root for a push-notification broadcast. It records the title, body, sender, recipient count, delivery status, an optional deduplication key, an optional scope key, and the per-platform native (OS-level) push outcome. It raises no domain event, not even on creation.
- Depends on:
AuditableAggregateRootEntity<TIdentifierType>
(base class), PushNotificationInvariants and
CommonInvariants (validation),
PushNotificationStatus, and
Result (factory return). It carries the
IdValueGeneratedAttribute
(
PushNotification.cs:14). - Concept, the aggregate-root factory idiom applied to a framework-owned entity (the canonical
entity-chain teaching is Group 02). Three design choices are
worth naming. First,
[IdValueGenerated](line 14) tells the persistence layer the database generates the id, soCreatesetsId = default(line 153) and lets SQL Server fill theIDENTITY. Second, the aggregate raises no domain event at all,Createincluded: the factory's doc comment (lines 104-107) records that nothing consumes one and that the id is not known until the first save.[Rubric §6, CQRS & Event-Driven]and[Rubric §4, DDD]both reward events that carry a business-observable fact to a real consumer; an event with no handler, stamped with adefaultid, would be neither, so the send's follow-on work is driven by the handler that created the row instead. Third, and this is the interesting one,DedupKey(lines 41-47) is the aggregate's idempotency anchor: the doc comment records that a filtered unique index on the column lets the database arbitrate a race between two retried sends, so the same notification is never delivered twice.[Rubric §29, Resilience & Business Continuity]assesses whether retries are safe; here the guarantee is pushed down to a database constraint rather than trusted to a read-then-write check.ScopeKey(lines 49-55) is explicitly not a security boundary: the comment states that a read supplying a scope sees the notifications carrying that scope plus every unscoped one, and a read supplying none still sees everything, so it is an opaque view filter[Rubric §11, Security]. - Walkthrough: three length constants first,
DedupKeyMaxLength = 128(line 18),ScopeKeyMaxLength = 128(line 21) andNativeDeliveryUnitMaxLength = 20(line 24). Then twelveprivate setproperties:Title,Body,SentByUserId,RecipientCount,Status(lines 27-39); the two nullable keysDedupKey(line 47) andScopeKey(line 55); and the native push outcome (ADR-044), four nullable countsAndroidSent,AndroidFailed,AppleSent,AppleFailed(lines 62-71) plus the nullableNativeDeliveryUnitnaming the provider's unit (for exampleBatch,EndpointorMessage, line 78). A null count means nothing was attempted on that platform, or the row predates the recorded outcome (lines 57-61). A private parameterless constructor (lines 81-85) seeds non-null strings for EF materialization; a private all-args constructor (lines 87-102) setsStatus = PushNotificationStatus.Pending(line 99) and normalizes both optional keys, whitespace collapses tonull(lines 100-101), so "empty string" can never become a distinct dedup identity. The staticCreatefactory (lines 121-157) combines four invariant checks throughResult.Combine(lines 129-145): title, body, and the twoEnsureStringMaxLengthguards for the dedup and scope keys, each carrying its own error code ("PushNotification.DedupKey.TooLong", line 135;"PushNotification.ScopeKey.TooLong", line 142) and an invariant-culture message. On any failure it returnsResult.Failure<PushNotification>(result.Errors)(lines 146-149), aggregating every broken rule rather than reporting only the first. Otherwise it constructs the entity withId = default(lines 151-154) and returns success (line 156), adding no domain event.MarkAsSentandMarkAsFailed(lines 162, 167) are one-line expression-bodiedvoidtransitions with no event: they record the delivery outcome for audit.AddNativePushOutcome(lines 185-196) is the third event-free mutator, and it accumulates rather than overwrites: each call adds one delivery page's per-platform outcome to the counts already recorded (doc comment, lines 169-175). A blank or nulldeliveryUnitkeeps the unit already stored, otherwise the new name replaces it (lines 187-190). Each of the four counts goes through the privateAccumulatehelper (lines 192-195, defined at lines 198-199): a null page value leaves the stored count as it is (that platform was not attempted on this page), and a non-null one is added to the stored count with null reading as zero, so the first page of a send records exactly what it reports. It leavesStatusalone becauseStatusis the SignalR leg's outcome, not the native one (lines 173-174). - Why it's built this way: living in
MMCA.Common.Domain, this aggregate is reused by ADC and Store without coupling to any app's module. ThePendingtoSent/Failedbookkeeping and the native outcome recording are intentionally event-free because they reflect an infrastructure callback, not a business decision. Keeping the native counts separate fromStatusmeans one broadcast can beSentover SignalR while, say, Apple delivery failed, and the history shows both. Accumulating per page, instead of overwriting, lets a broadcast delivered in several pages end with totals for the whole send rather than the last page's numbers. Both optional keys default tonull: no dedup key means every send creates a new notification, and no scope key makes the notification visible to every read, scoped or not (lines 112-119). - Caveats / not-in-source: the filtered unique index that makes
DedupKeya real race arbiter is described in the entity's doc comment (lines 43-45) but is declared in the EF configuration and migration, not here; the aggregate itself performs no uniqueness check. LikewiseAddNativePushOutcomedoes not validateNativeDeliveryUnitMaxLength: the limit is applied as the column length inMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/Notifications/PushNotificationConfiguration.cs:62-63, and the only caller passes an enum name or null, and calls it only when the page outcome carries a platform count or a failure (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:199-206). The accumulation also does not deduplicate: a page whose outcome is recorded twice is counted twice, and nothing in the aggregate guards against that. - Where it's used: created by SendPushNotificationHandler (one per broadcast), which then fans out a UserNotification per recipient; its native outcome is added page by page by DeliverPushNotificationPageInternalCommandHandler; read back through PushNotificationDTO and joined for the privacy export by UserNotificationExportService.
MarkNotificationReadHandler
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.UserNotifications.UseCases.MarkRead·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/MarkRead/MarkNotificationReadHandler.cs:12· Level 8 · class (sealed)
- What it is: the command handler that marks one inbox notification as read, but only if it belongs to the requesting user.
- Depends on: IUnitOfWork (repository plus save),
IQueryableExecutor (async materialization),
TimeProvider(BCL, testable clock), MarkNotificationReadCommand (input), UserNotification (the aggregate it mutates), and Result / Error (outcome). - Concept, ownership enforced in the query, not after it.
[Rubric §11, Security]assesses whether authorization is enforced where the data is touched. This handler never loads a row by id and then checks the owner in memory; it filters on bothIdandUserIdin the same predicate (MarkNotificationReadHandler.cs:26), so a mismatched owner simply yields zero rows and the handler answersNotFound(lines 30-36) rather than leaking that the notification exists for someone else.[Rubric §14, Testability]shows in the injectedTimeProvider: the read timestamp comes fromtimeProvider.GetUtcNow().UtcDateTime(line 38), notDateTime.UtcNow, so a test can pin the clock. - Walkthrough:
HandleAsync(lines 18-42) gets theUserNotificationrepository from the unit of work (line 22), builds aWhere(Id && UserId).Take(1)query and materializes it through the queryable executor (lines 24-28), returns anError.NotFoundErrorfailure with code"UserNotification.NotFound"when there is no match (lines 30-36), otherwise calls the aggregate'sMarkAsRead(...)with the injected UTC time (line 38), saves through the unit of work (line 39), and returns success (line 41). Every await usesConfigureAwait(false). - Why it's built this way: the
Take(1)plus owner-scoped filter is the cheapest safe read, and idempotency lives in the aggregate, not the handler: UserNotification.MarkAsReadreturns immediately whenIsReadis already true (MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/UserNotifications/UserNotification.cs:58-67), so a repeated mark neither overwrites the originalReadOnnor produces a spurious update. That keeps this handler a thin orchestrator. - Where it's used: dispatched by the inbox controller's mark-read action, with the authenticated user id supplied server-side.
MarkAllNotificationsReadHandler
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.UserNotifications.UseCases.MarkAllRead·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/MarkAllRead/MarkAllNotificationsReadHandler.cs:18· Level 8 · class
- What it is: the command handler that clears a user's unread notifications (all of them, or just the
ones in a scope) with one set-based
UPDATE: it builds a predicate over the user's unread rows and hands it to the repository'sExecuteUpdateAsync, never loading a row. - Depends on: IUnitOfWork, resolved as
IRepository<TEntity, TIdentifierType>
via
GetRepository, and the BCLTimeProvider(primary constructor, lines 18-20). Implements ICommandHandler<in TCommand, TResult><MarkAllNotificationsReadCommand, Result>and writes the same two columns UserNotification'sMarkAsReadowns. - Concept introduced: a set-based write that deliberately bypasses the change tracker. The type's
<remarks>(lines 13-17) carry the argument: an inbox can hold an unbounded number of unread rows, andMarkAsReadonly setsIsReadandReadOnand raises no domain event (MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/UserNotifications/UserNotification.cs:58-67), so issuingUPDATE ... SET IsRead = 1, ReadOn = @now WHERE ...loses nothing that loading and tracking each row would have kept. The repository contract spells out the cost of the bypass: no domain events, global query filters still apply to the predicate, and the update runs on the ambient transaction when one is active (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:469-494). Audit fields are not lost either: becauseExecuteUpdateskips the save pipeline's audit interceptor,EFRepositorystampsLastModifiedOnandLastModifiedByitself unless the caller set them (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepository.cs:115-129).[Rubric §12, Performance & Scalability]: one statement regardless of inbox size, with no materialization.[Rubric §4, DDD]assesses whether state changes go through the aggregate rather than around it: here they go around it on purpose, and the invariantMarkAsReadprotects (an already-read row keeps its originalReadOn,UserNotification.cs:60-63) is preserved by the!un.IsReadterm in the predicate, so a read row never matches and its timestamp is never overwritten.[Rubric §14, Testability]: the read timestamp comes from an injectedTimeProvider(line 20, used at line 48) rather thanDateTime.UtcNow, which is what makes the clock substitutable in a unit test. - Walkthrough: get the UserNotification write repository via
GetRepository(line 27); form the base predicateun.UserId == command.UserId && !un.IsReadas anExpression<Func<UserNotification, bool>>(lines 29-30); when and only when a non-blankScopeKeyarrived (line 37), copy it into a local (line 39), take the PushNotificationTable(line 40) and replace the predicate with one that adds a correlatedpushNotifications.Any(pn => pn.Id == un.PushNotificationId && (pn.ScopeKey == null || pn.ScopeKey == scopeKey))test (lines 42-45), which EF translates to anEXISTSsubquery; take one UTC instant for the whole batch (line 48) so every row in one call reports the same read time; callrepository.ExecuteUpdateAsyncwith the predicate and setters forIsRead = trueandReadOn = readOnUtc(lines 50-55); returnResult.Success()(line 57). - Why it's built this way: the scope condition mirrors the unread count for the two reasons the
comment on lines 32-36 gives: a scoped client must not mark rows it cannot see as read, and a no-scope
command keeps the legacy predicate exactly as it was rather than inheriting
PushNotification's soft-delete global query filter. Expressing the scope as anEXISTSsubquery rather than a join keeps the update targeted atUserNotificationalone while the push-notification filter applies to the subquery exactly as it does to the unread count's join (same comment). A repeated "mark all read" is a cheap no-op at the database: the predicate matches zero rows and nothing changes, which matters because the UI can fire it on every inbox open. The returned row count is discarded, since the command reports success either way. Since MarkAllNotificationsReadCommand does not implement ITransactional, the singleUPDATEstatement is the atomic unit; see Group 05 for the decorator order. - Where it's used: injected into InboxController as
ICommandHandler<MarkAllNotificationsReadCommand, Result>(NotificationInboxController.cs:33) and invoked by thePUT read-allaction (NotificationInboxController.cs:123), which returns 204 on success (NotificationInboxController.cs:125).
GetUnreadNotificationCountHandler
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.UserNotifications.UseCases.GetUnreadCount·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/UserNotifications/UseCases/GetUnreadCount/GetUnreadNotificationCountHandler.cs:13· Level 8 · class
- What it is: the query handler behind the unread badge: it counts a user's unread UserNotification rows, optionally narrowed to a scope, and returns the integer.
- Depends on: IUnitOfWork, resolved as
IReadRepository<TEntity, TIdentifierType>
via
GetReadRepository(line 22, and again for the scoped path at line 34), and IQueryableExecutor (primary constructor, lines 13-15). Implements IQueryHandler<in TQuery, TResult><GetUnreadNotificationCountQuery, Result<int>>. - Concept introduced: a conditional join, and why the unscoped path must stay byte-for-byte the
same. The comment on lines 27-30 is the teaching moment: the join to
PushNotification is introduced only for a scoped count, because an
unconditional join would drag
PushNotification's soft-delete global query filter into the legacy no-scope count and silently change a number no caller asked to change. A scoped count accepts that narrowing deliberately, since a scoped reader could not see a deleted parent anyway.[Rubric §8, Data Architecture]assesses awareness of how global query filters and joins interact; this is that awareness written into the code.[Rubric §12, Performance & Scalability]: the handler issues a server-sideCOUNToverun.UserId == query.UserId && !un.IsReadrather than fetching rows, so the bell can poll without materializing the inbox. It is also a good illustration of why IQueryableExecutor exists: the handler composes the predicate in Application and hands the still-unexecutedIQueryableto Infrastructure to run. - Walkthrough: get the UserNotification read-only repository from the unit of
work via
GetReadRepository(line 22); compose the base filter overTableNoTrackingfor the user's unread rows (lines 24-25); when and only when a non-blankScopeKeyarrived, resolve the PushNotification read-only repository the same way and re-form the query as a join keeping rows whose parent is unscoped or matches the scope (lines 31-40, withselect unso the projection staysUserNotification); runqueryableExecutor.CountAsync(line 42); returnResult.Success(count)(line 44). No paging, no mapping, no failure branch: the count either comes back or the call throws through the pipeline. - Why it's built this way:
string.IsNullOrWhiteSpace(line 31) is the gate, so a blank query-string scope is treated as absent rather than as a scope nothing matches. Reassigningunreadrather than branching into two separate counts keeps a single execution path for the terminal operator. - Where it's used: injected into InboxController
(
NotificationInboxController.cs:31), which serves the NotificationBell badge.
LiveChannelGrpcService
MMCA.ADC.Notification.Service ·
MMCA.ADC.Notification.Service.Grpc·MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/LiveChannelGrpcService.cs:31· Level 1 · class (sealed)
- What it is: the gRPC server endpoint that other services call to fan an ephemeral "live"
event out to connected clients. It implements the generated
LiveChannelPushService.LiveChannelPushServiceBaseand delegates each call to the framework's ILiveChannelPublisher. - Depends on: ILiveChannelPublisher (injected via the primary
constructor,
MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/LiveChannelGrpcService.cs:31; in this host it resolves to SignalRLiveChannelPublisher, registered byAddPushNotificationsbecause Notification is the host that maps the SignalR NotificationHub), the generatedLiveChannelPushServicebase (compiled from the.Contracts.proto,LiveChannelGrpcService.cs:32), andGrpc.Core.ServerCallContext. - Concept introduced, the live-channel ingress (ADR-039).
[Rubric §6, CQRS & Event-Driven]assesses whether state changes travel as events;[Rubric §7, Microservices Readiness]assesses whether cross-process collaboration rides typed transports. The conference-day live layer (LivePolls, SessionQuestions) lives in the Engagement service, but only the Notification host owns the SignalRIHubContextthat can reach browsers. So Engagement calls THIS gRPC endpoint post-commit to hand off an ephemeral event, which the service passes to the local publisher that fans it out over NotificationHub (doc commentLiveChannelGrpcService.cs:10-15). This is the server half; its client half is LiveChannelPublisherGrpcAdapter. - Walkthrough: the single
PushToChanneloverride (LiveChannelGrpcService.cs:47) null-guardsrequestandcontext(LiveChannelGrpcService.cs:51-52), validates the three fields (LiveChannelGrpcService.cs:54-56), then awaitspublisher.PublishAsync(request.ChannelKey, request.EventName, request.PayloadJson, context.CancellationToken)(LiveChannelGrpcService.cs:58-60) and returns an emptyPushToChannelResponse(LiveChannelGrpcService.cs:62). The transport still relays the event rather than modeling it, but it no longer accepts arbitrary strings: the class doc (LiveChannelGrpcService.cs:24-29) calls this the "bounded payloads" compensating control for an unauthenticated ingress.- Three caps (
LiveChannelGrpcService.cs:34-36):MaxChannelKeyLength= 200,MaxEventNameLength= 100,MaxPayloadBytes= 64 KiB (64 * 1024). AllowedChars(LiveChannelGrpcService.cs:43-44), aSearchValues<char>overabcdefghijklmnopqrstuvwxyz0123456789:.-, is the one character set shared by channel keys and event names; its doc comment (LiveChannelGrpcService.cs:38-42) notes it covers every producer format, NotificationScopeKey keys such asevent:1and the live-layer event names such aspoll.results-changed.ValidateName(LiveChannelGrpcService.cs:65-81) rejects a blank value, one over its cap, and one containing any character outsideAllowedChars(ContainsAnyExcept,LiveChannelGrpcService.cs:77).ValidatePayload(LiveChannelGrpcService.cs:83-89) rejects a payload whose UTF-8 byte count exceeds the cap; a null payload passes.- Every refusal is an
RpcExceptionwithStatusCode.InvalidArgumentbuilt byInvalidArgument(LiveChannelGrpcService.cs:91-92), thrown before the publisher is reached, with messages formatted underCultureInfo.InvariantCulture.[Rubric §11, Security]: input bounding is what limits the blast radius of a surface that cannot authenticate its caller.
- Three caps (
- Why it's built this way (security posture): the class carries no
[Authorize]attribute; the host applies the policy at the mapping instead, with.RequireAuthorization(ServiceTokenDefaults.ServiceCallerPolicy)(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:167). The comment above it (Program.cs:159-166) gives the reasoning.[Rubric §11, Security]: the edge writes (it fans poll results and approved questions out to every connected client), so it is never left to the internal-only reach (external:falseACA ingress, never routed by the Gateway) alone. Its one caller is Engagement's LiveChannelPublishProcessor background drain, which runs with noHttpContextand so has no user bearer to forward; Engagement's live-channel client always presents its own service token (Grpc:ServiceToken) instead. Because no caller forwards a user token, the edge takes the ServiceCaller policy and a signed-in user's bearer is refused, while the bounded-payload checks above still run on every admitted call. (The class doc comment,LiveChannelGrpcService.cs:16-22, describes the same posture but names the policyInternalCaller; the mapping inProgram.cs:167is what applies.) Transport-wise it rides the ADR-012 mixed-endpoint profile: Notification keeps its default endpointHttp1AndHttp2for SignalR WebSockets (Program.cs:79) and serves this h2c gRPC ingress on a dedicatedHttp2-only endpoint namedgrpc(port 8081 in the container, 5996 locally), declared in theKestrel:Endpointsconfig section rather than in code; the full reasoning is spelled out atProgram.cs:72-78. - Where it's used: mapped by the Notification service's
Program.cs(Program.cs:167); invoked by LiveChannelPublisherGrpcAdapter running inside Engagement.
LiveChannelPublisherGrpcAdapter
MMCA.ADC.Notification.Contracts ·
MMCA.ADC.Notification.Contracts·MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/LiveChannelPublisherGrpcAdapter.cs:29· Level 1 · class (sealed)
- What it is: the client half of the live-channel ingress. It is a hand-written adapter that implements the framework port ILiveChannelPublisher on top of the generated gRPC client, so a publishing service (Engagement) can keep calling the abstraction while the event actually travels to the Notification host over the wire.
- Depends on: ILiveChannelPublisher (Level 0, the implemented port); the
generated
LiveChannelPushService.LiveChannelPushServiceClientfrom the.Contracts.proto(its only constructor dependency, injected via the primary constructor,MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/LiveChannelPublisherGrpcAdapter.cs:29-30). It talks to LiveChannelGrpcService on the far side. - Concept introduced, the hand-written adapter over a generated gRPC client.
[Rubric §1, SOLID]assesses dependency inversion: Engagement's live handlers depend only onILiveChannelPublisher, and whether that resolves to the in-process SignalR publisher or this remote adapter is a composition-root decision (class doc,LiveChannelPublisherGrpcAdapter.cs:7-12).[Rubric §7, Microservices Readiness]assesses whether a module survives extraction: this class is exactly the piece that makes the extracted topology work without touching a single handler.[Rubric §29, Resilience & Business Continuity]assesses graceful degradation, and the policy is enforced one layer up. Live channel events are ephemeral by contract (ADR-039), but a failure (transport, name resolution, an open circuit) propagates from this adapter (LiveChannelPublisherGrpcAdapter.cs:13-28, ADR-096). The only caller, Engagement'sLiveChannelPublishProcessor, runs every publish insideBestEffort.ExecuteAsyncoff the request path, which swallows the failure, logs one Warning and counts it onbesteffort.dispatch.failed(operationlive-channel-publish:*); swallowing in the adapter as well would hide every push failure from that metric (ADR-121). A publishing command never awaits this adapter, so a down Notification service still cannot fail it. - Walkthrough
PushDeadline(LiveChannelPublisherGrpcAdapter.cs:35), a privatestatic readonly TimeSpanof 2 seconds. The comment above it (:32-34) explains the choice: it is deliberately tighter than the framework's default call deadline, HttpResilienceDefaults.GrpcCallDeadline(5 seconds,MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:87), because a live event that takes longer than two seconds is stale anyway and the publishing drain should not be held hostage waiting for it. A caller-set deadline wins over that default, so this one applies.PublishAsync(channelKey, eventName, payloadJson, cancellationToken)(LiveChannelPublisherGrpcAdapter.cs:38) builds aPushToChannelRequestfrom the three opaque strings and awaitsclient.PushToChannelAsync(...)withdeadline: DateTime.UtcNow.Add(PushDeadline)and the caller's token (:42-50).- The only catch is a filtered
catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled && cancellationToken.IsCancellationRequested)(:52), which rethrows asOperationCanceledException(ex.Status.Detail, ex, cancellationToken)(:54). The gRPC client reports the caller's own cancellation as aCancelledRpcException, whichBestEffortwould otherwise count as a failed push on every host shutdown. Every other failure leaves untouched, so[Rubric §13, Observability]is served by the caller's one Warning and metric rather than a log line here (the adapter no longer takes anILogger).
- Why it's built this way: writing the adapter by hand (rather than letting consumers inject the
generated client directly) is what keeps the gRPC dependency out of the Engagement handlers. The
best-effort policy is stated once, in the caller's
BestEffortwrapper, so a swallow here would only blind that wrapper. Its sibling UserNotificationExportServiceGrpcAdapter also lets transport failures propagate, because the caller needs to know the export section is unavailable. - Where it's used: registered by the Notification.Contracts
DependencyInjection's
AddNotificationLiveChannelClient, which usesservices.Replace(...)so the adapter overwrites the framework's NullLiveChannelPublisher default (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:55). The one caller today is the Engagement service's composition root (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:229).
NullLiveChannelPublisher
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications.Live·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Live/NullLiveChannelPublisher.cs:11· Level 1 · class (sealed)
- What it is: a no-op implementation of the ILiveChannelPublisher port. It is the default the container resolves when a host has not wired a real transport, so the live-channel path always has something to call.
- Depends on: ILiveChannelPublisher (Level 0). No externals beyond the BCL
Task. - Concept introduced, the Null Object pattern for optional infrastructure.
[Rubric §1, SOLID]assesses the Dependency Inversion Principle: application handlers depend only on the abstraction, and the concrete adapter is chosen at the composition root.[Rubric §29, Resilience & Business Continuity]assesses graceful degradation: rather than leave the port unregistered (which would make DI throw when a handler asks for it), the framework registers a member that does nothing, so a host that never configures push simply publishes into the void without failing. This is the same idea behind NullPushNotificationSender and NullNavigationPopulator<TEntity>. The recipient port is the deliberate exception:INotificationRecipientProviderhas no null default, andNotificationRecipientProviderValidatorfails startup when none is registered (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/NotificationRecipientProviderValidator.cs:7-23). - Walkthrough: one method,
PublishAsync(channelKey, eventName, payloadJson, cancellationToken)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Live/NullLiveChannelPublisher.cs:14), whose whole body is=> Task.CompletedTask(NullLiveChannelPublisher.cs:15). No exception, no logging, no work. - Why it's built this way: the class doc comment (
NullLiveChannelPublisher.cs:5-10) states the contract: downstream apps override this with SignalRLiveChannelPublisher viaAddPushNotifications(), or with their own transport (in ADC, a gRPC adapter that forwards to the host that maps the hub). Because the default resolves cleanly, no host is forced to configure a real-time transport (ADR-039, live channels are best-effort by design). - Where it's used: registered as the framework default with
services.TryAddTransient<ILiveChannelPublisher, NullLiveChannelPublisher>()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:419) so the port is always resolvable;AddPushNotificationsadds the SignalR implementation over it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:98), and in ADC Engagement's composition rootservices.Replace(...)overwrites it with the LiveChannelPublisherGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:55).
SendPushNotificationCommand
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.UseCases.Send·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationCommand.cs:21· Level 1 · record (sealed)
- What it is: the CQRS command that triggers a push-notification broadcast. It wraps a
SendPushNotificationRequest plus the sender's
UserIdentifierType, carries an optional deduplication key, and marks the whole send as transactional. - Depends on: ICommandWithRequest<out TRequest> (Level 0), ITransactional (Level 0), SendPushNotificationRequest (Level 0).
- Concept: the command-wraps-request idiom (see
ICommandWithRequest<out TRequest>, G05).
The public HTTP request is the small
Title/Body/ScopeKeyrecord; the command additionally carries server-derived context (SentByUserId, taken from the caller's token, not the body) so the client cannot spoof the sender. ExposingRequestsatisfies theICommandWithRequest<SendPushNotificationRequest>contract, which lets the generic validating command decorator run SendPushNotificationRequestValidator automatically in the pipeline.[Rubric §6, CQRS & Event-Driven],[Rubric §11, Security]. - Walkthrough: a two-parameter positional record implementing both
ICommandWithRequest<SendPushNotificationRequest>andITransactional(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationCommand.cs:21-23), plus one body member.Request(SendPushNotificationCommand.cs:22) is the validated DTO;SentByUserId(SendPushNotificationCommand.cs:23) is the audit/authorization context.DedupKey(SendPushNotificationCommand.cs:36), aninit-onlystring?, is the optional deduplication key, typically the caller'sIdempotency-Keyheader. Its doc comment (SendPushNotificationCommand.cs:25-35) states the contract: when present, a send whose key has already been seen returns the existing notification instead of creating a second one and sending again; when null (the default, and what the send endpoint passes when the request carries no key) every send creates a new notification. The key is scoped to the sender (SendPushNotificationCommand.cs:32-34): the handler stores and looks up a SHA-256 of{SentByUserId}:{key}, never the raw client key, so two senders reusing one client key never collide, and the stored value always fits the column.[Rubric §29, Resilience & Business Continuity]assesses whether a retry is safe: this property is what makes a retried broadcast at-most-once at the delivery level (see the matching logic in SendPushNotificationHandler). It complements, and is distinct from, the HTTP-level IdempotentAttribute response cache (ADR-017).
- Why it's built this way (the
ITransactionalmarker): the class doc (SendPushNotificationCommand.cs:11-19) is unusually explicit, and it is the key to reading the handler. The handler writes the audit row first and the per-recipient inbox rows second, so without a transaction a fault between the two would leave a committed notification row carryingDedupKeythat nothing ever delivered, and every later retry with that key would short-circuit on the dedup lookup and report success forever. UnderITransactionalthe Transactional decorator in the CQRS pipeline (ADR-014) rolls the failed attempt back whole, so the retry genuinely re-runs the send. The doc also names the accepted cost: the two sender calls run inside the transaction, bounded by their own timeouts and holding locks only on rows this request just inserted.[Rubric §8, Data Architecture],[Rubric §29, Resilience]. - Where it's used: dispatched by the push-notification API endpoint (the organizer-only NotificationsController); handled by SendPushNotificationHandler.
AttendeeNotificationRecipientProvider
MMCA.ADC.Notification.Application ·
MMCA.ADC.Notification.Application·MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/AttendeeNotificationRecipientProvider.cs:15· Level 1 · class (sealed)
What it is: the ADC-specific implementation of the framework's INotificationRecipientProvider boundary. It answers the question "who are the recipients of a broadcast push?" with "every attendee", by delegating to the Identity module's attendee query.
Depends on: INotificationRecipientProvider (implements it) and IAttendeeQueryService (constructor-injected,
AttendeeNotificationRecipientProvider.cs:15-16).Concept introduced, the app-supplied recipient strategy. The framework defines what a recipient provider must return but deliberately does not decide who recipients are; that is an application policy each host plugs in. This is the
[Rubric §1, SOLID]dependency-inversion story in miniature:MMCA.Commonowns the INotificationRecipientProvider abstraction, and ADC supplies the concrete "all attendees" rule; a host that registers the notification services but supplies no provider fails startup instead (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/NotificationRecipientProviderValidator.cs:18-23).[Rubric §3, Clean Architecture]is why the class lives in ADC's module rather than in Common: recipient policy is business-specific and must not leak into the reusable framework.[Rubric §7, Microservices Readiness]: the provider talks to Identity through an interface, so when Identity is extracted the same call becomes a gRPC hop with no change here.Walkthrough: a primary-constructor class taking
IAttendeeQueryService(AttendeeNotificationRecipientProvider.cs:15-16). Both members of the interface are non-async expression-bodied methods that return theTaskfrom Identity directly (noawait, so no extra state machine), with no added logic:GetRecipientPageAsync(afterUserId, take, cancellationToken)(AttendeeNotificationRecipientProvider.cs:19-23) returnsattendeeQueryService.GetAttendeeUserIdPageAsync(afterUserId, take, cancellationToken), one keyset page of attendee ids after the cursor.CountRecipientsAsync(cancellationToken)(AttendeeNotificationRecipientProvider.cs:26-27) returnsattendeeQueryService.CountAttendeesAsync(cancellationToken).
The remarks (
AttendeeNotificationRecipientProvider.cs:10-14) record why the mapping can be one to one: the framework's page contract says a page shorter thantakeends the delivery walk, so a provider that filters ids out must keep reading until the page is full (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/INotificationRecipientProvider.cs:16-22). Identity's attendee page already honours that contract (it reads past the synthetic load-test accounts it leaves out until the page is full or the audience is exhausted), and its count applies the same rule.Why it's built this way: keeping the provider a thin bridge means the "who is a recipient" decision has exactly one place to change, and the Identity module stays the owner of the attendee roster. Asking for a page at a time, rather than the whole roster, means no delivery page ever loads every attendee.
Where it's used: registered as the scoped
INotificationRecipientProviderin the Notification module's application-layer DependencyInjection (MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/DependencyInjection.cs:22);CountRecipientsAsyncis consumed by SendPushNotificationHandler for the audit count, andGetRecipientPageAsyncby DeliverPushNotificationPageInternalCommandHandler for each delivery page.
UserNotificationExportService
MMCA.ADC.Notification.Application ·
MMCA.ADC.Notification.Application·MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/UserNotificationExportService.cs:15· Level 8 · class (internal sealed)
- What it is: the Notification half of ADC's cross-service data-subject export (PRIVACY.md §7). It returns every notification row for one user, joined to its push content, unpaged and newest first, so Identity's export aggregator can include a person's inbox in their downloadable data.
- Depends on: IUserNotificationExportService (implements it, the
interface lives in
MMCA.ADC.Notification.Shared), IUnitOfWork, IQueryableExecutor, the framework UserNotification and PushNotification entities, and the UserNotificationExportItemDTO projection. - Concept, the privacy export read.
[Rubric §30, Compliance/Privacy/Data Governance]assesses whether a person can obtain the data held about them; this class is one section of that answer. It performs the same join as the inbox query but strips paging and always constrains to the requested user's rows (UserNotificationExportService.cs:29), so it can never return another subject's data.[Rubric §12, Performance & Scalability]shows in the twoTableNoTrackingreads (lines 27-28): the export is read-only, so change tracking is disabled. Note the class isinternal sealed(line 15): only the interface is public, so nothing outside the assembly can bind to the implementation[Rubric §1, SOLID]. - Walkthrough:
GetUserNotificationExportAsync(lines 20-43) gets both repositories from the unit of work (lines 24-25), builds a LINQ query-syntax join ofUserNotificationtoPushNotificationonPushNotificationId(lines 27-28), filterswhere un.UserId == userIdand orders bypn.CreatedOn descending(lines 29-30), projects into UserNotificationExportItemDTO including theScopeKey(lines 31-39), materializes through the queryable executor (line 41), and returns a fresh list via a collection expression (line 42). - Why it's built this way: reusing the inbox join keeps the export consistent with what the user sees in-app, while the no-tracking, unpaged read matches a one-shot export rather than an interactive page.
- Where it's used: registered as the scoped
IUserNotificationExportService by the module's application-layer
DependencyInjection
(
MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/DependencyInjection.cs:26); consumed by Identity's export aggregation over the cross-module interface (in-process when co-hosted, cross-process via the Notification service's gRPC ingress when extracted). There is no disabled-module stub: the Identity host, which never loads the Notification module, swaps in UserNotificationExportServiceGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:90).
DependencyInjection
MMCA.ADC.Notification.Application ·
MMCA.ADC.Notification.Application·MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/DependencyInjection.cs:12· Level 10 · class (static)
- What it is: the Notification module's application-layer DI composition. Its single extension
method
AddModuleNotificationApplicationwires ADC's recipient policy and export service, then pulls in the framework's shared notification handlers. - Depends on: INotificationRecipientProvider plus
AttendeeNotificationRecipientProvider,
IUserNotificationExportService plus
UserNotificationExportService, and the framework's
AddNotificationApplicationServices()registration. - Concept, the
extension(IServiceCollection)registration block. DI wiring here uses the C# preview extension-member syntax (DependencyInjection.cs:14), which lets a library add methods directly toIServiceCollection(taught in the primer).[Rubric §3, Clean Architecture]is visible in the split of responsibility: this method registers the module's app-specific choices (attendees as recipients, the export service) and then calls the framework'sAddNotificationApplicationServices()(line 29) for the reusable handlers, mapper, validator, and entity query service, so shared and app-specific wiring stay separate and only the app-specific half needs review when policy changes. - Walkthrough:
AddModuleNotificationApplication()(lines 19-32) takes no parameters. It registers AttendeeNotificationRecipientProvider as the scopedINotificationRecipientProvider(line 22), registers UserNotificationExportService as the scopedIUserNotificationExportServicefor the privacy export (line 26), calls the framework'sAddNotificationApplicationServices()(line 29), and returns the collection for chaining (line 31). Both module registrations useTryAddScoped(lines 22 and 26), so they apply only when no implementation of that interface is registered yet: a registration made before this method runs (a host override or a test double) wins, and calling the method twice does not stack a second descriptor. - Where it's used: called first thing by the API-layer
DependencyInjection
.AddNotificationModule(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:32), which is itself driven by NotificationModule.Register.
SignalRLiveChannelPublisher
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications.Live·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Live/SignalRLiveChannelPublisher.cs:11· Level 3 · class (sealed)
- What it is: the real (non-null) adapter for ILiveChannelPublisher. It fans an ephemeral channel event out to every connection subscribed to a channel by doing a SignalR group send through NotificationHub.
- Depends on: ILiveChannelPublisher (Level 0);
NotificationHub (Level 2, referenced for its group send and method-name constant).
External:
Microsoft.AspNetCore.SignalR(IHubContext<THub>). - Concept introduced, out-of-band delivery via
IHubContext<THub>.[Rubric §12, Performance & Scalability]assesses horizontal scale-out: because the publisher addresses the hub throughIHubContext<NotificationHub>(injected,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Live/SignalRLiveChannelPublisher.cs:11) rather than holding a hub connection, it works from any host that maps the hub, and when a Redis backplane is configured the group send fans out across replicas (doc commentSignalRLiveChannelPublisher.cs:6-10).[Rubric §1, SOLID]: the sameILiveChannelPublisherabstraction is implemented by the null default, this SignalR adapter, and (in ADC) a gRPC adapter, port and adapter taken to its conclusion. - Walkthrough: one method,
PublishAsync(channelKey, eventName, payloadJson, cancellationToken)(SignalRLiveChannelPublisher.cs:14):hubContext.Clients.Group(channelKey).SendAsync(NotificationHub.ReceiveChannelEventMethod, channelKey, eventName, payloadJson, cancellationToken)(SignalRLiveChannelPublisher.cs:15-17), returned directly as an expression-bodied, non-asyncmethod (noawait, so theTaskfromSendAsyncis the result). It invokes the hub'sReceiveChannelEventMethodconstant so the client and server agree on the method name, and passes the channel key, event name, and opaque JSON payload straight through. - Why it's built this way: live channels are transient by contract (ADR-039), so this adapter just addresses the group and sends, with no persistence and no per-recipient bookkeeping. A connection that is not subscribed at publish time simply never receives the event.
- Where it's used: registered over NullLiveChannelPublisher by
AddPushNotificationsin any host that maps the hub (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:98); in ADC it is the local implementation the Notification service's gRPC ingress (LiveChannelGrpcService) delegates to. The browser side lives in group 15.
DeliverPushNotificationPageInternalCommand
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.UseCases.Send·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommand.cs:23· Level 4 · record (sealed)
What it is: the durable work item for one page of a push-notification fan-out. It names the notification being delivered and a keyset cursor, and the internal-command queue (ADR-114) runs it later, outside the HTTP request that accepted the send.
Depends on: IInternalCommand (the queue marker) and ITransactional (the transaction marker), both on the record declaration (
MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommand.cs:23-25); InternalCommandNameAttribute gives it the stable wire nameMMCA.Notifications.DeliverPushNotificationPage.v1(DeliverPushNotificationPageInternalCommand.cs:22). The two members use thePushNotificationIdentifierTypeandUserIdentifierTypealiases.Concept introduced, a broadcast as a chain of paged internal commands.
[Rubric §6, CQRS & Event-Driven]and[Rubric §12, Performance & Scalability]: instead of writing every inbox row and pushing to every recipient inside one request, the send queues a first page, and each page queues the next (class doc,DeliverPushNotificationPageInternalCommand.cs:6-11). The page size is NotificationSettings.DeliveryPageSize, 500 by default and bounded[Range(1, 10000)](MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/NotificationSettings.cs:21-22).[Rubric §29, Resilience & Business Continuity]: because the record isITransactional, a page's inbox rows, its outcome on the notification row and the next page's schedule commit together or not at all (remarks,DeliverPushNotificationPageInternalCommand.cs:13-14).Walkthrough: a positional record with two members.
PushNotificationId(DeliverPushNotificationPageInternalCommand.cs:24): the notification being delivered.AfterUserId(DeliverPushNotificationPageInternalCommand.cs:25): the keyset cursor, the last recipient the previous page covered, ornullfor the first page (param doc:18-21).
The remarks note that the payload is two integers, which round-trip through JSON as the queue requires (
DeliverPushNotificationPageInternalCommand.cs:15).Where it's used: the first page (cursor
null) is scheduled by SendPushNotificationHandler (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationHandler.cs:110-112); every later page by DeliverPushNotificationPageInternalCommandHandler (DeliverPushNotificationPageInternalCommandHandler.cs:92-94), which is registered against it inAddNotificationApplicationServices(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:83-84). ADC's Notification and Identity hosts name it in comments: the recipient provider now runs from this command with noHttpContext, so Notification presents its service token to Identity's attendee edge (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:306-312,MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:141).
DeliverPushNotificationPageDeadLetterHandler
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.UseCases.Send·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageDeadLetterHandler.cs:28· Level 8 · class (internal sealed partial)
- What it is: the dead-letter callback for a
DeliverPushNotificationPageInternalCommand. When the
internal-command queue gives up on a delivery page, this handler marks the owning
PushNotification
Failed(class doc,MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageDeadLetterHandler.cs:8-13). - Depends on: IUnitOfWork and
ILogger<>, both injected via the primary constructor (DeliverPushNotificationPageDeadLetterHandler.cs:28-31). It implements the framework'sIInternalCommandDeadLetterHandler<DeliverPushNotificationPageInternalCommand>(:31), whoseHandleAsyncreceives the dead-lettered command and an InternalCommandDeadLetterNotice carrying the reason and the attempt count. - Concept introduced, closing the status gap a dead-lettered page leaves.
[Rubric §29, Resilience & Business Continuity]: a delivery walk continues only because each page schedules the next, so a page the queue dead-letters ends the walk at that page and the recipients after its cursor are not delivered. Without this handler the notification would stayPendingforever and the organizer would see nothing wrong (:9-12). The remarks (:14-25) add two rules: the handler is idempotent (marking an already failed notification again changes nothing, and a notification deleted meanwhile is skipped), and requeuing the dead-lettered page resumes the walk from its cursor and delivers the remaining recipients while the notification staysFailed, as it does after a page whose live leg failed: the status records that delivery did not run cleanly, and the inbox rows record who received it (ADR-114). - Walkthrough (
HandleAsync,DeliverPushNotificationPageDeadLetterHandler.cs:34-54)- guard both arguments with
ArgumentNullException.ThrowIfNull(:39-40). - load the notification tracked by
command.PushNotificationId(:42-45). - skip when the row is gone or its
Statusis already PushNotificationStatus.Failed(:46-49): this is the idempotency rule. - mark and save:
notification.MarkAsFailed()(:51), thenSaveChangesAsync(:52). - log one Warning naming the notification, the dead-letter reason and the attempt count
(
:53), through the source-generatedLogMarkedFailed(:56-57).[Rubric §13, Observability].
- guard both arguments with
- Why it's built this way: the page handler cannot record its own final failure, because by then the queue has stopped running it; a dead-letter callback keyed on the command type is the one place that still runs. Reading the status before writing keeps a repeated callback harmless.
- Where it's used: registered with
TryAddEnumerableas a scopedIInternalCommandDeadLetterHandler<DeliverPushNotificationPageInternalCommand>inAddNotificationApplicationServices(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:88-89) and invoked by the internal-command processor when a page is dead-lettered. The class isinternal; the tests drive it throughPushDeliveryHarness(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Notifications/PushDeliveryHarness.cs).
DeliverPushNotificationPageInternalCommandHandler
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.UseCases.Send·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:47· Level 8 · class (internal sealed partial)
- What it is: the handler that runs one
DeliverPushNotificationPageInternalCommand: it writes
the page's inbox rows, sends the page through the SignalR leg and the native leg, records the outcome
on the notification row, and schedules the next page, all in the page's own transaction (class doc,
DeliverPushNotificationPageInternalCommandHandler.cs:14-21). - Depends on: IUnitOfWork,
INotificationRecipientProvider (the audience),
IPushNotificationSender (the live leg),
INativePushSender (the OS-level leg),
IInternalCommandScheduler (the next
page),
IOptions<NotificationSettings>(the page size) andILogger<>, all injected via the primary constructor (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:47-55). It implements ICommandHandler<in TCommand, TResult> returning a plain Result (:55), and writes PushNotification and UserNotification. - Concept introduced, a re-runnable keyset walk.
[Rubric §29, Resilience & Business Continuity]: queue execution is at-least-once, so a host that dies after a page committed but before the processor stamped the queue row runs that page again. The remarks (DeliverPushNotificationPageInternalCommandHandler.cs:23-31) give the guard: only a page at or after this one ever writes an inbox row for a recipient past this page's cursor, and every page commit also commits the next schedule, so finding such a row means this page already committed and its continuation is queued. The result is exactly-once inbox rows and at-least-once live and native legs.[Rubric §8, Data Architecture]: each page reads only its own recipients from the provider, as a keyset page after the cursor walked in ascending id order, so a recipient added after the send is delivered when the walk reaches it and one removed is skipped, a page shorter than the page size is the provider's signal that the walk has reached its end, andPushNotification.RecipientCountstays the send-time count (:32-38). - Walkthrough (
HandleAsync,DeliverPushNotificationPageInternalCommandHandler.cs:58)- load the notification tracked (
:62-65). A missing row (deleted, or past retention) logs a Warning and returns success: nothing is left to deliver (:66-71). - re-run guard (
:73-77):PageAlreadyCommittedAsync(:110-118) asks the inbox repository whether any UserNotification for this notification exists past the cursor (or at all, for the first page) withignoreQueryFilters: true, because a soft-deleted row was delivered all the same. A hit logs and returns success without writing, sending or scheduling. - cut the page (
:79-80):NextPageAsync(:125-135) asks the provider for one keyset page,recipientProvider.GetRecipientPageAsync(afterUserId, pageSize, cancellationToken), then normalizes it defensively, keeping the ids after the cursor and returningDistinct().Order().Take(pageSize). The doc comment (:120-124) gives the reason: a provider that breaks the ordering contract cannot move the cursor backwards, and the normalization touches one page only. - deliver (
:81-84,DeliverAsyncat:138-153):AddRangeAsyncof oneUserNotification.Create(userId, notification.Id)per recipient, a save, then the live leg and the native leg, then one Information line per page.SendLiveAsync(:160-178) callspushNotificationSender.SendToUsersAsyncwith the page, the title, the body andLiveMetadata(notification.ScopeKey)(:237-240): a dictionary keyed by NotificationScopeKey.MetadataKeyfor a scoped send,nullotherwise, so a client viewing another scope can leave the notification out of its toast and badge. Any exception is caught under a justifiedCA1031suppression, callsnotification.MarkAsFailed()and logs an Error (:171-177); the page carries on.SendNativeAsync(:185-220, ADR-044) awaitsnativePushSender.SendToUsersAsyncfor a NativePushOutcome. Only an outcome with Android or Apple counts or a failure is added to the row, throughnotification.AddNativePushOutcome(unit, androidSent, androidFailed, appleSent, appleFailed)(:199-207), with the unit passed only when it is not NativePushDeliveryUnit.None; the comment at:195-198explains that a recorded unit without counts therefore always means a failure the sender could not attribute to a platform.outcome.FirstFailureand any thrown exception both log the Warning with the exception (:209-212,:214-219), because the production native-push alert reads that exception row (doc:180-184). The native leg never touchesStatus, and the default NullNativePushSender keeps it a no-op until a notification hub is configured (comment:147-149).
- end or continue (
:86-100): a short page (fewer thanpageSize) callsComplete(:223-231), which moves a still-Pendingnotification toSent(a page that marked itFailedkeeps that) and logs the completion with the send-time count. A full page schedules the next command with the page's last id as the cursor; a scheduling failure returnsResult.Failure, which rolls the page back so the retry delivers it again rather than ending the walk (comment:97). A page that keeps failing until the queue dead-letters it ends the walk there; its DeliverPushNotificationPageDeadLetterHandler marks the notificationFailedso it does not stayPending. - final save (
:102) and success.
- Six source-generated
[LoggerMessage]methods close the file (:242-258): page delivered and delivery complete (Information), delivery failed (Error), native failed and notification missing (Warning), and page already committed (Information).[Rubric §13, Observability].
- load the notification tracked (
- Why it's built this way: paging takes the fan-out out of the request and bounds each transaction
and each recipient-provider call (the provider is asked for
pageSizeids, never the whole audience), so a large audience never means one long request holding one long transaction (NotificationSettings.cs:16-19). Deriving "already done" from the inbox rows themselves, rather than from a separate progress table, keeps the guard inside the same transaction as the work it protects. - Where it's used: registered with
TryAddScopedas theICommandHandler<DeliverPushNotificationPageInternalCommand, Result>inAddNotificationApplicationServices(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:83-84) and dispatched by the internal-command processor (ADR-114). The class isinternal; the tests drive it throughPushDeliveryHarness(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Notifications/PushDeliveryHarness.cs).
SendPushNotificationRequestValidator
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.UseCases.Send·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationRequestValidator.cs:13· Level 8 · class (sealed)
What it is: the FluentValidation validator for SendPushNotificationRequest: it enforces that title and body are present and within the length limits declared by PushNotificationInvariants, and that an optional scope key stays within the aggregate's limit and, when present, has the shape the scope filters expect.
Depends on: SendPushNotificationRequest (Level 0, the validated type), PushNotificationInvariants (the domain limits), PushNotification (for
ScopeKeyMaxLength), NotificationScopeKey (forIsValidand the two prefixes), andFluentValidation.AbstractValidator<T>(NuGet base class).Concept: request validation as a pipeline concern, not handler code.
[Rubric §24, Forms, Validation & UX Safety](server-side validation with actionable messages) and[Rubric §15, Best Practices & Code Quality]. Reusing the same constants here and in the PushNotification domain factory keeps the API limit and the entity limit from drifting apart.Walkthrough: the constructor (
MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationRequestValidator.cs:15) defines four rules.Title(SendPushNotificationRequestValidator.cs:17-20) getsNotEmpty()plusMaximumLength(PushNotificationInvariants.TitleMaxLength)(200,MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/Invariants/PushNotificationInvariants.cs:13).Body(SendPushNotificationRequestValidator.cs:22-25) getsNotEmpty()plusMaximumLength(PushNotificationInvariants.BodyMaxLength)(2000,PushNotificationInvariants.cs:16).ScopeKeylength (SendPushNotificationRequestValidator.cs:30-32) getsMaximumLength(PushNotification.ScopeKeyMaxLength)(128,MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:21), and noNotEmpty: the inline comment (SendPushNotificationRequestValidator.cs:27-29) records that the scope key stays optional, a null or blank one being an unscoped send (the factory normalizes blank to null).ScopeKeyshape (SendPushNotificationRequestValidator.cs:34-37) getsMust(NotificationScopeKey.IsValid), applied onlyWhenthe key is not null or whitespace. The same comment gives the reason: a present key must have the shape every client scope filter and the hub's default channel-key pattern expect, or the notification reaches no scoped reader.
Each rule supplies a human-readable
WithMessage: the length messages interpolate the limit underCultureInfo.InvariantCulture, and the shape message names the accepted forms{NotificationScopeKey.EventPrefix}:{id}and{NotificationScopeKey.SessionPrefix}:{id}.Where it's used: registered by
AddValidatorsFromAssemblyContaining<SendPushNotificationRequestValidator>(includeInternalTypes: true)in the notification Application DI (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:79), which also makes this class the assembly anchor for every notification validator; invoked by the Validating command decorator in the CQRS pipeline (against the embeddedRequest, via ICommandWithRequest<out TRequest>) before SendPushNotificationHandler runs (ADR-014).
SendPushNotificationHandler
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.UseCases.Send·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationHandler.cs:47· Level 9 · class (sealed partial)
- What it is: the command handler for the push-notification broadcast. It short-circuits duplicate
sends by deduplication key, counts the recipients, persists the sender-side audit aggregate, and
schedules the first DeliverPushNotificationPageInternalCommand,
then returns a PushNotificationDTO. The recipient fan-out (inbox rows, the
SignalR leg and the native leg) runs page by page in those internal commands, never inside this
request (class doc,
MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationHandler.cs:16-20). - Depends on: IUnitOfWork (repositories plus save),
INotificationRecipientProvider (the audience count),
IInternalCommandScheduler (the
first delivery page), PushNotificationDTOMapper (the success-payload
mapper), and
ILogger<>(all injected via the primary constructor,SendPushNotificationHandler.cs:47-52); the persisted aggregate is PushNotification. Implements ICommandHandler<in TCommand, TResult> and returnsResult<PushNotificationDTO>(Result). The delivery transports moved to DeliverPushNotificationPageInternalCommandHandler. - Concept introduced, accept fast, deliver durably in pages, guarded by a dedup key.
[Rubric §6, CQRS & Event-Driven],[Rubric §8, Data Architecture],[Rubric §29, Resilience & Business Continuity]. The class doc's "Atomicity" paragraph (SendPushNotificationHandler.cs:21-30) states the contract: SendPushNotificationCommand isITransactionaland the scheduler writes on this request's own unit of work, so the audit row and the first page's queue row commit together or not at all. That is what keeps the dedup short-circuit honest: a committed row always has its delivery queued, so answering a retry with the existing row never hides a send nothing will deliver. The returned notification isPending; the last delivery page moves it toSent, or a page whose live leg failed toFailed(ADR-114). - Walkthrough (teaching order)
- null guard and deduplication gate (
SendPushNotificationHandler.cs:59-76): the command's DedupKey is normalized so whitespace counts as absent (SendPushNotificationHandler.cs:65-67, "a blank header cannot claim the single empty key"), and a present key is replaced by its sender-scoped hash (seeSenderScopedDedupKeybelow), so another caller reusing the same client key can neither suppress this send nor be handed this sender's notification (commentSendPushNotificationHandler.cs:61-64); when a key is present,FindByDedupKeyAsynclooks for an already-persisted notification and, on a hit, logs and returns the existing one mapped to a DTO without sending again (SendPushNotificationHandler.cs:68-75). - count recipients (
SendPushNotificationHandler.cs:80-81) withCountRecipientsAsyncon the app-specific INotificationRecipientProvider (in ADC, AttendeeNotificationRecipientProvider), anint, so the request never loads the audience itself. The comment at:78-79records that this count is for the audit row and the no-recipients answer only: the delivery pages read the recipients page by page, so a recipient added or removed meanwhile is delivered or skipped. A zero count short-circuits to aResult.Failurewith an ErrorValidationcodePushNotification.NoRecipients(SendPushNotificationHandler.cs:83-89), before any write. - create the audit aggregate (
SendPushNotificationHandler.cs:91-97) viaPushNotification.Create(title, body, sentByUserId, recipientCount, dedupKey, scopeKey);createResult.TryGetValue(out var notification)both checks success and binds the aggregate, and a failure propagates the errors asResult.Failure<PushNotificationDTO>(createResult.Errors)(SendPushNotificationHandler.cs:98-101); the bound aggregate is then added to the repository (SendPushNotificationHandler.cs:103-104). The aggregate raises no domain event on creation, so the save writes the audit row alone. - save, a lost dedup race propagates (
SendPushNotificationHandler.cs:106-108): a bareSaveChangesAsyncwith no catch, which also assigns the id the first page carries. The dedup lookup in step 1 is a check-then-act, so two concurrent sends of one key can both pass it and the loser fails here, on the insert, against the filtered unique index onDedupKey. The class doc's "Deduplication race" paragraph (SendPushNotificationHandler.cs:31-40) states the contract: the failure propagates as the persistence exception (a 409 throughDbUpdateExceptionHandler), the transactional decorator rolls the attempt back, and the client's retry is then answered by the dedup lookup with the winner's notification. Recovering in place is not possible in this layer: the failed insert stays tracked (nothing in the Application contract can detach it) so the commit would throw, and on PostgreSQL the unique violation has already aborted the transaction a requery would run in. - schedule the first page (
SendPushNotificationHandler.cs:110-118):scheduler.ScheduleAsync(new DeliverPushNotificationPageInternalCommand(notification.Id, AfterUserId: null)). A scheduling failure fails the command, which rolls the audit row back with it, so the client's retry re-runs the whole send instead of being answered by a row with no delivery queued (comment:115-116). - log and return (
SendPushNotificationHandler.cs:120-121): one Information line ("accepted ... delivery scheduled") and the mapped DTO.
SenderScopedDedupKey(SendPushNotificationHandler.cs:131-133) derives the stored key asConvert.ToHexString(SHA256.HashData(...))over the invariant-culture string{sentByUserId}:{clientKey}, so the persisted value is always 64 hex characters (within the column) whatever the client sent (doc commentSendPushNotificationHandler.cs:124-130).[Rubric §11, Security]: the client key alone no longer identifies a notification across senders.FindByDedupKeyAsync(SendPushNotificationHandler.cs:140-149) resolves the read repository from the unit of work (unitOfWork.GetReadRepository<...>(),SendPushNotificationHandler.cs:142), never an injected IRepository<TEntity, TIdentifierType>, so the lookup runs against the same data source as the write (its doc comment says exactly that,SendPushNotificationHandler.cs:135-139).- Two source-generated
[LoggerMessage]methods close the file (SendPushNotificationHandler.cs:151-155): delivery scheduled (Information) and dedup hit (Information). The delivery-side lines live on the page handler.[Rubric §13, Observability].
- null guard and deduplication gate (
- Why it's built this way: shipping the whole feature in the framework means both ADC and Store get
push for free, with the audience and both transports as injected abstractions (
[Rubric §29, Resilience, Reliability & Business Continuity]). Accepting the send in one short transaction and handing the fan-out to the durable internal-command queue keeps the request time independent of the audience size and makes delivery survive a host restart. The dedup key plus the filtered unique index gives the retry safety a broadcast needs: the index is declared withIsUnique()and a soft-delete-aware[DedupKey] IS NOT NULLfilter in the EF configuration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/Notifications/PushNotificationConfiguration.cs:78-80), so the database, not the application, is the arbiter of "already sent". The real-time sends do not go through the outbox: they run in the page handler, carried by the durable internal-command queue. - Where it's used: registered in
AddNotificationApplicationServices(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:63-64) and dispatched from NotificationsController (mounted into ADC by the Notification DI facade); the real-time legs then land on connected clients through NotificationHub and, for native push, through the configured OS notification hub, one page at a time. - Caveats / not-in-source: there is no automatic redelivery of a failed live push: a page whose
live leg throws marks the notification
Failedand the walk carries on with the next page.
UserNotificationExportGrpcService
MMCA.ADC.Notification.Service ·
MMCA.ADC.Notification.Service.Grpc·MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/UserNotificationExportGrpcService.cs:32· Level 9 · class (sealed)
- What it is: the gRPC server endpoint that exposes the in-process
IUserNotificationExportService over the wire. The Identity service
calls it to pull a user's notification inbox rows (ids, titles, sent/read dates, scope key) so it can
assemble the data-subject export document (PRIVACY.md section 12, per the class doc at
UserNotificationExportGrpcService.cs:13; the GDPR right of access). - Depends on: IUserNotificationExportService (injected via the
primary constructor,
MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Grpc/UserNotificationExportGrpcService.cs:32), the generatedUserNotificationExportService.UserNotificationExportServiceBase(compiled from the.Contracts.proto,UserNotificationExportGrpcService.cs:33), andGrpc.Core.ServerCallContext. Formats timestamps through the framework's GrpcWireFormat (MMCA.Common.Grpc, imported atUserNotificationExportGrpcService.cs:5), and projects into UserNotificationExportItemDTO shapes on the far side. - Concept introduced, cross-service data-subject export over internal gRPC.
[Rubric §30, Compliance, Privacy & Data Governance]assesses whether the system can satisfy a subject-access request across service boundaries: each service owns its own database (ADR-006), so the user's inbox rows live inADC_Notification, not in Identity; this RPC lets the Identity export aggregator gather that slice without a cross-database query.[Rubric §7, Microservices Readiness]and[Rubric §9, API & Contract Design]: the export contract is a versioned.protoshared through the.Contractspackage, the same extraction pattern as the live-channel ingress.[Rubric §27, i18n]: timestamps are serialized with the round-trip"O"format underCultureInfo.InvariantCulturebyGrpcWireFormat.FormatUtc(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/GrpcWireFormat.cs:42-43, called atUserNotificationExportGrpcService.cs:58, withFormatUtcOrEmptyat:60) so the export is locale-stable. - Walkthrough: the single
GetUserNotificationExportoverride (UserNotificationExportGrpcService.cs:36) null-guardsrequestandcontext(UserNotificationExportGrpcService.cs:40-41), then runs an ownership check on the caller (context.GetHttpContext().User,UserNotificationExportGrpcService.cs:43-47): unless the caller's user id equalsrequest.UserIdor it holds theRoleNames.Organizerrole (:44), the call throws anRpcExceptionwithStatusCode.PermissionDenied("The export is available only for the caller's own account."). It then awaitsinner.GetUserNotificationExportAsync(request.UserId, context.CancellationToken)(UserNotificationExportGrpcService.cs:49-51) to get the in-process items. It builds aGetUserNotificationExportResponse(UserNotificationExportGrpcService.cs:53) andAddRanges a projection of each item into aUserNotificationExportItem(UserNotificationExportGrpcService.cs:54-65):NotificationId,Title,SentOnviaGrpcWireFormat.FormatUtc(UserNotificationExportGrpcService.cs:58),IsRead,ReadOnviaGrpcWireFormat.FormatUtcOrEmpty(string.Emptywhen the notification is unread,UserNotificationExportGrpcService.cs:60;GrpcWireFormat.cs:51-52), andScopeKey(alsostring.Emptywhen null,UserNotificationExportGrpcService.cs:64, because proto3 has no null string, per the comment at:62-63; the adapter maps it back to null).FormatUtcstampsDateTimeKind.UtcwithDateTime.SpecifyKindbeforeToString("O", ...): the class doc (UserNotificationExportGrpcService.cs:25-29, restated once for every contract inGrpcWireFormat.cs:11-17) explains why, SQL Server hands backDateTimeKind.Unspecifiedvalues and the"O"format omits theZmarker for that kind, so the stamp only restores the marker the wire contract promises (the stored values are already UTC). Writing the format once in the framework means this server and its client adapter cannot drift apart. - Why it's built this way (security posture): unlike
LiveChannelGrpcService, this endpoint requires authorization: it is
mapped with
.RequireAuthorization()(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:175) and the class doc says why (UserNotificationExportGrpcService.cs:16-24).[Rubric §11, Security],[Rubric §30, Compliance, Privacy & Data Governance]: internal-only ingress is not sufficient here because the response carries personal data keyed by a rawUserId, so the calling service forwards the end user's JWT via JwtForwardingClientInterceptor, and the service itself answers only for the caller's ownUserIdor for an Organizer (the export privilege Identity's export endpoint grants), refusing anything else withPermissionDenied(class docUserNotificationExportGrpcService.cs:20-22, check:43-47). There is no service-caller bypass: the edge takes the default policy, which authenticates only the user bearer, so a service token never reaches the check (class doc:22-23). An authenticated caller therefore cannot read another user's inbox by naming that user's id on the wire. It is served on the same dedicatedHttp2-only "grpc" Kestrel endpoint as the live-channel ingress (ADR-012 mixed-endpoint profile,UserNotificationExportGrpcService.cs:13-15). - Where it's used: mapped by the Notification service's
Program.cs(Program.cs:175); the wire is dialed by its client half UserNotificationExportServiceGrpcAdapter, which runs inside the Identity service's export aggregator and stitches this Notification slice into the full data-subject export. The in-process implementation it wraps is UserNotificationExportService.
UserNotificationExportServiceGrpcAdapter
MMCA.ADC.Notification.Contracts ·
MMCA.ADC.Notification.Contracts·MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/UserNotificationExportServiceGrpcAdapter.cs:17· Level 9 · class (internal sealed)
- What it is: the client half of the data-subject export RPC. It implements
IUserNotificationExportService on top of the generated gRPC client,
so Identity's export aggregator keeps depending on the plain C# interface from
MMCA.ADC.Notification.Sharedwhile the inbox rows are actually fetched from the Notification service's database over the wire. - Depends on: IUserNotificationExportService (Level 1, the
implemented port); the generated
UserNotificationExportService.UserNotificationExportServiceClient(injected via the primary constructor,MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/UserNotificationExportServiceGrpcAdapter.cs:17-18); UserNotificationExportItemDTO (the returned shape); theUserIdentifierTypealias; GrpcWireFormat for parsing the wire timestamps. Its server counterpart is UserNotificationExportGrpcService. - Concept: the same error policy as
LiveChannelPublisherGrpcAdapter, with a different caller-side
degradation.
[Rubric §29, Resilience & Business Continuity]assesses degradation strategy per call site: both adapters let transport failures propagate, and each caller decides what a failure means. The live-channel caller swallows it insideBestEffortbecause a dropped ephemeral event is harmless; this adapter's caller marks the Notifications section of the exportAvailable = falserather than silently emit an empty one (class doc,UserNotificationExportServiceGrpcAdapter.cs:7-15).[Rubric §9, API & Contract Design]on version tolerance: the projection treats an empty proto3 string as "absent" in two places, so a peer replica that predates a field still deserializes. - Walkthrough
GetUserNotificationExportAsync(userId, cancellationToken)(UserNotificationExportServiceGrpcAdapter.cs:21-23) issuesclient.GetUserNotificationExportAsyncwith aGetUserNotificationExportRequest { UserId = userId }and the caller's token (:25-30). Notry/catch: failures surface. The adapter sets no deadline of its own: the typed client registered byAddTypedGrpcClient(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:87) gets the framework default from GrpcDefaultDeadlineInterceptor, which applies HttpResilienceDefaults.GrpcCallDeadline(5 seconds,MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:87;MMCA.Common/Source/Presentation/MMCA.Common.Grpc/Interceptors/GrpcDefaultDeadlineInterceptor.cs:47) to any call without one, so a hung (as opposed to refused) Notification peer still degrades its export section quickly.[Rubric §12, Performance & Scalability].- The projection (
:32-43) maps each wire item back into a UserNotificationExportItemDTO with a collection expression.SentOnis read byGrpcWireFormat.ParseUtc(:36). Two fields undo the proto3 encoding:ReadOnbecomesnullwhen the string is empty throughGrpcWireFormat.ParseUtcOrNull(:38), andScopeKeylikewise by an inline length check (:42), with the comment at:40-41recording that a peer replica predating the field and a genuinely unscoped notification both arrive as the empty string and mean the same thing. - The parsing itself lives in the framework, the counterpart of the server's
"O"formatting:ParseUtcisDateTime.ParseunderCultureInfo.InvariantCulturewithDateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/GrpcWireFormat.cs:37,:61-62). The comment there (GrpcWireFormat.cs:32-36) is worth reading in full: those two flags defend against a peer replica that still emits the marker-less form during a rolling deploy (without them a suffix-less value parses asKind=Unspecified, andAssumeUniversalalone yieldsKind=Local), while aZ-suffixed value takes the same path and keeps its instant.DateTimeStyles.RoundtripKindis deliberately absent becauseDateTime.Parserejects it alongside either flag with anArgumentException, and its job (preserving a non-UTC kind) is the opposite of what this contract wants. A malformed value throwsFormatException(GrpcWireFormat.cs:24-25), which this adapter lets propagate like any other failure.[Rubric §15, Best Practices & Code Quality]: a subtle BCL interaction is documented once, beside the shared helper both ends call.
- Why it's built this way: keeping the class
internal(:17) means nothing outside the.Contractspackage can bind to the concretion; consumers get it only through the DI helper below, always behind the interface. The rolling-deploy tolerance in the parser and the two empty-string mappings are what let Identity and Notification deploy independently, which is the point of ADR-008's topology. - Where it's used: registered by the Notification.Contracts
DependencyInjection's
AddNotificationUserExportClientviaservices.Replace(...)(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:90); the one caller today is the Identity service's composition root (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:289), whose ExportUserDataHandler consumes the interface.
DependencyInjection
MMCA.ADC.Notification.Contracts ·
MMCA.ADC.Notification.Contracts·MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:17· Level 10 · class (static,extension(IServiceCollection))
(The consumer-side gRPC client DI for the Notification service. Several other classes in this chapter
are also named DependencyInjection, one per layer; all of them keep the raw type name as their
heading.)
- What it is: the composition helper that a consuming service calls to point its notification ports at the extracted Notification service. Its two methods register a typed gRPC client and swap the local implementation for the matching adapter.
- Depends on: LiveChannelPublisherGrpcAdapter and
UserNotificationExportServiceGrpcAdapter (the registered
concretions); the ports ILiveChannelPublisher and
IUserNotificationExportService; the generated clients from the
.Contracts.proto; andAddTypedGrpcClient<TClient>fromMMCA.Common.Grpc(see the gRPC helper DependencyInjection), which brings the Aspire service discovery address, the JwtForwardingClientInterceptor, and the standard Polly resilience handler. Externals:Microsoft.Extensions.DependencyInjection.Extensions(ServiceCollectionDescriptorExtensions.Replace). - Concept introduced,
Replacerather thanTryAddat a consumer composition root. The framework registers defaults withTryAdd*, which is a no-op when something is already registered. A consumer that wants the remote adapter to win therefore cannot useTryAdd: it must overwrite. Both methods useservices.Replace(ServiceDescriptor.Scoped<TPort, TAdapter>())(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Contracts/DependencyInjection.cs:55and:90), and each carries an inline comment saying what it is overwriting: the framework's NullLiveChannelPublisher in the first case (:53-54), and in the second any registration made before the call (:89); the doc adds that the Identity host names only its own module, so no in-process export service exists there andReplacesimply adds the scoped adapter (:76-78). That in turn makes call order load-bearing, and the doc comments say so:AddNotificationLiveChannelClientmust run afterAddInfrastructure(...)(:36-38) andAddNotificationUserExportClientafterModuleLoader.DiscoverAndRegister(...)(:79-80).[Rubric §7, Microservices Readiness]and[Rubric §3, Clean Architecture]: the only thing that changes between the co-hosted monolith and the extracted topology is which descriptor sits in the container. - Walkthrough: one
extension(IServiceCollection services)block (DependencyInjection.cs:19) with two methods, each defaultingserviceNameto"_grpc.notification"and returning the collection for chaining.AddNotificationLiveChannelClient(string serviceName = "_grpc.notification")(DependencyInjection.cs:49) registersAddTypedGrpcClient<LiveChannelPushService.LiveChannelPushServiceClient>(serviceName).WithServiceToken()(:51) thenReplacesILiveChannelPublisherwith LiveChannelPublisherGrpcAdapter as scoped (:55). TheWithServiceToken()opt-in is explained in the doc (:40-45): the publisher's background drain runs with noHttpContext, so there is no user bearer to forward; the client attaches a service token instead, Notification maps this edge under the service-onlyServiceCallerpolicy, and the calling host must registerAddServiceTokenClient.[Rubric §11, Security].AddNotificationUserExportClient(string serviceName = "_grpc.notification")(DependencyInjection.cs:85) registersAddTypedGrpcClient<UserNotificationExportService.UserNotificationExportServiceClient>(serviceName)(:87), with no service token, so the end user's JWT is forwarded; it thenReplacesIUserNotificationExportServicewith UserNotificationExportServiceGrpcAdapter, also scoped (:90).- The named-endpoint default is the subtle part (
:28-33)."_grpc.notification"is Aspire service-discovery syntax for a named endpoint, not the service's default one. Notification's default endpoint has to stayHttp1AndHttp2for SignalR WebSockets, so its cleartext gRPC (h2c) lives on a separateHttp2-only Kestrel endpoint namedgrpc(ADR-012). Discovery resolveshttp://_grpc.notificationfrom theservices__notification__grpc__0configuration entry, injected by the AppHost'sWithReferencelocally and byinfra/main.bicepin production.
- Why it's built this way: putting both registrations in the
.Contractspackage (next to the.protoand the adapters) means a consuming service adds one line and inherits the correct endpoint, interceptor, resilience policy, and lifetime, with no knowledge of Notification's Kestrel layout. The second method's doc (:68-74) also records the consumer-side contract (theGET /users/{userId}/exportdocument, PRIVACY.md section 12): the export aggregation is best-effort per section, so if this peer stays unreachable after the resilience pipeline the Identity handler marks the Notifications section unavailable instead of failing the whole export. - Where it's used:
AddNotificationLiveChannelClientis called by the Engagement service's application pipeline (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:229);AddNotificationUserExportClientby the Identity service's (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:289). The matching AppHost references that inject theservices__notification__grpc__0entry areengagementService.WithReference(notificationService)(MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:285) andidentityService.WithReference(notificationService)(Program.cs:296), both deliberately without aWaitForso neither consumer blocks on Notification at startup (comments atProgram.cs:278-284and:282-290).
NullPushNotificationSender
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications.Push·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/NullPushNotificationSender.cs:10· Level 1 · class (sealed)
- What it is: the no-op default for the IPushNotificationSender port, the delivery-side counterpart of NullLiveChannelPublisher. It lets a host resolve and run the send pipeline even with no real-time transport configured.
- Depends on: IPushNotificationSender (Level 0). Uses the solution-wide
UserIdentifierTypealias (see primer §2). - Concept: cross-reference the Null Object pattern taught on
NullLiveChannelPublisher.
[Rubric §29, Resilience]: because push delivery is best-effort (the durable inbox is the source of truth), a missing transport must not break sending, it must simply deliver nothing. - Walkthrough: three methods, each
=> Task.CompletedTask:SendToUserAsync(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/NullPushNotificationSender.cs:13),SendToUsersAsync(NullPushNotificationSender.cs:17), andBroadcastAsync(NullPushNotificationSender.cs:21). Together they mirror the fullIPushNotificationSendersurface (single user, batch, broadcast) so the interface is satisfied without behavior. - Why it's built this way: the doc comment (
NullPushNotificationSender.cs:5-9) notes downstream apps override this with SignalRPushNotificationSender viaAddPushNotifications(). The send handler always calls the port; whether anything reaches a browser is a composition-root decision. - Where it's used: registered as the default
IPushNotificationSenderbyAddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:418); superseded by the SignalR sender in any host that callsAddPushNotifications(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:97).
NotificationModule
MMCA.ADC.Notification.API ·
MMCA.ADC.Notification.API·MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/NotificationModule.cs:14· Level 2 · class (sealed)
- What it is: the IModule entry point for the Notification bounded context. It is discovered at startup, declares its dependency on Identity, and hands registration off to the module's DependencyInjection.
- Depends on: IModule (implements it),
ApplicationSettings (part of the
Registersignature the interface fixes; this module accepts it and does not pass it on),IServiceCollection/IConfigurationBuilder, and the API-layer DependencyInjection. - Concept, the module manifest. The module system is taught in
Group 14; what this class shows is how thin a real module
manifest is. Three properties describe the module to
ModuleLoader, which registers modules in
topological (Kahn) order, and one method registers it.
RequiresDependencies => true(line 23) is the strict setting: Notification cannot come up without Identity, because its recipient provider needs the attendee roster.[Rubric §7, Microservices Readiness]assesses whether a module's boundary is explicit enough to extract:Dependencies => ["Identity"](line 20) is that boundary stated as data, which is also what lets ADC run Notification as its own service host. The one cross-module service the module publishes, the Notification half of the PRIVACY.md section 12 data-subject export, is reached by Identity over gRPC (class doc comment, lines 11-12) rather than through an in-process service, so the module does not overrideRegisterDisabledStubsand inherits the interface's empty default (MMCA.Common/Source/Core/MMCA.Common.Application/Modules/IModule.cs:34): a host that turns the module off has no in-process contract of this module left to satisfy. - Walkthrough:
Name => "Notification"(line 17) is the key ModuleLoader uses to order and address the module;Dependencies => ["Identity"](line 20) andRequiresDependencies => true(line 23) declare the hard edge.Register(lines 26-30) is a one-line expression body forwarding toservices.AddNotificationModule((IConfiguration)configuration)(line 30); the cast is needed because the interface hands the module anIConfigurationBuilder, and theapplicationSettingsargument is not used. There is no other member. - Why it's built this way: modules as data-declaring classes rather than hand-ordered startup calls is the pattern behind ADRs 007, 008, and 059. Keeping the manifest to properties plus one forwarding call leaves every registration decision in the module's DependencyInjection, where it reads as one ordered sequence.
- Where it's used: discovered by ModuleLoader;
the standalone Notification service host names this type's assembly as its only module assembly
(
MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:64-65). Covered byNotificationModuleTests(MMCA.ADC/Tests/Modules/Notification/MMCA.ADC.Notification.API.Tests/NotificationModuleTests.cs).
SmtpEmailSender
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Mail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Mail/SmtpEmailSender.cs:15· Level 2 · class (sealed)
- What it is: the SMTP adapter for the IEmailSender port. It sends mail through a
System.Net.Mail.SmtpClientconfigured from bound SmtpSettings. This is the entire "email channel" of the notification subsystem, independent of the push/inbox flow. - Depends on: IEmailSender (Level 0);
SmtpSettings (Level 0), taken as
IOptions<SmtpSettings>and unwrapped once into a readonly field by the constructor (SmtpEmailSender.cs:35); SmtpTransportSecurity, which the constructor calls to resolve TLS (SmtpEmailSender.cs:36). Externals:Microsoft.Extensions.Options(IOptions<T>),Microsoft.Extensions.Configuration(IConfiguration),Microsoft.Extensions.Hosting(IHostEnvironment),Microsoft.Extensions.Logging(ILogger<SmtpEmailSender>),System.Net.Mail(SmtpClient,MailMessage), andSystem.Net(NetworkCredential). - Concept introduced, the options-bound infrastructure adapter.
[Rubric §3, Clean Architecture]assesses whether transport detail stays at the edge: the portIEmailSenderlives in Application, and this SMTP concretion lives in Infrastructure, so nothing above it knows what "email" is made of.[Rubric §17, DevOps & Deployment]: host, port, credentials, and the default from/to addresses come from configuration bound at startup byAddInfrastructure(services.AddOptions<SmtpSettings>().Bind(configuration.GetSection(SmtpSettings.SectionName)),MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:100-101), never hard-coded, so the same code targets a real relay in production and a local SMTP container in development.[Rubric §11, Security](SEC-Common-54): TLS is not read verbatim fromSmtpSettings.EnableSsl. The constructor resolves it through SmtpTransportSecurity: an explicitSmtp:EnableSslsetting wins, otherwise TLS defaults on outside Development (SmtpEmailSender.cs:20-22and:36), so a deployed host that never set the flag does not send credentials in the clear.
- Walkthrough: one constructor, storing into
_smtpSettingsand_enableSsl(SmtpEmailSender.cs:17-18).SmtpEmailSender(IOptions<SmtpSettings>, IConfiguration, IHostEnvironment, ILogger<SmtpEmailSender>)(SmtpEmailSender.cs:28-37, doc:20-27): null-checks the options (ArgumentNullException.ThrowIfNull,:34), unwraps.Valueonce (:35), and resolves_enableSslviaSmtpTransportSecurity.Resolve(...)(:36), which can log a one-time warning when a deployed host disables TLS deliberately. There is no settings-only constructor, so every instance, container-built or hand-built, goes through the same TLS resolution.SendAsync(to, subject, body, isHtml, cancellationToken)(SmtpEmailSender.cs:40): guards the three strings withArgumentException.ThrowIfNullOrEmpty(SmtpEmailSender.cs:42-44), builds the client viaCreateClient(_smtpSettings, _enableSsl)inside ausing(:46), builds aMailMessagefrom_smtpSettings.From(alsousing,SmtpEmailSender.cs:48-51), and awaitsSendMailAsync(message, cancellationToken)(SmtpEmailSender.cs:53).SendAsync(subject, body, isHtml, cancellationToken)(SmtpEmailSender.cs:64-65): a convenience overload that forwards to the five-argument method with the default_smtpSettings.Torecipient, for admin/system mail with no explicit addressee.CreateClient(SmtpSettings, bool)(SmtpEmailSender.cs:76-93):internal static, factored out so the bounded timeout is assertable without a live relay (doc:67-75). Builds theSmtpClientfromHost/Portwith aNetworkCredentialand the resolvedenableSsl(justified#pragma warning disable S5332at:77, restored at:94, because TLS is resolved bySmtpTransportSecurityrather than read verbatim), and setsTimeoutfromSmtpSettings.TimeoutSeconds(:86):SmtpClient's own default is 100 seconds, longer than the callers in front of it, so an unresponsive relay would otherwise hold the request for the whole of it; the bound is validated at startup (ADR-070).- It also sets
DeliveryFormat = SmtpDeliveryFormat.International(SmtpEmailSender.cs:92). The comment above it (:88-91) gives the reason: the 7-bit default throws for an address with a non-ASCII local part, so that mail never left;Internationallets the client use SMTPUTF8 when the server advertises it. ASCII mail is delivered as before, and a relay that does not advertise SMTPUTF8 still gets 7-bit mail and refuses only a non-ASCII local part.[Rubric §27, i18n].
- Why it's built this way: a per-send client keeps the sender stateless and thread-safe with no
connection lifecycle to manage, acceptable for the low volume of system/admin mail this channel
carries. The type's doc comment (
SmtpEmailSender.cs:11-14) is explicit that a new client is created and disposed per send, no pooled long-lived connection. A single constructor that always resolves TLS leaves no path that readsEnableSslverbatim. Unlike push, email has no null-object default:SmtpEmailSenderitself is whatAddInfrastructureregisters asIEmailSender(services.TryAddTransient<IEmailSender, SmtpEmailSender>(),MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:417), so a host that never configures SMTP settings still resolves a real sender that will fail at send time rather than silently no-op. - Where it's used: injected as
IEmailSenderby callers (the port, not this class); the transient registration needsIConfiguration,IHostEnvironment, andILogger<SmtpEmailSender>from the container to build it, all of which a standard host provides. It is not called from the push/inbox send flow. - Caveats / not-in-source:
IOptions<T>(notIOptionsMonitor<T>) plus the read-once fields mean a configuration change after startup is not picked up by an already-constructed instance. The registration is transient, so a new instance per resolve re-reads.Value, but the semantics of a live reload are not exercised anywhere in this file.
NotificationHub
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationHub.cs:35· Level 3 · class (sealed, partial)
- What it is: the SignalR hub that anchors the group's real-time transport. It is deliberately thin:
it maps authenticated connections, bounds per-user connection count, and manages channel (SignalR
group) membership under a per-connection channel cap and join budget. It does not itself construct or fan out messages, that work lives in
SignalRPushNotificationSender and
SignalRLiveChannelPublisher, both of which push through
IHubContext<NotificationHub>(doc commentMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationHub.cs:12-17). - Depends on:
PushNotificationSettings (read
through
IOptions<T>for the channel-key pattern,MaxConnectionsPerUser,MaxChannelsPerConnection,ChannelJoinsPerMinute, andChannelJoinBurst); IChannelJoinAuthorizer (constructor-defaulted tonull, and with none registered every channel join is refused); the BCLTimeProvider(constructor-defaulted tonull, falling back toTimeProvider.System, the clock the join budget refills by); externalsMicrosoft.AspNetCore.SignalR(theHubbase class,Groups,Context,HubException,[HubMethodName]),Microsoft.AspNetCore.Authorization([Authorize]),Microsoft.Extensions.Options(IOptions<T>),Microsoft.Extensions.Logging(ILogger<NotificationHub>,[LoggerMessage]), and the BCLSystem.Text.RegularExpressions.RegexplusSystem.Collections.Concurrent.ConcurrentDictionary. - Concept introduced, the SignalR hub as a real-time transport endpoint. A SignalR
Hubis a server-side endpoint over a persistent connection (WebSockets where available). Clients invoke named hub methods on it, and the server pushes messages back to individual connections or to named groups (here called channels). This hub keeps only the membership half of that contract:JoinChannelAsync/LeaveChannelAsyncadd or remove the calling connection to a SignalR group, and delivery is done elsewhere throughIHubContext. Keeping the hub free of message construction means the sender and publisher services can be tested and scaled independently of the connection surface.[Rubric §11, Security]assesses whether the boundary authenticates and constrains input. The class carries a class-level[Authorize](NotificationHub.cs:34, header comment context), so only authenticated connections can open the hub, and every channel key is validated against a configured allow-pattern before a connection may join a group, so a client cannot subscribe to an arbitrary group name. Shape is not entitlement, though (SEC-ADC-25 / the join-authorizer note below): a well-formed key alone does not mean the caller is entitled to it, which is what IChannelJoinAuthorizer decides. The hub fails closed: with no authorizer registered every join is refused (NotificationHub.cs:213-216), so a host that uses channels must register one, while a host that uses none needs none because user-targeted notifications do not go through channels (constructor doc comment,NotificationHub.cs:20-25).OnConnectedAsync/OnDisconnectedAsync(NotificationHub.cs:76-108) additionally cap live connections per user identifier on this replica atPushNotificationSettings.MaxConnectionsPerUser(default 20,PushNotificationSettings.cs:50), the same per-process bound the in-memory rate limiters use: it constrains what one token can do to one process, the resource actually being exhausted. Channel joins are bounded per connection on two further axes (class remarks,NotificationHub.cs:27-33): at mostMaxChannelsPerConnectionchannels held at once (default 32,PushNotificationSettings.cs:63), and a token-bucket join budget ofChannelJoinsPerMinute(default 60,PushNotificationSettings.cs:76) with bursts of up toChannelJoinBurst(default 32,PushNotificationSettings.cs:85). The budget is spent before any other check, so a refused join costs the same as an accepted one and a loop of refused joins cannot drive the entitlement check without bound.[Rubric §12, Performance & Scalability]assesses whether hot paths avoid repeated work. The compiledRegexis cached in a staticConcurrentDictionarykeyed by the pattern string (NotificationHub.cs:61-62) so join/leave calls never recompile it, and each match runs under a 1-second timeout (ChannelKeyMatchTimeout) to bound worst-case matching (a defense against catastrophic-backtracking, ReDoS-style input).
- Walkthrough
- Primary-constructor DI of
IOptions<PushNotificationSettings>,ILogger<NotificationHub>, an optionalIChannelJoinAuthorizer? joinAuthorizer = null, and an optionalTimeProvider? timeProvider = null, over theHubbase (NotificationHub.cs:35-39). The class ispartialbecause of the source-generated[LoggerMessage]method near the bottom. The authorizer parameter is defaulted so the hub still resolves in a host that registers none, but such a host refuses every channel join (seeEnsureAuthorizedForChannelAsyncbelow); the clock is defaulted so production uses the system clock while a test can drive the join budget deterministically. - The shared method-name constants:
ReceiveNotificationMethod="ReceiveNotification"andReceiveChannelEventMethod="ReceiveChannelEvent"are the client-listen method names the sender and publisher target;JoinChannelMethod="JoinChannel"andLeaveChannelMethod="LeaveChannel"are the server methods clients invoke. Exposing them as constants keeps both ends of the wire from drifting on a magic string. ChannelKeyMatchTimeout(1 second) and theChannelKeyRegexCache(StringComparer.Ordinal) back the validation helper.ConnectionsPerUser(NotificationHub.cs:73): a staticConcurrentDictionary<string, int>,StringComparer.Ordinal, tracking live connection count per user identifier on this replica.SlotItemKey(NotificationHub.cs:54): a private const,"mmca.hub.slot", the key of the per-connection marker inContext.Itemsthat says this connection holds a counted slot.ChannelsItemKey(NotificationHub.cs:57),"mmca.hub.channels", is the key of the same bag's per-connection channel state (ConnectionChannels, below), so that state ends with the connection.OnConnectedAsync(NotificationHub.cs:76-96): whenMaxConnectionsPerUseris positive andContext.UserIdentifieris set, atomically increments the count withAddOrUpdate(:83); if the new count exceeds the cap, it gives the slot straight back viaDecrement(:88, so a refused connection cannot keep counting against the user and lock it out once the aborted ones drain) and throwsHubException("Too many concurrent connections for this account.")(:89); otherwise it marks the connection withContext.Items[SlotItemKey] = true(:92) and returnsbase.OnConnectedAsync()directly (:95). The override is a plainTask-returning method, notasync: nothing is awaited after the slot bookkeeping, so there is no state machine.OnDisconnectedAsync(NotificationHub.cs:99-108): decrements the caller's count only if the connection carries the marker (Context.Items.Remove(SlotItemKey),:102), then returnsbase.OnDisconnectedAsync(exception)(:107) withoutasync. The guard exists because SignalR also runsOnDisconnectedAsyncfor a connection whoseOnConnectedAsyncthrew; releasing a slot for that refused connection would erode the cap one refusal at a time (doc comment onConnectionsPerUser,:64-72).Decrement(string userId)(NotificationHub.cs:114-133): a lock-free loop overTryGetValue/TryRemove/TryUpdatethat removes the entry entirely at zero, so the dictionary tracks only users who are actually connected rather than everyone who ever was.JoinChannelAsync(string channelKey)(NotificationHub.cs:143-178): attributed[HubMethodName(JoinChannelMethod)], it fetches the connection's channel state (:145) and spends one join from the budget first (TrySpendJoin,:149), throwingHubException("Too many channel joins; try again shortly.")(:151) when the bucket is empty. It then validates the key viaEnsureValidChannelKey(:154) and reserves a membership slot withTryReserve(channelKey, MaxChannelsPerConnection, out var reserved)(:158), throwingHubException("Too many channels joined on this connection.")(:160) at the cap. The slot is taken before the entitlement check so two concurrent joins on one connection cannot both take the last one. Inside atryit awaitsEnsureAuthorizedForChannelAsync(channelKey)(:165) and thenGroups.AddToGroupAsync(Context.ConnectionId, channelKey, Context.ConnectionAborted)(:170-171);catch when (reserved)(:173-177) gives a freshly reserved slot back and rethrows, so a refused or failed join does not keep counting, while a failed re-join of a channel already held keeps its slot.LeaveChannelAsync(string channelKey)(NotificationHub.cs:185-193):[HubMethodName(LeaveChannelMethod)], anasyncmethod that validates (:187), awaitsGroups.RemoveFromGroupAsync(...)with the same connection token (:190-191), and then releases the channel's slot (ChannelsOfConnection().Release(channelKey),:192). Leaving spends no join budget and is not re-checked against the authorizer.ChannelsOfConnection()(NotificationHub.cs:196-206): returns theConnectionChannelsstored underChannelsItemKeyinContext.Items, creating and storing one on the connection's first join or leave (:203-204).ConnectionChannels(NotificationHub.cs:248-319): a private nested class holding one connection's joined set (HashSet<string>withStringComparer.Ordinal) and its token bucket, guarded by aLock(:250) because a host may allow a client parallel hub invocations (doc:244-247).TrySpendJoin(:256-285) always succeeds whenChannelJoinsPerMinuteis not positive (:258); otherwise the first call starts the bucket full atChannelJoinBurst(the-1sentinel,:252), later calls refill by elapsed minutes times the rate, capped at the burst (:273), and a join is refused when less than one token remains.TryReserve(:291-309) reports success without reserving for a channel already held, refuses when a positive cap is reached (:301), and otherwise adds the key.Release(:312-318) removes it.EnsureAuthorizedForChannelAsync(NotificationHub.cs:211-227): fails closed. WhenjoinAuthorizerisnullit logs a Warning throughLogJoinRefusedNoAuthorizer(:215) and throwsHubException("Not authorized for this channel.")(:216); otherwise it awaitsjoinAuthorizer.CanJoinAsync(Context.User, channelKey, Context.ConnectionAborted)and throws the sameHubExceptionon afalseresult (:225). Either way a caller not entitled to the channel is refused before the group membership is created and never receives a single published payload.LogJoinRefusedNoAuthorizer(NotificationHub.cs:241-242): a source-generated[LoggerMessage(Level = LogLevel.Warning)]that names the refused channel key and states that noIChannelJoinAuthorizeris registered, so a host that forgot to register one sees why its joins fail instead of a bare client-side error.- Both
JoinChannelAsync/LeaveChannelAsynctake noCancellationTokenparameter, and the comment atNotificationHub.cs:167-169explains why: a hub method signature is the client-visible RPC contract bound by SignalR's dispatcher, so the cancellation token comes from the connection (Context.ConnectionAborted) instead, and the repo'sCancellationTokenConventionTestscarry an explicit exemption for it.[Rubric §15, Best Practices & Code Quality]: the convention is enforced by a test, and the deviation is documented at the deviation site. EnsureValidChannelKey(NotificationHub.cs:229):GetOrAdds the cachedRegexforsettings.Value.ChannelKeyPattern; an empty or non-matching key throwsHubException("Invalid channel key.")(:237), which SignalR surfaces to the caller rather than tearing down the connection.
- Primary-constructor DI of
- Why it's built this way: routing delivery through
IHubContextinstead of hub instance methods lets the framework construct and send messages from anywhere (background senders, a gRPC ingress) without holding a live hub instance, and it is the shape SignalR scale-out (a Redis backplane) expects. The thin hub plus a configured channel-key pattern is the framework default; the pattern lives in PushNotificationSettings (it defaults to NotificationScopeKey.Pattern,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:37) so a host tunes which channels exist without touching code. None of the connection cap, the per-connection join bounds, or the join authorizer changes the wire contract: each surfaces as aHubExceptionon the existing methods. The cap is zero-safe (a non-positiveMaxConnectionsPerUserdisables it,NotificationHub.cs:81), and so are the join bounds (a non-positiveChannelJoinsPerMinuteturns the budget off,:258; a non-positiveMaxChannelsPerConnectionlifts the channel cap,:301); the authorizer is deliberately not: a missing one refuses every join rather than letting any authenticated caller into any well-formed channel, so forgetting the registration fails safe and visibly (the Warning log) instead of silently leaking channel payloads. - Where it's used: mapped by a consuming host through the API-layer helper
MapNotificationHub, which reads the path from settings and only maps when push is enabled (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/SignalRExtensions.cs:22-37); the default path is/hubs/notifications(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:25), and in ADC the Notification service calls it atMMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:157. It is driven by SignalRPushNotificationSender (per-user notification delivery) and SignalRLiveChannelPublisher (ephemeral channel events), both viaIHubContext<NotificationHub>.AddPushNotificationsregisters theIUserIdProvider(ClaimBasedUserIdProvider) that maps a connection's claims to the user id the sender addresses (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:102). ADC's LiveChannelJoinAuthorizer (MMCA.ADC.Notification.Service.Live) is the concreteIChannelJoinAuthorizerthe ADC Notification service registers, without which its channel joins would all be refused. The per-connection join bounds are covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Hubs/NotificationHubChannelBoundsTests.cs.
NotificationPermissionGrants
MMCA.ADC.Notification.Shared ·
MMCA.ADC.Notification.Shared.Authorization·MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Shared/Authorization/NotificationPermissionGrants.cs:26· Level 3 · class (static)
- What it is: the one place ADC binds the Notification module's single capability to a role. Its
only member,
Apply(PermissionRegistryBuilder permissions), grants NotificationPermissions.Manage(sending push notifications and reading the send history) to RoleNames.Organizerand to no other role (lines 28-31). - Depends on: PermissionRegistryBuilder (the parameter it accumulates into), RoleNames, and NotificationPermissions.
- Concept, one grant map two callers can share. The binding used to be written inline as a lambda at
the one call site that needed it. Pulling it into a named, static
Applymethod lets a second host apply the identical grant instead of restating it: the token-minting Identity host also calls it (see Usage below), so the role that may broadcast push notifications cannot drift between the service that enforces the capability and the service that mints the token carrying it.[Rubric §11, Security]assesses whether a role-to-permission binding has one source of truth: a second caller of the same map is exactly the case this guards against, an accidental second grant that disagrees with the first. - Walkthrough:
Apply(line 33) null-guardspermissionswithArgumentNullException.ThrowIfNull(line 35), then callspermissions.Grant(RoleNames.Organizer, NotificationPermissions.Manage)(line 37). There is no other member. - Why it's built this way: a static class with one method keeps the grant a pure function of the registry builder, so calling it twice from two different hosts is safe and cannot pick up ambient state.
- Where it's used: called from the ADC Notification module's
DependencyInjection
.AddNotificationModuleand fromMMCA.ADC.Identity.Service'sTokenPermissionGrants, so the capability the Identity host encodes into a minted token matches the one the Notification host enforces.
SignalRPushNotificationSender
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications.Push·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/SignalRPushNotificationSender.cs:12· Level 3 · class (sealed)
- What it is: the real adapter for IPushNotificationSender. It delivers a notification to specific users, a batch of users, or everyone, through NotificationHub, and chunks large audiences so one send does not overwhelm the SignalR connection manager.
- Depends on: IPushNotificationSender (Level 0);
NotificationHub (Level 2). Externals:
Microsoft.AspNetCore.SignalR(IHubContext<THub>),System.Globalization(invariantToString). - Concept: cross-reference out-of-band delivery via
IHubContexttaught on SignalRLiveChannelPublisher.[Rubric §12, Performance & Scalability]here is about batching: a privateconst int BatchSize = 100(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/SignalRPushNotificationSender.cs:14) caps how many user ids ride a singleClients.Users(batch)call, so broadcasting to a large attendee list is split into bounded sends rather than one giant fan-out.[Rubric §27, i18n]in miniature: user ids are stringified withCultureInfo.InvariantCulture(SignalRPushNotificationSender.cs:19and:47) so the SignalR user-id keys are locale-stable. - Walkthrough
SendToUserAsync(userId, title, body, metadata, cancellationToken)(SignalRPushNotificationSender.cs:17): addressesClients.User(userId.ToString(CultureInfo.InvariantCulture))and invokesNotificationHub.ReceiveNotificationMethod(SignalRPushNotificationSender.cs:18-20), returning theSendAsynctask directly (non-async).SendToUsersAsync(userIds, ...)(SignalRPushNotificationSender.cs:23): iteratesBatchUserIds(userIds)and sends each batch toClients.Users(batch)(SignalRPushNotificationSender.cs:25-31).BroadcastAsync(...)(SignalRPushNotificationSender.cs:35): addressesClients.All(SignalRPushNotificationSender.cs:36-37), also returning the task directly. OnlySendToUsersAsyncstaysasync, because it awaits inside a loop.BatchUserIds(userIds)(SignalRPushNotificationSender.cs:39): a private static iterator that accumulates invariant-culture id strings into aListandyield returns each time it reachesBatchSize, flushing the remainder at the end (SignalRPushNotificationSender.cs:41-55).
- Why it's built this way: all three delivery shapes route through the one hub context and the one shared method-name constant, so the client listens on a single event regardless of how it was targeted. Batching keeps a broadcast to thousands of recipients from constructing one oversized argument list for the connection manager.
- Where it's used: registered over NullPushNotificationSender by
AddPushNotifications(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:97); called by SendPushNotificationHandler after the inbox rows are persisted, inside a swallow-everythingtry/catchso a transport hiccup is recorded as a status rather than thrown.
UserNotification
MMCA.Common.Domain ·
MMCA.Common.Domain.Notifications.UserNotifications·MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/UserNotifications/UserNotification.cs:12· Level 5 · class (sealed)
- What it is: the framework-level aggregate root that tracks delivery of a single
PushNotification to one user, giving each recipient a per-user inbox row with
IsRead/ReadOnstate. - Depends on:
AuditableAggregateRootEntity<TIdentifierType>
(its base, closed over
UserNotificationIdentifierType,MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/UserNotifications/UserNotification.cs:12); IdValueGeneratedAttribute (the[IdValueGenerated]marker,UserNotification.cs:11); Result; the identifier aliasesUserNotificationIdentifierType,UserIdentifierType, andPushNotificationIdentifierType; andTimeProvider(BCL, the injectable clock the caller reads from). - Concept: the fan-out-on-send inbox row. One PushNotification produces N
UserNotificationrows, one per recipient, so read state is tracked per user.[Rubric §4, Domain-Driven Design]assesses whether behavior and invariants live inside the aggregate: state changes flow only through the factory andMarkAsRead, never through public setters (every property has aprivate set,UserNotification.cs:15-24).[Rubric §14, Testability]assesses whether time is injectable:MarkAsReadtakes the read instant as a parameter rather than reading an ambient clock, so behavior is deterministic under test. - Walkthrough
- State:
UserId(UserNotification.cs:15),PushNotificationId(UserNotification.cs:18),IsRead(UserNotification.cs:21), and the nullableReadOntimestamp (UserNotification.cs:24), allprivate set. Two private constructors: the parameterless one EF Core needs (UserNotification.cs:27) and the state-setting one the factory calls (UserNotification.cs:31-36), which seedsIsRead = false. Create(userId, pushNotificationId)(UserNotification.cs:44-47): a directResult.Success(new UserNotification(...) { Id = default }). There is no validation, the only inputs are two foreign keys, andId = defaultbecause[IdValueGenerated](UserNotification.cs:11) hands id generation to the database.MarkAsRead(DateTime readOnUtc)(UserNotification.cs:58): idempotent, an earlyif (IsRead) return(UserNotification.cs:60-63) preserves the original read time on repeat calls; otherwise it setsIsRead = trueandReadOn = readOnUtc(UserNotification.cs:65-66). The instant is supplied by the caller (from an injectedTimeProvider, per the method's own doc atUserNotification.cs:49-57), so the domain stays free of ambient clock access. No domain event is raised on read.
- State:
- Why it's built this way: idempotent
MarkAsReadshrugs off duplicate UI calls without corrupting the first read time, and passing the clock in keeps the entity pure. Database-generated ids ([IdValueGenerated]) suit a high-volume fan-out table where a factory-assigned sequence would be extra coordination. - Where it's used: created by SendPushNotificationHandler for each recipient; read by GetMyNotificationsQuery's handler for the inbox; flipped by MarkNotificationReadHandler and its mark-all sibling behind InboxController. Its rows are also the data UserNotificationExportService projects into the data-subject export.
PushNotificationInvariants
MMCA.Common.Domain ·
MMCA.Common.Domain.Notifications.PushNotifications.Invariants·MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/Invariants/PushNotificationInvariants.cs:10· Level 6 · class (static)
- What it is: the domain rule set for a push notification's text. It owns the two length limits (title 200, body 2000) and the two checks that enforce them, so nothing else has to restate what a valid notification title or body looks like.
- Depends on: CommonInvariants (every check
delegates to it) and Result (
Result.Combine). Externals:System.Globalization(CultureInfo.InvariantCulturefor the message text). It depends on no entity, not even PushNotification, which is what lets three different layers reference it without creating a cycle. - Concept: the static invariant class is taught at
CommonInvariants; this is that pattern applied
to one aggregate. What is worth studying here is the single source of truth for a length limit.
TitleMaxLengthandBodyMaxLengthare read in three places that would otherwise drift apart: the domain factory (MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:130-131), the request validator that rejects bad input before a command ever reaches a handler (SendPushNotificationRequestValidator,MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationRequestValidator.cs:19-20,24-25), and the EF column definition (PushNotificationConfiguration,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/Notifications/PushNotificationConfiguration.cs:29,33). Raising a limit is therefore one edit plus a migration, not four edits and a production truncation.[Rubric §4, DDD]assesses whether business rules live in the domain rather than in the layers that happen to call it: the rule is stated once, in the Domain assembly, and the Application and Infrastructure layers consume it rather than duplicate it.[Rubric §8, Data Architecture]assesses whether domain constraints and the physical schema agree: theHasMaxLengthcall literally reads the domain value, so the column can never be narrower or wider than the rule that guards it. - Walkthrough
TitleMaxLength = 200(line 13) andBodyMaxLength = 2000(line 16) arepublic static readonly int, notconst. The distinction has a visible consequence: astatic readonlyvalue is resolved at runtime, so it cannot be used as an attribute argument. That is why the one length an attribute needs,PushNotification.ScopeKeyMaxLengthbehind the inbox controller's[StringLength(...)], is declaredpublic const inton the entity instead (PushNotification.cs:21), while these two, which are only ever read from ordinary code, are not.EnsureTitleIsValid(string title, string source)(line 18) returnsResult.Combineover twoCommonInvariantscalls (lines 19-21):EnsureStringIsNotEmptywith code"PushNotification.Title.Empty", thenEnsureStringMaxLengthwith code"PushNotification.Title.TooLong"and a message interpolated fromTitleMaxLengthunderCultureInfo.InvariantCulture.Result.Combineaccumulates rather than short-circuits, so a caller sees every violated rule at once.EnsureBodyIsValid(string body, string source)(line 23) is the same shape overBodyMaxLengthand the"PushNotification.Body.*"codes (lines 24-26).- Both take a
sourcestring and forward it to the underlying helper, which puts it on theErrorfor tracing (MMCA.Common/Source/Core/MMCA.Common.Domain/Invariants/CommonInvariants.cs:30-34). Callers passnameof(Create), so a failure names the factory that rejected the input rather than the invariant helper. - Note the asymmetry inherited from the helpers:
EnsureStringMaxLengthlets null and empty pass (CommonInvariants.cs:47-51), which is exactly why each rule pairs it with the non-empty check.
- Why it's built this way: keeping the rules in a static class rather than on the entity lets the Application and Infrastructure layers reference them without referencing an aggregate they have no business constructing, and keeps the entity factory readable as a list of named rules.
- Where it's used: PushNotification
.Createcombines both checks with its own dedup-key and scope-key length checks (PushNotification.cs:129-145); SendPushNotificationRequestValidator reuses the values for its FluentValidation rules; the EF configuration reuses them for the column widths. Covered directly byPushNotificationInvariantsTests(MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Notifications/PushNotificationInvariantsTests.cs:7).
PushNotificationDTOMapper
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.DTOs·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/DTOs/PushNotificationDTOMapper.cs:12· Level 8 · class (sealed, partial)
- What it is: the Mapperly-generated mapper that projects the PushNotification
domain entity onto its PushNotificationDTO response shape, one instance at a
time. It implements
IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>closed overPushNotification/PushNotificationDTO/PushNotificationIdentifierType(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/DTOs/PushNotificationDTOMapper.cs:13). - Depends on:
IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>, PushNotification, PushNotificationDTO, PushNotificationStatus; externalRiok.Mapperly.Abstractions([Mapper],[MapProperty]) and the BCLArgumentNullException. - Concept: compile-time DTO mapping (ADR-001).
The
[Mapper]attribute (line 11) makes the Mapperly source generator emit the body of thepartialMapToDTOat build time, so the projection costs no reflection at runtime and a property that stops matching is a compile error rather than a silent null.[Rubric §9, API & Contract Design]assesses whether the domain type is kept off the wire: this mapper is the one place aPushNotificationbecomes a contract object, so the entity never leaks into a response body.[Rubric §15, Best Practices & Code Quality]assesses whether generated code replaces hand-copied boilerplate: the only hand-written lines here are the collection helper and one enum converter. - Walkthrough
MapToDTO(PushNotification entity)(line 17) ispartial: Mapperly writes the member-by-member copy. The single override is[MapProperty(nameof(PushNotification.Status), nameof(PushNotificationDTO.Status), Use = nameof(MapStatusToString))](line 16), which routes the status through the custom converter instead of a straight assignment. The override is needed because the entity'sStatusis aPushNotificationStatusenum while the DTO's is arequired string(MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/PushNotifications/PushNotificationDTO.cs:26).MapToDTOs(IReadOnlyCollection<PushNotification> entityCollection)(line 20) is hand-written: it null-guards withArgumentNullException.ThrowIfNull(line 22) and then projects with a collection expression overSelect(MapToDTO)(line 23).MapStatusToString(PushNotificationStatus status)(line 26) is the private converter, a plainstatus.ToString(), so a client reads"Sent"rather than a numeric enum value.
- Why it's built this way: Mapperly keeps mapping fast and analyzer-checked while still allowing a per-property override where a straight copy would be wrong (the enum-to-string case). Rendering the status as its name rather than its ordinal means adding an enum member cannot renumber an existing contract value.
- Where it's used: registered twice by the Application-layer DependencyInjection
below (as itself and as the
IEntityDTOMapper<...>interface,MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:51-53), and consumed through it by SendPushNotificationHandler and GetNotificationHistoryHandler to shape what NotificationsController returns. It is not the only path: the mapper serves by-id reads and the non-projectable fallback, while qualifying list reads are served by PushNotificationDTOProjector (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:84-88).
PushNotificationDTOProjector
MMCA.Common.Application ·
MMCA.Common.Application.Notifications.PushNotifications.DTOs·MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/DTOs/PushNotificationDTOProjector.cs:24· Level 8 · class (sealed, partial)
- What it is: the Mapperly-generated projection from PushNotification to
PushNotificationDTO, and at the same time the framework's projection contract
IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>closed overPushNotification/PushNotificationDTO/PushNotificationIdentifierType(line 25). Where the mapper above converts an already-materialized entity, this converts anIQueryable<PushNotification>into anIQueryable<PushNotificationDTO>, so the database returns only the DTO's columns instead of whole notification rows that are mapped afterwards (documented atMMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/DTOs/PushNotificationDTOProjector.cs:8-14). Registering it is what switches notification list reads onto the server-side projection path. - Depends on:
IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>, PushNotification, PushNotificationDTO; externalsRiok.Mapperly.Abstractions([Mapper], line 23) andSystem.Linq(IQueryable<T>). It has no constructor and no state, so it is safe to resolve at any lifetime. - Concept introduced, mapping an expression tree instead of an object, and opting one aggregate into
projection pushdown. A normal mapper is compiled code that runs after rows arrive. A projection has
to be an expression tree the database provider can translate into SQL, so every step of the
mapping must be expressible in that tree. That constraint explains the status handling:
PushNotificationDTOMapper renders
Statuswith a custom method (Use = nameof(MapStatusToString)), and a projection cannot call a method the provider has never heard of. Mapperly's enum-to-string mapping is expressible, so it is inlined as a conditional over the known members, which the provider emits as a SQLCASE, producing exactly the stringsPushNotificationStatus.ToString()would (explained at lines 15-22). The opt-in is a registration, not a code change in any handler.EntityQueryService<TEntity, TEntityDTO, TIdentifierType>declares a five-argument constructor and a six-argument one that additionally takes anIEntityDTOProjector<...>(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:35-40andEntityQueryService.cs:73-79). The container picks the longer constructor when a projector is registered and the shorter one when it is not, because one parameter set is a strict superset of the other; that is the documented reason it is a second constructor rather than an optional parameter, sinceMicrosoft.Extensions.DependencyInjectionhas no notion of an optional dependency (EntityQueryService.cs:57-63). So registering this class in DependencyInjection below is the entire opt-in gesture. The projection path is not taken unconditionally. The decision is taken per read atEntityQueryService.cs:346, andCanProjectrequires three things (EntityQueryService.cs:717-720): a projector is registered, the caller did not ask for tracking (a projection yields DTOs, which the change tracker has nothing to do with), and there are no unsupported cross-source includes (those are loaded row by row after materialization by the navigation populator, which a projection has no rows to hand it). Field shaping deliberately does not disqualify, because shaping runs after materialization over whatever object the pipeline produced (EntityQueryService.cs:713-714).[Rubric §1, SOLID]assesses dependency inversion and interface segregation: the contract has exactly one member, and the query service depends on that interface rather than on Mapperly or on this class.[Rubric §12, Performance & Scalability]assesses whether reads move only the data they need: a projected list read transfers the DTO's columns rather than every column of the notification row, and it skips change-tracker materialization entirely.[Rubric §8, Data Architecture]assesses how the query layer shapes data at the source: pushing the shape into SQL is the difference between shaping at the database and shaping in the process. - Walkthrough
[Mapper](line 23) marks the class for the Mapperly source generator;public sealed partial class(line 24) lets the generator supply the member body in the other half of the partial type.ProjectTo(IQueryable<PushNotification> source)(line 28) is the one member, declaredpublic partialand implementing the interface member directly. Mapperly writes the body: asource.Select(x => new PushNotificationDTO { ... })whose initializer includes the inlined status conditional. Nothing is enumerated here: the returned queryable is still open for the pipeline'sWhere,OrderBy,Skip, andTake.
- Why it's built this way: one generated class that is both the projection and the injectable
contract, so no hand-written adapter sits between Mapperly and DI. It stays separate from the instance
mapper because the two have genuinely different capability sets (one may call arbitrary C#, the other
may not), and keeping them separate is what makes their equivalence testable. The Application-layer
registration uses
TryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:58-60), so a consuming app can register its own projector first and keep it. See ADR-055, which defines projection pushdown as an optional capability of the read contract and records the trade-off: nothing tells a caller which path ran, so a projector that stops being registered loses the optimization with no signal beyond query latency. - Where it's used: registered twice by the Application-layer DependencyInjection
below (as itself and as the interface,
DependencyInjection.cs:58-60), then resolved byEntityQueryService<TEntity, TEntityDTO, TIdentifierType>closed over the notification triple, which serves GetNotificationHistoryHandler's paged reads. Its output is pinned equal to the mapper's byPushNotificationDTOProjectorTests(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Notifications/PushNotificationDTOProjectorTests.cs:16; a[Theory]over everyPushNotificationStatusmember at lines 51-63), which also asserts thatProjectToreturns a still-composable queryable rather than a materialized list (lines 100-110) and that a null source throwsArgumentNullException(lines 112-118). Its SQL translatability is covered byPushNotificationProjectionTranslationTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/PushNotificationProjectionTranslationTests.cs:15), which runsProjectTothrough a real SQLite provider. - Caveats / not-in-source: the generated body is not in the repository (it is emitted at build
time), so the exact SQL
CASEshape is not readable from these files; the tests above assert the observable result rather than the generated text.
DevicesController
MMCA.Common.API ·
MMCA.Common.API.Controllers.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/DevicesController.cs:26· Level 9 · class (sealed)
- What it is: the REST controller that lets any authenticated user manage THEIR own native
push-device installations (ADR-044).
PUT /Notifications/Devicesupserts the installation (called after login and on token rotation) andDELETE /Notifications/Devices/{installationId}removes it (called before logout), per the class documentation atMMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/DevicesController.cs:14-20. - Depends on: ApiControllerBase (its base,
line 28); IPushDeviceRegistrar
(primary-constructor parameter, line 27);
ICurrentUserService (line 28);
DeviceInstallationRequest (the PUT body, line 40);
NotificationFeatures (line 24); Result
and Error. Externals: ASP.NET Core MVC (
[ApiController],[Route],[HttpPut],[HttpDelete],ProblemDetails),Asp.Versioning([ApiVersion("1.0")], line 23),Microsoft.AspNetCore.Authorization([Authorize], line 25), andMicrosoft.FeatureManagement.Mvc([FeatureGate], line 24). - Concept introduced, the ownership-stamped resource whose id comes from the client. Every other
controller in this group addresses server-generated ids. A device installation id is a
client-generated GUID instead, because the device mints it before it has ever talked to the server
(documented at lines 15-19). Two consequences are visible in the code. First, the owner is never taken
from the request: both actions re-derive
userIdfromICurrentUserService.UserId(lines 43 and 67) and pass it to the registrar, so a caller cannot register or delete a device on someone else's behalf. Second, the delete is deliberately indistinguishable between "no such installation" and "not yours": IPushDeviceRegistrar verifies the owninguser:{id}tag and reports both cases as success (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/IPushDeviceRegistrar.cs:40-48), so the endpoint cannot be used as an existence oracle for other users' installation ids (restated on the action itself,DevicesController.cs:53-59).[Rubric §11, Security]assesses whether authorization and ownership are enforced at the boundary: class-level[Authorize](line 25) plus server-side ownership stamping plus a uniform 204 on delete is the whole posture here.[Rubric §9, API & Contract Design]assesses REST-shape consistency: both actions declare typed[ProducesResponseType]results (204 on success, plus aProblemDetailsfailure shape: 400 and 409 on the upsert at lines 37-38, where the 409 answers an installation id owned by another user: the client mints a new id and retries, per the action doc at lines 30-34, and 401 on the delete at lines 61-62) and share theHandleFailure-or-success return shape used across the group. - Walkthrough
- Primary-constructor DI of the registrar and the current-user service (lines 26-28); the class is
sealedand derives fromApiControllerBase, which suppliesHandleFailure. UpsertAsync([FromBody] DeviceInstallationRequest request, ...)(line 39): readscurrentUserService.UserId(line 43); a null user short-circuits throughHandleFailure([Error.Unauthorized("PushDevice.Unauthorized", "User is not authenticated.")])(lines 44-47). Otherwise it awaitsregistrar.UpsertAsync(userId.Value, request, cancellationToken)(line 49) and returnsNoContent()(204) orHandleFailure(result.Errors)(line 50).DeleteAsync(string installationId, ...)(line 63): the id arrives from the route ([HttpDelete("{installationId}")], line 60). The same null-user guard runs (lines 68-71), thenregistrar.DeleteAsync(userId.Value, installationId, cancellationToken)(line 73), the ownership-scoped overload, and the action answers 204 on any non-failure (line 74).
- Primary-constructor DI of the registrar and the current-user service (lines 26-28); the class is
- Why it's built this way: the controller is wrapped in
[FeatureGate(NotificationFeatures.PushNotifications)](line 24), so with theNotification.PushNotificationsflag off the routes are simply not there rather than answering as dead endpoints. Routing all storage through IPushDeviceRegistrar keeps the controller free of any push-provider detail, which is what lets the default implementation stay a no-op until a notification hub is configured (ADR-044). - Where it's used: made routable by the API-layer DependencyInjection helper
below (
AddNotificationControllers); called by a native client's login and logout flows. Covered byDevicesControllerTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Notifications/DevicesControllerTests.cs:18).
InboxController
MMCA.Common.API ·
MMCA.Common.API.Controllers.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationInboxController.cs:29· Level 9 · class (sealed)
- What it is: the REST controller for one user's in-app notification inbox: read the inbox (paged),
read the unread count, mark one notification read, and mark everything read. An authenticated caller
reaches only their own inbox. Note the file name and the type name differ: the class is
InboxController, so the[controller]token in[Route("Notifications/[controller]")](line 25) yieldsNotifications/Inbox, but it lives inNotificationInboxController.cs. - Depends on: ApiControllerBase;
ICurrentUserService (line 34); the handler contracts
IQueryHandler<in TQuery, TResult>andICommandHandler<in TCommand, TResult>(lines 30-33); the four use cases GetMyNotificationsQuery, GetUnreadNotificationCountQuery, MarkNotificationReadCommand and MarkAllNotificationsReadCommand; UserNotificationDTO; PushNotification (for theScopeKeyMaxLengthconstant, line 46);PagedCollectionResult<T>, Result, Error; NotificationFeatures. Externals: ASP.NET Core MVC,Asp.Versioning,Microsoft.FeatureManagement.Mvc, andSystem.ComponentModel.DataAnnotations([Range],[StringLength]). - Concept introduced, the feature-gated controller that injects handlers directly. There is no
service layer between HTTP and the use cases: the constructor takes the four
IQueryHandler/ICommandHandlerclosures it needs (lines 30-33) and every action does exactly three things, resolve the caller, build the query or command, translate theResultto a status code. Everything cross-cutting (logging, caching, validation, transaction) is added by the CQRS decorator pipeline around those handlers, so none of it appears here.[Rubric §6, CQRS & Event-Driven]assesses whether presentation delegates to command/query handlers rather than to service wrappers: this class is the reference shape for that.[Rubric §11, Security]assesses boundary authorization: a plain[Authorize](line 28) gates the class, since any authenticated identity may have an inbox and no capability is required, and every action re-scopes tocurrentUserService.UserIdso the data read is user-scoped, not merely route-scoped. Contrast NotificationsController below, whose broadcast surface carries thenotifications:managecapability instead.[Rubric §9, API & Contract Design]assesses contract consistency:[ApiVersion("1.0")](line 26), typed[ProducesResponseType]on each action, and query-string paging with[Range(1, int.MaxValue)]validation (lines 44-45). - Concept introduced, the optional
scopefilter. Three of the four actions take an optionalscopequery parameter bounded by[StringLength(PushNotification.ScopeKeyMaxLength)](128 characters,MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:21), which narrows the inbox to notifications carrying that scope plus the unscoped ones; omitting it returns everything (documented lines 36-40). The parameter is threaded through the read, the badge count, and the bulk write on purpose: a scoped caller must never clear notifications its own inbox read hid from it (lines 105-109). See ADR-024. - Walkthrough
- Primary-constructor DI of two query handlers, two command handlers, and the current-user service (lines 29-34).
GetInboxAsync(line 43):[HttpGet](line 41);pageNumberdefaults to 1 andpageSizeto 20 (lines 44-45), both[Range(1, int.MaxValue)]; the optionalscopeis line 46. A null user short-circuits toError.Unauthorized("Notification.Unauthorized", ...)(lines 49-53). It buildsnew GetMyNotificationsQuery(userId.Value, pageNumber, pageSize, scope)(line 55), awaits the handler (lines 56-57), and returns 200 with thePagedCollectionResult<T>orHandleFailure(line 59).GetUnreadCountAsync(line 69): routeunread-count(line 66) and[ResponseCache(NoStore = true)](line 67), so the badge count is never served from a cache. It issuesnew GetUnreadNotificationCountQuery(userId.Value, scope)(line 79) and returns the rawint(line 82).MarkReadAsync(line 89): route{id:int}/read(line 86), the id bound[FromRoute]asUserNotificationIdentifierType(line 90). It issuesnew MarkNotificationReadCommand(id, userId.Value)(line 99) and returns 204 or, per its declared contract, a 404ProblemDetails(lines 87-88).MarkAllReadAsync(line 112): routeread-all(line 110), no body, optionalscope(line 113). It issuesnew MarkAllNotificationsReadCommand(userId.Value, scope)(line 122) and returns 204 (line 125).
- Why it's built this way: passing
userIdinto every query and command keeps authorization a data concern rather than only a routing concern, which is what makes the same handlers reusable from a non-HTTP caller. The class-level[FeatureGate(NotificationFeatures.PushNotifications)](line 27) makes the whole inbox surface disappear when the flag is off, so a host that has not opted into notifications does not advertise endpoints it cannot serve. - Where it's used: registered into MVC application parts by
AddNotificationControllers(DependencyInjection, API layer, below); consumed by the in-app inbox UI (the unread badge plus the notification list). Covered byNotificationInboxControllerTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Notifications/NotificationInboxControllerTests.cs:17).
NotificationsController
MMCA.Common.API ·
MMCA.Common.API.Controllers.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationsController.cs:30· Level 9 · class (sealed)
- What it is: the manage-only REST controller for push notifications:
POST /Notificationssends a notification to all recipients and returns 201,GET /Notificationsreturns the paged send history. Both actions require thenotifications:managecapability. - Depends on: the same controller family as InboxController
(ApiControllerBase,
ICurrentUserService,
Result, Error,
PagedCollectionResult<T>, NotificationFeatures), plus HasPermissionAttribute and NotificationPermissions (line 29), SendPushNotificationCommand, GetNotificationHistoryQuery, SendPushNotificationRequest, PushNotificationDTO, IdempotentAttribute (line 44) and IdempotencyHeaders (line 62). Externals: ASP.NET Core MVC,Asp.Versioning,Microsoft.FeatureManagement.Mvc, andSystem.Globalization(CultureInfo). - Concept: the feature-gated, handler-injecting controller shape is taught at
InboxController. What differs here is the authorization boundary:
[HasPermission(NotificationPermissions.Manage)](line 29) restricts both actions to callers holding thenotifications:managecapability, because sending is a broadcast while the inbox is per-user. The gate names a capability rather than a role, so each host decides which of its roles holds it (stated atNotificationsController.cs:20-23); see NotificationPermissions for the constant and HasPermissionAttribute for the machinery behind the attribute.[Rubric §11, Security]assesses least privilege: the write side carries its own stricter, capability-based gate instead of reusing the authenticated-only one the inbox uses.[Rubric §9, API & Contract Design]assesses REST correctness:SendAsyncanswersCreated(...)with a relativeLocationURI built from the new notification's id (line 74). - Concept introduced, two-level retry safety (response replay plus delivery dedup). The send path is
protected twice over, and the doc comment at lines 35-42 spells out why one level is not enough.
[Idempotent](line 44) makes the IdempotencyFilter replay the original HTTP response for a repeatedIdempotency-Key(ADR-017). That protects the response, but only while the cached entry survives. So the action ALSO reads the raw header itself and carries it into the domain as the command'sDedupKey(lines 60-69), where a key that has already been seen returns the existing notification instead of sending a second time (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationCommand.cs:25-36). The filter protects the response; theDedupKeyprotects delivery when the cache is cold, evicted, or degraded. See ADR-024.[Rubric §29, Resilience & Business Continuity]assesses whether a retried or replayed request can cause duplicate side effects: the two levels together mean a client can retry a send freely. - Walkthrough
- Primary-constructor DI of the send command handler, the history query handler, and the current-user service (lines 30-33).
SendAsync([FromBody] SendPushNotificationRequest request, ...)(line 48): guards a null user withError.Unauthorized("Notification.Unauthorized", ...)(lines 52-56). It then readsIdempotencyHeaders.IdempotencyKeyoffRequest.Headersdirectly (lines 62-66); an absent or whitespace-only value leavesdedupKeynull, which is the behavior where every send creates a new notification (comment lines 58-59). The header is read manually rather than bound with[FromHeader](and Sonar's S6932 suppressed with that reason, lines 61 and 67) so protocol plumbing shared with the idempotency filter does not appear in the generated OpenAPI contract. It buildsnew SendPushNotificationCommand(request, userId.Value) { DedupKey = dedupKey }(line 69). The result is branched with!result.TryGetValue(out var created)(line 72): a failure goes toHandleFailure(result.Errors), and a success returnsCreated(new Uri(string.Create(CultureInfo.InvariantCulture, $"/notifications/{created.Id}"), UriKind.Relative), created)(line 74), so the success path reads the boundcreatedvalue rather than a null-forgivingresult.Value!.GetHistoryAsync(line 80):[HttpGet](line 78) with[Range(1, int.MaxValue)]paging,pageSizedefaulting to 10 (lines 81-82). It runsnew GetNotificationHistoryQuery(pageNumber, pageSize)(line 85) and returns 200 with the paged PushNotificationDTO collection (line 91). Unlike the inbox, history takes no user filter and no null-user guard: the capability gate already established who may read it, and a holder sees every send.
- Why it's built this way: splitting the broadcast surface from the per-user inbox surface lets each
controller carry exactly its own authorization gate, so widening the inbox's gate can never widen the
send gate by accident. Both stay behind
[FeatureGate(NotificationFeatures.PushNotifications)](line 28). - Where it's used: registered via
AddNotificationControllers(DependencyInjection, API layer, below); consumed by the organizer push-notification UI. Covered byNotificationsControllerTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Notifications/NotificationsControllerTests.cs:16).
DependencyInjection
MMCA.Common.API ·
MMCA.Common.API.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.API/Notifications/DependencyInjection.cs:9· Level 10 · class (static)
(API-layer notification DI. A second DependencyInjection, the ADC Notification module's one, follows
below; both keep the raw type name as their heading.)
- What it is: the API-layer DI helper for the notification subsystem. Its one member,
AddNotificationControllers, adds this package's assembly to the MVC application parts, which makes the host's dependency on the three notification controllers explicit. - Depends on: the NotificationsController type, used only as an assembly
anchor (line 26); externals
Microsoft.Extensions.DependencyInjection(IMvcBuilder) and ASP.NET Core MVC application parts. - Concept introduced, an explicit application part for controllers that ship in a NuGet package.
ASP.NET Core discovers controllers through the host's application parts. The notification controllers
live in
MMCA.Common.API, a referenced package, and the member's own documentation (lines 13-22) records that a referencing host usually discovers them already: the SDK-generatedMvcApplicationPartsAssemblyInfolists every referenced assembly that depends on MVC, so the controllers are routed and appear in the host's OpenAPI document even without this call, and adding the part again is a no-op. The call therefore states the dependency rather than switching something on. The same comment names the step that IS required: exposing the endpoints does not serve them, and the host must also callAddNotificationApplicationServicesor the inbox endpoints fail to resolve their handlers (lines 19-21).AddNotificationControllersis written as anextension(IMvcBuilder builder)member (line 11) that callsbuilder.AddApplicationPart(typeof(NotificationsController).Assembly)(line 26), which covers all three controllers in one call because they share an assembly.[Rubric §7, Microservices Readiness]assesses whether a capability packages cleanly for reuse across hosts: shipping the controllers together with their own one-line registration means the whole notification HTTP surface moves into an extracted service without editing the controllers.[Rubric §3, Clean Architecture]assesses whether composition stays at the edge: the host's composition root names the notification surface it depends on instead of leaving it implicit in a package reference. - Walkthrough: inside the
extension(IMvcBuilder builder)block (line 11),AddNotificationControllers()(line 24) adds the application part (line 26) and returns the builder for fluent chaining (line 27). There is no other member; the class isstatic(line 9). - Why it's built this way: exposing the registration as a named
extension(IMvcBuilder)member keeps a host's composition root declarative and reads asAddControllers().AddNotificationControllers()(see primer §4). This is the API counterpart to the Application-layerAddNotificationApplicationServicesbelow: one call wires the handlers, the other exposes them over HTTP, and only the handler registration is load-bearing for serving requests. - Where it's used: called from a consuming host's MVC setup, alongside the Application-layer
registration (for example
MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:48).
DependencyInjection
MMCA.ADC.Notification.API ·
MMCA.ADC.Notification.API·MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:17· Level 4 · class (static)
- What it is: the Notification module's outermost DI composition. Its single extension method
AddNotificationModuleassembles the whole module: application services, EF configuration, the SignalR push pipeline, the optional native-push channel, the one permission grant, and the framework controllers. - Depends on:
IConfiguration(its one parameter), the application-layer DependencyInjection.AddModuleNotificationApplication,AddNotificationInfrastructure(configuration)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:29),AddPushNotifications(configuration),AddAzureNotificationHubsPush(configuration)fromMMCA.Common.Azure(MMCA.Common/Source/Hosting/MMCA.Common.Azure/AzureServiceCollectionExtensions.cs:97),AddPermissions(...)plus NotificationPermissionGrants, andAddControllers().AddNotificationControllers()(the API-layer DependencyInjection). - Concept, the module composition root as a single ordered method. Where the application-layer
DependencyInjection registers only ADC's policy choices, this one composes
every layer of the module in one readable sequence, so a reader can see the module's entire surface
without opening five files.
[Rubric §3, Clean Architecture]assesses layer separation: the calls descend from application to infrastructure to presentation in that order, and the framework pieces (AddPushNotifications,AddAzureNotificationHubsPush,AddNotificationControllers) come fromMMCA.Commonpackages while only the permission grant is app-specific. The native-push vendor is chosen here, at the module edge, by calling the Azure Notification Hubs adapter from the separateMMCA.Common.Azurepackage (comment lines 36-38), rather than inside the framework's core infrastructure.[Rubric §11, Security]shows in that grant: the doc comment (lines 21-29) states the whole authorization story for the module in one place, that NotificationPermissions.Manageis held by RoleNames.Organizerand by no other role, so an attendee cannot broadcast and no content editor holds a notification capability it was not given. The map itself now lives in NotificationPermissionGrants rather than an inline lambda here, because the token-minting Identity host applies the identical binding (comment lines 41-44). - Walkthrough: an
extension(IServiceCollection services)block (line 19) containingAddNotificationModule(IConfiguration)(lines 30-51). It callsAddModuleNotificationApplication()(line 32) for ADC's handlers and policies,AddNotificationInfrastructure(configuration)(line 33) for the EF configuration, theNotificationSettingsbound from theNotificationssection, and the retention sweep unlessNotifications:RetentionEnabledis false (its doc comment,DependencyInjection.Notifications.cs:21-27),AddPushNotifications(configuration)(line 34) for the SignalR sender and hub, andAddAzureNotificationHubsPush(configuration)(line 39) for the native third channel over Azure Notification Hubs. The comment on that call (lines 36-38) records that it is a no-op unless theNativePushconfiguration section is enabled and complete, which is why it is safe to call unconditionally in every environment. Then the single grant,services.AddPermissions(NotificationPermissionGrants.Apply)(line 45), and finallyservices.AddControllers().AddNotificationControllers()(line 48), which adds the framework's notification controllers as an explicit ASP.NET Core application part. The collection is returned for chaining (line 50). - Why it's built this way: one method that a module's
Registercalls keeps the whole notification surface (handlers, persistence, push channels, grant, controllers) composed in one place, and naming the Azure adapter here keeps the vendor choice at the app edge. Registering the native channel unconditionally and letting configuration decide keeps environment differences inappsettings, not in code (ADR-044). - Where it's used: called from NotificationModule
.Register(MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/NotificationModule.cs:30).
⬅ Caching • Index • Navigation Metadata & Populators (EF-decoupled eager loading) ➡