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
+11 -3
View File
@@ -220,7 +220,9 @@ Event streaming uses `AttachEventSubscriber` which returns a disposable lease. W
The single worker event channel has exactly one direct reader: the `SessionEventDistributor` pump (`MapWorkerEventsAsync`). Both gateway-owned internal consumers — the dashboard mirror and the central alarm monitor — attach as distributor subscribers rather than draining the worker channel themselves. `GatewaySession.AttachInternalEventSubscriber` mirrors the dashboard-mirror lease (`isInternal: true`): the alarm monitor calls it directly on its session so it consumes the same mapped `MxEvent`s the pump fans to every subscriber, without counting against `MaxEventSubscribersPerSession` and without a slow reconcile faulting the session. This is what keeps the alarm feed and the dashboard from splitting the stream between two raw drains (which would silently lose Acknowledge and provider-mode transitions); the worker channel is single-reader and a second `WorkerClient.ReadEventsAsync` consumer throws so a regression fails loudly.
The monitor takes that lease **before** it issues `SubscribeAlarms`, so no transition window is missed: the pump has been running since `MarkReady` started the dashboard mirror, and the distributor only fans to subscribers registered at fan-out time, so a lease taken after the subscribe + first-reconcile round trips would lose every transition raised inside that window. Transitions arriving while the monitor subscribes and reconciles buffer in the lease's bounded channel and are applied after the reconcile, which is order-safe because a live transition can update an alarm the reconciled snapshot already holds.
An internal subscriber may pass a filter (`AttachInternalEventSubscriber(filter)`, `SessionEventDistributor.Register(isInternal, filter)`). The pump applies it before the subscriber's `TryWrite`, so a rejected event neither wakes the reader nor uses channel capacity. The alarm monitor filters to `OnAlarmTransition` and `OnAlarmProviderModeChanged`, the only bodies its loop acts on. The filter runs on the pump thread — normally the worker pipe read loop, see "Event path threading" in [GatewayProcessDesign](./GatewayProcessDesign.md) — so it must be a cheap, pure check that never throws.
The monitor takes that lease **before** it issues `SubscribeAlarms`, so no transition window is missed: the pump has been running since `MarkReady` started it, and the distributor only fans to subscribers registered at fan-out time, so a lease taken after the subscribe + first-reconcile round trips would lose every transition raised inside that window. Transitions arriving while the monitor subscribes and reconciles buffer in the lease's bounded channel and are applied after the reconcile, which is order-safe because a live transition can update an alarm the reconciled snapshot already holds.
The repair transitions the monitor's reconcile broadcasts on the alarm feed (Raise/Clear presence deltas and the acked-state delta) are **at-least-once**: a reconcile reads the worker's current state while the matching live transition may still be buffered in the lease, so both can be broadcast and the duplicates are indistinguishable — alarm-feed consumers must apply transitions idempotently. This is a property of the reconcile design, not of the buffering above. The monitor dedups the common case best-effort (NEXT-03): a buffered live transition that positively matches the cache's worker timestamp and resulting state — or, for Clear, a tombstone keyed on the cleared instance's original raise timestamp — was already broadcast as a repair and is suppressed; unset timestamps never suppress, so the consumer contract is unchanged.
@@ -230,6 +232,12 @@ The same one-distributor-per-session rule is enforced at the other end of the li
Sessions open with `MxGateway:Sessions:DefaultLeaseSeconds` (default 1800) added to the open timestamp. Unary client activity refreshes the lease by the same duration (`TouchClientActivity` is the only path that moves the lease). `IsLeaseExpired` cooperates with `SessionManager.CloseExpiredLeasesAsync`, which iterates a registry snapshot and closes any session whose lease has expired with `LeaseExpiredReason`. `SessionLeaseMonitorHostedService` runs that sweep every `MxGateway:Sessions:LeaseSweepIntervalSeconds` seconds (default 30).
#### Lazy dashboard mirror
`MarkReady` starts the distributor pump whenever a dashboard broadcaster is configured, so the worker channel is drained from `Ready` onward with or without a subscriber: the replay ring fills, the alarm lease sees every transition, and a dead worker is noticed. The mirror subscriber itself is attached only while the session has a dashboard viewer. The production broadcaster implements `IDashboardViewerPresence`, backed by `EventsHubViewerRegistry`, which raises `ViewerPresenceChanged` when a session gains its first viewer (an `EventsHub` connection or an in-process session-details subscription) or loses its last one. The session subscribes at `MarkReady`, reconciles on each change — attach when watched, dispose the lease when not — and unsubscribes in `DisposeAsync`. Before this, every session's mirror loop woke for every event only for `Publish` to discard it, because the steady state has no viewer; that was one thread-pool work item per event per session (mxaccessgw#235).
The change does not affect who may watch or what they see: `IDashboardSessionAcl` still gates the subscribe seam and `Publish` still redacts values. A viewer that subscribes sees events fanned after the mirror attaches, a few microseconds after its registration, which matches the existing edge where a hub connection is registered before it joins its SignalR group. A broadcaster that does not implement `IDashboardViewerPresence` (test doubles) is mirrored for the session's whole life, as before.
#### Teardown parallelism
A sweep pass is two phases. *Selection* stays a single sequential pass over the snapshot, because that is what gives the precedence rule (lease-expiry, then faulted, then detach-grace, then unattached-grace) and the `TryBeginCloseIfExpired` TOCTOU re-check their meaning. *Closing* then runs over the already-selected set with `Parallel.ForEachAsync` at `MaxParallelSessionCloses`, a compile-time constant of `4` in `SessionManager`. Each close is bounded by `MxGateway:Worker:ShutdownTimeoutSeconds` (default 10), so a one-at-a-time sweep lets a few hung workers serialize reaping and starve session slots for the rest. Parallel closing is safe because `TryBeginCloseIfExpired` already flipped each selected session to `Closing` under its own lock — that idempotent begin-close is the per-session exclusivity invariant, so no two teardowns can ever run against one session. The degree is a fixed constant rather than an option, and bounded rather than unlimited, because every concurrent close is one x86 worker process being shut down or killed; the fan-out exists to hide a few hung workers, not to tear the whole registry down at once.
@@ -256,7 +264,7 @@ Mechanically: when the last external subscriber detaches and `DetachGraceSeconds
#### Worker exit outside a gateway close
`IWorkerClient` has no state-change callback, so a worker that reached `Closed` or `Faulted` *without the gateway closing it* — the client sent the `ShutdownWorker` control command and the worker exited cleanly, the worker crashed, its pipe broke, a heartbeat timed out — used to leave the session reporting `Ready` until its lease expired (a live finding: `WorkerClient` was `Closed` on the shutdown ack, the session still `Ready`, even with an event stream attached). The session now observes it from its own worker-event pump source (`MapWorkerEventsAsync`): the single distributor pump is the session's one always-on view of the worker (it runs from `MarkReady` via the dashboard mirror), and `WorkerClient` enters its terminal state *before* it completes the event channel, so when the enumeration ends the terminal state is visible. `ObserveWorkerTerminalState` then faults a `Ready` session whose worker is `Closed`/`Faulted`. The pump also calls it when its first readiness check (`GetReadyWorkerClientAsync`) fails. A worker that dies between the open's attach and the pump's first read never reaches the event enumeration, so its `finally` never runs. Without that second call the session would stay `Ready` over the dead worker until its lease expired.
`IWorkerClient` has no state-change callback, so a worker that reached `Closed` or `Faulted` *without the gateway closing it* — the client sent the `ShutdownWorker` control command and the worker exited cleanly, the worker crashed, its pipe broke, a heartbeat timed out — used to leave the session reporting `Ready` until its lease expired (a live finding: `WorkerClient` was `Closed` on the shutdown ack, the session still `Ready`, even with an event stream attached). The session now observes it from its own worker-event pump source (`MapWorkerEventsAsync`): the single distributor pump is the session's one always-on view of the worker (it runs from `MarkReady` when a dashboard broadcaster is configured), and `WorkerClient` enters its terminal state *before* it completes the event channel, so when the enumeration ends the terminal state is visible. `ObserveWorkerTerminalState` then faults a `Ready` session whose worker is `Closed`/`Faulted`. The pump also calls it when its first readiness check (`GetReadyWorkerClientAsync`) fails. A worker that dies between the open's attach and the pump's first read never reaches the event enumeration, so its `finally` never runs. Without that second call the session would stay `Ready` over the dead worker until its lease expired.
The choice is **`Faulted`, not `Closed`**: `Closed` means the gateway closed the session, and a `Closed` session left in the registry would linger until its lease expired with nothing reaping it. A faulted session is permanently unusable (every command fails the readiness check, as the worker is gone), stays observable via `GetSessionStatus` with `FinalFault` naming the worker state, and is reaped by the faulted-session sweep below after `FaultedGraceSeconds` — which is where `SessionClosed` is accounted, exactly once, through the ordinary `CloseSessionCoreAsync` path (`WorkerClient.ShutdownAsync` on a `Closed` client returns immediately, so no kill fallback or warning). Only a `Ready` session follows its worker: during a gateway-initiated close the worker closing is the expected outcome, not a fault.
@@ -268,7 +276,7 @@ A session that faults (for example, a slow single-subscriber client that overflo
Detach-grace only helps a session that *had* a subscriber. A client that opens a session and then disappears before it ever calls `StreamEvents` — OtOpcUa's `GalaxyDriver` failing part-way through its start-up is the motivating case — leaves a `Ready` session with no subscriber, no detach timestamp and a lease 30 minutes out, pinning one of `MaxSessions` and a live x86 worker for all of `DefaultLeaseSeconds`. `MxGateway:Sessions:UnattachedSessionGraceSeconds` (default `0`, off) closes that gap: when positive, `CloseExpiredLeasesAsync` also checks `IsUnattachedGraceExpired(now)` and reaps, with the distinct `UnattachedGraceExpiredReason` (`"unattached-grace-expired"`), any `Ready` session that has never had a subscriber of either kind and has been idle for the window.
Four deliberate limits keep the rule from catching legitimate sessions. It applies only to `Ready` sessions, and its idle clock starts at `Ready` (`MarkReady` stamps `_readyAtUtc`), so a slow worker start neither reaps the session mid-startup nor eats the window before the client even has the session id. Idle is measured from the later of that Ready stamp and the session's *last client activity* (its most recent unary command), so a unary-only client (reads and writes, never streams) is not reaped while it keeps calling; the rule is an idle timeout for sessions that never streamed, not a deadline to stream. It stops applying the moment the first subscriber attaches, after which detach-grace and the normal lease govern the session. And an *internal* in-process subscriber counts as attached for this rule (`AttachInternalEventSubscriber` sets a separate `_everHadInternalEventSubscriber` latch): the gateway's own `GatewayAlarmMonitor` session only ever attaches that way, and it must not be reaped by its own gateway every cycle. The latch is separate from `_everHadEventSubscriber` because that one drives detach-grace, which is keyed on external subscribers only. The dashboard mirror, which every session registers at `MarkReady`, is deliberately *not* a subscriber for this rule. The alarm monitor is the only gateway-owned session exempted. The dashboard Browse page's live-data session (`DashboardLiveDataService`) is unary-only: it registers and reads but never attaches a subscriber, so once it has been idle for the window the rule reaps it. That is expected. The service checks its cached session on every call (`EnsureReadyAsync`) and opens and registers a new one when the old one is gone. Like the other sweep conditions it is re-verified inside `TryBeginCloseIfExpired`, so a subscriber that attaches between selection and the close wins the race. Operators should set the window comfortably above a well-behaved client's open-to-first-`StreamEvents` time; the close lands on the next sweep after the window elapses, up to `LeaseSweepIntervalSeconds` later.
Four deliberate limits keep the rule from catching legitimate sessions. It applies only to `Ready` sessions, and its idle clock starts at `Ready` (`MarkReady` stamps `_readyAtUtc`), so a slow worker start neither reaps the session mid-startup nor eats the window before the client even has the session id. Idle is measured from the later of that Ready stamp and the session's *last client activity* (its most recent unary command), so a unary-only client (reads and writes, never streams) is not reaped while it keeps calling; the rule is an idle timeout for sessions that never streamed, not a deadline to stream. It stops applying the moment the first subscriber attaches, after which detach-grace and the normal lease govern the session. And an *internal* in-process subscriber counts as attached for this rule (`AttachInternalEventSubscriber` sets a separate `_everHadInternalEventSubscriber` latch): the gateway's own `GatewayAlarmMonitor` session only ever attaches that way, and it must not be reaped by its own gateway every cycle. The latch is separate from `_everHadEventSubscriber` because that one drives detach-grace, which is keyed on external subscribers only. The dashboard mirror, which a session registers while a dashboard viewer watches it, is deliberately *not* a subscriber for this rule. The alarm monitor is the only gateway-owned session exempted. The dashboard Browse page's live-data session (`DashboardLiveDataService`) is unary-only: it registers and reads but never attaches a subscriber, so once it has been idle for the window the rule reaps it. That is expected. The service checks its cached session on every call (`EnsureReadyAsync`) and opens and registers a new one when the old one is gone. Like the other sweep conditions it is re-verified inside `TryBeginCloseIfExpired`, so a subscriber that attaches between selection and the close wins the race. Operators should set the window comfortably above a well-behaved client's open-to-first-`StreamEvents` time; the close lands on the next sweep after the window elapses, up to `LeaseSweepIntervalSeconds` later.
#### Reconnect and replay
+5 -3
View File
@@ -152,16 +152,18 @@ The monitor consumes its session's events as an **internal distributor
subscriber** (`GatewaySession.AttachInternalEventSubscriber`), not by draining
the worker event channel directly. The single worker event channel therefore has
exactly one reader — the per-session `SessionEventDistributor` pump — which fans
every event to both the dashboard mirror and the alarm feed; the alarm subscriber
events to the dashboard mirror and the alarm feed; the alarm subscriber
is internal (`isInternal: true`), so it is not counted against
`MaxEventSubscribersPerSession` and a slow alarm reconcile can never fault the
session. The worker event channel is single-reader and asserts it (a second
`WorkerClient.ReadEventsAsync` consumer throws), so a regression cannot silently
split the event stream between two drains.
split the event stream between two drains. The monitor's lease carries a
distributor-side filter that admits only `OnAlarmTransition` and
`OnAlarmProviderModeChanged`, so data changes on its session never wake it.
The monitor takes that internal lease **before** it sends `SubscribeAlarms`, and
drains it after the first reconcile. The pump is already running by then (the
dashboard mirror starts it at `MarkReady`) and the distributor fans only to
session starts it at `MarkReady`) and the distributor fans only to
subscribers registered at fan-out time, so attaching after the subscribe +
reconcile round trips would drop every transition raised in that window —
including an `Acknowledge`, which the presence-only reconcile deltas would never
@@ -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;