Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs
T
Joseph Doherty a5ef7ea6d8 feat(grpc-data): X0 node-side tolerant readers drop unknown operation bits per row (counted) instead of rejecting the snapshot
Covers the deployment runtime (plan site) plus two node-side validator passes the plan missed:
DeploymentArtifact data-row parse and LocalExportCatalog.Compile now use DataConnectionValidator.ValidateDeployed.
Authoring (Validate) still rejects the reserved bits.
2026-11-23 17:21:35 -05:00

641 lines
40 KiB
C#

using System.Diagnostics.Metrics;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A node-effective artifact and the durable credential-scope floor it requires.</summary>
public sealed record DataConnectionDeploymentSnapshot(long ScopeVersion, string ArtifactRevision, IReadOnlyList<DataConnection> Connections,
RedundancyMode ConsumerMode = RedundancyMode.None);
/// <summary>Host-effective role eligibility and the continuity epoch observed under its role fence.</summary>
public sealed record DataConnectionConsumerRoleSnapshot(RedundancyMode Mode, bool Eligible, long Epoch);
/// <summary>Persists the node's current connection-to-secret allowlist before any route is made ready.</summary>
public interface IDataConnectionScopeActivator
{
Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken);
}
/// <summary>Owns configured connections and reconciles only the latest node-effective scope.</summary>
public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
{
private sealed record Spec(string Id, long Revision, DataTarget Target, Uri[] Endpoints, HashSet<string> EligibleNodes,
string Secret, DataOperations Operations, TimeSpan Timeout, int Batch, int Page, int MessageBytes,
int Streams, int Monitored, long PendingBytes);
private sealed record Desired(long ScopeVersion, string ArtifactRevision, long Generation, RedundancyMode ConsumerMode,
IReadOnlyDictionary<string, Spec> Specs, IReadOnlyDictionary<string, string> Allowlist);
private sealed class Entry(Spec spec, long generation, GrpcDataConnection connection, CancellationToken token,
RedundancyMode artifactMode, DataConnectionConsumerRoleSnapshot? role)
{
internal readonly Spec Spec = spec;
internal readonly long Generation = generation;
internal readonly GrpcDataConnection Connection = connection;
internal readonly CancellationToken Token = token;
internal readonly object RouteIdentity = new();
internal readonly RedundancyMode ArtifactMode = artifactMode;
internal readonly DataConnectionConsumerRoleSnapshot? Role = role;
internal volatile bool Live = true;
internal bool Ready;
internal int Leases;
}
/// <summary>Counter of connection rows whose unknown operation bits were dropped (X0 tolerant reader).</summary>
public const string UnknownOperationsCounterName = "otopcua.dataconnection.unknown_operations_dropped";
private static readonly Counter<long> UnknownOperationsCounter = OtOpcUaTelemetry.Meter.CreateCounter<long>(
UnknownOperationsCounterName, unit: "{row}",
description: "Data-connection rows carrying operation bits this node does not understand; the bits were dropped (no grant).");
private readonly object _sync = new();
private readonly ILogger _log;
private IReadOnlyDictionary<string, DataOperations> _droppedOperations = new Dictionary<string, DataOperations>();
private long _unknownOperationRows;
private readonly string _node, _owner;
private readonly IDataConnectionSecurityProvider _security;
private readonly IDataConnectionScopeActivator _activator;
private readonly DataConnectionManager _manager;
private readonly int _maximum;
private readonly TimeProvider _clock;
private readonly Func<bool> _consumerMayAcquire;
private readonly Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? _consumerRoleSnapshot;
private readonly bool _useCompactBatches;
private readonly CancellationTokenSource _stop = new();
private readonly ITimer _retryTimer;
private readonly Dictionary<string, Entry> _entries = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, long> _routeRevisions = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<Task> _retirements = new();
private Desired? _desired;
private Task? _worker, _disposeTask;
private bool _wake, _scopeReady, _disposed, _attemptPending;
private string? _attemptRevision;
private long _generation, _securityGeneration, _retryGeneration, _retryNotBefore;
private int _retryFailures;
public DataConnectionDeploymentRuntime(string nodeId, string ownerCluster, IDataConnectionSecurityProvider security,
IDataConnectionScopeActivator scopeActivator, int maxConnections, TimeProvider? clock = null,
Func<bool>? consumerMayAcquire = null, bool useCompactBatches = true,
Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? consumerRoleSnapshot = null, ILogger? logger = null)
{
_log = logger ?? NullLogger.Instance;
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId); ArgumentException.ThrowIfNullOrWhiteSpace(ownerCluster);
if (maxConnections <= 0) throw new ArgumentOutOfRangeException(nameof(maxConnections));
_node = nodeId; _owner = ownerCluster; _security = security ?? throw new ArgumentNullException(nameof(security));
_activator = scopeActivator ?? throw new ArgumentNullException(nameof(scopeActivator)); _maximum = maxConnections;
_clock = clock ?? TimeProvider.System; _consumerMayAcquire = consumerMayAcquire ?? (() => true); _useCompactBatches = useCompactBatches;
_consumerRoleSnapshot = consumerRoleSnapshot;
_retryTimer = _clock.CreateTimer(static state => ((DataConnectionDeploymentRuntime)state!).OnRetry(), this,
Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
_manager = new DataConnectionManager(nodeId, maxConnections);
_manager.AvailabilityChanged += OnAvailability;
_security.Changed += OnSecurityChanged;
}
/// <summary>True only after the current scope version and allowlist are durably accepted.</summary>
public bool CurrentScopeReady { get { lock (_sync) return !_disposed && _scopeReady; } }
/// <summary>
/// X0 diagnostics: per enabled connection of the current artifact, the operation bits it was authored with that
/// this node does not understand and therefore dropped (an unknown grant is no grant). Empty when none.
/// </summary>
public IReadOnlyDictionary<string, DataOperations> DroppedUnknownOperations { get { lock (_sync) return _droppedOperations; } }
/// <summary>Cumulative count of connection rows that had unknown bits dropped, once per accepted artifact.</summary>
public long UnknownOperationRowsDropped => Interlocked.Read(ref _unknownOperationRows);
/// <summary>Configured redundancy mode from the current validated artifact.</summary>
public RedundancyMode CurrentConsumerMode { get { lock (_sync) return _desired?.ConsumerMode ?? RedundancyMode.None; } }
/// <summary>Captures only this node's applied scope and current transport evidence.</summary>
public IReadOnlyList<ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot> CaptureDiagnostics(IReadOnlyDictionary<string, int>? retainedSourceCounts = null)
{
lock (_sync)
{
if (_disposed || _desired is not { } desired) return [];
return desired.Specs.Values.Select(spec =>
{
if (!_attemptPending && _scopeReady && _entries.TryGetValue(spec.Id, out var entry) && entry.Ready)
return entry.Connection.CaptureDiagnostics(spec.Revision, desired.ScopeVersion, desired.ArtifactRevision) with
{ SourceCount = retainedSourceCounts is null ? null : retainedSourceCounts.TryGetValue(spec.Id, out var count) ? count : 0 };
return new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot(spec.Id, spec.Revision,
_attemptPending ? "connecting" : _retryNotBefore > _clock.GetTimestamp() ? "backoff" : "connecting",
null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime);
}).ToArray();
}
}
/// <summary>Withdraws current routes before parsing or staging a different artifact.</summary>
public void BeginAttempt(string artifactRevision)
{
ArgumentException.ThrowIfNullOrWhiteSpace(artifactRevision);
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_attemptPending && _scopeReady && _desired is { } accepted &&
string.Equals(accepted.ArtifactRevision, artifactRevision, StringComparison.Ordinal))
{ _attemptRevision = artifactRevision; return; }
if (_attemptPending && string.Equals(_attemptRevision, artifactRevision, StringComparison.Ordinal)) return;
_attemptRevision = artifactRevision; _attemptPending = true; _scopeReady = false; _wake = false;
DisarmRetryLocked();
var generation = checked(++_generation);
if (_desired is not null) _desired = _desired with { Generation = generation };
var old = _entries.Values.ToArray(); _entries.Clear();
_manager.ApplyScope(new Dictionary<string, DataConnectionScope>(StringComparer.OrdinalIgnoreCase));
foreach (var entry in old) Retire(entry);
}
}
/// <summary>Copies and validates desired data, synchronously denies old routes, and schedules reconciliation.</summary>
public void Apply(DataConnectionDeploymentSnapshot snapshot)
{
ArgumentNullException.ThrowIfNull(snapshot);
if (snapshot.ScopeVersion <= 0 || !Enum.IsDefined(snapshot.ConsumerMode)) throw new ArgumentOutOfRangeException(nameof(snapshot));
ArgumentException.ThrowIfNullOrWhiteSpace(snapshot.ArtifactRevision);
ArgumentNullException.ThrowIfNull(snapshot.Connections);
if (snapshot.Connections.Count > _maximum) throw new ArgumentException("Connection capacity exceeded.", nameof(snapshot));
var specs = new Dictionary<string, Spec>(StringComparer.OrdinalIgnoreCase);
var allow = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var dropped = new Dictionary<string, DataOperations>(StringComparer.OrdinalIgnoreCase);
foreach (var item in snapshot.Connections)
{
ArgumentNullException.ThrowIfNull(item);
ArgumentException.ThrowIfNullOrWhiteSpace(item.DataConnectionId);
if (!item.Enabled) continue;
if (!string.Equals(item.ClusterId, _owner, StringComparison.OrdinalIgnoreCase) ||
item.ConsumerNodeIds is null || !item.ConsumerNodeIds.Contains(_node, StringComparer.OrdinalIgnoreCase) ||
!string.Equals(item.SecretScopeClusterId, _owner, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("Connection is not enabled for this consumer and owner.", nameof(snapshot));
ArgumentException.ThrowIfNullOrWhiteSpace(item.SecretReference);
var target = new DataTarget(item.TargetMode, item.ExpectedClusterId, item.ExpectedNodeId, item.Consistency); target.Validate();
if (item.Revision <= 0 || item.TimeoutMilliseconds <= 0 || item.MaxBatchItems <= 0 || item.MaxPageItems <= 0 ||
item.MaxMessageBytes <= 0 || item.MaxStreams <= 0 || item.MaxMonitoredItems <= 0 || item.MaxPendingBytes <= 0 ||
item.Endpoints is null || item.Endpoints.Count == 0 || item.Endpoints.Count > 32 || item.EligibleTargetNodeIds is null)
throw new ArgumentException("Connection limits or endpoints are invalid.", nameof(snapshot));
// X0 tolerant reader (plan §4.3): a bit a newer central authored that this build does not implement is
// dropped from THIS row only, fail closed, and counted. It used to reject the whole snapshot. A row left
// with no understood operation stays configured and grants nothing.
var operations = item.AllowedOperations & DataOperationSets.Understood;
if (operations != item.AllowedOperations) dropped[item.DataConnectionId] = item.AllowedOperations & ~DataOperationSets.Understood;
var endpoints = item.Endpoints.Select(value => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps
? uri : throw new ArgumentException("Only HTTPS endpoints are accepted.", nameof(snapshot))).Distinct().ToArray();
var eligible = new HashSet<string>(item.EligibleTargetNodeIds, StringComparer.OrdinalIgnoreCase);
if (target.Mode == DataTargetMode.Cluster && (eligible.Count == 0 || eligible.Any(string.IsNullOrWhiteSpace)))
throw new ArgumentException("Cluster target has no eligible nodes.", nameof(snapshot));
var spec = new Spec(item.DataConnectionId, item.Revision, target, endpoints, eligible, item.SecretReference,
operations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems,
item.MaxPageItems, item.MaxMessageBytes, item.MaxStreams, item.MaxMonitoredItems, item.MaxPendingBytes);
if (!specs.TryAdd(spec.Id, spec) || !allow.TryAdd(spec.Id, spec.Secret))
throw new ArgumentException("Duplicate connection identity.", nameof(snapshot));
}
Entry[] old;
lock (_sync)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_attemptRevision is not null && !string.Equals(_attemptRevision, snapshot.ArtifactRevision, StringComparison.Ordinal))
throw new InvalidOperationException("Artifact does not match the latest deployment attempt.");
if (_desired is { } previous)
{
if (snapshot.ScopeVersion < previous.ScopeVersion) throw new InvalidOperationException("Scope version moved backwards.");
if (snapshot.ScopeVersion == previous.ScopeVersion && !SameAllowlist(previous.Allowlist, allow))
throw new InvalidOperationException("A scope version cannot identify different allowlists.");
if (string.Equals(snapshot.ArtifactRevision, previous.ArtifactRevision, StringComparison.Ordinal))
{
if (snapshot.ScopeVersion != previous.ScopeVersion || snapshot.ConsumerMode != previous.ConsumerMode || !SameSpecs(previous.Specs, specs))
throw new InvalidOperationException("An artifact revision cannot identify different definitions.");
// Same revision re-applied: identical rows, so the dropped set is unchanged and is not recounted.
if (!_attemptPending) { if (!_scopeReady) DisarmRetryLocked(); WakeLocked(); return; }
}
}
_attemptPending = false; DisarmRetryLocked();
var generation = checked(++_generation);
_routeRevisions.Clear();
foreach (var id in specs.Keys) _routeRevisions.Add(id, generation);
var priorRevision = _desired?.ArtifactRevision;
_desired = new(snapshot.ScopeVersion, snapshot.ArtifactRevision, generation, snapshot.ConsumerMode, specs, allow);
RecordDroppedLocked(snapshot.ArtifactRevision, priorRevision, dropped);
_scopeReady = false;
old = _entries.Values.ToArray(); _entries.Clear();
ApplyManagerScopeLocked(_desired);
foreach (var entry in old) Retire(entry);
WakeLocked();
}
}
private void RecordDroppedLocked(string revision, string? priorRevision, Dictionary<string, DataOperations> dropped)
{
_droppedOperations = dropped;
if (dropped.Count == 0 || string.Equals(revision, priorRevision, StringComparison.Ordinal)) return;
Interlocked.Add(ref _unknownOperationRows, dropped.Count);
foreach (var (id, bits) in dropped)
{
UnknownOperationsCounter.Add(1);
_log.LogWarning("Data connection {DataConnectionId} in artifact {ArtifactRevision} grants operation bits {UnknownOperations} " +
"this node does not implement; they were dropped (no grant). Upgrade this node before relying on them.",
id, revision, (int)bits);
}
}
private static bool SameAllowlist(IReadOnlyDictionary<string, string> left, IReadOnlyDictionary<string, string> right) =>
left.Count == right.Count && left.All(x => right.TryGetValue(x.Key, out var value) && string.Equals(value, x.Value, StringComparison.Ordinal));
private static bool SameSpecs(IReadOnlyDictionary<string, Spec> left, IReadOnlyDictionary<string, Spec> right) =>
left.Count == right.Count && left.All(pair => right.TryGetValue(pair.Key, out var b) && SameSpec(pair.Value, b));
private static bool SameSpec(Spec a, Spec b) =>
string.Equals(a.Id, b.Id, StringComparison.OrdinalIgnoreCase) && a.Revision == b.Revision && a.Target == b.Target &&
a.Endpoints.SequenceEqual(b.Endpoints) && a.EligibleNodes.SetEquals(b.EligibleNodes) &&
string.Equals(a.Secret, b.Secret, StringComparison.Ordinal) && a.Operations == b.Operations && a.Timeout == b.Timeout &&
a.Batch == b.Batch && a.Page == b.Page && a.MessageBytes == b.MessageBytes && a.Streams == b.Streams &&
a.Monitored == b.Monitored && a.PendingBytes == b.PendingBytes;
private bool MayAcquire() { try { return _consumerMayAcquire(); } catch (Exception) { return false; } }
private DataConnectionConsumerRoleSnapshot? CaptureRole(RedundancyMode mode)
{ try { return _consumerRoleSnapshot?.Invoke(mode); } catch (Exception) { return null; } }
private bool RouteCurrent(Entry entry)
{
if (!entry.Live || entry.Token.IsCancellationRequested) return false;
if (entry.Role is not { Eligible: true, Epoch: > 0 and < long.MaxValue } captured)
return true;
var current = CaptureRole(entry.ArtifactMode);
return current is { Eligible: true, Epoch: > 0 and < long.MaxValue } && current.Mode == captured.Mode && current.Epoch == captured.Epoch;
}
private void ApplyManagerScopeLocked(Desired desired)
{
// The manager owns configured-node scope and physical lifetime only. Role checks
// independently guard activation, acquisition, and each borrowed operation.
var scope = new Dictionary<string, DataConnectionScope>(StringComparer.OrdinalIgnoreCase);
foreach (var spec in desired.Specs.Values)
scope.Add(spec.Id, new DataConnectionScope(_routeRevisions[spec.Id], new HashSet<string>(StringComparer.OrdinalIgnoreCase) { _node }));
_manager.ApplyScope(scope);
}
/// <summary>Immediately drains routes on a local role change; called outside the role publication fence.</summary>
public void NotifyConsumerRoleChanged()
{
Entry[] old;
lock (_sync)
{
if (_disposed || _desired is null) return;
if (_attemptPending) return;
if (_consumerRoleSnapshot is not null && _entries.Count > 0)
{
var snapshots = _entries.Values.Select(entry => (Entry: entry, Current: CaptureRole(entry.ArtifactMode))).ToArray();
if (snapshots.All(x => x.Entry.Role is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue }) &&
snapshots.Any(x => x.Current is not { Epoch: > 0 })) return;
if (snapshots.All(x => x.Entry.Role is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue } captured &&
x.Current is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue } current && captured.Epoch == current.Epoch))
{ WakeLocked(); return; }
}
DisarmRetryLocked();
var generation = checked(++_generation);
_desired = _desired with { Generation = generation };
foreach (var id in _desired.Specs.Keys) _routeRevisions[id] = generation;
old = _entries.Values.ToArray(); _entries.Clear();
ApplyManagerScopeLocked(_desired);
foreach (var entry in old) Retire(entry);
WakeLocked();
}
}
private void OnAvailability() { lock (_sync) { if (!_disposed && !_attemptPending) WakeLocked(); } }
private void OnSecurityChanged(string id)
{
lock (_sync)
{
if (_disposed) return;
checked { _securityGeneration++; }
if (!_scopeReady) DisarmRetryLocked();
if (_desired is not null && _entries.Remove(id, out var entry))
{
var generation = checked(++_generation);
_desired = _desired with { Generation = generation };
_routeRevisions[id] = generation;
ApplyManagerScopeLocked(_desired);
Retire(entry);
}
if (!_attemptPending) WakeLocked();
}
}
private void DisarmRetryLocked()
{
_retryGeneration = 0; _retryNotBefore = 0; _retryFailures = 0;
_retryTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
private void ScheduleRetryLocked(long generation)
{
var power = _retryFailures;
_retryFailures = Math.Min(_retryFailures + 1, 7);
var delay = TimeSpan.FromMilliseconds(Math.Min(30_000, 250 * (1 << power)));
_retryGeneration = generation;
_retryNotBefore = checked(_clock.GetTimestamp() + (long)(delay.TotalSeconds * _clock.TimestampFrequency));
_retryTimer.Change(delay, Timeout.InfiniteTimeSpan);
}
private void OnRetry()
{
lock (_sync)
{
if (_disposed || _attemptPending || _retryGeneration == 0 || _desired?.Generation != _retryGeneration) return;
var now = _clock.GetTimestamp();
if (now < _retryNotBefore)
{
_retryTimer.Change(_clock.GetElapsedTime(now, _retryNotBefore), Timeout.InfiniteTimeSpan);
return;
}
_retryGeneration = 0;
WakeLocked();
}
}
private void WakeLocked()
{
_wake = true;
if (_worker is null) _worker = Task.Run(ReconcileAsync);
}
private async Task ReconcileAsync()
{
while (true)
{
Desired? desired;
bool floorAlreadyReady;
lock (_sync)
{
if (_disposed || !_wake) { _worker = null; return; }
_wake = false; desired = _attemptPending ? null : _desired; floorAlreadyReady = _scopeReady;
}
if (desired is null) continue;
if (!floorAlreadyReady)
{
try { await _activator.SetScopeAsync(desired.ScopeVersion, desired.Allowlist, _stop.Token).ConfigureAwait(false); }
catch (OperationCanceledException) when (_stop.IsCancellationRequested) { continue; }
catch (Exception)
{
lock (_sync)
if (!_disposed && !_attemptPending && !_scopeReady && _desired?.Generation == desired.Generation)
ScheduleRetryLocked(desired.Generation);
continue;
}
}
lock (_sync)
{
if (_disposed || _attemptPending || _desired?.Generation != desired.Generation) continue;
_scopeReady = true;
if (!MayAcquire())
{
if (desired.Specs.Count > 0) ScheduleRetryLocked(desired.Generation);
else DisarmRetryLocked();
continue;
}
// Reassert configured scope after a deferred physical retirement frees a slot.
ApplyManagerScopeLocked(desired);
}
var retryNeeded = false;
foreach (var spec in desired.Specs.Values)
{
Entry? existing;
long securityGeneration;
DataConnectionConsumerRoleSnapshot? beforeRole;
lock (_sync)
{
if (_disposed || _attemptPending || _desired?.Generation != desired.Generation) break;
if (!MayAcquire()) { retryNeeded = true; break; }
_entries.TryGetValue(spec.Id, out existing);
if (existing?.Ready == true) continue;
securityGeneration = _securityGeneration;
beforeRole = CaptureRole(desired.ConsumerMode);
}
var available = false;
try
{
foreach (var endpoint in spec.Endpoints)
{
var security = await _security.ResolveAsync(spec.Id, endpoint, _stop.Token).ConfigureAwait(false);
if (security is not null && !string.IsNullOrWhiteSpace(security.Bearer) &&
!string.IsNullOrWhiteSpace(security.CredentialVersion) && !string.IsNullOrWhiteSpace(security.TrustFingerprint))
{ available = true; break; }
}
}
catch (OperationCanceledException) when (_stop.IsCancellationRequested) { break; }
catch (Exception) { }
if (!available) { retryNeeded = true; continue; }
lock (_sync)
{
if (_disposed || _attemptPending || _desired?.Generation != desired.Generation || _securityGeneration != securityGeneration) continue;
if (!MayAcquire()) { retryNeeded = true; break; }
if (_entries.TryGetValue(spec.Id, out existing)) { existing.Ready = true; continue; }
var role = CaptureRole(desired.ConsumerMode);
if (_consumerRoleSnapshot is not null && (role is null || !role.Eligible || role.Epoch <= 0 || role.Epoch == long.MaxValue))
{ retryNeeded = true; continue; }
if (_consumerRoleSnapshot is not null && (beforeRole is null || !beforeRole.Eligible || beforeRole.Epoch <= 0 ||
beforeRole.Epoch == long.MaxValue || beforeRole.Mode != role!.Mode || beforeRole.Epoch != role.Epoch))
{ retryNeeded = true; continue; }
DataConnectionScopeLease scope;
try { scope = _manager.Acquire(spec.Id); }
catch (UnauthorizedAccessException) { continue; }
try
{
var connection = new GrpcDataConnection(spec.Id, spec.Target, spec.Endpoints, _security, scope,
spec.MessageBytes, spec.Endpoints.Length, _clock, spec.EligibleNodes,
spec.Streams, spec.Monitored, maxPendingCommandBytes: spec.PendingBytes, enableCompactBatches: _useCompactBatches);
_entries.Add(spec.Id, new Entry(spec, desired.Generation, connection, scope.CancellationToken, desired.ConsumerMode, role) { Ready = true });
}
catch (Exception) { scope.Dispose(); retryNeeded = true; }
}
}
lock (_sync)
{
if (!_disposed && !_attemptPending && _desired?.Generation == desired.Generation)
{
if (retryNeeded) ScheduleRetryLocked(desired.Generation);
else DisarmRetryLocked();
}
}
}
}
private void Retire(Entry entry)
{
entry.Live = false;
var task = entry.Connection.DisposeAsync().AsTask();
lock (_sync) _retirements.Add(task);
_ = ObserveRetirementAsync(task);
}
private async Task ObserveRetirementAsync(Task task)
{
try { await task.ConfigureAwait(false); } catch (Exception) { }
lock (_sync) { _retirements.Remove(task); if (!_disposed) WakeLocked(); }
}
/// <summary>Gets a non-owning, scope-bound connection lease when that individual credential is ready.</summary>
public bool TryAcquire(string id, out DataConnectionDeploymentLease? lease)
{
lock (_sync)
{
lease = null;
if (!_disposed && _desired is { } desired && _entries.TryGetValue(id, out var stale) &&
stale.Role is { Eligible: true, Epoch: > 0 and < long.MaxValue } captured &&
CaptureRole(stale.ArtifactMode) is { Epoch: > 0 and < long.MaxValue } observed &&
(observed.Mode != captured.Mode || !observed.Eligible || observed.Epoch != captured.Epoch))
{
_entries.Remove(id);
var generation = checked(++_generation);
_desired = desired with { Generation = generation };
_routeRevisions[id] = generation;
ApplyManagerScopeLocked(_desired);
Retire(stale);
if (!_attemptPending) WakeLocked();
}
if (_disposed || !_scopeReady || !MayAcquire() || !_entries.TryGetValue(id, out var entry) || !entry.Ready || !RouteCurrent(entry) ||
entry.Token.IsCancellationRequested || entry.Leases >= 1024) return false;
entry.Leases++;
lease = new DataConnectionDeploymentLease(entry.Connection, entry.Token, entry.Spec.Operations, entry.Spec.Timeout,
entry.Spec.Batch, entry.Spec.Page, entry.Spec.MessageBytes, entry.Spec.Streams, entry.Spec.Monitored, entry.Spec.PendingBytes,
() => { lock (_sync) return !_disposed && _scopeReady && MayAcquire() && entry.Ready && RouteCurrent(entry) &&
_entries.TryGetValue(id, out var current) && ReferenceEquals(entry, current); },
() => { lock (_sync) entry.Leases--; }, () => RouteCurrent(entry), entry.RouteIdentity);
return true;
}
}
public ValueTask DisposeAsync()
{
lock (_sync)
{
if (_disposeTask is not null) return new(_disposeTask);
_disposed = true; _scopeReady = false; DisarmRetryLocked(); _security.Changed -= OnSecurityChanged; _manager.AvailabilityChanged -= OnAvailability;
_ = _stop.CancelAsync();
_manager.Dispose();
var old = _entries.Values.ToArray(); _entries.Clear();
foreach (var entry in old) Retire(entry);
_disposeTask = FinishDisposeAsync(_worker, _retirements.ToArray());
return new(_disposeTask);
}
}
private async Task FinishDisposeAsync(Task? worker, Task[] retirements)
{
if (worker is not null) try { await worker.ConfigureAwait(false); } catch (Exception) { }
try { await Task.WhenAll(retirements).ConfigureAwait(false); } catch (Exception) { }
_retryTimer.Dispose(); _stop.Dispose();
}
}
/// <summary>A non-owning handle with the deployed operation and resource policy.</summary>
public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable
{
private readonly IDataConnection _inner;
private readonly CancellationToken _scope;
private readonly DataOperations _allowed;
private readonly TimeSpan _timeout;
private readonly int _batch, _page, _bytes, _streams, _monitored;
private readonly long _pendingBytes;
private readonly Func<bool> _current;
private readonly Action _release;
private readonly Func<bool> _routeCurrent;
internal object? RouteIdentity { get; }
private int _disposed;
internal DataConnectionDeploymentLease(IDataConnection inner, CancellationToken scope, DataOperations allowed, TimeSpan timeout,
int batch, int page, int bytes, int streams, int monitored, long pendingBytes, Func<bool> current, Action release, Func<bool>? routeCurrent = null, object? routeIdentity = null)
{
_inner = inner; _scope = scope; _allowed = allowed; _timeout = timeout; _batch = batch; _page = page; _bytes = bytes;
_streams = streams; _monitored = monitored; _pendingBytes = pendingBytes; _current = current; _release = release;
_routeCurrent = routeCurrent ?? (() => !scope.IsCancellationRequested);
RouteIdentity = routeIdentity;
}
internal Func<bool> RouteCurrent => _routeCurrent;
/// <summary>The configured row's operations, already masked to the understood set.</summary>
internal DataOperations AllowedOperations => _allowed;
public IDataConnection Connection => this;
public CancellationToken CancellationToken => _scope;
public DataTarget Target => _inner.Target;
public TimeProvider Clock => _inner.Clock;
private void Check(DataOperations operation = DataOperations.None)
{
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
_scope.ThrowIfCancellationRequested();
if (!_current()) throw new InvalidOperationException("Connection is no longer ready in the current scope.");
if (operation != DataOperations.None && (_allowed & operation) != operation) throw new UnauthorizedAccessException("Operation is not enabled for this connection.");
}
private DataBudget Limit(DataBudget budget, int maxItems)
{
budget.Validate();
return new(budget.Timeout < _timeout ? budget.Timeout : _timeout, Math.Min(budget.MaxItems, maxItems),
Math.Min(Math.Min(budget.MaxBytes, _bytes), _pendingBytes));
}
public async Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken)
{
Check(); var result = await _inner.GetCapabilitiesAsync(Limit(budget, _batch), cancellationToken).ConfigureAwait(false); Check();
var l = result.Limits;
var limits = l with { MaxPageItems = Math.Min(l.MaxPageItems, _page), MaxBatchItems = Math.Min(l.MaxBatchItems, _batch),
MaxMessageBytes = Math.Min(l.MaxMessageBytes, _bytes), MaxStreams = Math.Min(l.MaxStreams, _streams),
MaxMonitoredItems = Math.Min(l.MaxMonitoredItems, _monitored), MaxPendingBytes = Math.Min(l.MaxPendingBytes, _pendingBytes) };
return result with { Operations = result.Operations & _allowed, Limits = limits };
}
public async Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken)
{
Check(DataOperations.Browse); var value = await _inner.BrowseAsync(request with { Budget = Limit(request.Budget, _page) }, cancellationToken).ConfigureAwait(false);
Check(DataOperations.Browse); return value;
}
public async Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{
Check(DataOperations.Metadata); if (request.Views.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request));
var value = await _inner.GetMetadataAsync(request with { Budget = Limit(request.Budget, _batch) }, cancellationToken).ConfigureAwait(false);
Check(DataOperations.Metadata); return value;
}
public async Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
{
Check(DataOperations.Read); if (request.Items.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request));
var value = await _inner.ReadAsync(request with { Budget = Limit(request.Budget, _batch) }, cancellationToken).ConfigureAwait(false);
try { Check(DataOperations.Read); return value; }
catch { foreach (var item in value) item.Dispose(); throw; }
}
public async Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{
Check(DataOperations.Write); if (request.Items.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request));
var value = await _inner.WriteAsync(request with { Budget = Limit(request.Budget, _batch) }, cancellationToken).ConfigureAwait(false);
try { Check(DataOperations.Write); return value; }
catch (Exception ex) when (ex is OperationCanceledException or InvalidOperationException or UnauthorizedAccessException)
{ return request.Items.Select(x => new WriteItemResult(x.CorrelationId, new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown after scope change."))).ToArray(); }
}
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
Check(DataOperations.Subscribe); var stream = await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false);
try { Check(DataOperations.Subscribe); return stream is IDataSubscriptionProvenance provenance
? new ProvenancedScopedSubscription(this, stream, provenance.Serving)
: new ScopedSubscription(this, stream); }
catch { await stream.DisposeAsync().ConfigureAwait(false); throw; }
}
private sealed class ProvenancedScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner, ServingIdentity serving)
: ScopedSubscription(owner, inner), IDataSubscriptionProvenance
{
public ServingIdentity Serving { get; } = serving;
}
private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport
{
public bool SupportsFreshnessChallenges => inner is IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true };
public int FreshnessMaxItems => inner is IDataSubscriptionFreshnessSupport support && support.SupportsFreshnessChallenges
? Math.Min(support.FreshnessMaxItems, Math.Min(owner._batch, owner._monitored)) : 0;
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
owner.Check(DataOperations.Subscribe);
var count = command switch { OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count,
ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count,
ChallengeSubscriptionFreshness c => c.Items.Count, _ => owner._monitored + 1 };
if (count > owner._monitored) throw new ArgumentOutOfRangeException(nameof(command));
if (command is ChallengeSubscriptionFreshness challenge)
{
if (!SupportsFreshnessChallenges) throw new InvalidOperationException("Peer did not negotiate freshness challenges.");
if (count <= 0 || count > FreshnessMaxItems) throw new ArgumentOutOfRangeException(nameof(command));
// Conservative preflight before any wire encoding, including UTF-8 expansion and per-handle overhead.
var bytes = 128L + 4L * (challenge.SubscriptionId?.Length ?? 0) + 4L * (challenge.CommandId?.Length ?? 0);
foreach (var handle in challenge.Items)
{
if (handle is null) throw new ArgumentException("Invalid challenge handle.", nameof(command));
bytes = checked(bytes + 128L + 4L * (handle.SubscriptionId?.Length ?? 0));
}
if (bytes > Math.Min(owner._bytes, owner._pendingBytes)) throw new ArgumentOutOfRangeException(nameof(command));
}
if (command is OpenSubscription open) command = open with { SnapshotBudget = owner.Limit(open.SnapshotBudget, owner._monitored) };
return inner.SendAsync(command, cancellationToken);
}
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var frame in inner.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
try { owner.Check(DataOperations.Subscribe); }
catch { if (frame is IDisposable owned) owned.Dispose(); throw; }
yield return frame;
}
}
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) _release(); }
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
}