Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs
T
Joseph Doherty 8c28506d96 fix(dataconn): #1026 name every origin reset cause; stop binding checks invalidating live sources; renew cohort leases in batches
Gate #1026 (2048 projected items, rig seed --scale 2048) still failed after #1115. Three defects, found by
first making the origin and the consumer say why:

Diagnostics (origin + consumer)
- SourceInvalidationReason (bounded enum, classified from the publisher's reason constants): counted per
  reason (`otopcua.dataconn.source.invalidations{reason}`, `Invalidate.<Reason>` in SourceIngressDiagnostics),
  recorded on the source and logged at Debug (PartitionedSampleHub.Logger).
- An interest lease records why it stopped; the origin Subscribe stream's Reset text names it ("Source
  invalidated (<reason>).", "Source retired.", "Source interest released.", "Source routing changed.",
  "Source partition reset.", "Source binding replaced.") instead of always "Source change history expired.";
  logged at Information (Released at Debug). The texts are for people/counters only: the consumer classifies
  them into ResetSourceInvalidated / ResetInterestLost (no peer branches on them; the rig probe whitelist is
  updated).
- Consumer: renewal started/succeeded/failed/budget/slot counters, RenewalFail.<point> and
  AttemptEnd.<reason> (bounded, constant keys).

1. Origin: a binding check invalidated live sources. The driver actor's source-binding retry re-walks every
   desired reference (offset 0, every <= 30 s once any one failed); for an already-bound reference it took the
   source's serialization gate, and when the poll thread was publishing that source both sides invalidated it
   (BindingContention / SerializationContention) and reset every origin stream holding it. Live s1026-c: the
   only invalidation reasons were those two (5+5 during the open, recurring every ~30 s). EnsureDriverBinding now
   answers an already-bound, current source without the gate. Live after: 0 BindingContention.

2. Consumer: per-item metadata lease renewal could not keep up. Each projected item renewed its 15 s lease with
   its own capabilities + GetMetadata pair holding a 256 KiB unary reservation; at the default 1 MiB budget four
   ran at once and the rest retried on the next 250 ms tick (~16 items/s). Live s1026-d: 155 703 renewals
   started, 153 019 refused by the unary budget, 2 564 committed; ~1900 of 2048 items stood down
   BadUserAccessDenied; 0 recovered after the origin restart. RemoteNamespaceResolver.RenewExactBatchAsync renews
   many items with one capabilities call and one GetMetadata per origin MaxBatchItems (the single-item renewal is
   now the batch of one: same checks, lease bound and commit); a cohort renews every due item of a tick in
   batches of 128, and the between-attempt renewal (every item after an origin restart) is batched too.

3. Consumer: two demands of one node in one cohort deadlocked the batch: the second joined (#969) the first's
   claim, and the batch waited for the joiner before publishing its verdict. The batch now publishes first.

Live (OrbStack rig, 160 + 1888 items, 4 Hz churn, SOURCE pair restart): s1026-f run 1 open 10.2 s, recovery
1.5 s, 0 resets of any kind; s1026-h run 2 PASS (open 3.1 s, recovery 3.6 s, 0 resets, no history-expired or
source-invalidated log line). Remaining (not fixed here): s1026-h run 1 recovered only 852 of 1888 large-mapping
items after the restart: their renewals fail in the catalog cache's predecessor-chain bound
(RenewalFail.Cache.PredecessorChain 81 163).

Tests: GrpcData1026BindingContentionTests (fails without the fast path), GrpcData1026RenewalBatchWireTests
(one tick renews all due items in one metadata call - fails with per-item renewals; two demands of one node -
fails without the ordering fix), GrpcData1026ResetReasonTests.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-05 05:43:03 -05:00

646 lines
33 KiB
C#

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();
// R-25: per-driver view of _drivers (reference -> key), so RetireDriver / PublishDriverStatus walk one driver's refs
// instead of scanning every bound ref of every driver under _gate. Always mutated beside _drivers.
private readonly Dictionary<string, Dictionary<string, BackingSourceKey>> _driverKeys = new(StringComparer.Ordinal);
private readonly Dictionary<string, BackingSourceKey> _virtuals = new(StringComparer.Ordinal);
internal sealed class SourceSlot
{
public readonly object Gate = new();
public SourceBinding? Current;
public long Sequence;
public int RepairQueued;
public int RepairAttempts;
}
internal 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;
if (!_driverKeys.TryGetValue(driver, out var perDriver))
_driverKeys[driver] = perDriver = new Dictionary<string, BackingSourceKey>(StringComparer.Ordinal);
perDriver[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);
// #1026: already bound to this producer and current in the hub — exactly EnsureBinding's no-op answer, decided
// without the source's serialization gate. The driver actor's binding retry re-walks EVERY desired reference
// (offset 0, backing off to 30 s, forever once any one failed), and each walk used to take each bound source's
// gate. Under a 2048-source acquisition that collided with the poll thread's TryPublish holding the same gate,
// and BOTH sides invalidate on contention (binding contention here, serialization contention there), so a live,
// correctly bound source was invalidated and every origin stream holding it was reset — every retry pass.
var bound = Volatile.Read(ref slot.Current);
if (bound is not null && ReferenceEquals(bound.Producer, producer) && bound.Active &&
bound.Ticket.Generation.Incarnation == incarnation && _tickets.TryGetValue(key, out var recorded) &&
recorded == bound.Ticket && _hub.IsTicketCurrentNonBlocking(bound.Ticket)) return true;
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, SourceInvalidationReasons.BindingContention);
return false;
}
try { return EnsureBinding(key, incarnation); }
finally { Monitor.Exit(slot.Gate); }
}
finally { Monitor.Exit(_gate); }
}
/// <summary>A snapshot of <paramref name="driver"/>'s bound source keys. Caller holds <c>_gate</c>.</summary>
private BackingSourceKey[] DriverKeys(string driver) =>
_driverKeys.TryGetValue(driver, out var perDriver) ? [.. perDriver.Values] : [];
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 DriverKeys(driver))
if (_tickets.TryGetValue(key, out var ticket)) TryRemove(ticket);
}
}
public void PublishDriverStatus(string driver, uint status)
{
lock (_gate)
foreach (var key in DriverKeys(driver))
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, SourceInvalidationReasons.RebindUnavailable); 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, SourceInvalidationReasons.IngressCapacity);
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
return false;
}
value = OwnedDataSample.Copy(snapshot.Value, binding.Shape);
if (!Monitor.TryEnter(slot.Gate))
{ _hub.Invalidate(ticket, SourceInvalidationReasons.SerializationContention); 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, SourceInvalidationReasons.ServingIdentityUnavailable); 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, SourceInvalidationReasons.CommitRejected);
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, SourceInvalidationReasons.UnsupportedSample); return false; }
finally
{
value?.Dispose();
sample?.Dispose();
reservation?.Dispose();
Interlocked.Decrement(ref binding.InFlight);
}
}
/// <summary>An owned, budgeted callback sample whose handle has not yet been acknowledged.</summary>
internal sealed class StagedSourceSample : IDisposable
{
private readonly SourceSamplePublisher _owner;
private readonly SourceBinding _binding;
private readonly SourceTicket _ticket;
private readonly uint _status;
private readonly DateTimeOffset? _source, _server;
private IIngressReservation? _reservation;
private DataValue? _value;
private int _finished;
internal StagedSourceSample(SourceSamplePublisher owner, SourceBinding binding, SourceTicket ticket,
DataValueSnapshot snapshot, IIngressReservation reservation, DataValue value)
{
_owner = owner; _binding = binding; _ticket = ticket; _status = snapshot.StatusCode;
_source = OwnedDataSample.Timestamp(snapshot.SourceTimestampUtc);
_server = OwnedDataSample.Timestamp(snapshot.ServerTimestampUtc);
_reservation = reservation; _value = value;
}
internal bool Commit()
{
if (Interlocked.Exchange(ref _finished, 1) != 0) return false;
var reservation = _reservation!; _reservation = null;
var value = _value!; _value = null;
DataSample? sample = null;
try
{
var slot = _binding.Slot;
if (!Monitor.TryEnter(slot.Gate)) { _owner._hub.Invalidate(_ticket, SourceInvalidationReasons.StagedContention); return false; }
try
{
if (!_binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), _binding)) return false;
var serving = _owner._serving();
if (serving is null || serving.NodeId != _ticket.Key.ServingNodeId ||
serving.Incarnation != _ticket.Key.ServingIncarnation || string.IsNullOrWhiteSpace(serving.Role))
{ _owner._hub.Invalidate(_ticket, SourceInvalidationReasons.StagedIdentityUnavailable); return false; }
var sequence = checked(++slot.Sequence);
sample = new DataSample(value, _status, _source, _server, serving, sequence);
value = null!;
if (!reservation.TryCommit(sample, sequence))
{ _owner._hub.Invalidate(_ticket, SourceInvalidationReasons.StagedAdmissionRejected); return false; }
sample = null;
return true;
}
finally { Monitor.Exit(slot.Gate); }
}
catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException)
{ _owner._hub.Invalidate(_ticket, SourceInvalidationReasons.StagedCommitFailed); return false; }
finally
{
value?.Dispose(); sample?.Dispose(); reservation.Dispose();
Interlocked.Decrement(ref _binding.InFlight);
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref _finished, 1) != 0) return;
_value?.Dispose(); _value = null;
_reservation?.Dispose(); _reservation = null;
Interlocked.Decrement(ref _binding.InFlight);
}
}
/// <summary>Reserves and owns a borrowed callback value synchronously, before handle validation.</summary>
internal bool TryStage(SourceTicket ticket, DataValueSnapshot snapshot, out StagedSourceSample? staged)
{
staged = null;
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;
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, SourceInvalidationReasons.StagedIngressCapacity); return false; }
value = OwnedDataSample.Copy(snapshot.Value, binding.Shape);
staged = new StagedSourceSample(this, binding, ticket, snapshot, reservation, value);
reservation = null; value = null;
return true;
}
catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException)
{ _hub.Invalidate(ticket, SourceInvalidationReasons.StagedValueInvalid); return false; }
finally
{
if (staged is null) { value?.Dispose(); reservation?.Dispose(); Interlocked.Decrement(ref binding.InFlight); }
}
}
/// <summary>Attempts status-only acquisition ingress without waiting or refreshing value age.</summary>
public bool TryPublishAcquisitionStatus(SourceTicket ticket, uint status)
{
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
if (!Monitor.TryEnter(slot.Gate))
{
_hub.Invalidate(ticket, SourceInvalidationReasons.StatusContention);
return false;
}
try
{
var binding = Volatile.Read(ref slot.Current);
if (binding is null || binding.Ticket != ticket || !binding.Active) return false;
if (Volatile.Read(ref binding.InFlight) != 0)
{
_hub.Invalidate(ticket, SourceInvalidationReasons.StatusOvertookInFlight);
return false;
}
if (_hub.TryPublishStatus(ticket, checked(++slot.Sequence), status, null, null)) return true;
_hub.Invalidate(ticket, SourceInvalidationReasons.StatusAdmissionFailed);
return false;
}
catch (OverflowException)
{
_hub.Invalidate(ticket, SourceInvalidationReasons.StatusSequenceExhausted);
return false;
}
finally { Monitor.Exit(slot.Gate); }
}
internal void WithAcquisitionStatusLockForTest(SourceTicket ticket, bool publisherGate, Action action)
{
if (publisherGate) { lock (_gate) action(); return; }
if (!_slots.TryGetValue(ticket.Key, out var slot)) throw new InvalidOperationException("Source slot is unavailable.");
lock (slot.Gate) action();
}
/// <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, SourceInvalidationReasons.StatusFenceFailed);
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
return false;
}
_hub.Invalidate(next, SourceInvalidationReasons.StatusFenceOvertook);
}
if (_hub.TryPublishStatus(next, checked(++slot.Sequence), status, null, null)) return true;
_hub.Invalidate(next, SourceInvalidationReasons.StatusCapacity);
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 _);
if (_driverKeys.TryGetValue(driver, out var perDriver) && perDriver.Remove(reference) && perDriver.Count == 0)
_driverKeys.Remove(driver);
}
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, SourceInvalidationReasons.RemovalCapacity);
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; }
}
}
}