diff --git a/docs/GatewayDashboardDesign.md b/docs/GatewayDashboardDesign.md index 40e36bd4..55e96ef6 100644 --- a/docs/GatewayDashboardDesign.md +++ b/docs/GatewayDashboardDesign.md @@ -274,7 +274,7 @@ bearer). Each hub class is `[Authorize(Policy = HubClientsPolicy)]`. | Hub | Path | Producer | Payload | Routing | |---|---|---|---|---| | `DashboardSnapshotHub` | `/hubs/snapshot` | `DashboardSnapshotPublisher` (BackgroundService consuming `IDashboardSnapshotService.WatchSnapshotsAsync`) | `SnapshotUpdated`: `DashboardSnapshot` **without** `configuration`; `ConfigurationUpdated`: `EffectiveGatewayConfiguration` | Ticks go to all connected clients on every snapshot interval, but only while at least one client is connected (see "Idle gating" below). The effective configuration is startup-static and the largest part of the record, so it is `[JsonIgnore]`d on `DashboardSnapshot` and sent once per connection instead: `OnConnectedAsync` pushes `ConfigurationUpdated` and then the current `SnapshotUpdated`, and the hub method `GetConfiguration()` returns it on demand. Each tick broadcast is bounded to 1 s; a send that misses the bound is abandoned, so one slow client cannot delay the next tick for everyone. | -| `AlarmsHub` | `/hubs/alarms` | `AlarmsHubPublisher` (BackgroundService consuming `IGatewayAlarmService.StreamAsync(filter: null)`) | `AlarmFeedMessage` (`active_alarm` / `snapshot_complete` / `transition` / `provider_status` / `snapshot_status`) | Guarded by `MxGateway.Dashboard.Alarms`, not `HubClients`: a real authenticated dashboard role is required, so the `Authentication:Mode=Disabled` and anonymous-localhost bypasses are excluded (SEC-40). Connected clients auto-join `__alarms__`; all admitted clients receive every message — the feed is galaxy-wide and carries no session provenance, so no per-caller scoping applies (see "Alarm-feed visibility"). Publisher auto-reconnects every 5s on stream faults. Every subscription to the monitor — the first and each resubscribe — is preceded by an `AlarmFeedReset` frame (`{ generation }`, monotonic per process): the monitor primes each new subscription with a full `active_alarm` snapshot ending in `snapshot_complete`, so a client must discard its accumulated alarm state on the marker and rebuild from that snapshot rather than double-counting it. Each broadcast is bounded to 2 s and abandoned on timeout: awaiting it unbounded let one slow client stall the drain until the monitor dropped the publisher as a slow subscriber, and the resubscribe then replayed the whole snapshot to every client. The tradeoff: a client whose send is abandoned misses that one frame and receives no reset for it, so its alarm view can be stale until the next resubscribe (or until SignalR drops the stalled connection); there is no in-family consumer of `/hubs/alarms` today. The alarm value fields (`current_value` / `limit_value`) are stripped from a deep-cloned copy of the message when `Dashboard:ShowTagValues` is false (the default) — on both value-bearing payload arms, so neither a live transition nor a snapshot record leaks a process value; every other field still renders. The source message is never mutated: it fans out from the same feed to gRPC `StreamAlarms` subscribers, which this dashboard-display flag does not govern. Arms carrying no value are forwarded as-is, uncloned. | +| `AlarmsHub` | `/hubs/alarms` | `AlarmsHubPublisher` (BackgroundService consuming `IGatewayAlarmService.StreamAsync(filter: null)`) | `AlarmFeedMessage` (`active_alarm` / `snapshot_complete` / `transition` / `provider_status` / `snapshot_status`) | Guarded by `MxGateway.Dashboard.Alarms`, not `HubClients`: a real authenticated dashboard role is required, so the `Authentication:Mode=Disabled` and anonymous-localhost bypasses are excluded (SEC-40). Connected clients auto-join `__alarms__`; all admitted clients receive every message — the feed is galaxy-wide and carries no session provenance, so no per-caller scoping applies (see "Alarm-feed visibility"). Publisher auto-reconnects every 5s on stream faults. Every subscription to the monitor — the first and each resubscribe — is preceded by an `AlarmFeedReset` frame (`{ generation }`, monotonic per process): the monitor primes each new subscription with a full `active_alarm` snapshot ending in `snapshot_complete`, so a client must discard its accumulated alarm state on the marker and rebuild from that snapshot rather than double-counting it. The publisher's subscription normally opens before any browser connects, so `AlarmsHub.OnConnectedAsync` also primes each new connection itself: it joins the group, sends that client an `AlarmFeedReset` with generation `0`, then the provider status, snapshot status, `active_alarm` rows and `snapshot_complete` read from a fresh monitor subscription (redacted by the same rule). Without it a client connecting after startup saw only later transitions and never the standing alarms or the current provider status. The reset goes out before the snapshot is read, so a transition is either in the snapshot or arrives live after the reset; one applied while the snapshot rows are being sent can land ahead of the older row for the same alarm, which the alarm's next transition or reconcile repair corrects. Each broadcast is bounded to 2 s and abandoned on timeout: awaiting it unbounded let one slow client stall the drain until the monitor dropped the publisher as a slow subscriber, and the resubscribe then replayed the whole snapshot to every client. The tradeoff: a client whose send is abandoned misses that one frame and receives no reset for it, so its alarm view can be stale until the next resubscribe (or until SignalR drops the stalled connection); there is no in-family consumer of `/hubs/alarms` today. The alarm value fields (`current_value` / `limit_value`) are stripped from a deep-cloned copy of the message when `Dashboard:ShowTagValues` is false (the default) — on both value-bearing payload arms, so neither a live transition nor a snapshot record leaks a process value; every other field still renders. The source message is never mutated: it fans out from the same feed to gRPC `StreamAlarms` subscribers, which this dashboard-display flag does not govern. Arms carrying no value are forwarded as-is, uncloned. | | `EventsHub` | `/hubs/events` | `DashboardEventBroadcaster` invoked by each session's internal dashboard-mirror subscriber on its `SessionEventDistributor` (registered when the session becomes Ready) | `MxEvent` | Clients call `SubscribeSession(sessionId)` to join `session:{id}`, which also registers them in `EventsHubViewerRegistry`. Delivery to the group goes through one bounded per-session pump (see "Mirror gating"), so a slow viewer loses its oldest events instead of accumulating pending sends — the mirror is gated on that registry, which counts hub and in-process viewers alike (see "Mirror gating" below). The dashboard is a first-class distributor subscriber, so it receives the session's events whether or not a gRPC client is streaming. It sees RAW session events — not the per-gRPC-subscriber `AfterWorkerSequence` filtering that `EventStreamService` applies at its own boundary — because the dashboard is a separate LDAP-authenticated monitoring view meant to show the session's full event activity. Tag values are stripped from the mirrored `MxEvent` copy by `DashboardEventBroadcaster` when `Dashboard:ShowTagValues` is false (the default) — event metadata (tag reference, quality, status, timestamps) still renders, but the value fields are blanked, so no value leaks through this seam. `SubscribeSession` is gated by `IDashboardSessionAcl` (SEC-25 / TST-15): a denied caller gets a `HubException`, is not joined to the group, and is not registered as a viewer, so the mirror stays off for a session nobody is legitimately watching. The same ACL gates the in-process seam the session-details page uses, so neither path is the weaker one. Value redaction remains an independent layer — it bounds what a *permitted* subscriber sees. | No hub client ships in this repository: the server-rendered pages read the diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmFeedReset.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmFeedReset.cs index e1742f4b..f8a5f543 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmFeedReset.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmFeedReset.cs @@ -9,6 +9,8 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs; /// /// /// Monotonic subscription counter for this gateway process, starting at 1. Lets a -/// client tell a resubscribe from a duplicate delivery. +/// client tell a resubscribe from a duplicate delivery. Generation 0 is the per-connection +/// prime sent to a client when it connects, ahead of the current snapshot; a client handles +/// it exactly like any other reset. /// public sealed record AlarmFeedReset(long Generation); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs index d0c6287f..0670d28e 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs @@ -1,5 +1,8 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.MxGateway.Server.Alarms; +using ZB.MOM.WW.MxGateway.Server.Configuration; namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs; @@ -19,9 +22,17 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs; /// read-only environment bypasses (Authentication:Mode=Disabled, anonymous localhost) no /// longer receive the feed. The /alarms page carries the same policy — the two readers of /// one monitor must not disagree about who may see it. +/// +/// On connect the client is primed with the current state (a generation-0 +/// , provider and snapshot status, the active alarms, then +/// snapshot_complete) before it relies on the group's live frames; see +/// . +/// /// +/// The gateway's central alarm feed. +/// Gateway options supplying Dashboard:ShowTagValues. [Authorize(Policy = DashboardAuthenticationDefaults.AlarmsPolicy)] -public sealed class AlarmsHub : Hub +public sealed class AlarmsHub(IGatewayAlarmService alarmService, IOptions options) : Hub { /// Group every admitted connection joins on connect. public const string AllAlarmsGroup = "__alarms__"; @@ -40,6 +51,14 @@ public sealed class AlarmsHub : Hub public override async Task OnConnectedAsync() { await Groups.AddToGroupAsync(Context.ConnectionId, AllAlarmsGroup).ConfigureAwait(false); + + // Joined first, so nothing broadcast after the snapshot is read can be missed (DSH-005). + await AlarmsHubPublisher.PrimeConnectionAsync( + alarmService, + Clients.Caller, + options.Value.Dashboard.ShowTagValues, + Context.ConnectionAborted) + .ConfigureAwait(false); await base.OnConnectedAsync().ConfigureAwait(false); } } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs index adce9ca4..0eab4519 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs @@ -146,6 +146,56 @@ public sealed class AlarmsHubPublisher : BackgroundService } } + /// + /// Primes one newly connected client with the feed's current state: a + /// marker with generation 0, then the provider + /// status, the snapshot status, one active_alarm frame per active alarm and the + /// snapshot_complete sentinel — the same preamble a StreamAlarms subscriber + /// gets, redacted by the same ShowTagValues rule as the group broadcast. + /// + /// + /// The publisher holds one monitor subscription for the process lifetime and group-sends + /// the snapshot only when that subscription (re)opens, which is normally before any client + /// is connected; without this a client joining later saw only subsequent transitions + /// (DSH-005). The caller joins the group before priming and the reset is sent before the + /// snapshot is read, so a transition is either already in the snapshot or arrives as a + /// live frame after the reset. A transition applied while the snapshot frames are being + /// sent can arrive ahead of the (older) snapshot row for the same alarm; the next + /// transition or reconcile repair for that alarm corrects it, consistent with the feed's + /// at-least-once, apply-as-state contract. + /// + /// The gateway's central alarm feed. + /// The connecting client. + /// Whether alarm values may reach browser clients. + /// The connection-aborted token. + /// A task that completes once the snapshot sentinel has been sent. + internal static async Task PrimeConnectionAsync( + IGatewayAlarmService alarmService, + IClientProxy caller, + bool showTagValues, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(alarmService); + ArgumentNullException.ThrowIfNull(caller); + + await caller.SendAsync(AlarmsHub.ResetMessage, new AlarmFeedReset(0), cancellationToken) + .ConfigureAwait(false); + + using CancellationTokenSource stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + await foreach (AlarmFeedMessage message in alarmService + .StreamAsync(alarmFilterPrefix: null, stop.Token) + .ConfigureAwait(false)) + { + AlarmFeedMessage outbound = showTagValues ? message : RedactValues(message); + await caller.SendAsync(AlarmsHub.AlarmMessage, outbound, cancellationToken).ConfigureAwait(false); + if (message.PayloadCase == AlarmFeedMessage.PayloadOneofCase.SnapshotComplete) + { + // The preamble is complete; live frames reach this client through the group. + break; + } + } + } + /// /// Sends one frame to the alarms group within the send timeout. A slow or failed /// send is logged and dropped so the feed keeps draining; only host shutdown @@ -193,7 +243,7 @@ public sealed class AlarmsHubPublisher : BackgroundService /// names only the arms that have something to redact, so adding a valueless /// arm to the contract needs no change here. /// - private static AlarmFeedMessage RedactValues(AlarmFeedMessage source) + internal static AlarmFeedMessage RedactValues(AlarmFeedMessage source) { switch (source.PayloadCase) { diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs index 2cda0437..acaff93c 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs @@ -287,6 +287,47 @@ public sealed class AlarmsHubPublisherTests }; } + /// + /// DSH-005: a client connecting long after the publisher subscribed is primed with the + /// current state itself — a generation-0 reset, then the status frames, every active + /// alarm (values redacted) and the snapshot sentinel — without any new transition. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task PrimeConnectionAsync_SendsResetThenTheCurrentSnapshot() + { + AlarmFeedMessage activeOne = BuildActiveAlarm(); + AlarmFeedMessage activeTwo = BuildActiveAlarm(); + activeTwo.ActiveAlarm.AlarmFullReference = "Tank03.Level.Hi"; + ScriptedAlarmService service = new( + [ + new AlarmFeedMessage { ProviderStatus = new AlarmProviderStatus { Mode = AlarmProviderMode.Subtag, Degraded = true } }, + new AlarmFeedMessage { SnapshotStatus = new AlarmSnapshotStatus { Truncated = false } }, + activeOne, + activeTwo, + new AlarmFeedMessage { SnapshotComplete = true }, + ]); + CapturingClientProxy caller = new(); + + using CancellationTokenSource cts = new(TestTimeout); + await AlarmsHubPublisher.PrimeConnectionAsync(service, caller, showTagValues: false, cts.Token); + + IReadOnlyList<(string Method, object? Argument)> frames = caller.Frames; + Assert.Equal(6, frames.Count); + Assert.Equal(AlarmsHub.ResetMessage, frames[0].Method); + Assert.Equal(new AlarmFeedReset(0), frames[0].Argument); + Assert.All(frames.Skip(1), frame => Assert.Equal(AlarmsHub.AlarmMessage, frame.Method)); + + IReadOnlyList sent = caller.Sent; + Assert.Equal(AlarmProviderMode.Subtag, sent[0].ProviderStatus.Mode); + Assert.Equal(AlarmFeedMessage.PayloadOneofCase.SnapshotStatus, sent[1].PayloadCase); + Assert.Equal("Tank02.Level.Lo", sent[2].ActiveAlarm.AlarmFullReference); + Assert.Equal("Tank03.Level.Hi", sent[3].ActiveAlarm.AlarmFullReference); + Assert.Null(sent[2].ActiveAlarm.CurrentValue); + Assert.Null(sent[3].ActiveAlarm.CurrentValue); + Assert.True(sent[4].SnapshotComplete); + } + /// /// Yields one scripted batch per subscription. Every batch but the last ends its /// stream — the monitor completing a subscription — so the publisher resubscribes;