feat: add immutable partitioned data publication hub

This commit is contained in:
Joseph Doherty
2026-11-16 01:13:10 -05:00
parent b2249ce2cb
commit 8f28a0eabf
47 changed files with 6184 additions and 173 deletions
@@ -0,0 +1,490 @@
using System.Collections.Concurrent;
using System.Globalization;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Trusted acquisition shape; aliases share this source-level descriptor.</summary>
public readonly record struct SourceValueShape(DataValueKind Kind, DataValueKind? ElementKind, int Rank)
{
public static SourceValueShape FromDriverType(string dataType, bool isArray)
{
var kind = dataType switch
{
"Boolean" or "Bool" => DataValueKind.Boolean,
"SByte" => DataValueKind.Int8, "Byte" => DataValueKind.UInt8,
"Int16" => DataValueKind.Int16, "UInt16" => DataValueKind.UInt16,
"Int32" or "Int" => DataValueKind.Int32, "UInt32" or "UInt" => DataValueKind.UInt32,
"Int64" => DataValueKind.Int64, "UInt64" => DataValueKind.UInt64,
"Float" => DataValueKind.Float, "Double" => DataValueKind.Double,
"String" => DataValueKind.String, "ByteString" => DataValueKind.Bytes,
"DateTime" => DataValueKind.Timestamp, "Guid" => DataValueKind.Guid,
_ => DataValueKind.Unspecified
};
return isArray ? new(DataValueKind.Array, kind, 1) : new(kind, null, -1);
}
}
/// <summary>Constructs acquisition identities independently of catalog views and principals.</summary>
public static class SourceKey
{
public static BackingSourceKey ForDriver(string cluster, string driver, string reference, string node, string incarnation) =>
new(cluster.ToUpperInvariant(), "driver", string.Concat(driver.Length.ToString(CultureInfo.InvariantCulture), ":", driver, reference), node, incarnation);
public static BackingSourceKey ForVirtual(string cluster, string virtualTagId, string node, string incarnation) =>
new(cluster.ToUpperInvariant(), "virtual", virtualTagId, node, incarnation);
internal static bool TryDriver(BackingSourceKey key, out string driver, out string reference)
{
driver = reference = string.Empty;
if (key.SourceKind != "driver") return false;
var colon = key.StableSourceId.IndexOf(':');
if (colon <= 0 || !int.TryParse(key.StableSourceId.AsSpan(0, colon), NumberStyles.None, CultureInfo.InvariantCulture, out var length) ||
length < 0 || length > key.StableSourceId.Length - colon - 1) return false;
driver = key.StableSourceId.Substring(colon + 1, length);
reference = key.StableSourceId[(colon + 1 + length)..];
return true;
}
}
/// <summary>Sequences source data and lifecycle changes before the asynchronous actor boundary.</summary>
public sealed class SourceSamplePublisher
{
private readonly ISourceSampleHub _hub;
private readonly Func<ServingIdentity?> _serving;
private readonly string? _originClusterId;
private readonly object _gate = new();
private readonly Dictionary<BackingSourceKey, SourceTicket> _tickets = new();
private readonly Dictionary<(string Driver, string Reference), BackingSourceKey> _drivers = new();
private readonly Dictionary<string, BackingSourceKey> _virtuals = new(StringComparer.Ordinal);
private sealed class SourceSlot
{
public readonly object Gate = new();
public SourceBinding? Current;
public long Sequence;
public int RepairQueued;
public int RepairAttempts;
}
private sealed class SourceBinding(SourceTicket ticket, SourceSlot slot, ProducerFence? producer, SourceValueShape? shape)
{
public SourceTicket Ticket { get; } = ticket;
public SourceSlot Slot { get; } = slot;
public ProducerFence? Producer { get; } = producer;
public SourceValueShape? Shape { get; } = shape;
public int InFlight;
public bool Active => Producer is null || !Producer.IsRetired;
}
private readonly ConcurrentDictionary<BackingSourceKey, SourceSlot> _slots = new();
private readonly ConcurrentDictionary<(string Driver, string Reference), SourceBinding> _driverRoutes = new();
private readonly Dictionary<(string Driver, string Reference), SourceValueShape> _driverShapes = new();
private const int MaxRegisteredDriverShapes = 100_000;
private const int MaxProducerIncarnations = 100_000;
private readonly ConcurrentDictionary<string, SourceBinding> _virtualRoutes = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ProducerFence> _driverIncarnations = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ProducerFence> _virtualIncarnations = new(StringComparer.Ordinal);
private readonly ConcurrentQueue<SourceSlot> _repairQueue = new();
private const int MaxPendingRepairs = 4096;
private int _repairCount;
private int _repairWorkerScheduled;
private readonly Timer _repairTimer;
private long _nextDriverIncarnation;
public SourceSamplePublisher(ISourceSampleHub hub, ServingIdentity serving) : this(hub, () => serving, null) { }
public SourceSamplePublisher(ISourceSampleHub hub, Func<ServingIdentity?> serving, string? originClusterId = null)
{
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
_serving = serving ?? throw new ArgumentNullException(nameof(serving));
_originClusterId = originClusterId;
_repairTimer = new Timer(static state => ((SourceSamplePublisher)state!).ScheduleRepairWorker(), this,
Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
public SourceTicket Bind(BackingSourceKey key, SourceGeneration generation)
{
var ticket = new SourceTicket(key, generation);
lock (_gate)
{
if (!_slots.TryGetValue(key, out var slot)) slot = new SourceSlot();
lock (slot.Gate)
{
ProducerFence? producer = null;
if (SourceKey.TryDriver(key, out var driver, out var reference))
_driverIncarnations.TryGetValue(driver, out producer);
else if (key.SourceKind == "virtual")
_virtualIncarnations.TryGetValue(key.StableSourceId, out producer);
if (producer is not null && producer.Incarnation != generation.Incarnation) producer = null;
if (!_hub.TryBind(ticket, producer)) throw new InvalidOperationException("The source generation could not be bound.");
_slots.TryAdd(key, slot);
_nextDriverIncarnation = Math.Max(_nextDriverIncarnation, generation.Incarnation);
SourceValueShape? shape = null;
if (SourceKey.TryDriver(key, out var shapeDriver, out var shapeRef) &&
_driverShapes.TryGetValue((shapeDriver, shapeRef), out var registeredShape)) shape = registeredShape;
var binding = new SourceBinding(ticket, slot, producer, shape);
_tickets[key] = ticket;
Volatile.Write(ref slot.Current, binding);
if (SourceKey.TryDriver(key, out driver, out reference))
{
_drivers[(driver, reference)] = key;
_driverRoutes[(driver, reference)] = binding;
}
else if (key.SourceKind == "virtual")
{
_virtuals[key.StableSourceId] = key;
_virtualRoutes[key.StableSourceId] = binding;
}
return ticket;
}
}
}
public bool TryCapture(BackingSourceKey key, out SourceTicket ticket)
{
ticket = default;
if (!_slots.TryGetValue(key, out var slot)) return false;
var binding = Volatile.Read(ref slot.Current);
if (binding is null || !binding.Active) return false;
ticket = binding.Ticket;
return true;
}
public bool TryCaptureDriver(string driver, string reference, out SourceTicket ticket)
{
ticket = default;
if (!_driverRoutes.TryGetValue((driver, reference), out var binding) || !binding.Active ||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
ticket = binding.Ticket;
return true;
}
public bool TryCaptureDriver(string driver, string reference, long incarnation, out SourceTicket ticket)
{
ticket = default;
if (!_driverIncarnations.TryGetValue(driver, out var producer) || producer.Incarnation != incarnation || producer.IsRetired ||
!_driverRoutes.TryGetValue((driver, reference), out var binding) || !ReferenceEquals(binding.Producer, producer) ||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
ticket = binding.Ticket;
return !producer.IsRetired;
}
public long RegisterDriverIncarnation(string driver)
{
lock (_gate)
{
if (!_driverIncarnations.ContainsKey(driver) && _driverIncarnations.Count >= MaxProducerIncarnations)
throw new InvalidOperationException("Driver producer registry is full.");
if (_driverIncarnations.TryGetValue(driver, out var old)) old.Retire();
var token = checked(++_nextDriverIncarnation);
_driverIncarnations[driver] = new ProducerFence(token);
return token;
}
}
public bool IsDriverIncarnationActive(string driver, long incarnation) =>
_driverIncarnations.TryGetValue(driver, out var producer) && producer.Incarnation == incarnation && !producer.IsRetired;
public void RetireCurrentDriver(string driver)
{ if (_driverIncarnations.TryGetValue(driver, out var producer)) RetireDriver(driver, producer.Incarnation); }
public bool RegisterDriverShape(string driver, string reference, SourceValueShape shape)
{
lock (_gate)
{
var key = (driver, reference);
if (_driverShapes.TryGetValue(key, out var old) && old == shape) return true;
if (!_driverShapes.ContainsKey(key) && _driverShapes.Count >= MaxRegisteredDriverShapes) return false;
_driverShapes[key] = shape;
if (_driverRoutes.TryGetValue(key, out var binding)) TryRebind(binding.Ticket, out _);
return true;
}
}
public void ForgetDriverShape(string driver, string reference)
{ lock (_gate) _driverShapes.Remove((driver, reference)); }
public bool EnsureDriverBinding(string cluster, string driver, string reference, long incarnation)
{
// A slow control-plane reconciliation or retirement must not stall legacy acquisition.
if (!Monitor.TryEnter(_gate)) return false;
try
{
if (!_driverIncarnations.TryGetValue(driver, out var producer) || producer.Incarnation != incarnation || producer.IsRetired) return false;
if (!_driverShapes.ContainsKey((driver, reference))) return false;
var serving = _serving();
if (serving is null || string.IsNullOrWhiteSpace(cluster)) return false;
var key = SourceKey.ForDriver(cluster, driver, reference, serving.NodeId, serving.Incarnation);
if (!_slots.TryGetValue(key, out var slot)) return EnsureBinding(key, incarnation);
if (!Monitor.TryEnter(slot.Gate))
{
var binding = Volatile.Read(ref slot.Current);
if (binding?.Producer is { } current && ReferenceEquals(current, producer) && !current.IsRetired)
_hub.Invalidate(binding.Ticket, "source binding contention");
return false;
}
try { return EnsureBinding(key, incarnation); }
finally { Monitor.Exit(slot.Gate); }
}
finally { Monitor.Exit(_gate); }
}
public void RetireDriver(string driver, long incarnation)
{
// The hub sees the same fence. Reads and snapshots are denied before the slow per-tag walk.
if (!_driverIncarnations.TryGetValue(driver, out var producer) || producer.Incarnation != incarnation) return;
producer.Retire();
lock (_gate)
{
if (!_driverIncarnations.TryGetValue(driver, out var current) || !ReferenceEquals(current, producer)) return;
_driverIncarnations.TryRemove(driver, out _);
foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray())
if (_tickets.TryGetValue(key, out var ticket)) TryRemove(ticket);
}
}
public void PublishDriverStatus(string driver, uint status)
{
lock (_gate)
foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray())
if (_tickets.TryGetValue(key, out var ticket)) TryPublishStatus(ticket, status, out _);
}
public bool TryCaptureVirtual(string id, out SourceTicket ticket)
{
ticket = default;
if (!_virtualRoutes.TryGetValue(id, out var binding) || !binding.Active ||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
ticket = binding.Ticket;
return true;
}
public long RegisterVirtualIncarnation(string id)
{
lock (_gate)
{
if (!_virtualIncarnations.ContainsKey(id) && _virtualIncarnations.Count >= MaxProducerIncarnations)
throw new InvalidOperationException("Virtual producer registry is full.");
if (_virtualIncarnations.TryGetValue(id, out var old)) RetireVirtualIncarnation(id, old.Incarnation);
var token = checked(++_nextDriverIncarnation);
_virtualIncarnations[id] = new ProducerFence(token);
return token;
}
}
public bool IsVirtualIncarnationActive(string id, long incarnation) =>
_virtualIncarnations.TryGetValue(id, out var producer) && producer.Incarnation == incarnation && !producer.IsRetired;
public void RetireCurrentVirtual(string id)
{ if (_virtualIncarnations.TryGetValue(id, out var producer)) RetireVirtualIncarnation(id, producer.Incarnation); }
public bool EnsureVirtualBinding(string id, long incarnation)
{
lock (_gate)
{
if (!_virtualIncarnations.TryGetValue(id, out var producer) || producer.Incarnation != incarnation || producer.IsRetired) return false;
var serving = _serving();
if (serving is null) return false;
if (_virtuals.TryGetValue(id, out var existing)) return EnsureBinding(existing, incarnation);
if (string.IsNullOrWhiteSpace(_originClusterId)) return false;
return EnsureBinding(SourceKey.ForVirtual(_originClusterId, id, serving.NodeId, serving.Incarnation), incarnation);
}
}
private bool EnsureBinding(BackingSourceKey key, long incarnation)
{
if (_tickets.TryGetValue(key, out var existing))
{
if (existing.Generation.Incarnation == incarnation && _hub.IsTicketCurrentNonBlocking(existing)) return true;
if (existing.Generation.Incarnation == incarnation)
{
try { Bind(key, existing.Generation with { Lifecycle = checked(existing.Generation.Lifecycle + 1) }); return true; }
catch (InvalidOperationException) { _hub.Invalidate(existing, "source rebind unavailable"); return false; }
}
// A failed removal has already retired/fenced the old generation in the hub.
TryRemove(existing);
}
try { Bind(key, new SourceGeneration(incarnation, 1)); return true; }
catch (InvalidOperationException) { return false; }
}
public void RetireVirtualIncarnation(string id, long incarnation)
{
if (!_virtualIncarnations.TryGetValue(id, out var producer) || producer.Incarnation != incarnation) return;
producer.Retire();
lock (_gate)
if (_virtualIncarnations.TryGetValue(id, out var current) && ReferenceEquals(current, producer))
{
_virtualIncarnations.TryRemove(id, out _);
if (_virtualRoutes.TryGetValue(id, out var binding) && ReferenceEquals(binding.Producer, producer))
TryRemove(binding.Ticket);
}
}
public bool TryCaptureVirtual(string id, long incarnation, out SourceTicket ticket)
{
ticket = default;
if (!_virtualIncarnations.TryGetValue(id, out var producer) || producer.Incarnation != incarnation || producer.IsRetired ||
!_virtualRoutes.TryGetValue(id, out var binding) || !ReferenceEquals(binding.Producer, producer) ||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
ticket = binding.Ticket;
return !producer.IsRetired;
}
public bool TryPublish(SourceTicket ticket, DataValueSnapshot snapshot)
{
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
var binding = Volatile.Read(ref slot.Current);
if (binding is null || binding.Ticket != ticket || !binding.Active) return false;
Interlocked.Increment(ref binding.InFlight);
IIngressReservation? reservation = null;
DataValue? value = null;
DataSample? sample = null;
try
{
if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false;
var size = OwnedDataSample.Estimate(snapshot.Value, binding.Shape);
if (!_hub.TryReserveIngress(ticket, size, out reservation) || reservation is null)
{
_hub.Invalidate(ticket, "source ingress capacity");
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
return false;
}
value = OwnedDataSample.Copy(snapshot.Value, binding.Shape);
if (!Monitor.TryEnter(slot.Gate))
{ _hub.Invalidate(ticket, "source serialization contention"); return false; }
try
{
if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false;
var serving = _serving();
if (serving is null || serving.NodeId != ticket.Key.ServingNodeId || serving.Incarnation != ticket.Key.ServingIncarnation ||
string.IsNullOrWhiteSpace(serving.Role) || serving.CatalogEpoch < 0 || serving.AuthorityEpoch < 0)
{ _hub.Invalidate(ticket, "serving identity unavailable"); return false; }
var sequence = checked(++slot.Sequence);
sample = new DataSample(value, snapshot.StatusCode, OwnedDataSample.Timestamp(snapshot.SourceTimestampUtc),
OwnedDataSample.Timestamp(snapshot.ServerTimestampUtc), serving, sequence);
value = null;
if (!reservation.TryCommit(sample, sequence))
{
_hub.Invalidate(ticket, "source commit rejected");
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
return false;
}
sample = null;
return true;
}
finally { Monitor.Exit(slot.Gate); }
}
catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException)
{ _hub.Invalidate(ticket, "unsupported or oversized source sample"); return false; }
finally
{
value?.Dispose();
sample?.Dispose();
reservation?.Dispose();
Interlocked.Decrement(ref binding.InFlight);
}
}
/// <summary>Synchronously invalidates a malformed callback's captured source generation.</summary>
public void Invalidate(SourceTicket ticket, string reason) => _hub.Invalidate(ticket, reason);
private void ScheduleRepair(SourceSlot slot, SourceTicket ticket)
{
if (Interlocked.CompareExchange(ref slot.RepairQueued, 1, 0) != 0) return;
if (Interlocked.Increment(ref _repairCount) > MaxPendingRepairs)
{
Interlocked.Decrement(ref _repairCount);
Volatile.Write(ref slot.RepairQueued, 0);
_hub.InvalidatePartitionFor(ticket.Key, "source repair capacity");
return;
}
Volatile.Write(ref slot.RepairAttempts, 0);
_repairQueue.Enqueue(slot);
ScheduleRepairWorker();
}
private void ScheduleRepairWorker()
{
if (Interlocked.CompareExchange(ref _repairWorkerScheduled, 1, 0) == 0)
ThreadPool.QueueUserWorkItem(static state => ((SourceSamplePublisher)state!).RunRepairs(), this);
}
private void RunRepairs()
{
var remaining = Math.Min(64, Volatile.Read(ref _repairCount));
while (remaining-- > 0 && _repairQueue.TryDequeue(out var slot))
{
var binding = Volatile.Read(ref slot.Current);
var completed = binding is null || !binding.Active;
if (!completed)
{
lock (_gate)
{
var current = Volatile.Read(ref slot.Current);
completed = current is null || !current.Active ||
EnsureBinding(current.Ticket.Key, current.Ticket.Generation.Incarnation);
}
}
if (!completed && Interlocked.Increment(ref slot.RepairAttempts) >= 16)
{
var last = Volatile.Read(ref slot.Current);
if (last is not null) _hub.InvalidatePartitionFor(last.Ticket.Key, "source repair exhausted");
completed = true;
}
if (completed)
{
Volatile.Write(ref slot.RepairQueued, 0);
Interlocked.Decrement(ref _repairCount);
}
else _repairQueue.Enqueue(slot);
}
Volatile.Write(ref _repairWorkerScheduled, 0);
if (Volatile.Read(ref _repairCount) > 0)
_repairTimer.Change(TimeSpan.FromMilliseconds(250), Timeout.InfiniteTimeSpan);
}
public bool TryPublishStatus(SourceTicket ticket, uint status, out SourceTicket next)
{
lock (_gate)
{
next = default;
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
lock (slot.Gate)
{
var binding = Volatile.Read(ref slot.Current);
if (binding is null || binding.Ticket != ticket || !binding.Active) return false;
next = ticket;
if (Volatile.Read(ref binding.InFlight) > 0)
{
try { next = Bind(ticket.Key, ticket.Generation with { Lifecycle = checked(ticket.Generation.Lifecycle + 1) }); }
catch (InvalidOperationException)
{
_hub.Invalidate(ticket, "source status fence failed");
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
return false;
}
_hub.Invalidate(next, "status overtook in-flight source sample");
}
if (_hub.TryPublishStatus(next, checked(++slot.Sequence), status, null, null)) return true;
_hub.Invalidate(next, "source status capacity");
if (!_hub.IsTicketCurrentNonBlocking(next)) ScheduleRepair(slot, next);
return false;
}
}
}
public bool TryRemove(SourceTicket ticket)
{
lock (_gate)
{
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
lock (slot.Gate)
{
var binding = Volatile.Read(ref slot.Current);
if (binding is null || binding.Ticket != ticket) return false;
Volatile.Write(ref slot.Current, null);
_slots.TryRemove(ticket.Key, out _);
_tickets.Remove(ticket.Key);
if (SourceKey.TryDriver(ticket.Key, out var driver, out var reference))
{ _drivers.Remove((driver, reference)); _driverRoutes.TryRemove((driver, reference), out _); }
else if (ticket.Key.SourceKind == "virtual")
{ _virtuals.Remove(ticket.Key.StableSourceId); _virtualRoutes.TryRemove(ticket.Key.StableSourceId, out _); }
if (_hub.TryRemove(ticket, checked(++slot.Sequence))) return true;
_hub.Invalidate(ticket, "source removal capacity");
return false;
}
}
}
/// <summary>Closes an old physical binding and opens a newer, initially unready generation.</summary>
public bool TryRebind(SourceTicket ticket, out SourceTicket next)
{
lock (_gate)
{
next = default;
if (!TryRemove(ticket)) return false;
var generation = ticket.Generation with { Lifecycle = checked(ticket.Generation.Lifecycle + 1) };
try { next = Bind(ticket.Key, generation); return true; }
catch (InvalidOperationException) { return false; }
}
}
}