perf(dashboard): AlarmsHubPublisher holds no monitor subscription while no hub client is connected (DSH-009, #256)

This commit is contained in:
Joseph Doherty
2026-12-03 09:44:51 -05:00
parent fa12691118
commit 3f9ea6a86c
6 changed files with 219 additions and 43 deletions
+1 -1
View File
@@ -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
@@ -106,6 +106,7 @@ public static class DashboardServiceCollectionExtensions
static provider => provider.GetRequiredService<Hubs.DashboardEventBroadcaster>());
services.AddSingleton<Hubs.DashboardSnapshotHubConnectionCounter>();
services.AddHostedService<Hubs.DashboardSnapshotPublisher>();
services.AddSingleton<Hubs.AlarmsHubConnectionCounter>();
services.AddHostedService<Hubs.AlarmsHubPublisher>();
services.AddHttpContextAccessor();
services.AddSingleton<IAuditActorAccessor, HttpAuditActorAccessor>();
@@ -21,7 +21,7 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
/// one monitor must not disagree about who may see it.
/// </remarks>
[Authorize(Policy = DashboardAuthenticationDefaults.AlarmsPolicy)]
public sealed class AlarmsHub : Hub
public sealed class AlarmsHub(AlarmsHubConnectionCounter connectionCounter) : Hub
{
/// <summary>Group every admitted connection joins on connect.</summary>
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);
}
/// <inheritdoc />
public override async Task OnDisconnectedAsync(Exception? exception)
{
connectionCounter.Decrement();
await base.OnDisconnectedAsync(exception).ConfigureAwait(false);
}
}
@@ -0,0 +1,40 @@
namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
/// <summary>
/// Process-wide count of live <see cref="AlarmsHub"/> connections. Read by
/// <see cref="AlarmsHubPublisher"/> 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.
/// </summary>
public sealed class AlarmsHubConnectionCounter
{
private int _count;
/// <summary>Gets the number of live alarms hub connections.</summary>
public int Count => Volatile.Read(ref _count);
/// <summary>Records a new alarms hub connection.</summary>
/// <returns>The connection count after the increment.</returns>
public int Increment() => Interlocked.Increment(ref _count);
/// <summary>
/// Records an alarms hub disconnection, clamped at zero inside the compare-and-swap for the
/// same reason as <see cref="DashboardSnapshotHubConnectionCounter.Decrement"/>: 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.
/// </summary>
/// <returns>The connection count after the decrement.</returns>
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;
}
}
@@ -32,6 +32,13 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
/// per-caller scope the feed does not carry.
/// </para>
/// <para>
/// The loop is idle-gated on <see cref="AlarmsHubConnectionCounter"/>. 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.
/// </para>
/// <para>
/// Each broadcast is time-bounded (<see cref="DefaultSendTimeout"/>). 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
/// <summary>Upper bound on one alarm broadcast before it is abandoned.</summary>
internal static readonly TimeSpan DefaultSendTimeout = TimeSpan.FromSeconds(2);
/// <summary>How often the idle publisher re-checks for a connected client, and the live one for none.</summary>
internal static readonly TimeSpan DefaultIdlePollInterval = TimeSpan.FromSeconds(1);
private readonly IGatewayAlarmService _alarmService;
private readonly IHubContext<AlarmsHub> _hubContext;
private readonly ILogger<AlarmsHubPublisher> _logger;
private readonly TimeSpan _sendTimeout;
private readonly AlarmsHubConnectionCounter _connectionCounter;
private readonly TimeSpan _idlePollInterval;
private readonly bool _showTagValues;
private long _subscriptionGeneration;
/// <summary>Initializes a new instance of the <see cref="AlarmsHubPublisher"/> class.</summary>
/// <param name="alarmService">The gateway's central alarm feed.</param>
/// <param name="hubContext">Hub context used to broadcast to the alarms group.</param>
/// <param name="connectionCounter">Live alarms hub connection count used to idle-gate the subscription.</param>
/// <param name="options">Gateway options supplying <c>Dashboard:ShowTagValues</c>.</param>
/// <param name="logger">Logger for best-effort broadcast failures.</param>
public AlarmsHubPublisher(
IGatewayAlarmService alarmService,
IHubContext<AlarmsHub> hubContext,
AlarmsHubConnectionCounter connectionCounter,
IOptions<GatewayOptions> options,
ILogger<AlarmsHubPublisher> logger)
: this(alarmService, hubContext, options, logger, DefaultSendTimeout)
: this(alarmService, hubContext, connectionCounter, options, logger, DefaultSendTimeout, DefaultIdlePollInterval)
{
}
/// <summary>Initializes a new instance with a custom send timeout (test hook).</summary>
/// <param name="alarmService">The gateway's central alarm feed.</param>
/// <param name="hubContext">Hub context used to broadcast to the alarms group.</param>
/// <param name="connectionCounter">Live alarms hub connection count used to idle-gate the subscription.</param>
/// <param name="options">Gateway options supplying <c>Dashboard:ShowTagValues</c>.</param>
/// <param name="logger">Logger for best-effort broadcast failures.</param>
/// <param name="sendTimeout">Upper bound on one broadcast.</param>
/// <param name="idlePollInterval">How often the connection count is re-checked.</param>
internal AlarmsHubPublisher(
IGatewayAlarmService alarmService,
IHubContext<AlarmsHub> hubContext,
AlarmsHubConnectionCounter connectionCounter,
IOptions<GatewayOptions> options,
ILogger<AlarmsHubPublisher> 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.
}
}
/// <summary>
/// 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
@@ -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;
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<AlarmsHubPublisher>.Instance,
sendTimeout);
sendTimeout,
TimeSpan.FromMilliseconds(20));
}
/// <summary>
@@ -296,6 +342,13 @@ public sealed class AlarmsHubPublisherTests
private sealed class ScriptedAlarmService(params IReadOnlyList<AlarmFeedMessage>[] batches) : IGatewayAlarmService
{
private int _subscriptions;
private int _active;
/// <summary>Gets how many times a subscription was opened.</summary>
public int SubscriptionCount => Volatile.Read(ref _subscriptions);
/// <summary>Gets how many subscriptions are currently open.</summary>
public int ActiveSubscriptions => Volatile.Read(ref _active);
/// <inheritdoc />
public GatewayAlarmMonitorState State => GatewayAlarmMonitorState.Monitoring;
@@ -318,29 +371,37 @@ public sealed class AlarmsHubPublisherTests
[EnumeratorCancellation] CancellationToken cancellationToken)
{
int index = Interlocked.Increment(ref _subscriptions) - 1;
IReadOnlyList<AlarmFeedMessage> 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<AlarmFeedMessage> 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);
}
}