Hmz.Core.Realtime
0.1.0
dotnet add package Hmz.Core.Realtime --version 0.1.0
NuGet\Install-Package Hmz.Core.Realtime -Version 0.1.0
<PackageReference Include="Hmz.Core.Realtime" Version="0.1.0" />
<PackageVersion Include="Hmz.Core.Realtime" Version="0.1.0" />
<PackageReference Include="Hmz.Core.Realtime" />
paket add Hmz.Core.Realtime --version 0.1.0
#r "nuget: Hmz.Core.Realtime, 0.1.0"
#:package Hmz.Core.Realtime@0.1.0
#addin nuget:?package=Hmz.Core.Realtime&version=0.1.0
#tool nuget:?package=Hmz.Core.Realtime&version=0.1.0
Hmz.Core.Realtime
The realtime delivery engine of Hmz backends on ASP.NET Core. A feature publishes a live hint
through IRealtimePublisher; the engine fans it out to every connected client of the audience over
one multiplexed server-sent events (SSE) stream per client. Notifications is the first consumer;
any other feature (Reporting: report.ready, report.progress) publishes the same way with no
change here.
It depends on Hmz.Core.Realtime.Abstractions (the contracts), Hmz.Core.SharedKernel
(ICurrentUser, ProblemDetails mapping) and ASP.NET Core. Namespace: Hmz.Core.Realtime.
Setup
services.AddRealtime(configuration); // Notifications' AddNotificationEngine calls it too
app.MapRealtimeStream("realtime/stream")
.MapToApiVersion(ApiVersion.Default)
.WithTags("Realtime")
.RequireSignedInUser(); // the host owns version, tags, auth and OpenAPI
MapRealtimeStream throws at startup when AddRealtime was not called.
Architecture
feature --IRealtimePublisher--> IRealtimeBackplane --(every instance)--> IRealtimeTransport --> connections
in-process default SSE built in
- Publisher (
IRealtimePublisher): never throws for a delivery failure (logged and counted); an invalid type or id throwsArgumentExceptionwhen the event is built. The payload is serialized once at publish time. - Backplane (
IRealtimeBackplane): the defaultInProcessRealtimeBackplanedelivers to the transports of this process. It assumes one API instance: with several, a user receives only the events published on the instance their stream is connected to, until an out-of-process backplane adapter (Redis, PostgreSQLNOTIFY, NATS) is registered through its own extension method. Publishers and transports do not change. - Transports (
IRealtimeTransport): SSE is built in. A SignalR adapter can be added side by side in its own package; every registered transport is subscribed to the backplane at startup. - Presence (
IRealtimePresence): the in-process backplane answers from this instance's transports. A replacement backplane that cannot tell makes every user "maybe connected". - Authorizers (
IRealtimeEventAuthorizer, optional): narrow which event types a connection may receive; register them withTryAddEnumerable, as singletons or scoped.CanReceiveAsyncis asked once per connection and type on the stream's own loop, never on the publisher's thread, with the services of the stream request's scope (a scopedIPermissionCheckersees the permissions your middleware resolved), and the answer is cached for the stream's life. Until a type is decided its events wait in the queue. An exception denies (logged); a cancellation is not cached. Cache slow lookups (permissions) yourself. - Reconnect requests: when what a decision rests on changes (roles, permissions, deactivation),
call
realtime.RequestReconnectAsync(RealtimeAudience.Users(ids))after the change commits. Those streams getevent: reconnectand close, and the client's new stream is authorized afresh (a deactivated user is refused). It travels through the backplane like any event. - User resolver (
IRealtimeUserResolver): the default readsICurrentUser.UserId; null answers 401. Register another singleton to map the principal differently.
Every default is registered with TryAdd. Replace one by registering yours before AddRealtime, or
after it with AddSingleton (the last registration is resolved). The engine never picks an
implementation from an options value.
Publishing after a commit
A realtime event is a hint: the client refetches when it arrives. It must never arrive before the data it announces is committed, or the refetch finds nothing. The data is persisted first; losing a hint is acceptable, unless the event must reach the client, in which case use the outbox.
| Path | Guarantee | Use for |
|---|---|---|
IRealtimePublisher.PublishAsync, called after the commit returned |
At most once; you place the call | Code without a surrounding transaction |
IRealtimeAfterCommitPublisher.PublishAfterCommit |
At most once, after the context's transaction commits; dropped on rollback; lost on a crash in between | The default for hints inside a unit of work, a handler or an inbox delivery |
outbox.AddRealtimeEvent with AddRealtimeOutboxDelivery<TDbContext> |
At least once; commits with the data and survives a crash; a retry can repeat it | Events a client must get (a long job finished) |
The first two follow local events on unit-of-work completion (ABP); the outbox follows the transactional outbox of CAP, MassTransit and Wolverine.
After commit
services.AddDbContext<ReportingDbContext>((provider, options) => options
.UseNpgsql(connectionString)
.AddRealtimeAfterCommit(provider)); // requires AddRealtime
// In a handler, inside the context's transaction or after SaveChanges:
afterCommit.PublishAfterCommit(dbContext, "report.ready", RealtimeAudience.User(userId),
new ReportReady(report.Id), ReportingJson.Default.ReportReady, id: report.Id.ToString());
- Inside an open transaction of that context the event is buffered and published, in order, when the transaction commits; a rollback drops it.
- With no open transaction,
SaveChangeshas already committed, so the event is published at once: call it afterSaveChanges, never before. - A context without
AddRealtimeAfterCommitthrowsInvalidOperationExceptioninstead of silently losing every event. - An ambient
TransactionScopeis not tracked (the context has no transaction of its own, so the event is published at once); use the context's transactions.
Outbox (at least once)
// Once per application, with its inbox on a context that maps AddInboxMessages():
services.AddRealtimeOutboxDelivery<ReportingDbContext>(configuration);
// In a handler, before SaveChanges, through the module's outbox:
outbox.AddRealtimeEvent("report.ready", RealtimeAudience.User(userId),
new ReportReady(report.Id), ReportingJson.Default.ReportReady, id: report.Id.ToString());
await unitOfWork.SaveChangesAsync(ct);
- The event becomes an
hmz.realtime.event.v1outbox row (type, id, user ids, raw JSON payload) in the same commit as the data. The module's outbox processor publishes it, and the consumer sends it through the backplane directly, so a backplane failure is retried by the inbox. - It needs the module's outbox (
AddIntegrationEventOutbox<TDbContext>andAddOutboxNotifications). Only user audiences travel this way. - A retry can deliver an event twice: give it an
idso a client can ignore the repeat.
Notifications keeps its own commit interceptor, because its signals need post-commit database work (unread counts) before they are published.
The stream
The client opens it with fetch and the bearer header (never a token in the URL), optionally with
?types=notification,report.ready (comma-separated or repeated, at most 32 types).
event: ping
data: {}
event: notification
data: {"v":1,"type":"notification.created","id":"<uuid>","unreadCount":3}
id: <uuid>
event: report.ready
data: {"reportId":"<uuid>","name":"Sales"}
- The event name is the event type; the data is the JSON payload as published;
id:is written only when the event has an id. The stream does not replay events (Last-Event-IDis ignored): refetch over REST after a reconnect. event: reconnect(data{}) asks the client to reconnect at once, without backoff: the server closes the stream right after it. It comes through any?types=filter. The server sends it when the user's access changed (RequestReconnectAsync), so the new stream is authorized with the current roles and permissions, or refused for a deactivated user.- A
pingevent is sent as soon as the stream opens (so the client sees it open) and then everyHeartbeat. It is a named event because the in-boxSseFormattercannot write comment frames. - Headers:
Content-Type: text/event-stream,Cache-Control: no-cache,X-Accel-Buffering: no(a proxy-defined header that turns off buffering). - The stream ends at the access token's
expclaim; reconnect with a fresh token. Opening more thanMaxStreamsPerUserstreams on one instance closes the oldest. A slow client keeps the latestQueueCapacityevents. - Problems:
Realtime.Unauthorized(401),Realtime.InvalidTypes(400).
Options and meter
| Option | Default |
|---|---|
Realtime:Stream:Heartbeat |
00:00:25 |
Realtime:Stream:MaxStreamsPerUser |
5 |
Realtime:Stream:QueueCapacity |
64 |
Options are validated at startup. Add the meter Hmz.Core.Realtime (RealtimeTelemetry.MeterName):
hmz.realtime.events.published, .failed, .delivered, .dropped and hmz.realtime.streams.open.
| 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.Realtime.Abstractions (>= 0.1.0)
- Hmz.Core.SharedKernel (>= 0.1.21)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Hmz.Core.Realtime:
| Package | Downloads |
|---|---|
|
Hmz.Core.Notifications
In-app notification engine for Hmz backends on EF Core and PostgreSQL: deduplicated per-recipient store, audience and scope rules, REST endpoints, live signals through Hmz.Core.Realtime after commit and retention. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.0 | 72 | 11/17/2026 |