fix(dashboard): bound EventsHub delivery with one drop-oldest pump per session
Publish fired a group SendAsync per event and returned, so a slow remote viewer accumulated unbounded pending sends plus cloned MxEvents. Hub delivery now goes through a 256-deep DropOldest channel per hub-watched session with a single drain task and time-bounded sends. The registry counts hub viewers separately and raises HubViewersReleased so the pump is torn down with the last remote viewer; in-process-only sessions start no pump.
This commit is contained in:
+219
-54
@@ -12,7 +12,8 @@ namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;
|
||||
/// <c>MxGateway:Dashboard:ShowTagValues</c>: tag values are stripped
|
||||
/// from the mirrored copy when the flag is off, present when it is on, and the
|
||||
/// shared source event is never mutated. Also verifies the viewer gate — the
|
||||
/// mirror does no work at all for a session nobody is watching.
|
||||
/// mirror does no work at all for a session nobody is watching, and that hub
|
||||
/// delivery goes through one bounded drop-oldest pump per hub-watched session.
|
||||
/// </summary>
|
||||
public sealed class DashboardEventBroadcasterTests
|
||||
{
|
||||
@@ -22,11 +23,12 @@ public sealed class DashboardEventBroadcasterTests
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
EventsHubViewerRegistry viewers = new();
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
MxEvent source = BuildEventWithValue();
|
||||
|
||||
broadcaster.Publish("session-1", source);
|
||||
|
||||
Assert.Equal(0, broadcaster.ActiveHubPumpCount);
|
||||
Assert.Equal(0, hubContext.SendCount);
|
||||
Assert.Null(hubContext.LastArgument);
|
||||
}
|
||||
@@ -38,40 +40,105 @@ public sealed class DashboardEventBroadcasterTests
|
||||
CapturingHubContext hubContext = new();
|
||||
EventsHubViewerRegistry viewers = new();
|
||||
viewers.AddViewer("conn-1", "session-2");
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
|
||||
broadcaster.Publish("session-1", BuildEventWithValue());
|
||||
|
||||
Assert.Equal(0, broadcaster.ActiveHubPumpCount);
|
||||
Assert.Equal(0, hubContext.SendCount);
|
||||
}
|
||||
|
||||
/// <summary>Once the last viewer leaves, the mirror stops sending again.</summary>
|
||||
/// <summary>Once the last hub viewer leaves, the session's pump is torn down and sending stops.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public void Publish_AfterLastViewerLeaves_StopsSending()
|
||||
public async Task Publish_AfterLastViewerLeaves_StopsSending()
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
EventsHubViewerRegistry viewers = new();
|
||||
viewers.AddViewer("conn-1", "session-1");
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
|
||||
broadcaster.Publish("session-1", BuildEventWithValue());
|
||||
Assert.Equal(1, hubContext.SendCount);
|
||||
await hubContext.WaitForSendCountAsync(1);
|
||||
Assert.Equal(1, broadcaster.ActiveHubPumpCount);
|
||||
|
||||
viewers.RemoveViewer("conn-1", "session-1");
|
||||
Assert.Equal(0, broadcaster.ActiveHubPumpCount);
|
||||
|
||||
broadcaster.Publish("session-1", BuildEventWithValue());
|
||||
|
||||
Assert.Equal(0, broadcaster.ActiveHubPumpCount);
|
||||
Assert.Equal(1, hubContext.SendCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A hub viewer that cannot keep up costs a bounded queue, not an unbounded pile of
|
||||
/// pending sends: while one send is stuck, further events drop oldest-first at the
|
||||
/// pump's capacity, only one send is ever in flight, and the newest event survives.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Publish_WhenHubSendStalls_BuffersAtMostTheCapacityAndKeepsTheNewest()
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
hubContext.Proxy.Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
EventsHubViewerRegistry viewers = WatchedSession1();
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: true, viewers);
|
||||
const int published = 2000;
|
||||
|
||||
broadcaster.Publish("session-1", BuildSequencedEvent(0));
|
||||
await hubContext.WaitForSendCountAsync(1);
|
||||
for (int i = 1; i < published; i++)
|
||||
{
|
||||
broadcaster.Publish("session-1", BuildSequencedEvent(i));
|
||||
}
|
||||
|
||||
// One send stuck in flight, nothing else started behind it.
|
||||
Assert.Equal(1, hubContext.SendCount);
|
||||
Assert.Equal(1, hubContext.Proxy.MaxConcurrentSends);
|
||||
|
||||
hubContext.Proxy.Gate.SetResult();
|
||||
await hubContext.WaitForLastItemHandleAsync(published - 1);
|
||||
|
||||
// The stuck event plus at most one full queue — the rest were dropped oldest-first.
|
||||
Assert.InRange(hubContext.SendCount, 2, DashboardEventBroadcaster.HubQueueCapacity + 1);
|
||||
Assert.Equal(1, hubContext.Proxy.MaxConcurrentSends);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A send that never completes is abandoned at the send timeout, so one stuck
|
||||
/// connection cannot stop the pump delivering later events.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Publish_WhenHubSendNeverCompletes_AbandonsItAtTheTimeoutAndContinues()
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
hubContext.Proxy.Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
hubContext.Proxy.IgnoreCancellation = true;
|
||||
using DashboardEventBroadcaster broadcaster = Create(
|
||||
hubContext,
|
||||
showTagValues: true,
|
||||
WatchedSession1(),
|
||||
hubSendTimeout: TimeSpan.FromMilliseconds(50));
|
||||
|
||||
broadcaster.Publish("session-1", BuildSequencedEvent(1));
|
||||
broadcaster.Publish("session-1", BuildSequencedEvent(2));
|
||||
|
||||
await hubContext.WaitForSendCountAsync(2);
|
||||
}
|
||||
|
||||
/// <summary>Values are stripped from the mirror when ShowTagValues is off; metadata survives.</summary>
|
||||
[Fact]
|
||||
public void Publish_WhenShowTagValuesFalse_RedactsValuesButKeepsMetadata()
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task Publish_WhenShowTagValuesFalse_RedactsValuesButKeepsMetadata()
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, WatchedSession1());
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, WatchedSession1());
|
||||
MxEvent source = BuildEventWithValue();
|
||||
|
||||
broadcaster.Publish("session-1", source);
|
||||
await hubContext.WaitForSendCountAsync(1);
|
||||
|
||||
MxEvent sent = Assert.IsType<MxEvent>(hubContext.LastArgument);
|
||||
Assert.Null(sent.Value);
|
||||
@@ -88,13 +155,15 @@ public sealed class DashboardEventBroadcasterTests
|
||||
|
||||
/// <summary>Redaction applies to a clone, so the shared source event keeps its values.</summary>
|
||||
[Fact]
|
||||
public void Publish_WhenShowTagValuesFalse_DoesNotMutateSourceEvent()
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task Publish_WhenShowTagValuesFalse_DoesNotMutateSourceEvent()
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, WatchedSession1());
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, WatchedSession1());
|
||||
MxEvent source = BuildEventWithValue();
|
||||
|
||||
broadcaster.Publish("session-1", source);
|
||||
await hubContext.WaitForSendCountAsync(1);
|
||||
|
||||
// The redaction must apply to a clone; the shared source keeps its values.
|
||||
Assert.NotNull(source.Value);
|
||||
@@ -106,13 +175,15 @@ public sealed class DashboardEventBroadcasterTests
|
||||
|
||||
/// <summary>Values pass through unredacted when ShowTagValues is on.</summary>
|
||||
[Fact]
|
||||
public void Publish_WhenShowTagValuesTrue_KeepsValues()
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task Publish_WhenShowTagValuesTrue_KeepsValues()
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: true, WatchedSession1());
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: true, WatchedSession1());
|
||||
MxEvent source = BuildEventWithValue();
|
||||
|
||||
broadcaster.Publish("session-1", source);
|
||||
await hubContext.WaitForSendCountAsync(1);
|
||||
|
||||
MxEvent sent = Assert.IsType<MxEvent>(hubContext.LastArgument);
|
||||
Assert.NotNull(sent.Value);
|
||||
@@ -125,16 +196,18 @@ public sealed class DashboardEventBroadcasterTests
|
||||
/// An in-process subscriber gets the same redacted clone the hub group gets,
|
||||
/// and the shared source event is still left untouched.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public void Subscribe_WhenShowTagValuesFalse_DeliversRedactedCloneWithoutMutatingSource()
|
||||
public async Task Subscribe_WhenShowTagValuesFalse_DeliversRedactedCloneWithoutMutatingSource()
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
EventsHubViewerRegistry viewers = new();
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
EventsHubViewerRegistry viewers = WatchedSession1();
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
using IDashboardEventSubscription subscription = broadcaster.Subscribe("session-1");
|
||||
MxEvent source = BuildEventWithValue();
|
||||
|
||||
broadcaster.Publish("session-1", source);
|
||||
await hubContext.WaitForSendCountAsync(1);
|
||||
|
||||
MxEvent received = ReadOne(subscription);
|
||||
Assert.Null(received.Value);
|
||||
@@ -153,17 +226,16 @@ public sealed class DashboardEventBroadcasterTests
|
||||
Assert.NotNull(source.OnAlarmTransition.LimitValue);
|
||||
}
|
||||
|
||||
/// <summary>An in-process subscription opens the viewer gate the same way a hub client does.</summary>
|
||||
/// <summary>
|
||||
/// An in-process subscription opens the viewer gate the same way a hub client does,
|
||||
/// but starts no hub pump: with no remote connection there is nobody to send to.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Subscribe_OpensTheViewerGate()
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
EventsHubViewerRegistry viewers = new();
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
|
||||
broadcaster.Publish("session-1", BuildEventWithValue());
|
||||
Assert.Equal(0, hubContext.SendCount);
|
||||
Assert.Null(hubContext.LastArgument);
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
|
||||
using IDashboardEventSubscription subscription = broadcaster.Subscribe("session-1");
|
||||
|
||||
@@ -171,8 +243,9 @@ public sealed class DashboardEventBroadcasterTests
|
||||
|
||||
broadcaster.Publish("session-1", BuildEventWithValue());
|
||||
|
||||
Assert.Equal(1, hubContext.SendCount);
|
||||
Assert.NotNull(hubContext.LastArgument);
|
||||
Assert.Equal("session-1", ReadOne(subscription).SessionId);
|
||||
Assert.Equal(0, broadcaster.ActiveHubPumpCount);
|
||||
Assert.Equal(0, hubContext.SendCount);
|
||||
}
|
||||
|
||||
/// <summary>Disposing the last in-process subscription restores the no-viewers short-circuit.</summary>
|
||||
@@ -181,11 +254,10 @@ public sealed class DashboardEventBroadcasterTests
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
EventsHubViewerRegistry viewers = new();
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
IDashboardEventSubscription subscription = broadcaster.Subscribe("session-1");
|
||||
|
||||
broadcaster.Publish("session-1", BuildEventWithValue());
|
||||
Assert.Equal(1, hubContext.SendCount);
|
||||
Assert.Equal("session-1", ReadOne(subscription).SessionId);
|
||||
|
||||
subscription.Dispose();
|
||||
@@ -194,26 +266,28 @@ public sealed class DashboardEventBroadcasterTests
|
||||
|
||||
broadcaster.Publish("session-1", BuildEventWithValue());
|
||||
|
||||
Assert.Equal(1, hubContext.SendCount);
|
||||
Assert.Equal(0, hubContext.SendCount);
|
||||
Assert.False(subscription.Reader.TryRead(out _));
|
||||
}
|
||||
|
||||
/// <summary>Hub viewers and in-process subscribers are audiences of their own session only.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public void Publish_DeliversOnlyToTheSubscribedSessionsAudience()
|
||||
public async Task Publish_DeliversOnlyToTheSubscribedSessionsAudience()
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
EventsHubViewerRegistry viewers = new();
|
||||
viewers.AddViewer("conn-1", "session-1");
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
using IDashboardEventSubscription subscription = broadcaster.Subscribe("session-2");
|
||||
|
||||
// The hub viewer's session must not spill into the in-process feed.
|
||||
broadcaster.Publish("session-1", BuildEventWithValue());
|
||||
|
||||
Assert.Equal(1, hubContext.SendCount);
|
||||
await hubContext.WaitForSendCountAsync(1);
|
||||
Assert.False(subscription.Reader.TryRead(out _));
|
||||
|
||||
// The in-process-only session reaches its subscriber and starts no hub pump.
|
||||
broadcaster.Publish("session-2", BuildEventWithValue("session-2"));
|
||||
|
||||
Assert.Equal("session-2", ReadOne(subscription).SessionId);
|
||||
@@ -221,7 +295,8 @@ public sealed class DashboardEventBroadcasterTests
|
||||
// A session with no audience at all still short-circuits.
|
||||
broadcaster.Publish("session-3", BuildEventWithValue("session-3"));
|
||||
|
||||
Assert.Equal(2, hubContext.SendCount);
|
||||
Assert.Equal(1, broadcaster.ActiveHubPumpCount);
|
||||
Assert.Equal(1, hubContext.SendCount);
|
||||
}
|
||||
|
||||
/// <summary>Disposing twice is a no-op and cannot release a sibling subscription's registration.</summary>
|
||||
@@ -230,7 +305,7 @@ public sealed class DashboardEventBroadcasterTests
|
||||
{
|
||||
CapturingHubContext hubContext = new();
|
||||
EventsHubViewerRegistry viewers = new();
|
||||
DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
using DashboardEventBroadcaster broadcaster = Create(hubContext, showTagValues: false, viewers);
|
||||
IDashboardEventSubscription first = broadcaster.Subscribe("session-1");
|
||||
using IDashboardEventSubscription second = broadcaster.Subscribe("session-1");
|
||||
|
||||
@@ -241,7 +316,6 @@ public sealed class DashboardEventBroadcasterTests
|
||||
|
||||
broadcaster.Publish("session-1", BuildEventWithValue());
|
||||
|
||||
Assert.Equal(1, hubContext.SendCount);
|
||||
Assert.False(first.Reader.TryRead(out _));
|
||||
Assert.Equal("session-1", ReadOne(second).SessionId);
|
||||
}
|
||||
@@ -258,7 +332,8 @@ public sealed class DashboardEventBroadcasterTests
|
||||
private static DashboardEventBroadcaster Create(
|
||||
CapturingHubContext hubContext,
|
||||
bool showTagValues,
|
||||
EventsHubViewerRegistry viewers)
|
||||
EventsHubViewerRegistry viewers,
|
||||
TimeSpan? hubSendTimeout = null)
|
||||
{
|
||||
GatewayOptions gatewayOptions = new()
|
||||
{
|
||||
@@ -269,7 +344,21 @@ public sealed class DashboardEventBroadcasterTests
|
||||
hubContext,
|
||||
viewers,
|
||||
Options.Create(gatewayOptions),
|
||||
NullLogger<DashboardEventBroadcaster>.Instance);
|
||||
NullLogger<DashboardEventBroadcaster>.Instance,
|
||||
hubSendTimeout ?? TimeSpan.FromSeconds(30));
|
||||
}
|
||||
|
||||
/// <summary>Builds a value-less event whose item handle carries its publish order.</summary>
|
||||
/// <param name="sequence">Publish order stamped into <see cref="MxEvent.ItemHandle"/>.</param>
|
||||
/// <returns>The event.</returns>
|
||||
private static MxEvent BuildSequencedEvent(int sequence)
|
||||
{
|
||||
return new MxEvent
|
||||
{
|
||||
Family = MxEventFamily.OnDataChange,
|
||||
SessionId = "session-1",
|
||||
ItemHandle = sequence,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A registry with one hub connection watching <c>session-1</c>.</summary>
|
||||
@@ -313,81 +402,157 @@ public sealed class DashboardEventBroadcasterTests
|
||||
/// <summary>Gets the group manager.</summary>
|
||||
public IGroupManager Groups { get; } = new NoopGroupManager();
|
||||
|
||||
/// <summary>Gets the capturing proxy every client lookup resolves to.</summary>
|
||||
public CapturingClientProxy Proxy => _clients.Proxy;
|
||||
|
||||
/// <summary>Gets the first argument of the most recent send call.</summary>
|
||||
public object? LastArgument => _clients.GroupProxy.LastArgument;
|
||||
public object? LastArgument => _clients.Proxy.LastArgument;
|
||||
|
||||
/// <summary>Gets the number of send calls this fake has observed.</summary>
|
||||
public int SendCount => _clients.GroupProxy.SendCount;
|
||||
public int SendCount => _clients.Proxy.SendCount;
|
||||
|
||||
/// <summary>Waits until at least <paramref name="count"/> sends have started.</summary>
|
||||
/// <param name="count">The send count to wait for.</param>
|
||||
/// <returns>A task that completes once the count is reached.</returns>
|
||||
public Task WaitForSendCountAsync(int count) =>
|
||||
WaitUntilAsync(() => SendCount >= count, $"{count} sends (saw {SendCount})");
|
||||
|
||||
/// <summary>Waits until a send carrying the given item handle has started.</summary>
|
||||
/// <param name="itemHandle">Item handle of the event to wait for.</param>
|
||||
/// <returns>A task that completes once the event was sent.</returns>
|
||||
public Task WaitForLastItemHandleAsync(int itemHandle) =>
|
||||
WaitUntilAsync(
|
||||
() => LastArgument is MxEvent sent && sent.ItemHandle == itemHandle,
|
||||
$"a send of item handle {itemHandle}");
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition, string description)
|
||||
{
|
||||
DateTime deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Timed out waiting for {description}.");
|
||||
}
|
||||
|
||||
await Task.Delay(5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CapturingHubClients : IHubClients
|
||||
{
|
||||
/// <summary>Gets the capturing client proxy shared by this fake.</summary>
|
||||
public CapturingClientProxy GroupProxy { get; } = new();
|
||||
public CapturingClientProxy Proxy { get; } = new();
|
||||
|
||||
/// <summary>Gets the shared capturing proxy for all connections.</summary>
|
||||
public IClientProxy All => GroupProxy;
|
||||
public IClientProxy All => Proxy;
|
||||
|
||||
/// <summary>Returns the shared capturing proxy, ignoring exclusions.</summary>
|
||||
/// <param name="excludedConnectionIds">Ignored.</param>
|
||||
/// <returns>The shared capturing proxy.</returns>
|
||||
public IClientProxy AllExcept(IReadOnlyList<string> excludedConnectionIds) => GroupProxy;
|
||||
public IClientProxy AllExcept(IReadOnlyList<string> excludedConnectionIds) => Proxy;
|
||||
|
||||
/// <summary>Returns the shared capturing proxy for any connection.</summary>
|
||||
/// <param name="connectionId">Ignored.</param>
|
||||
/// <returns>The shared capturing proxy.</returns>
|
||||
public IClientProxy Client(string connectionId) => GroupProxy;
|
||||
public IClientProxy Client(string connectionId) => Proxy;
|
||||
|
||||
/// <summary>Returns the shared capturing proxy for any connection set.</summary>
|
||||
/// <param name="connectionIds">Ignored.</param>
|
||||
/// <returns>The shared capturing proxy.</returns>
|
||||
public IClientProxy Clients(IReadOnlyList<string> connectionIds) => GroupProxy;
|
||||
public IClientProxy Clients(IReadOnlyList<string> connectionIds) => Proxy;
|
||||
|
||||
/// <summary>Returns the shared capturing proxy for any group.</summary>
|
||||
/// <param name="groupName">Ignored.</param>
|
||||
/// <returns>The shared capturing proxy.</returns>
|
||||
public IClientProxy Group(string groupName) => GroupProxy;
|
||||
public IClientProxy Group(string groupName) => Proxy;
|
||||
|
||||
/// <summary>Returns the shared capturing proxy for any group, ignoring exclusions.</summary>
|
||||
/// <param name="groupName">Ignored.</param>
|
||||
/// <param name="excludedConnectionIds">Ignored.</param>
|
||||
/// <returns>The shared capturing proxy.</returns>
|
||||
public IClientProxy GroupExcept(string groupName, IReadOnlyList<string> excludedConnectionIds) => GroupProxy;
|
||||
public IClientProxy GroupExcept(string groupName, IReadOnlyList<string> excludedConnectionIds) => Proxy;
|
||||
|
||||
/// <summary>Returns the shared capturing proxy for any group set.</summary>
|
||||
/// <param name="groupNames">Ignored.</param>
|
||||
/// <returns>The shared capturing proxy.</returns>
|
||||
public IClientProxy Groups(IReadOnlyList<string> groupNames) => GroupProxy;
|
||||
public IClientProxy Groups(IReadOnlyList<string> groupNames) => Proxy;
|
||||
|
||||
/// <summary>Returns the shared capturing proxy for any user.</summary>
|
||||
/// <param name="userId">Ignored.</param>
|
||||
/// <returns>The shared capturing proxy.</returns>
|
||||
public IClientProxy User(string userId) => GroupProxy;
|
||||
public IClientProxy User(string userId) => Proxy;
|
||||
|
||||
/// <summary>Returns the shared capturing proxy for any user set.</summary>
|
||||
/// <param name="userIds">Ignored.</param>
|
||||
/// <returns>The shared capturing proxy.</returns>
|
||||
public IClientProxy Users(IReadOnlyList<string> userIds) => GroupProxy;
|
||||
public IClientProxy Users(IReadOnlyList<string> userIds) => Proxy;
|
||||
}
|
||||
|
||||
private sealed class CapturingClientProxy : IClientProxy
|
||||
{
|
||||
private int _sendCount;
|
||||
private int _inFlight;
|
||||
private int _maxConcurrentSends;
|
||||
private object? _lastArgument;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a gate every send waits on before completing; null completes
|
||||
/// sends synchronously. Set it before the first publish.
|
||||
/// </summary>
|
||||
public TaskCompletionSource? Gate { get; set; }
|
||||
|
||||
/// <summary>Gets or sets a value indicating whether a gated send ignores its cancellation token.</summary>
|
||||
public bool IgnoreCancellation { get; set; }
|
||||
|
||||
/// <summary>Gets the first argument of the most recent send call.</summary>
|
||||
public object? LastArgument { get; private set; }
|
||||
public object? LastArgument => Volatile.Read(ref _lastArgument);
|
||||
|
||||
/// <summary>Gets the number of send calls made through this proxy.</summary>
|
||||
public int SendCount { get; private set; }
|
||||
public int SendCount => Volatile.Read(ref _sendCount);
|
||||
|
||||
/// <summary>Records the send call arguments and completes synchronously.</summary>
|
||||
/// <summary>Gets the highest number of sends that were in flight at once.</summary>
|
||||
public int MaxConcurrentSends => Volatile.Read(ref _maxConcurrentSends);
|
||||
|
||||
/// <summary>Records the send call arguments and completes once the gate (if any) opens.</summary>
|
||||
/// <param name="method">The SignalR method name.</param>
|
||||
/// <param name="args">The method arguments.</param>
|
||||
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
||||
/// <returns>A completed task.</returns>
|
||||
/// <returns>A task that completes when the send is released.</returns>
|
||||
public Task SendCoreAsync(string method, object?[] args, CancellationToken cancellationToken = default)
|
||||
{
|
||||
SendCount++;
|
||||
LastArgument = args.Length > 0 ? args[0] : null;
|
||||
return Task.CompletedTask;
|
||||
Volatile.Write(ref _lastArgument, args.Length > 0 ? args[0] : null);
|
||||
Interlocked.Increment(ref _sendCount);
|
||||
|
||||
TaskCompletionSource? gate = Gate;
|
||||
if (gate is null || gate.Task.IsCompleted)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
return TrackAsync(gate.Task, IgnoreCancellation ? CancellationToken.None : cancellationToken);
|
||||
}
|
||||
|
||||
private async Task TrackAsync(Task gate, CancellationToken cancellationToken)
|
||||
{
|
||||
int inFlight = Interlocked.Increment(ref _inFlight);
|
||||
int observed;
|
||||
do
|
||||
{
|
||||
observed = Volatile.Read(ref _maxConcurrentSends);
|
||||
}
|
||||
while (inFlight > observed
|
||||
&& Interlocked.CompareExchange(ref _maxConcurrentSends, inFlight, observed) != observed);
|
||||
|
||||
try
|
||||
{
|
||||
await gate.WaitAsync(cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Decrement(ref _inFlight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -164,4 +164,48 @@ public sealed class EventsHubViewerRegistryTests
|
||||
|
||||
Assert.False(registry.HasViewers("session-1"));
|
||||
}
|
||||
|
||||
/// <summary>In-process subscribers count as viewers but not as hub viewers.</summary>
|
||||
[Fact]
|
||||
public void HasHubViewers_CountsOnlyRemoteConnections()
|
||||
{
|
||||
EventsHubViewerRegistry registry = new();
|
||||
|
||||
registry.AddViewer(EventsHubViewerRegistry.InProcessConnectionIdPrefix + "a", "session-1");
|
||||
|
||||
Assert.True(registry.HasViewers("session-1"));
|
||||
Assert.False(registry.HasHubViewers("session-1"));
|
||||
|
||||
registry.AddViewer("conn-1", "session-1");
|
||||
|
||||
Assert.True(registry.HasHubViewers("session-1"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The released event fires once, when the last hub viewer leaves — whether it
|
||||
/// unsubscribes or disconnects — and never for in-process subscribers.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void HubViewersReleased_FiresWhenTheLastHubViewerLeaves()
|
||||
{
|
||||
EventsHubViewerRegistry registry = new();
|
||||
List<string> released = [];
|
||||
registry.HubViewersReleased += released.Add;
|
||||
|
||||
registry.AddViewer("conn-1", "session-1");
|
||||
registry.AddViewer("conn-2", "session-1");
|
||||
registry.AddViewer(EventsHubViewerRegistry.InProcessConnectionIdPrefix + "a", "session-1");
|
||||
|
||||
registry.RemoveViewer("conn-1", "session-1");
|
||||
Assert.Empty(released);
|
||||
|
||||
registry.ReleaseConnection("conn-2");
|
||||
Assert.Equal(["session-1"], released);
|
||||
Assert.False(registry.HasHubViewers("session-1"));
|
||||
|
||||
// The in-process subscriber still keeps the session watched, and leaving raises nothing.
|
||||
Assert.True(registry.HasViewers("session-1"));
|
||||
registry.RemoveViewer(EventsHubViewerRegistry.InProcessConnectionIdPrefix + "a", "session-1");
|
||||
Assert.Equal(["session-1"], released);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user