perf(gateway): attach the dashboard mirror only while a viewer watches (#235)

Every session ran a dashboard-mirror distributor subscriber that woke for every
event only for Publish to discard it, since normally nobody has a
session-details page open. The viewer registry now raises
ViewerPresenceChanged on a session's first viewer and last viewer; the
production broadcaster exposes it as IDashboardViewerPresence, and a session
attaches its mirror while watched and disposes the lease when not.

MarkReady still starts the pump, so draining, replay retention, the alarm lease
and dead-worker detection are unchanged. ACL and value redaction are untouched.
Broadcasters without presence (test doubles) keep the always-on mirror.

Internal distributor subscribers can now pass a filter applied before the
pump's TryWrite; the alarm monitor admits only alarm transitions and provider
mode changes, so data changes no longer wake it.
This commit is contained in:
Joseph Doherty
2026-11-21 08:18:26 -05:00
parent 5516561084
commit 9b9fdecc9b
10 changed files with 543 additions and 77 deletions
@@ -267,7 +267,10 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
// subscribe and reconcile simply buffer in this lease's bounded channel; if it ever
// overflowed, the internal subscriber is disconnected (it never faults the session),
// the enumeration below ends, and the supervisor loop restarts the lifecycle.
using IEventSubscriberLease alarmLease = session.AttachInternalEventSubscriber();
//
// The lease is filtered to the two families the loop below acts on, so data changes
// and other events on the session never wake the monitor only to be discarded.
using IEventSubscriberLease alarmLease = session.AttachInternalEventSubscriber(IsAlarmMonitorEvent);
await SubscribeAlarmsAsync(session.SessionId, subscription, stoppingToken).ConfigureAwait(false);
await ReconcileAsync(session.SessionId, stoppingToken).ConfigureAwait(false);
@@ -466,6 +469,13 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
}
}
// Distributor-side filter for the monitor's internal lease: admits only the event bodies the
// monitor's consume loop acts on. Runs on the session's pump thread, so it is a pure body-case
// test and never throws.
private static bool IsAlarmMonitorEvent(MxEvent mxEvent)
=> mxEvent.BodyCase is MxEvent.BodyOneofCase.OnAlarmTransition
or MxEvent.BodyOneofCase.OnAlarmProviderModeChanged;
// Applies a live transition to the cache and broadcasts it to subscribers.
private void ApplyTransition(OnAlarmTransitionEvent transition)
{
@@ -38,7 +38,7 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
/// <see cref="EventsHubViewerRegistry.HubViewersReleased"/> reports the last one gone.
/// </para>
/// </remarks>
public sealed class DashboardEventBroadcaster : IDashboardEventBroadcaster, IDashboardSessionEventSubscriber, IDisposable, IAsyncDisposable
public sealed class DashboardEventBroadcaster : IDashboardEventBroadcaster, IDashboardSessionEventSubscriber, IDashboardViewerPresence, IDisposable, IAsyncDisposable
{
/// <summary>
/// Queue depth per in-process subscriber. The consumer is a Blazor page
@@ -143,6 +143,16 @@ public sealed class DashboardEventBroadcaster : IDashboardEventBroadcaster, IDas
}
}
/// <inheritdoc />
public event Action<string>? ViewerPresenceChanged
{
add => _viewerRegistry.ViewerPresenceChanged += value;
remove => _viewerRegistry.ViewerPresenceChanged -= value;
}
/// <inheritdoc />
public bool HasViewers(string sessionId) => _viewerRegistry.HasViewers(sessionId);
/// <inheritdoc />
public void Publish(string sessionId, MxEvent mxEvent)
{
@@ -151,10 +161,11 @@ public sealed class DashboardEventBroadcaster : IDashboardEventBroadcaster, IDas
return;
}
// Every session's dashboard-mirror subscriber calls Publish for every event,
// whether or not a browser is on that session's page. Without this gate the
// steady state — no dashboard viewer at all — still paid a deep protobuf
// clone (redaction is on by default) per event. Bail before it.
// A session attaches its dashboard-mirror subscriber only while the registry
// reports a viewer (IDashboardViewerPresence), but the mirror can still deliver
// events in the moment between the last viewer leaving and the mirror detaching.
// Without this gate each of those would pay a deep protobuf clone (redaction is
// on by default) that reaches nobody. Bail before it.
if (!_viewerRegistry.HasViewers(sessionId))
{
return;
@@ -68,13 +68,26 @@ public sealed class EventsHubViewerRegistry
return;
}
_viewersBySession.AddOrUpdate(sessionId, 1, static (_, count) => count + 1);
int viewers = _viewersBySession.AddOrUpdate(sessionId, 1, static (_, count) => count + 1);
if (IsHubConnection(connectionId))
{
_hubViewersBySession.AddOrUpdate(sessionId, 1, static (_, count) => count + 1);
}
if (viewers == 1)
{
ViewerPresenceChanged?.Invoke(sessionId);
}
}
/// <summary>
/// Raised with a session id when it gains its first viewer of either audience or
/// loses its last one. Handlers run on the changing thread, must not throw or
/// block, and must re-read <see cref="HasViewers"/>: two concurrent changes can
/// raise in either order.
/// </summary>
public event Action<string>? ViewerPresenceChanged;
/// <summary>
/// Raised with a session id when its last remote hub viewer leaves (unsubscribe
/// or disconnect). In-process subscribers do not raise it. Handlers run on the
@@ -169,11 +182,16 @@ public sealed class EventsHubViewerRegistry
/// <param name="sessionId">Session id whose counts are released.</param>
private void Release(string connectionId, string sessionId)
{
ReleaseSession(_viewersBySession, sessionId);
bool lastViewer = ReleaseSession(_viewersBySession, sessionId);
if (IsHubConnection(connectionId) && ReleaseSession(_hubViewersBySession, sessionId))
{
HubViewersReleased?.Invoke(sessionId);
}
if (lastViewer)
{
ViewerPresenceChanged?.Invoke(sessionId);
}
}
/// <summary>
@@ -0,0 +1,35 @@
namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
/// <summary>
/// Reports whether any dashboard audience is watching a session, and when that
/// changes. A session uses it to attach its dashboard-mirror distributor
/// subscriber only while someone is watching.
/// </summary>
/// <remarks>
/// Without it every session ran a mirror subscriber that woke for every event
/// only for <see cref="IDashboardEventBroadcaster.Publish"/> to discard it,
/// because in the steady state nobody has a session-details page open. That
/// wake-up was one thread-pool work item per event per session (mxaccessgw#235).
/// A broadcaster that does not implement this interface is mirrored for the
/// session's whole life, which is the behavior test doubles rely on.
/// <para>
/// This only decides whether events reach <see cref="IDashboardEventBroadcaster.Publish"/>.
/// Who may watch a session (<see cref="IDashboardSessionAcl"/>) and what a
/// watcher sees (value redaction) are decided elsewhere and are unaffected.
/// </para>
/// </remarks>
public interface IDashboardViewerPresence
{
/// <summary>
/// Raised with a session id when the session gains its first dashboard viewer
/// or loses its last one. Handlers run on the thread that changed the viewer
/// set, must not throw or block, and should re-read <see cref="HasViewers"/>
/// rather than infer the direction: concurrent changes can raise in either order.
/// </summary>
event Action<string>? ViewerPresenceChanged;
/// <summary>Gets a value indicating whether any dashboard audience is watching the session.</summary>
/// <param name="sessionId">Session id to test.</param>
/// <returns><see langword="true"/> when at least one viewer is registered.</returns>
bool HasViewers(string sessionId);
}
@@ -63,9 +63,20 @@ public sealed class GatewaySession : IAsyncDisposable
// silently and invisibly to metrics.
private bool _eventDistributorDisposed;
private bool _dashboardMirrorStarted;
// Set under _syncRoot by DisposeAsync when it collects the mirror; no attach may follow it.
private bool _dashboardMirrorStopped;
// Serializes mirror attach/detach (StartDashboardMirror and viewer-presence reconciles).
// Taken before _syncRoot and the distributor's lifecycle lock, never while holding either.
private readonly object _dashboardMirrorGate = new();
// The current mirror attachment; null while no dashboard viewer watches the session.
private IEventSubscriberLease? _dashboardMirrorLease;
// Every mirror loop started and not yet known to have finished, awaited by DisposeAsync.
private Task? _dashboardMirrorTask;
// Session-lifetime token source shared by every mirror loop; cancelled and disposed by
// DisposeAsync.
private CancellationTokenSource? _dashboardMirrorCts;
private IDashboardViewerPresence? _dashboardViewerPresence;
private Action<string>? _dashboardViewerPresenceHandler;
private readonly Dictionary<(int ServerHandle, int ItemHandle), SessionItemRegistration> _items = [];
private readonly ArrayAddressNormalizer? _addressNormalizer;
@@ -631,16 +642,16 @@ public sealed class GatewaySession : IAsyncDisposable
/// Transitions the session to the Ready state.
/// </summary>
/// <remarks>
/// On becoming Ready the session starts its internal dashboard mirror when a
/// dashboard broadcaster was supplied. The mirror registers an internal subscriber on
/// the distributor and starts the pump <em>before</em> any gRPC client attaches, so the
/// dashboard EventsHub receives session events even with no gRPC subscriber streaming —
/// fixing the "dark feed" where the dashboard only saw events while a gRPC client was
/// actively streaming. Registering the internal subscriber BEFORE
/// <see cref="SessionEventDistributor.StartAsync"/> also avoids the hazard where
/// starting the pump at Ready with zero subscribers drained a fast-completing worker
/// stream into nothing and left a later subscriber hanging: there is now always a
/// subscriber (the dashboard one) registered before the pump starts.
/// On becoming Ready the session starts its dashboard mirroring when a dashboard
/// broadcaster was supplied. That starts the distributor pump <em>before</em> any gRPC
/// client attaches, so the dashboard EventsHub receives session events even with no gRPC
/// subscriber streaming — fixing the "dark feed" where the dashboard only saw events
/// while a gRPC client was actively streaming. The mirror's internal subscriber itself is
/// attached only while a dashboard viewer watches the session when the broadcaster
/// reports viewer presence (<see cref="IDashboardViewerPresence"/>), and for the
/// session's whole life otherwise. A subscriber that registers after the pump drained a
/// fast-completing worker stream is completed by the distributor rather than left
/// hanging, so the pump may start with no subscriber registered.
/// </remarks>
public void MarkReady()
{
@@ -777,11 +788,17 @@ public sealed class GatewaySession : IAsyncDisposable
/// <see cref="SessionManagerErrorCode.SessionNotReady"/>.
/// </para>
/// </remarks>
/// <param name="filter">
/// Optional predicate applied by the distributor pump before an event is written to this
/// subscriber, so events the consumer would discard never wake it. It runs on the pump
/// thread for every event and must be cheap, pure, and must not throw. <see langword="null"/>
/// delivers every event.
/// </param>
/// <returns>The internal subscriber's lease; dispose it to unregister.</returns>
/// <exception cref="SessionManagerException">
/// The session or its worker client is not <c>Ready</c>.
/// </exception>
public IEventSubscriberLease AttachInternalEventSubscriber()
public IEventSubscriberLease AttachInternalEventSubscriber(Func<MxEvent, bool>? filter = null)
{
// Readiness gate, mirroring AttachEventSubscriber. It must run BEFORE
// EnsureDistributorCreated: a premature attach would construct the distributor and start
@@ -805,7 +822,7 @@ public sealed class GatewaySession : IAsyncDisposable
// start if we are first), register the internal subscriber BEFORE the pump starts so a
// subscriber is always present at pump start, then start the pump if requested.
SessionEventDistributor distributor = EnsureDistributorCreated(out bool startNow);
IEventSubscriberLease lease = distributor.Register(isInternal: true);
IEventSubscriberLease lease = distributor.Register(isInternal: true, filter);
StartPumpIfRequested(distributor, startNow);
lock (_syncRoot)
{
@@ -833,21 +850,22 @@ public sealed class GatewaySession : IAsyncDisposable
distributor.StartAsync(CancellationToken.None).GetAwaiter().GetResult();
}
// Registers the gateway-owned internal dashboard subscriber on the distributor and starts
// a background loop that mirrors every fanned event to the dashboard broadcaster. Called
// once when the session becomes Ready (idempotent). The internal subscriber is registered
// BEFORE the pump starts (see StartDistributorAndRegister / EnsureDistributorCreated), so
// a subscriber is always present at pump start — the dashboard receives events with no
// gRPC subscriber attached, and the "zero-subscriber drain into the void" hang
// cannot occur. No-op when no dashboard broadcaster was supplied (unit tests).
// Starts the session's dashboard mirroring once, when the session becomes Ready
// (idempotent). No-op when no dashboard broadcaster was supplied (unit tests).
//
// Race-safety (Issue 1): _dashboardMirrorLease and _dashboardMirrorTask are published
// atomically under a SINGLE second lock section, and DisposeAsync reads/nulls them under
// that same lock. After EnsureDistributorCreated/Register/StartPump (all outside _syncRoot
// to avoid lock inversion with the distributor's own lifecycle lock), we re-enter
// _syncRoot and check for concurrent disposal. If the session is already Closing/Closed/
// Faulted at that point, we dispose the just-created lease immediately and do NOT start
// the mirror task, so nothing is orphaned.
// The distributor pump is started here either way, so the worker's event channel is
// drained from Ready onward whether or not anyone is streaming — the replay ring fills,
// the alarm monitor's lease sees every transition, and ObserveWorkerTerminalState notices a
// dead worker. Registering a subscriber before the pump starts is no longer required for
// correctness: a subscriber that registers after the pump completed gets its channel
// completed by the distributor's _completed latch instead of hanging.
//
// What is lazy is the mirror subscriber itself (mxaccessgw#235). When the broadcaster
// reports viewer presence (IDashboardViewerPresence — the production broadcaster does), the
// mirror is attached only while the session has a dashboard viewer and detached when the
// last one leaves, so an unwatched session no longer wakes a mirror loop for every event
// just for Publish to discard it. A broadcaster without presence (test doubles) is mirrored
// for the session's whole life, exactly as before.
private void StartDashboardMirror()
{
IDashboardEventBroadcaster? broadcaster = _eventStreaming.DashboardBroadcaster;
@@ -856,32 +874,142 @@ public sealed class GatewaySession : IAsyncDisposable
return;
}
CancellationToken loopToken;
lock (_syncRoot)
{
if (_dashboardMirrorStarted || _state is SessionState.Closing or SessionState.Closed or SessionState.Faulted)
if (_dashboardMirrorStarted || IsDashboardMirrorBlockedUnderLock())
{
return;
}
_dashboardMirrorStarted = true;
_dashboardMirrorCts = new CancellationTokenSource();
loopToken = _dashboardMirrorCts.Token;
}
// Create the distributor (claiming the start if we are first) and register the
// internal subscriber BEFORE starting the pump. isInternal: true keeps the dashboard
// subscriber out of the single-subscriber overflow accounting, so a slow/broken
// dashboard mirror only disconnects itself and never faults the session.
// These three calls are OUTSIDE _syncRoot to avoid holding it across
// EnsureDistributorCreated's own lock and StartAsync's Task.Run.
//
// The state check above can be overtaken by a close+dispose before we get here, and
// EnsureDistributorCreated now says so instead of building an orphan distributor. The
// dashboard mirror is a best-effort observability attachment on a session that is already
// gone, so it is abandoned here rather than propagated out of MarkReady — the mirror-started
// latch stays set (nothing may start one on a disposed session) and the loop's token source
// is released so it is not orphaned.
if (broadcaster is not IDashboardViewerPresence presence)
{
lock (_dashboardMirrorGate)
{
AttachDashboardMirrorUnderGate(broadcaster);
}
return;
}
if (!TryStartDistributorPumpForDashboard())
{
return;
}
void OnViewerPresenceChanged(string changedSessionId)
{
if (string.Equals(changedSessionId, SessionId, StringComparison.Ordinal))
{
ReconcileDashboardMirror(broadcaster, presence);
}
}
lock (_syncRoot)
{
if (IsDashboardMirrorBlockedUnderLock())
{
return;
}
// Subscribed under _syncRoot, together with the published handler, so DisposeAsync —
// which unsubscribes under the same lock — can never miss a subscription made
// concurrently with it. Adding a delegate runs no callback, so nothing executes
// under the lock here.
_dashboardViewerPresence = presence;
_dashboardViewerPresenceHandler = OnViewerPresenceChanged;
presence.ViewerPresenceChanged += OnViewerPresenceChanged;
}
// Subscribe first, then reconcile: a viewer that arrived before the subscription is
// seen by this reconcile, and one that arrives after it raises the event.
ReconcileDashboardMirror(broadcaster, presence);
}
// True when no mirror may attach: the session is tearing down or gone, or DisposeAsync has
// already collected the mirror. Callers hold _syncRoot.
private bool IsDashboardMirrorBlockedUnderLock()
=> _dashboardMirrorStopped
|| _state is SessionState.Closing or SessionState.Closed or SessionState.Faulted;
// Creates the distributor and starts its pump without registering a subscriber. Returns
// false when the session was disposed first; the mirror is then abandoned rather than
// propagated out of MarkReady, since it is best-effort observability on a session that is
// already gone.
private bool TryStartDistributorPumpForDashboard()
{
try
{
SessionEventDistributor distributor = EnsureDistributorCreated(out bool startNow);
StartPumpIfRequested(distributor, startNow);
return true;
}
catch (SessionManagerException exception)
{
_eventStreaming.DistributorLogger.LogDebug(
exception,
"Dashboard event mirror for session {SessionId} was abandoned: the session was disposed "
+ "before the mirror could attach.",
SessionId);
return false;
}
}
// Brings the mirror attachment in line with the current viewer presence. Runs on the
// thread that changed the viewer set (a SignalR hub call or a dashboard page), so it never
// blocks: attaching registers a subscriber and schedules the mirror loop, detaching disposes
// the lease, which completes the mirror channel so the loop ends on its own. Serialized by
// _dashboardMirrorGate, and idempotent, so presence events that race or arrive out of order
// still converge: each reconcile reads the state current at the time it runs, and the last
// one runs after the last change.
private void ReconcileDashboardMirror(IDashboardEventBroadcaster broadcaster, IDashboardViewerPresence presence)
{
try
{
lock (_dashboardMirrorGate)
{
bool attached;
bool blocked;
lock (_syncRoot)
{
attached = _dashboardMirrorLease is not null;
blocked = IsDashboardMirrorBlockedUnderLock();
}
bool wanted = !blocked && presence.HasViewers(SessionId);
if (wanted && !attached)
{
AttachDashboardMirrorUnderGate(broadcaster);
}
else if (!wanted && attached)
{
DetachDashboardMirrorUnderGate();
}
}
}
catch (Exception exception)
{
// Presence handlers must never throw into the viewer registry. The mirror is
// best-effort; a failed attach leaves the dashboard without events for this session
// until the next presence change. Logs identifiers only.
_eventStreaming.DistributorLogger.LogDebug(
exception,
"Dashboard event mirror reconcile failed for session {SessionId}.",
SessionId);
}
}
// Registers the internal dashboard subscriber and starts its mirror loop. isInternal: true
// keeps it out of the single-subscriber overflow accounting, so a slow or broken dashboard
// mirror only disconnects itself and never faults the session. The distributor calls are
// outside _syncRoot to avoid lock inversion with the distributor's own lifecycle lock; the
// lease and task are then published under _syncRoot, where DisposeAsync reads and nulls
// them, after re-checking for a concurrent teardown. Callers hold _dashboardMirrorGate.
private void AttachDashboardMirrorUnderGate(IDashboardEventBroadcaster broadcaster)
{
SessionEventDistributor distributor;
bool startNow;
try
@@ -890,14 +1018,6 @@ public sealed class GatewaySession : IAsyncDisposable
}
catch (SessionManagerException exception)
{
CancellationTokenSource? abandonedCts;
lock (_syncRoot)
{
abandonedCts = _dashboardMirrorCts;
_dashboardMirrorCts = null;
}
abandonedCts?.Dispose();
_eventStreaming.DistributorLogger.LogDebug(
exception,
"Dashboard event mirror for session {SessionId} was abandoned: the session was disposed "
@@ -909,27 +1029,47 @@ public sealed class GatewaySession : IAsyncDisposable
IEventSubscriberLease lease = distributor.Register(isInternal: true);
StartPumpIfRequested(distributor, startNow);
// Publish BOTH the lease and the task atomically under one lock section so
// DisposeAsync always sees them in a consistent state: either both are set or
// both are null. If the session already started disposal before we got here,
// dispose the lease immediately instead of orphaning it.
lock (_syncRoot)
{
if (_state is SessionState.Closing or SessionState.Closed or SessionState.Faulted)
CancellationTokenSource? cts = _dashboardMirrorCts;
if (cts is null || IsDashboardMirrorBlockedUnderLock())
{
// Disposal already ran (or is in progress) — discard the just-created
// lease now so it is not orphaned. Do NOT launch the mirror task.
// Disposal already ran (or is in progress) — discard the just-created lease now
// so it is not orphaned. Do NOT launch the mirror task.
lease.Dispose();
return;
}
_dashboardMirrorLease = lease;
_dashboardMirrorTask = Task.Run(
CancellationToken loopToken = cts.Token;
Task loopTask = Task.Run(
() => RunDashboardMirrorAsync(broadcaster, lease, loopToken),
CancellationToken.None);
_dashboardMirrorLease = lease;
// Earlier, detached loops end on their own once their channel is completed, but
// DisposeAsync still awaits them before it disposes the shared token source.
Task? previous = _dashboardMirrorTask;
_dashboardMirrorTask = previous is null || previous.IsCompleted
? loopTask
: Task.WhenAll(previous, loopTask);
}
}
// Disposes the current mirror lease: the distributor unregisters the subscriber and
// completes its channel, and the mirror loop drains what is left (Publish discards it, as
// nobody is watching) and exits. Callers hold _dashboardMirrorGate.
private void DetachDashboardMirrorUnderGate()
{
IEventSubscriberLease? lease;
lock (_syncRoot)
{
lease = _dashboardMirrorLease;
_dashboardMirrorLease = null;
}
lease?.Dispose();
}
// Reads the internal dashboard subscriber's channel and publishes each RAW fanned event
// to the dashboard broadcaster. The dashboard is a first-class distributor subscriber,
// so it sees the session's full raw event activity — NOT the per-gRPC-subscriber
@@ -2169,6 +2309,14 @@ public sealed class GatewaySession : IAsyncDisposable
CancellationTokenSource? dashboardCts;
lock (_syncRoot)
{
_dashboardMirrorStopped = true;
if (_dashboardViewerPresence is not null && _dashboardViewerPresenceHandler is not null)
{
_dashboardViewerPresence.ViewerPresenceChanged -= _dashboardViewerPresenceHandler;
}
_dashboardViewerPresence = null;
_dashboardViewerPresenceHandler = null;
dashboardLease = _dashboardMirrorLease;
dashboardTask = _dashboardMirrorTask;
dashboardCts = _dashboardMirrorCts;
@@ -363,12 +363,19 @@ public sealed class SessionEventDistributor : IAsyncDisposable
/// disconnected from the mirror. Defaults to <see langword="false"/> (external
/// subscriber) so every existing call site is unchanged.
/// </param>
/// <param name="filter">
/// Optional predicate the pump applies before writing an event to this subscriber; an
/// event it rejects is skipped for this subscriber only, so it neither wakes the reader
/// nor occupies channel capacity. It runs on the pump thread — normally the worker pipe
/// read loop — for every event, so it must be cheap, pure, and must not throw.
/// <see langword="null"/> (the default) delivers every event.
/// </param>
/// <returns>The lease for the newly-registered subscriber.</returns>
public IEventSubscriberLease Register(bool isInternal = false)
public IEventSubscriberLease Register(bool isInternal = false, Func<MxEvent, bool>? filter = null)
{
Channel<MxEvent> channel = CreateSubscriberChannel();
long id = Interlocked.Increment(ref _nextSubscriberId);
Subscriber subscriber = new(id, channel, isInternal);
Subscriber subscriber = new(id, channel, isInternal, filter);
return RegisterSubscriber(subscriber);
}
@@ -517,7 +524,7 @@ public sealed class SessionEventDistributor : IAsyncDisposable
{
Channel<MxEvent> channel = CreateSubscriberChannel();
long id = Interlocked.Increment(ref _nextSubscriberId);
Subscriber subscriber = new(id, channel, isInternal);
Subscriber subscriber = new(id, channel, isInternal, filter: null);
// Snapshot replay AND register under a single _replayLock section so the live channel
// begins exactly where the replay snapshot ends — see the remarks for the no-gap /
@@ -680,6 +687,11 @@ public sealed class SessionEventDistributor : IAsyncDisposable
// THIS subscriber only; the pump, the session, and every other subscriber
// keep running. Logs identifiers (worker sequence, subscriber id, session)
// only, never the event payload or tag values.
if (subscriber.Filter is { } filter && !filter(mxEvent))
{
continue;
}
if (!subscriber.Channel.Writer.TryWrite(mxEvent))
{
OnSubscriberOverflow(subscriber, mxEvent.WorkerSequence);
@@ -1035,7 +1047,7 @@ public sealed class SessionEventDistributor : IAsyncDisposable
private readonly record struct ReplayEntry(MxEvent Event, DateTimeOffset RetainedAt, int SizeBytes);
private sealed class Subscriber(long id, Channel<MxEvent> channel, bool isInternal)
private sealed class Subscriber(long id, Channel<MxEvent> channel, bool isInternal, Func<MxEvent, bool>? filter)
{
/// <summary>Gets the subscriber's monotonic id, assigned at registration.</summary>
public long Id { get; } = id;
@@ -1049,6 +1061,12 @@ public sealed class SessionEventDistributor : IAsyncDisposable
/// fault the session.
/// </summary>
public bool IsInternal { get; } = isInternal;
/// <summary>
/// Gets the optional per-subscriber predicate; an event it rejects is not written to
/// this subscriber. <see langword="null"/> delivers every event.
/// </summary>
public Func<MxEvent, bool>? Filter { get; } = filter;
}
private sealed class SubscriberLease(SessionEventDistributor distributor, Subscriber subscriber)
@@ -208,4 +208,32 @@ public sealed class EventsHubViewerRegistryTests
registry.RemoveViewer(EventsHubViewerRegistry.InProcessConnectionIdPrefix + "a", "session-1");
Assert.Equal(["session-1"], released);
}
/// <summary>
/// The presence event fires when a session gains its first viewer of either audience and
/// when it loses its last one, and not for the viewers in between. Sessions drive their
/// lazy dashboard mirror from it.
/// </summary>
[Fact]
public void ViewerPresenceChanged_FiresOnFirstViewerAndOnLastViewerOnly()
{
EventsHubViewerRegistry registry = new();
List<(string SessionId, bool HasViewers)> changes = [];
registry.ViewerPresenceChanged += sessionId => changes.Add((sessionId, registry.HasViewers(sessionId)));
registry.AddViewer(EventsHubViewerRegistry.InProcessConnectionIdPrefix + "a", "session-1");
registry.AddViewer("conn-1", "session-1");
registry.AddViewer("conn-1", "session-1");
Assert.Equal([("session-1", true)], changes);
registry.RemoveViewer(EventsHubViewerRegistry.InProcessConnectionIdPrefix + "a", "session-1");
Assert.Single(changes);
registry.ReleaseConnection("conn-1");
Assert.Equal([("session-1", true), ("session-1", false)], changes);
// An unmatched removal changes nothing and raises nothing.
registry.RemoveViewer("conn-1", "session-1");
Assert.Equal(2, changes.Count);
}
}
@@ -232,6 +232,119 @@ public sealed class GatewaySessionDashboardMirrorTests
Assert.Equal(1, session.ActiveEventSubscriberCount);
}
/// <summary>
/// With a broadcaster that reports viewer presence, the mirror subscriber is attached only
/// while the session has a viewer: events emitted with nobody watching never reach
/// Publish, events emitted while watched do, and the subscriber detaches again when the
/// last viewer leaves. The pump still starts at Ready, so the distributor keeps draining
/// the worker with no subscriber at all.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DashboardMirror_WithViewerPresence_AttachesOnlyWhileWatched()
{
System.Threading.Channels.Channel<WorkerEvent> live = System.Threading.Channels.Channel.CreateUnbounded<WorkerEvent>();
FakeWorkerClient workerClient = new() { Live = live };
PresenceRecordingBroadcaster broadcaster = new();
await using GatewaySession session = CreateSession(workerClient, broadcaster);
session.AttachWorkerClient(workerClient);
session.MarkReady();
// Nobody watching: the pump drains the worker into the replay ring and fans to no one.
Assert.Equal(1, broadcaster.HandlerCount);
await live.Writer.WriteAsync(CreateWorkerEvent(1, MxEventFamily.OnDataChange));
await WaitUntilAsync(() => workerClient.LiveYielded == 1);
Assert.Equal(0, broadcaster.PublishCalls);
broadcaster.SetViewers(session.SessionId, watched: true);
await live.Writer.WriteAsync(CreateWorkerEvent(2, MxEventFamily.OnDataChange));
await WaitUntilAsync(() => broadcaster.Captures.Count == 1);
broadcaster.SetViewers(session.SessionId, watched: false);
await live.Writer.WriteAsync(CreateWorkerEvent(3, MxEventFamily.OnDataChange));
await WaitUntilAsync(() => workerClient.LiveYielded == 3);
broadcaster.SetViewers(session.SessionId, watched: true);
await live.Writer.WriteAsync(CreateWorkerEvent(4, MxEventFamily.OnDataChange));
await WaitUntilAsync(() => broadcaster.Captures.Count == 2);
Assert.Equal([2UL, 4UL], broadcaster.Captures.Select(capture => capture.MxEvent.WorkerSequence).ToArray());
// Events 1 and 3 were fanned while no mirror was attached, so Publish never saw them
// (event 4 is ordered after 3 on the single pump, so 3 has been fanned by now).
Assert.Equal(2, broadcaster.PublishCalls);
Assert.Equal(0, session.ActiveEventSubscriberCount);
}
/// <summary>
/// A presence change for another session leaves this session's mirror alone, and
/// disposing the session unsubscribes its presence handler so the singleton broadcaster
/// does not keep a reference to every session ever opened.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DashboardMirror_WithViewerPresence_IgnoresOtherSessionsAndUnsubscribesOnDispose()
{
System.Threading.Channels.Channel<WorkerEvent> live = System.Threading.Channels.Channel.CreateUnbounded<WorkerEvent>();
FakeWorkerClient workerClient = new() { Live = live };
PresenceRecordingBroadcaster broadcaster = new();
GatewaySession session = CreateSession(workerClient, broadcaster);
session.AttachWorkerClient(workerClient);
session.MarkReady();
broadcaster.SetViewers("some-other-session", watched: true);
await live.Writer.WriteAsync(CreateWorkerEvent(1, MxEventFamily.OnDataChange));
await WaitUntilAsync(() => workerClient.LiveYielded == 1);
Assert.Equal(0, broadcaster.PublishCalls);
await session.DisposeAsync();
Assert.Equal(0, broadcaster.HandlerCount);
// A presence change after disposal must not resurrect a mirror on the dead session.
broadcaster.SetViewers(session.SessionId, watched: true);
Assert.Equal(0, broadcaster.PublishCalls);
}
/// <summary>
/// An internal subscriber registered with a filter only receives the events the filter
/// admits — the alarm monitor's lease uses this so data changes never wake it — while an
/// unfiltered subscriber on the same pump still receives every event in order.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task InternalSubscriber_WithFilter_ReceivesOnlyAdmittedEvents()
{
FakeWorkerClient workerClient = new();
workerClient.Events.Add(CreateWorkerEvent(1, MxEventFamily.OnDataChange));
workerClient.Events.Add(CreateAlarmTransitionEvent(2, AlarmTransitionKind.Raise));
workerClient.Events.Add(CreateWorkerEvent(3, MxEventFamily.OnDataChange));
workerClient.Events.Add(CreateAlarmTransitionEvent(4, AlarmTransitionKind.Acknowledge));
workerClient.CompleteAfterConfiguredEvents = true;
workerClient.HoldEventsUntilReleased();
RecordingDashboardEventBroadcaster broadcaster = new();
await using GatewaySession session = CreateSession(workerClient, broadcaster);
session.AttachWorkerClient(workerClient);
session.MarkReady();
using IEventSubscriberLease alarmLease = session.AttachInternalEventSubscriber(
mxEvent => mxEvent.BodyCase == MxEvent.BodyOneofCase.OnAlarmTransition);
workerClient.ReleaseEvents();
List<MxEvent> alarmEvents = [];
using CancellationTokenSource timeout = new(TestTimeout);
await foreach (MxEvent mxEvent in alarmLease.Reader.ReadAllAsync(timeout.Token))
{
alarmEvents.Add(mxEvent);
}
await WaitUntilAsync(() => broadcaster.Captures.Count == 4);
Assert.Equal([2UL, 4UL], alarmEvents.Select(mxEvent => mxEvent.WorkerSequence).ToArray());
Assert.Equal([1UL, 2UL, 3UL, 4UL], broadcaster.Captures.Select(capture => capture.MxEvent.WorkerSequence).ToArray());
}
private static GatewaySession CreateSession(
IWorkerClient workerClient,
IDashboardEventBroadcaster broadcaster)
@@ -297,6 +410,59 @@ public sealed class GatewaySessionDashboardMirrorTests
private static Task WaitUntilAsync(Func<bool> predicate, [CallerArgumentExpression(nameof(predicate))] string? condition = null)
=> Eventually.WaitUntilAsync(predicate, TestTimeout, condition);
/// <summary>
/// Broadcaster that reports viewer presence and records Publish calls, so a test can
/// drive viewers coming and going and observe what reaches the dashboard seam.
/// </summary>
private sealed class PresenceRecordingBroadcaster : IDashboardEventBroadcaster, IDashboardViewerPresence
{
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, bool> _watched = new(StringComparer.Ordinal);
private readonly System.Collections.Concurrent.ConcurrentQueue<DashboardEventCapture> _captures = new();
private Action<string>? _handlers;
private int _publishCalls;
/// <inheritdoc />
public event Action<string>? ViewerPresenceChanged
{
add => _handlers += value;
remove => _handlers -= value;
}
/// <summary>Gets the number of subscribed presence handlers.</summary>
public int HandlerCount => _handlers?.GetInvocationList().Length ?? 0;
/// <summary>Gets the number of Publish calls of any kind, watched or not.</summary>
public int PublishCalls => Volatile.Read(ref _publishCalls);
/// <summary>Gets a snapshot of every Publish call that reached a watched session.</summary>
public IReadOnlyList<DashboardEventCapture> Captures => _captures.ToArray();
/// <summary>Marks the session watched or unwatched and raises the presence event.</summary>
/// <param name="sessionId">Session whose viewer presence changes.</param>
/// <param name="watched">Whether a viewer is now present.</param>
public void SetViewers(string sessionId, bool watched)
{
_watched[sessionId] = watched;
_handlers?.Invoke(sessionId);
}
/// <inheritdoc />
public bool HasViewers(string sessionId) => _watched.TryGetValue(sessionId, out bool watched) && watched;
/// <inheritdoc />
public void Publish(string sessionId, MxEvent mxEvent)
{
Interlocked.Increment(ref _publishCalls);
// Mirrors the production gate, so an event a detaching loop drains after the last
// viewer left is not recorded as delivered.
if (HasViewers(sessionId))
{
_captures.Enqueue(new DashboardEventCapture(sessionId, mxEvent));
}
}
}
private sealed class ThrowingDashboardEventBroadcaster : IDashboardEventBroadcaster
{
private int _publishAttempts;
@@ -423,9 +589,31 @@ public sealed class GatewaySessionDashboardMirrorTests
yield break;
}
if (Live is not null)
{
await foreach (WorkerEvent workerEvent in Live.Reader.ReadAllAsync(cancellationToken))
{
Interlocked.Increment(ref _liveYielded);
yield return workerEvent;
}
yield break;
}
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
}
/// <summary>
/// When set, <see cref="ReadEventsAsync"/> yields from this channel after
/// <see cref="Events"/>, so a test can emit events at chosen points.
/// </summary>
public System.Threading.Channels.Channel<WorkerEvent>? Live { get; set; }
/// <summary>Gets the number of <see cref="Live"/> events handed to the consumer so far.</summary>
public int LiveYielded => Volatile.Read(ref _liveYielded);
private int _liveYielded;
/// <inheritdoc />
public Task ShutdownAsync(TimeSpan timeout, CancellationToken cancellationToken) => Task.CompletedTask;