Hmz.Core.Notifications
0.1.1
dotnet add package Hmz.Core.Notifications --version 0.1.1
NuGet\Install-Package Hmz.Core.Notifications -Version 0.1.1
<PackageReference Include="Hmz.Core.Notifications" Version="0.1.1" />
<PackageVersion Include="Hmz.Core.Notifications" Version="0.1.1" />
<PackageReference Include="Hmz.Core.Notifications" />
paket add Hmz.Core.Notifications --version 0.1.1
#r "nuget: Hmz.Core.Notifications, 0.1.1"
#:package Hmz.Core.Notifications@0.1.1
#addin nuget:?package=Hmz.Core.Notifications&version=0.1.1
#tool nuget:?package=Hmz.Core.Notifications&version=0.1.1
Hmz.Core.Notifications
An in-app notification engine for Hmz backends on EF Core and PostgreSQL: a bell, an unread
count, a live update, and "this was handled" for requests someone acts on. It stores one
deduplicated row per recipient, applies the audience and scope rules of your application,
exposes the REST endpoints, publishes live signals through the realtime engine
(Hmz.Core.Realtime) after the commit, and purges old rows.
It is app-neutral. Brands, products and permissions are application concepts plugged in through
extension points; the package references no application assembly. It depends on
Hmz.Core.Notifications.Abstractions, Hmz.Core.Realtime (live signals), Hmz.Core.SharedKernel
(messaging, ICurrentUser, Result and ProblemDetails mapping, the lease of the retention worker),
EF Core, Npgsql and ASP.NET Core. Namespace:
Hmz.Core.Notifications; the contracts live in Hmz.Core.Notifications.Abstractions.
Hosting it in a module DbContext
The table lives in the schema of the module that hosts the engine, next to its inbox. The application generates the migration.
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public const string Schema = "notifications";
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(Schema);
modelBuilder.ApplyNotificationModel(Schema); // the Notifications table
modelBuilder.AddInboxMessages(); // inbox of the events the sources consume
}
}
services.AddDbContext<AppDbContext>((provider, options) =>
{
options.UseNpgsql(connectionString);
options.AddNotificationSignals(provider); // live signals only after the commit
});
services.AddNotificationEngine<AppDbContext>(configuration);
services.AddNotificationType(AccessPending); // once per type
services.AddAudienceRuleResolver<PermissionHoldersAudience, PermissionHoldersResolver>();
services.AddNotificationScopeAccess<TenantScopeAccess>();
AddNotificationEngine also registers the messaging runtime (AddMessaging), the realtime engine
(AddRealtime), the default lease provider (AddLocalDistributedLease), the retention worker and
the options. Both are added with TryAdd, so a replacement you register wins. dotnet ef migrations add then produces the Notifications table and its three indexes in your schema. The names are
part of the contract (see Database).
Registering a type
public static readonly NotificationType AccessPending = new(
"account.access-pending", // stable, never renamed
NotificationPriority.P1,
DefaultAudience: [new PermissionHoldersAudience("users.approve", Scoped: true)],
Resolvable: true, // a later fact can close it
RetentionDays: null); // null: Notifications:Retention:ReadDays
A source is an inbox handler of an integration event of your module. Inside it, call the
dispatcher: it runs on the handler's DbContext, so the rows commit with the inbox entry.
await dispatcher.DispatchAsync(new NotificationRequest(AccessPending.Code, $"access:{userId}", occurredAt)
{
ActorUserId = actorId, // always excluded
Scope = new NotificationScope("tenant", tenantId),
Target = new NotificationTarget("user", new Dictionary<string, object?> { ["userId"] = userId }),
Payload = new { UserId = userId }, // data, never rendered text
}, ct);
await resolver.ResolveAsync(AccessPending.Code, $"access:{userId}", ct); // idempotent
Dispatch resolves every audience rule (one after another: they share the scoped DbContext),
unions the users, drops the actor, drops the recipients without access to the scope, and inserts
all remaining rows in one statement. Replaying a source is a no-op. It throws
InvalidOperationException for an unregistered type code or scope kind.
An audience resolver
public sealed class PermissionHoldersResolver(IUserDirectory users)
: IAudienceRuleResolver<PermissionHoldersAudience>
{
public Task<IReadOnlyCollection<long>> ResolveAsync(
PermissionHoldersAudience rule, NotificationScope? scope, CancellationToken ct = default) =>
users.FindHoldersAsync(rule.Permission, rule.Scoped ? scope?.Id : null, ct);
}
UsersAudience has a built-in resolver. You may define your own AudienceRule records and
register a resolver for each.
A scope access
One implementation per scope kind (the kind must not contain a colon).
public sealed class TenantScopeAccess(ITenantDirectory tenants) : INotificationScopeAccess
{
public string ScopeKind => "tenant";
public Task<IReadOnlyCollection<long>> FilterRecipientsAsync(
IReadOnlyCollection<long> userIds, string scopeId, CancellationToken ct = default) =>
tenants.UsersWithAccessAsync(userIds, scopeId, ct);
public async Task<NotificationScopeAccessSet> GetAccessibleScopesAsync(long userId, CancellationToken ct = default) =>
new(All: false, await tenants.AccessibleIdsAsync(userId, ct));
}
The scope is checked when storing (FilterRecipientsAsync) and again on every list, count and
read (GetAccessibleScopesAsync), so revoked access hides rows at once. A row whose scope kind
has no registered access is hidden. The access is not cached across requests.
Endpoints
app.MapNotificationEndpoints("notifications")
.MapToApiVersion(ApiVersion.Default)
.WithTags("Notifications")
.RequireSignedInUser(); // SharedKernel 0.1.20; the host owns version, tags and access
All routes are self-scoped through ICurrentUser.UserId (null: 401).
| Route | Result |
|---|---|
GET {prefix}?cursor&limit(1..100, 20)&unreadOnly |
NotificationPageResponse { items, nextCursor }, newest first, keyset cursor |
GET {prefix}/unread-count |
{ count } (neither read nor resolved) |
POST {prefix}/{id}/read |
204; 404 problem when missing, hidden or not the caller's |
POST {prefix}/read-all |
{ updated } |
Problems: Notifications.InvalidCursor, Notifications.InvalidLimit (400), Notifications.NotFound
(404), Notifications.Unauthorized (401).
Live signals: envelope v1
Signals reach the client on the one realtime stream of the application, which the host maps once
for every feature (see Hmz.Core.Realtime):
app.MapRealtimeStream("realtime/stream").RequireSignedInUser();
The client opens it with fetch and the bearer header (never a token in the URL), optionally with
?types=notification to receive only the notification events.
event: ping
data: {}
event: notification
data: {"v":1,"type":"notification.created","id":"<uuid>","unreadCount":3}
id: <notification id, only when one notification is concerned>
typeis one ofnotification.created,notification.read,notification.read-all,notification.resolved.id(in the data and as the event id) is omitted when no single notification is concerned.unreadCountis the recipient's count after the change.- The envelope is a wire contract. It never changes in place; a new shape is version 2.
- Signals are hints: after a signal or a reconnect, refetch over REST. A lost signal costs nothing.
- The
pingevent, the headers, the stream limit per user and the cut at the token'sexpare those of the realtime stream (Realtime:Streamoptions).
How a signal travels: inside the caller's transaction it is buffered per transaction
(NotificationSignalInterceptor) and dropped on rollback; after the commit it goes on the in-process
IMessageBus as a NotificationSignalMessage; the engine's handler then computes the unread count
of each recipient that may be connected (IRealtimePresence) and publishes one notification event
per recipient through IRealtimePublisher. Only rows really inserted (or changed) are signalled.
Several API instances
The default realtime backplane is in process, so live updates assume one API instance: with a
second replica a user only receives the signals published by the instance they are connected to
(REST reads stay correct). Register an out-of-process IRealtimeBackplane adapter (Redis,
PostgreSQL NOTIFY, NATS) to fan out across instances; Notifications does not change. The retention
worker takes the IDistributedLeaseProvider lease per pass; the default grants it on every
instance, so register a shared lease (for example a PostgreSQL advisory lock) to purge on one.
Retention, options, meter
A hosted service deletes rows that are read or resolved longer ago than the retention (the later of
ReadAt and ResolvedAt), in batches of one set-based DELETE ... WHERE "Id" IN (SELECT ... LIMIT n)
each (EF Core ExecuteDelete). Unread, unresolved rows are never deleted.
NotificationType.RetentionDays overrides the default for one type.
| Option | Default |
|---|---|
Notifications:Retention:ReadDays |
90 |
Notifications:Retention:Interval |
1.00:00:00 |
Notifications:Retention:BatchSize |
1000 |
Options are validated at startup; the stream options are Realtime:Stream (see
Hmz.Core.Realtime). Add the meter Hmz.Core.Notifications (NotificationTelemetry.MeterName)
to your telemetry: hmz.notifications.created, .deduplicated and .signals.dropped; open
streams are hmz.realtime.streams.open on the Hmz.Core.Realtime meter.
Database
ApplyNotificationModel(schema) maps table Notifications (Id uuid v7, RecipientUserId
bigint, TypeCode varchar(100), DedupKey varchar(200), ScopeKind varchar(50)?,
ScopeId varchar(100)?, ActorUserId bigint?, Target jsonb?, Payload jsonb?, CreatedAt,
ReadAt?, ResolvedAt?) with PK_Notifications, the unique
UX_Notifications_TypeCode_DedupKey_RecipientUserId, IX_Notifications_RecipientUserId_CreatedAt
(CreatedAt descending) and the partial IX_Notifications_RecipientUserId_Unread
(ReadAt IS NULL AND ResolvedAt IS NULL). The engine's raw insert SQL reads table and column names
from the model, so a host mapping does not break it.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Hmz.Core.Notifications.Abstractions (>= 0.1.1)
- Hmz.Core.Realtime (>= 0.1.0)
- Hmz.Core.SharedKernel (>= 0.1.21)
- Microsoft.EntityFrameworkCore (>= 10.0.11)
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.11)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 10.0.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.