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:
Joseph Doherty
2026-12-03 10:28:36 -05:00
parent 9ba33e7caa
commit d66aa5e9ff
3 changed files with 164 additions and 34 deletions
@@ -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: