fix(galaxy): #991 G-5 the per-event subscriber lookup no longer allocates and the pump reuses one handle per subscription
This commit is contained in:
@@ -608,7 +608,7 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
var snapshot = ToSnapshot(ev);
|
||||
foreach (var (subscriptionId, fullReference) in subscribers)
|
||||
{
|
||||
var handle = _handleFactory(subscriptionId);
|
||||
var handle = HandleFor(subscriptionId);
|
||||
try
|
||||
{
|
||||
OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, fullReference, snapshot));
|
||||
@@ -622,6 +622,21 @@ internal sealed class EventPump : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
// #991 G-5: one handle object per subscription instead of one per subscriber per event. Touched only by the
|
||||
// dispatch thread (every FanOut runs there), so it needs no lock. Subscription ids are never reused, and
|
||||
// subscribe-once reads mint one each, so the cache is simply dropped when it grows past the bound.
|
||||
private readonly Dictionary<long, ISubscriptionHandle> _handleCache = [];
|
||||
private const int HandleCacheBound = 4_096;
|
||||
|
||||
private ISubscriptionHandle HandleFor(long subscriptionId)
|
||||
{
|
||||
if (_handleCache.TryGetValue(subscriptionId, out var cached)) return cached;
|
||||
if (_handleCache.Count >= HandleCacheBound) _handleCache.Clear();
|
||||
var created = _handleFactory(subscriptionId);
|
||||
_handleCache[subscriptionId] = created;
|
||||
return created;
|
||||
}
|
||||
|
||||
private DataValueSnapshot ToSnapshot(MxEvent ev)
|
||||
{
|
||||
if (!MxValueDecoder.TryDecode(ev.Value, out var value))
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Immutable;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
@@ -31,7 +30,10 @@ internal sealed class SubscriptionRegistry
|
||||
public const long ProbeSubscriptionId = -1;
|
||||
|
||||
private readonly ConcurrentDictionary<long, SubscriptionEntry> _bySubscriptionId = new();
|
||||
private readonly ConcurrentDictionary<int, ImmutableHashSet<long>> _subscribersByItemHandle = new();
|
||||
// #991 G-5: each item handle's subscribers as a pre-built, never-mutated array — rebuilt (copy-on-write, under
|
||||
// _parkGate) only when a subscription binds or unbinds, so the per-event lookup on the dispatch thread hands the
|
||||
// array out as-is instead of allocating a list, a LINQ Distinct and a boxed set enumerator per event.
|
||||
private readonly ConcurrentDictionary<int, (long SubscriptionId, string FullReference)[]> _subscribersByItemHandle = new();
|
||||
private long _nextSubscriptionId;
|
||||
|
||||
/// <summary>True when <paramref name="subscriptionId"/> is currently registered.</summary>
|
||||
@@ -154,14 +156,15 @@ internal sealed class SubscriptionRegistry
|
||||
return BindOutcome.UnknownId;
|
||||
}
|
||||
|
||||
_bySubscriptionId[subscriptionId] = new SubscriptionEntry(subscriptionId, bindings, _session);
|
||||
foreach (var binding in bindings)
|
||||
var entry = new SubscriptionEntry(subscriptionId, bindings, _session);
|
||||
_bySubscriptionId[subscriptionId] = entry;
|
||||
// The entry's index holds each positive handle once (failed gw subscribes — handle <= 0 — expect no
|
||||
// events), with the subscription's reference for it.
|
||||
foreach (var (itemHandle, fullRef) in entry.FullRefByItemHandle)
|
||||
{
|
||||
if (binding.ItemHandle <= 0) continue; // failed gw subscribe — no events expected
|
||||
_subscribersByItemHandle.AddOrUpdate(
|
||||
binding.ItemHandle,
|
||||
_ => [subscriptionId],
|
||||
(_, set) => set.Add(subscriptionId));
|
||||
_subscribersByItemHandle[itemHandle] = _subscribersByItemHandle.TryGetValue(itemHandle, out var current)
|
||||
? WithSubscriber(current, subscriptionId, fullRef)
|
||||
: [(subscriptionId, fullRef)];
|
||||
}
|
||||
AfterMapWriteForTests?.Invoke();
|
||||
promoted = PromoteParkedEventsLocked(bindings);
|
||||
@@ -172,19 +175,32 @@ internal sealed class SubscriptionRegistry
|
||||
|
||||
private void RemoveFromReverseMap(SubscriptionEntry entry)
|
||||
{
|
||||
foreach (var binding in entry.Bindings)
|
||||
foreach (var itemHandle in entry.FullRefByItemHandle.Keys)
|
||||
{
|
||||
if (binding.ItemHandle <= 0) continue;
|
||||
if (!_subscribersByItemHandle.TryGetValue(binding.ItemHandle, out var set)) continue;
|
||||
var remaining = set.Remove(entry.SubscriptionId);
|
||||
if (remaining.IsEmpty)
|
||||
{
|
||||
_subscribersByItemHandle.TryRemove(binding.ItemHandle, out _);
|
||||
}
|
||||
else _subscribersByItemHandle[binding.ItemHandle] = remaining;
|
||||
if (!_subscribersByItemHandle.TryGetValue(itemHandle, out var current)) continue;
|
||||
var remaining = Array.FindAll(current, s => s.SubscriptionId != entry.SubscriptionId);
|
||||
if (remaining.Length == 0) _subscribersByItemHandle.TryRemove(itemHandle, out _);
|
||||
else if (remaining.Length != current.Length) _subscribersByItemHandle[itemHandle] = remaining;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A copy of <paramref name="current"/> with <paramref name="subscriptionId"/> set to <paramref name="fullRef"/>.</summary>
|
||||
private static (long SubscriptionId, string FullReference)[] WithSubscriber(
|
||||
(long SubscriptionId, string FullReference)[] current, long subscriptionId, string fullRef)
|
||||
{
|
||||
var index = Array.FindIndex(current, s => s.SubscriptionId == subscriptionId);
|
||||
if (index >= 0)
|
||||
{
|
||||
var replaced = ((long SubscriptionId, string FullReference)[])current.Clone();
|
||||
replaced[index] = (subscriptionId, fullRef);
|
||||
return replaced;
|
||||
}
|
||||
var grown = new (long SubscriptionId, string FullReference)[current.Length + 1];
|
||||
current.CopyTo(grown, 0);
|
||||
grown[^1] = (subscriptionId, fullRef);
|
||||
return grown;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove a subscription. Returns the bindings the caller should pass to
|
||||
/// <c>UnsubscribeBulkAsync</c>; null when the id was never registered.
|
||||
@@ -220,21 +236,14 @@ internal sealed class SubscriptionRegistry
|
||||
/// </summary>
|
||||
/// <param name="itemHandle">The gateway item handle.</param>
|
||||
/// <returns>A list of subscription and reference pairs for the item handle.</returns>
|
||||
public IReadOnlyList<(long SubscriptionId, string FullReference)> ResolveSubscribers(int itemHandle)
|
||||
{
|
||||
if (!_subscribersByItemHandle.TryGetValue(itemHandle, out var bag)) return [];
|
||||
|
||||
// Each subscription may include the tag once. Walk every active subscription that
|
||||
// claims this handle and pull the full ref from its index in O(1).
|
||||
var result = new List<(long, string)>();
|
||||
foreach (var subId in bag.Distinct())
|
||||
{
|
||||
if (!_bySubscriptionId.TryGetValue(subId, out var entry)) continue;
|
||||
if (entry.FullRefByItemHandle.TryGetValue(itemHandle, out var fullRef))
|
||||
result.Add((subId, fullRef));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/// <remarks>
|
||||
/// Allocation-free (#991 G-5): returns the handle's pre-built subscriber array itself. It is never mutated —
|
||||
/// a bind or unbind publishes a new array — so the caller may enumerate it while the map changes.
|
||||
/// </remarks>
|
||||
public IReadOnlyList<(long SubscriptionId, string FullReference)> ResolveSubscribers(int itemHandle) =>
|
||||
_subscribersByItemHandle.TryGetValue(itemHandle, out var subscribers)
|
||||
? subscribers
|
||||
: Array.Empty<(long SubscriptionId, string FullReference)>();
|
||||
|
||||
/// <summary>
|
||||
/// Drop every subscription and the whole reverse map. Used by the driver's runtime teardown:
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Channels;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-5 — every data-change event used to allocate, in the subscriber lookup alone, a result list, a LINQ
|
||||
/// <c>Distinct</c> iterator with its own hash set, and a boxed immutable-set enumerator, plus a new subscription
|
||||
/// handle per subscriber per event. The reverse map now stores each item handle's subscribers as a pre-built
|
||||
/// array (lookup is allocation-free) and the pump reuses one handle object per subscription.
|
||||
/// </summary>
|
||||
public sealed class FanOutAllocationTests
|
||||
{
|
||||
/// <summary>Resolving a handle's subscribers allocates nothing once the map is built.</summary>
|
||||
[Fact]
|
||||
public void ResolveSubscribers_does_not_allocate()
|
||||
{
|
||||
var registry = new SubscriptionRegistry();
|
||||
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
|
||||
registry.Register(2, [new TagBinding("Tank.Level", 7), new TagBinding("Tank.Temp", 8)]);
|
||||
registry.ResolveSubscribers(7).Count.ShouldBe(2); // warm-up (JIT)
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
var total = 0;
|
||||
for (var i = 0; i < 1_000; i++) total += registry.ResolveSubscribers(7).Count;
|
||||
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
|
||||
total.ShouldBe(2_000);
|
||||
allocated.ShouldBe(0L, "the per-event subscriber lookup must not allocate");
|
||||
}
|
||||
|
||||
/// <summary>Semantics kept: one entry per subscription, the subscription's own reference, removals honoured.</summary>
|
||||
[Fact]
|
||||
public void ResolveSubscribers_keeps_its_semantics()
|
||||
{
|
||||
var registry = new SubscriptionRegistry();
|
||||
registry.Register(1, [new TagBinding("A.X", 5), new TagBinding("A.X", 5)]); // a duplicate binding stays one entry
|
||||
registry.Register(2, [new TagBinding("B.X", 5)]);
|
||||
|
||||
registry.ResolveSubscribers(5).OrderBy(s => s.SubscriptionId).ShouldBe([(1L, "A.X"), (2L, "B.X")]);
|
||||
|
||||
registry.Rebind(1, [new TagBinding("A.X", 6)]);
|
||||
registry.ResolveSubscribers(5).ShouldBe([(2L, "B.X")]);
|
||||
registry.ResolveSubscribers(6).ShouldBe([(1L, "A.X")]);
|
||||
|
||||
registry.Remove(2);
|
||||
registry.ResolveSubscribers(5).ShouldBeEmpty();
|
||||
registry.TrackedItemHandleCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>The pump hands every event of one subscription the same handle instance.</summary>
|
||||
[Fact]
|
||||
public async Task The_pump_reuses_one_handle_per_subscription()
|
||||
{
|
||||
var subscriber = new ChannelSubscriber();
|
||||
var registry = new SubscriptionRegistry();
|
||||
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
|
||||
var handles = new List<ISubscriptionHandle>();
|
||||
var twoSeen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
await using var pump = new EventPump(subscriber, registry, channelCapacity: 8, clientName: "G5");
|
||||
pump.OnDataChange += (_, e) =>
|
||||
{
|
||||
handles.Add(e.SubscriptionHandle);
|
||||
if (handles.Count == 2) twoSeen.TrySetResult();
|
||||
};
|
||||
pump.Start();
|
||||
|
||||
await subscriber.EmitAsync(7, 1.0);
|
||||
await subscriber.EmitAsync(7, 2.0);
|
||||
await TestWait.ForAsync(twoSeen.Task, "both events must be dispatched");
|
||||
|
||||
handles[1].ShouldBeSameAs(handles[0]);
|
||||
((GalaxySubscriptionHandle)handles[0]).SubscriptionId.ShouldBe(1);
|
||||
}
|
||||
|
||||
private sealed class ChannelSubscriber : IGalaxySubscriber
|
||||
{
|
||||
private readonly Channel<MxEvent> _events = Channel.CreateUnbounded<MxEvent>();
|
||||
|
||||
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
|
||||
IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
|
||||
=> Task.FromResult<IReadOnlyList<SubscribeResult>>([]);
|
||||
|
||||
public Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
|
||||
public async IAsyncEnumerable<MxEvent> StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
await foreach (var ev in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
yield return ev;
|
||||
}
|
||||
|
||||
public ValueTask EmitAsync(int handle, double value) => _events.Writer.WriteAsync(new MxEvent
|
||||
{
|
||||
Family = MxEventFamily.OnDataChange,
|
||||
ItemHandle = handle,
|
||||
Value = new MxValue { DoubleValue = value },
|
||||
Quality = 192,
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user