Hmz.Core.Notifications 0.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Hmz.Core.Notifications --version 0.1.0
                    
NuGet\Install-Package Hmz.Core.Notifications -Version 0.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Hmz.Core.Notifications" Version="0.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hmz.Core.Notifications" Version="0.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Hmz.Core.Notifications" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Hmz.Core.Notifications --version 0.1.0
                    
#r "nuget: Hmz.Core.Notifications, 0.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Hmz.Core.Notifications@0.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Hmz.Core.Notifications&version=0.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Hmz.Core.Notifications&version=0.1.0
                    
Install as a Cake Tool

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 and a server-sent events (SSE) stream, 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.SharedKernel (messaging, ICurrentUser, Result and ProblemDetails mapping), 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 retention worker and the options. 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 }
GET {prefix}/stream text/event-stream

Problems: Notifications.InvalidCursor, Notifications.InvalidLimit (400), Notifications.NotFound (404), Notifications.Unauthorized (401).

The stream: envelope v1

The client opens the stream with fetch and the bearer header (never a token in the URL).

event: notification
id: <notification id, or empty>
data: {"v":1,"type":"notification.created","id":"<uuid>","unreadCount":3}

: ping
  • type is one of notification.created, notification.read, notification.read-all, notification.resolved. id is omitted when no single notification is concerned.
  • 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.
  • : ping comments keep proxies from closing the stream. Headers include Cache-Control: no-cache and X-Accel-Buffering: no (a proxy-defined header that turns off buffering).
  • The stream ends at the access token's exp claim; reconnect with a fresh token. Opening more than MaxStreamsPerUser streams closes the oldest.

One API instance

The connection registry is in process and signals travel over the in-process IMessageBus, so live updates assume one API instance: with a second replica a user only receives signals published by the instance they are connected to (REST reads stay correct). The seam for more replicas or an external gateway is IRealtimeSignalPublisher: register another implementation (Postgres NOTIFY, Redis, NATS) after AddNotificationEngine.

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. 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
Notifications:Stream:Heartbeat 00:00:25
Notifications:Stream:MaxStreamsPerUser 5

Options are validated at startup. Add the meter Hmz.Core.Notifications (NotificationTelemetry.MeterName) to your telemetry: hmz.notifications.created, .deduplicated, .signals.dropped and .streams.open.

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 SQL reads table and column names from the model, so a host mapping does not break it.

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.1 64 11/17/2026
0.1.0 59 11/16/2026