From 3f9ea6a86c3585c5f067c186484905816fdae860 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:44:51 -0500 Subject: [PATCH] perf(dashboard): AlarmsHubPublisher holds no monitor subscription while no hub client is connected (DSH-009, #256) --- docs/GatewayDashboardDesign.md | 2 +- .../DashboardServiceCollectionExtensions.cs | 1 + .../Dashboard/Hubs/AlarmsHub.cs | 13 ++- .../Hubs/AlarmsHubConnectionCounter.cs | 40 +++++++ .../Dashboard/Hubs/AlarmsHubPublisher.cs | 103 ++++++++++++++---- .../Dashboard/AlarmsHubPublisherTests.cs | 103 ++++++++++++++---- 6 files changed, 219 insertions(+), 43 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubConnectionCounter.cs diff --git a/docs/GatewayDashboardDesign.md b/docs/GatewayDashboardDesign.md index 40e36bd4..e6f4b74d 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. The publisher is idle-gated on a live-connection count (`AlarmsHubConnectionCounter`): with no hub client connected it holds no monitor subscription and does no cloning or sending, the first connection opens one, and the last disconnect closes it. 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. | | `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/DashboardServiceCollectionExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs index 7a9e3ec1..c67f8682 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs @@ -106,6 +106,7 @@ public static class DashboardServiceCollectionExtensions static provider => provider.GetRequiredService()); services.AddSingleton(); services.AddHostedService(); + services.AddSingleton(); services.AddHostedService(); services.AddHttpContextAccessor(); services.AddSingleton(); 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..3ed24323 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs @@ -21,7 +21,7 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs; /// one monitor must not disagree about who may see it. /// [Authorize(Policy = DashboardAuthenticationDefaults.AlarmsPolicy)] -public sealed class AlarmsHub : Hub +public sealed class AlarmsHub(AlarmsHubConnectionCounter connectionCounter) : Hub { /// Group every admitted connection joins on connect. public const string AllAlarmsGroup = "__alarms__"; @@ -40,6 +40,17 @@ public sealed class AlarmsHub : Hub public override async Task OnConnectedAsync() { await Groups.AddToGroupAsync(Context.ConnectionId, AllAlarmsGroup).ConfigureAwait(false); + + // Counted after the group join so the publisher, which subscribes to the monitor once the + // count is non-zero, never broadcasts the priming snapshot to a group this client is not in. + connectionCounter.Increment(); await base.OnConnectedAsync().ConfigureAwait(false); } + + /// + public override async Task OnDisconnectedAsync(Exception? exception) + { + connectionCounter.Decrement(); + await base.OnDisconnectedAsync(exception).ConfigureAwait(false); + } } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubConnectionCounter.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubConnectionCounter.cs new file mode 100644 index 00000000..44b4eaa1 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubConnectionCounter.cs @@ -0,0 +1,40 @@ +namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs; + +/// +/// Process-wide count of live connections. Read by +/// to idle-gate the alarm broadcast: the server-rendered +/// Alarms page does not use the hub, so in most deployments there is no connection and nothing +/// to broadcast to. +/// +public sealed class AlarmsHubConnectionCounter +{ + private int _count; + + /// Gets the number of live alarms hub connections. + public int Count => Volatile.Read(ref _count); + + /// Records a new alarms hub connection. + /// The connection count after the increment. + public int Increment() => Interlocked.Increment(ref _count); + + /// + /// Records an alarms hub disconnection, clamped at zero inside the compare-and-swap for the + /// same reason as : SignalR can + /// raise a disconnect for a connection whose connect faulted, and a negative count would gate + /// the publisher off while a real client is attached. + /// + /// The connection count after the decrement. + public int Decrement() + { + int current; + int next; + do + { + current = Volatile.Read(ref _count); + next = current > 0 ? current - 1 : 0; + } + while (Interlocked.CompareExchange(ref _count, next, current) != current); + + return next; + } +} 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..f532d943 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs @@ -32,6 +32,13 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs; /// per-caller scope the feed does not carry. /// /// +/// The loop is idle-gated on . With no hub client +/// connected the publisher holds no monitor subscription at all, so it pays no redaction clone, +/// no group send and no snapshot replay for output nobody receives; the first connection opens the +/// subscription (and so receives the reset marker and the primed snapshot), and the last +/// disconnect closes it. +/// +/// /// Each broadcast is time-bounded (). A group send /// completes only once every member accepted the frame, so awaiting it unbounded /// let one slow browser stall this loop; the stalled loop stopped draining its @@ -53,45 +60,58 @@ public sealed class AlarmsHubPublisher : BackgroundService /// Upper bound on one alarm broadcast before it is abandoned. internal static readonly TimeSpan DefaultSendTimeout = TimeSpan.FromSeconds(2); + /// How often the idle publisher re-checks for a connected client, and the live one for none. + internal static readonly TimeSpan DefaultIdlePollInterval = TimeSpan.FromSeconds(1); + private readonly IGatewayAlarmService _alarmService; private readonly IHubContext _hubContext; private readonly ILogger _logger; private readonly TimeSpan _sendTimeout; + private readonly AlarmsHubConnectionCounter _connectionCounter; + private readonly TimeSpan _idlePollInterval; private readonly bool _showTagValues; private long _subscriptionGeneration; /// Initializes a new instance of the class. /// The gateway's central alarm feed. /// Hub context used to broadcast to the alarms group. + /// Live alarms hub connection count used to idle-gate the subscription. /// Gateway options supplying Dashboard:ShowTagValues. /// Logger for best-effort broadcast failures. public AlarmsHubPublisher( IGatewayAlarmService alarmService, IHubContext hubContext, + AlarmsHubConnectionCounter connectionCounter, IOptions options, ILogger logger) - : this(alarmService, hubContext, options, logger, DefaultSendTimeout) + : this(alarmService, hubContext, connectionCounter, options, logger, DefaultSendTimeout, DefaultIdlePollInterval) { } /// Initializes a new instance with a custom send timeout (test hook). /// The gateway's central alarm feed. /// Hub context used to broadcast to the alarms group. + /// Live alarms hub connection count used to idle-gate the subscription. /// Gateway options supplying Dashboard:ShowTagValues. /// Logger for best-effort broadcast failures. /// Upper bound on one broadcast. + /// How often the connection count is re-checked. internal AlarmsHubPublisher( IGatewayAlarmService alarmService, IHubContext hubContext, + AlarmsHubConnectionCounter connectionCounter, IOptions options, ILogger logger, - TimeSpan sendTimeout) + TimeSpan sendTimeout, + TimeSpan idlePollInterval) { ArgumentNullException.ThrowIfNull(options); _alarmService = alarmService ?? throw new ArgumentNullException(nameof(alarmService)); _hubContext = hubContext ?? throw new ArgumentNullException(nameof(hubContext)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _sendTimeout = sendTimeout; + _connectionCounter = connectionCounter ?? throw new ArgumentNullException(nameof(connectionCounter)); + _idlePollInterval = idlePollInterval; _showTagValues = options.Value.Dashboard.ShowTagValues; } @@ -105,26 +125,49 @@ public sealed class AlarmsHubPublisher : BackgroundService { try { - // Sent before the subscription opens, so it reaches clients ahead of - // the snapshot the monitor primes the new subscription with. - long generation = Interlocked.Increment(ref _subscriptionGeneration); - await BroadcastAsync( - AlarmsHub.ResetMessage, - new AlarmFeedReset(generation), - stoppingToken) - .ConfigureAwait(false); - - await foreach (AlarmFeedMessage message in _alarmService - .StreamAsync(alarmFilterPrefix: null, stoppingToken) - .ConfigureAwait(false)) + // No client, no subscription: nothing to clone, send or replay. + if (_connectionCounter.Count == 0) { - if (stoppingToken.IsCancellationRequested) - { - break; - } + await Task.Delay(_idlePollInterval, stoppingToken).ConfigureAwait(false); + continue; + } - AlarmFeedMessage outbound = _showTagValues ? message : RedactValues(message); - await BroadcastAsync(AlarmsHub.AlarmMessage, outbound, stoppingToken).ConfigureAwait(false); + // Cancelled when the last client disconnects (or the host stops), which ends the + // monitor subscription; the loop then idles until the next connection. + using CancellationTokenSource subscription = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); + Task idleWatcher = CancelWhenIdleAsync(subscription); + try + { + // Sent before the subscription opens, so it reaches clients ahead of + // the snapshot the monitor primes the new subscription with. + long generation = Interlocked.Increment(ref _subscriptionGeneration); + await BroadcastAsync( + AlarmsHub.ResetMessage, + new AlarmFeedReset(generation), + subscription.Token) + .ConfigureAwait(false); + + await foreach (AlarmFeedMessage message in _alarmService + .StreamAsync(alarmFilterPrefix: null, subscription.Token) + .ConfigureAwait(false)) + { + if (subscription.IsCancellationRequested) + { + break; + } + + AlarmFeedMessage outbound = _showTagValues ? message : RedactValues(message); + await BroadcastAsync(AlarmsHub.AlarmMessage, outbound, subscription.Token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested) + { + // The last client left; fall through to the idle check. + } + finally + { + await subscription.CancelAsync().ConfigureAwait(false); + await idleWatcher.ConfigureAwait(false); } } catch (OperationCanceledException) @@ -146,6 +189,26 @@ public sealed class AlarmsHubPublisher : BackgroundService } } + private async Task CancelWhenIdleAsync(CancellationTokenSource subscription) + { + try + { + while (!subscription.IsCancellationRequested) + { + await Task.Delay(_idlePollInterval, subscription.Token).ConfigureAwait(false); + if (_connectionCounter.Count == 0) + { + await subscription.CancelAsync().ConfigureAwait(false); + return; + } + } + } + catch (OperationCanceledException) + { + // The subscription ended first; nothing left to watch. + } + } + /// /// 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 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..cda2e0e6 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs @@ -195,11 +195,55 @@ public sealed class AlarmsHubPublisherTests Assert.Equal("Tank02.Level.Lo", hubContext.Sent[1].ActiveAlarm.AlarmFullReference); } + private static AlarmsHubConnectionCounter ConnectedCounter() + { + AlarmsHubConnectionCounter counter = new(); + counter.Increment(); + return counter; + } + + /// + /// DSH-009: with no hub client connected the publisher holds no monitor subscription and sends + /// nothing; the first connection opens one (reset marker, then the primed frames) and the last + /// disconnect closes it again. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ExecuteAsync_WithNoConnectedClients_DoesNotSubscribeOrSend() + { + AlarmFeedMessage active = BuildActiveAlarm(); + ScriptedAlarmService alarmService = new([active]); + CapturingHubContext hubContext = new(); + AlarmsHubConnectionCounter counter = new(); + AlarmsHubPublisher publisher = CreatePublisher( + alarmService, hubContext, AlarmsHubPublisher.DefaultSendTimeout, showTagValues: false, counter); + + using CancellationTokenSource cts = new(); + await publisher.StartAsync(cts.Token).WaitAsync(TestTimeout); + + await Task.Delay(300); + Assert.Equal(0, alarmService.SubscriptionCount); + Assert.Empty(hubContext.Frames); + + counter.Increment(); + await WaitUntilAsync(() => hubContext.Sent.Count >= 1); + Assert.Equal(1, alarmService.SubscriptionCount); + Assert.Equal(AlarmsHub.ResetMessage, hubContext.Frames[0].Method); + + // The last client leaves: the subscription is closed and the loop idles again. + counter.Decrement(); + await WaitUntilAsync(() => alarmService.ActiveSubscriptions == 0); + + await cts.CancelAsync(); + await publisher.StopAsync(CancellationToken.None); + } + private static AlarmsHubPublisher CreatePublisher( IGatewayAlarmService alarmService, CapturingHubContext hubContext, TimeSpan sendTimeout, - bool showTagValues = true) + bool showTagValues = true, + AlarmsHubConnectionCounter? counter = null) { GatewayOptions gatewayOptions = new() { @@ -209,9 +253,11 @@ public sealed class AlarmsHubPublisherTests return new AlarmsHubPublisher( alarmService, hubContext, + counter ?? ConnectedCounter(), Options.Create(gatewayOptions), NullLogger.Instance, - sendTimeout); + sendTimeout, + TimeSpan.FromMilliseconds(20)); } /// @@ -296,6 +342,13 @@ public sealed class AlarmsHubPublisherTests private sealed class ScriptedAlarmService(params IReadOnlyList[] batches) : IGatewayAlarmService { private int _subscriptions; + private int _active; + + /// Gets how many times a subscription was opened. + public int SubscriptionCount => Volatile.Read(ref _subscriptions); + + /// Gets how many subscriptions are currently open. + public int ActiveSubscriptions => Volatile.Read(ref _active); /// public GatewayAlarmMonitorState State => GatewayAlarmMonitorState.Monitoring; @@ -318,29 +371,37 @@ public sealed class AlarmsHubPublisherTests [EnumeratorCancellation] CancellationToken cancellationToken) { int index = Interlocked.Increment(ref _subscriptions) - 1; - IReadOnlyList messages = batches[Math.Min(index, batches.Length - 1)]; - if (index >= batches.Length) - { - // Past the script: stay open and quiet rather than replaying the last batch. - messages = []; - } - - foreach (AlarmFeedMessage message in messages) - { - yield return message; - } - - if (index < batches.Length - 1) - { - yield break; - } - + Interlocked.Increment(ref _active); try { - await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + IReadOnlyList messages = batches[Math.Min(index, batches.Length - 1)]; + if (index >= batches.Length) + { + // Past the script: stay open and quiet rather than replaying the last batch. + messages = []; + } + + foreach (AlarmFeedMessage message in messages) + { + yield return message; + } + + if (index < batches.Length - 1) + { + yield break; + } + + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } } - catch (OperationCanceledException) + finally { + Interlocked.Decrement(ref _active); } }