perf(dashboard): gate event mirror on live viewers — no clone, no send for unwatched sessions

DashboardEventBroadcaster.Publish ran a deep protobuf Clone (redaction is on by
default) and a group SendAsync for every event of every session, before anything
checked whether a dashboard client was actually watching. In the steady state the
session:{id} group is empty, so that work was thrown away per event.

SignalR does not expose group membership, so EventsHub now mirrors its own
add/remove into a singleton EventsHubViewerRegistry, and OnDisconnectedAsync
releases everything a dropped connection held (SessionDetailsPage disposes the
connection rather than unsubscribing). Publish returns early when the session has
no viewers, before the redaction clone. Watched sessions behave exactly as before.

Lazy mirror-lease start/stop was deliberately not attempted — it entangles the
dashboard with SessionEventDistributor subscribe lifetime for no saving beyond
this gate; recorded in docs/GatewayDashboardDesign.md.
This commit is contained in:
Joseph Doherty
2026-08-15 12:07:33 -04:00
parent da8463534b
commit 6c5218913b
7 changed files with 465 additions and 10 deletions
@@ -0,0 +1,147 @@
using System.Collections.Concurrent;
namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
/// <summary>
/// Tracks which sessions currently have at least one live <see cref="EventsHub"/>
/// subscriber, so <see cref="DashboardEventBroadcaster"/> can skip the redaction
/// clone and the group send for sessions nobody is watching.
/// </summary>
/// <remarks>
/// SignalR does not expose group membership, so the hub mirrors its own
/// <c>AddToGroup</c>/<c>RemoveFromGroup</c> calls here. In the steady state no
/// browser is on a session-details page, yet every session's dashboard-mirror
/// subscriber still called <c>Publish</c> for every event — a deep protobuf
/// clone (values are redacted by default) plus a send to an empty group, per
/// event, thrown away. This registry is the cheap gate in front of that work.
/// <para>
/// Per-connection subscriptions are tracked as well, because a browser tab that
/// simply goes away never calls <c>UnsubscribeSession</c>; the hub's
/// <c>OnDisconnectedAsync</c> releases everything the connection held.
/// </para>
/// </remarks>
public sealed class EventsHubViewerRegistry
{
private readonly ConcurrentDictionary<string, int> _viewersBySession = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _sessionsByConnection =
new(StringComparer.Ordinal);
/// <summary>
/// Records that <paramref name="connectionId"/> is watching
/// <paramref name="sessionId"/>. Repeat calls for the same pair are
/// idempotent, so one <see cref="RemoveViewer"/> always clears them.
/// </summary>
/// <param name="connectionId">SignalR connection id of the subscriber.</param>
/// <param name="sessionId">Session id being watched.</param>
public void AddViewer(string connectionId, string sessionId)
{
if (string.IsNullOrWhiteSpace(connectionId) || string.IsNullOrWhiteSpace(sessionId))
{
return;
}
ConcurrentDictionary<string, byte> sessions = _sessionsByConnection.GetOrAdd(
connectionId,
static _ => new ConcurrentDictionary<string, byte>(StringComparer.Ordinal));
// The per-connection set is the source of truth for the count: only a
// subscription that was genuinely new increments the session's viewers.
if (!sessions.TryAdd(sessionId, 0))
{
return;
}
_viewersBySession.AddOrUpdate(sessionId, 1, static (_, count) => count + 1);
}
/// <summary>
/// Records that <paramref name="connectionId"/> stopped watching
/// <paramref name="sessionId"/>. A removal with no matching
/// <see cref="AddViewer"/> is a no-op, so the count cannot go negative.
/// </summary>
/// <param name="connectionId">SignalR connection id of the subscriber.</param>
/// <param name="sessionId">Session id no longer being watched.</param>
public void RemoveViewer(string connectionId, string sessionId)
{
if (string.IsNullOrWhiteSpace(connectionId) || string.IsNullOrWhiteSpace(sessionId))
{
return;
}
if (!_sessionsByConnection.TryGetValue(connectionId, out ConcurrentDictionary<string, byte>? sessions)
|| !sessions.TryRemove(sessionId, out _))
{
return;
}
ReleaseSession(sessionId);
}
/// <summary>
/// Releases every subscription held by <paramref name="connectionId"/>.
/// Called from the hub's disconnect callback, which is the only reliable
/// signal for a browser tab that closed without unsubscribing.
/// </summary>
/// <param name="connectionId">SignalR connection id that dropped.</param>
public void ReleaseConnection(string connectionId)
{
if (string.IsNullOrWhiteSpace(connectionId))
{
return;
}
if (!_sessionsByConnection.TryRemove(connectionId, out ConcurrentDictionary<string, byte>? sessions))
{
return;
}
foreach (string sessionId in sessions.Keys)
{
// TryRemove, not a bare enumeration: a concurrent RemoveViewer on the
// same detached set must not let the session be decremented twice.
if (sessions.TryRemove(sessionId, out _))
{
ReleaseSession(sessionId);
}
}
}
/// <summary>Gets a value indicating whether any hub connection is watching the session.</summary>
/// <param name="sessionId">Session id to test.</param>
/// <returns><see langword="true"/> when at least one connection is subscribed.</returns>
public bool HasViewers(string sessionId) =>
!string.IsNullOrEmpty(sessionId)
&& _viewersBySession.TryGetValue(sessionId, out int count)
&& count > 0;
/// <summary>
/// Decrements the session's viewer count, dropping the entry entirely at
/// zero so the dictionary does not grow one key per session ever viewed.
/// The compare-and-swap loop keeps the decrement correct against a
/// concurrent <see cref="AddViewer"/> on the same session.
/// </summary>
/// <param name="sessionId">Session id whose count is released.</param>
private void ReleaseSession(string sessionId)
{
while (true)
{
if (!_viewersBySession.TryGetValue(sessionId, out int count))
{
return;
}
if (count <= 1)
{
if (_viewersBySession.TryRemove(new KeyValuePair<string, int>(sessionId, count)))
{
return;
}
}
else if (_viewersBySession.TryUpdate(sessionId, count - 1, count))
{
return;
}
}
}
}