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:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user