using System.Runtime.CompilerServices; using Google.Protobuf; using Grpc.Core; using Grpc.Net.Client; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Commons.Protos; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Versioned security material supplied by the consuming host. public sealed record DataConnectionSecurity(string CredentialVersion, string TrustFingerprint, string Bearer, Func CreateHandler) { public override string ToString() => $"DataConnectionSecurity {{ CredentialVersion = {CredentialVersion}, TrustFingerprint = {TrustFingerprint}, Bearer = [redacted] }}"; } public interface IDataConnectionSecurityProvider { ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken); event Action? Changed; } public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endpoint, string CredentialVersion, string TrustFingerprint); /// Caller-bound remote facade. All channels and requests are bounded by configured local limits. public sealed partial class GrpcDataConnection : IDataConnection { private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer) { internal readonly DataConnectionChannelIdentity Identity = identity; internal readonly GrpcChannel Channel = channel; internal readonly W.DataConnectionService.DataConnectionServiceClient Client = new(channel); internal readonly string Bearer = bearer; internal readonly CancellationTokenSource Retired = new(); } private sealed record Selected(ChannelEntry Channel, DataCapabilities Capabilities); private readonly object _sync = new(); private readonly string _id; private readonly Uri[] _endpoints; private readonly HashSet? _eligibleNodeIds; private readonly IDataConnectionSecurityProvider _security; private readonly DataConnectionScopeLease _scope; private readonly int _maxMessageBytes, _maxChannels, _maxStreams, _maxMonitoredItems, _maxPendingCommands; private readonly TimeSpan _maxCommandTimeout; private readonly SemaphoreSlim _unaryCapacity; private readonly CommandStateBudget _commandBudget; private readonly Dictionary _channels = new(); private bool _disposed; private long _securityGeneration; private int _activeStreams, _retiringChannels, _activeWork; private readonly HashSet _streams = new(); private readonly CancellationTokenSource _shutdown = new(); private readonly TaskCompletionSource _drained = new(TaskCreationOptions.RunContinuationsAsynchronously); private Task? _disposeTask, _shutdownCancellation; private long _nextProbeTimestamp; private int _probeFailures; private readonly Dictionary _streamEpochs = new(StringComparer.Ordinal); private long _streamEpochBytes; internal Func? BeforeStreamInstallForTests { get; set; } internal Action? PendingIdentityObserverForTests { get; set; } internal Func? AfterTimerCancelledForTests { get; set; } public DataTarget Target { get; } public TimeProvider Clock { get; } public GrpcDataConnection(string connectionId, DataTarget target, IEnumerable endpoints, IDataConnectionSecurityProvider security, DataConnectionScopeLease scope, int maxMessageBytes, int maxChannels, TimeProvider? clock = null, IReadOnlySet? eligibleNodeIds = null, int maxStreams = 16, int maxMonitoredItems = 10_000, int maxPendingCommands = 256, int maxConcurrentUnaryCalls = 64, TimeSpan? maxCommandTimeout = null, long maxPendingCommandBytes = 4 * 1024 * 1024) { ArgumentException.ThrowIfNullOrWhiteSpace(connectionId); ArgumentNullException.ThrowIfNull(target); target.Validate(); ArgumentNullException.ThrowIfNull(endpoints); _endpoints = endpoints.Distinct().ToArray(); if (_endpoints.Length == 0 || _endpoints.Any(x => !x.IsAbsoluteUri || x.Scheme != Uri.UriSchemeHttps)) throw new ArgumentException("Only configured HTTPS endpoints are accepted.", nameof(endpoints)); if (maxMessageBytes <= 0 || maxChannels <= 0 || _endpoints.Length > maxChannels || maxStreams <= 0 || maxMonitoredItems <= 0 || maxPendingCommands <= 0 || maxConcurrentUnaryCalls <= 0 || maxPendingCommandBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxChannels)); _maxCommandTimeout = maxCommandTimeout ?? TimeSpan.FromSeconds(30); if (_maxCommandTimeout <= TimeSpan.Zero || _maxCommandTimeout > TimeSpan.FromDays(1)) throw new ArgumentOutOfRangeException(nameof(maxCommandTimeout)); _maxStreams = maxStreams; _maxMonitoredItems = maxMonitoredItems; _maxPendingCommands = maxPendingCommands; _unaryCapacity = new(maxConcurrentUnaryCalls, maxConcurrentUnaryCalls); _commandBudget = new CommandStateBudget(Math.Min(maxPendingCommandBytes, 4L * 1024 * 1024)); if (target.Mode == DataTargetMode.Cluster && (eligibleNodeIds is null || eligibleNodeIds.Count == 0 || eligibleNodeIds.Any(string.IsNullOrWhiteSpace))) throw new ArgumentException("Cluster targets require configured eligible node identities.", nameof(eligibleNodeIds)); _eligibleNodeIds = eligibleNodeIds is null ? null : new(eligibleNodeIds, StringComparer.OrdinalIgnoreCase); _id = connectionId; Target = target; _security = security ?? throw new ArgumentNullException(nameof(security)); _scope = scope ?? throw new ArgumentNullException(nameof(scope)); _maxMessageBytes = maxMessageBytes; _maxChannels = maxChannels; Clock = clock ?? TimeProvider.System; _security.Changed += SecurityChanged; } public static int[] RetryableWriteIndexes(IReadOnlyList outcomes) => outcomes .Select((item, index) => (item, index)).Where(x => x.item.Outcome.State == DataWriteState.RejectedBeforeDispatch) .Select(x => x.index).ToArray(); private sealed class CommandStateBudget(long maximum) { private readonly object _gate = new(); private long _used; internal bool TryReserve(long amount) { lock (_gate) { if (amount < 0 || amount > maximum - _used) return false; _used += amount; return true; } } internal void Release(long amount) { lock (_gate) { _used -= amount; } } } private void SecurityChanged(string connectionId) { if (!string.Equals(_id, connectionId, StringComparison.OrdinalIgnoreCase)) return; lock (_sync) { _nextProbeTimestamp = 0; _probeFailures = 0; } RetireAll(); } private bool ProbeAllowed() { lock (_sync) return _nextProbeTimestamp == 0 || Clock.GetTimestamp() >= _nextProbeTimestamp; } private void ProbeSucceeded() { lock (_sync) { _probeFailures = 0; _nextProbeTimestamp = 0; } } private void ProbeFailed() { lock (_sync) { var power = _probeFailures; _probeFailures = Math.Min(_probeFailures + 1, 7); var milliseconds = Math.Min(30_000d, 250d * (1 << power)) * (0.8 + Random.Shared.NextDouble() * 0.4); _nextProbeTimestamp = checked(Clock.GetTimestamp() + (long)(milliseconds / 1000d * Clock.TimestampFrequency)); } } private bool ClaimStreamEpoch(string id, long epoch) { lock (_sync) { if (_disposed || string.IsNullOrWhiteSpace(id) || epoch <= 0 || _streamEpochs.TryGetValue(id, out var previous) && epoch <= previous) return false; if (!_streamEpochs.ContainsKey(id)) { var charge = checked(64L + 2L * id.Length); if (_streamEpochs.Count >= 100_000 || _streamEpochBytes + charge > 4 * 1024 * 1024) return false; _streamEpochBytes += charge; } _streamEpochs[id] = epoch; return true; } } private void RetireAll() { lock (_sync) { _securityGeneration++; _diagnosticState = "connecting"; _diagnosticEndpoint = null; _diagnosticServing = null; _lastSampleAtUtc = null; _metadataLeaseExpiresAtUtc = null; _lastVerifiedAtUtc = null; _sampleAgeUpper = null; foreach (var item in _channels.Values) { _retiringChannels++; var cancelled = item.Retired.CancelAsync(); _ = FinishChannelRetirementAsync(item, cancelled); } _channels.Clear(); } } private async Task FinishChannelRetirementAsync(ChannelEntry item, Task cancelled) { // Physical Dispose and arbitrary cancellation callbacks may block. Keep quota charged until both end. await Task.Yield(); try { await Task.WhenAll(cancelled, Task.Run(item.Channel.Dispose)).ConfigureAwait(false); } catch (Exception) { } finally { item.Retired.Dispose(); lock (_sync) { _retiringChannels--; CheckDrainedLocked(); } } } private void EnterWork() { lock (_sync) { Check(); _activeWork++; } } private void ExitWork() { lock (_sync) { _activeWork--; CheckDrainedLocked(); } } private void CheckDrainedLocked() { if (_disposed && _activeWork == 0 && _retiringChannels == 0 && _activeStreams == 0) _drained.TrySetResult(); } private void Check() { ObjectDisposedException.ThrowIf(_disposed, this); _scope.CancellationToken.ThrowIfCancellationRequested(); } private async Task ChannelAsync(Uri endpoint, CancellationToken ct) { long generation; lock (_sync) { Check(); generation = _securityGeneration; } var security = await _security.ResolveAsync(_id, endpoint, ct).ConfigureAwait(false) ?? throw new UnauthorizedAccessException("Connection credential or trust unavailable."); ArgumentException.ThrowIfNullOrWhiteSpace(security.CredentialVersion); ArgumentException.ThrowIfNullOrWhiteSpace(security.TrustFingerprint); ArgumentException.ThrowIfNullOrWhiteSpace(security.Bearer); var key = new DataConnectionChannelIdentity(_id, endpoint, security.CredentialVersion, security.TrustFingerprint); lock (_sync) { Check(); if (generation != _securityGeneration) throw new InvalidOperationException("Security changed while resolving."); if (_channels.TryGetValue(key, out var existing)) return existing; if (_channels.Count + _retiringChannels >= _maxChannels) throw new InvalidOperationException("Channel capacity exhausted."); var handler = security.CreateHandler(); try { var channel = GrpcChannel.ForAddress(endpoint, new GrpcChannelOptions { HttpHandler = handler, DisposeHttpClient = true, DisableResolverServiceConfig = true, MaxReceiveMessageSize = _maxMessageBytes, MaxSendMessageSize = _maxMessageBytes }); var entry = new ChannelEntry(key, channel, security.Bearer); _channels.Add(key, entry); return entry; } catch { handler.Dispose(); throw; } } } private Metadata Headers(ChannelEntry channel) { var headers = new Metadata { { "authorization", "Bearer " + channel.Bearer }, { "x-data-target-mode", Target.Mode.ToString() }, { "x-data-consistency", Target.Consistency.ToString() }, { "x-data-cluster-id", Target.ExpectedClusterId } }; if (Target.Mode == DataTargetMode.Node) headers.Add("x-data-node-id", Target.ExpectedNodeId!); return headers; } private TimeSpan Remaining(long start, DataBudget budget) { var remaining = budget.Timeout - Clock.GetElapsedTime(start); if (remaining <= TimeSpan.Zero) throw new TimeoutException("Original data request budget expired."); return remaining; } private CallOptions Options(ChannelEntry channel, long start, DataBudget budget, CancellationToken ct) => new(Headers(channel), DateTime.UtcNow + Remaining(start, budget), ct); private DataDecodeLimits Limits(DataBudget budget, DataCapabilities caps) => new(Math.Min(budget.MaxItems, caps.Limits.MaxBatchItems), (int)Math.Min(Math.Min(budget.MaxBytes, _maxMessageBytes), caps.Limits.MaxMessageBytes), caps.Limits.MaxValueElements); private async Task SelectAsync(Uri endpoint, long start, DataBudget budget, bool write, CancellationToken ct) { var channel = await ChannelAsync(endpoint, ct).ConfigureAwait(false); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, channel.Retired.Token, _shutdown.Token); var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 3 }, Options(channel, start, budget, linked.Token)).ResponseAsync.ConfigureAwait(false); var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(budget.MaxItems, _maxMessageBytes)); if (!caps.ResponseServingIdentity || (write && (caps.ProtocolMinor < 3 || !caps.WriteServingGenerationEnforced)) || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) || Target.Mode == DataTargetMode.Cluster && !_eligibleNodeIds!.Contains(caps.Serving.NodeId)) throw new InvalidOperationException("Endpoint is not an authenticated ready target."); linked.Token.ThrowIfCancellationRequested(); RecordSelected(endpoint, caps); return new(channel, caps); } private static void Verify(W.Serving? serving, Selected selected) { if (serving is null || DataProtoMapper.DecodeServing(serving) != selected.Capabilities.Serving) throw new InvalidOperationException("Response serving identity changed."); selected.Channel.Retired.Token.ThrowIfCancellationRequested(); } private async Task QueryAsync(DataBudget budget, Func> call, CancellationToken ct) { budget.Validate(); var start = Clock.GetTimestamp(); Exception? failure = null; EnterWork(); var admitted = false; try { using var admission = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, _shutdown.Token); admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false); if (!admitted) throw new InvalidOperationException("Unary capacity exhausted."); if (!ProbeAllowed()) throw new InvalidOperationException("Data endpoint discovery is backing off."); foreach (var endpoint in _endpoints) { Check(); try { var selected = await SelectAsync(endpoint, start, budget, false, ct).ConfigureAwait(false); ProbeSucceeded(); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); var remaining = budget with { Timeout = Remaining(start, budget) }; var result = await call(selected, remaining, Options(selected.Channel, start, budget, linked.Token)).ConfigureAwait(false); try { linked.Token.ThrowIfCancellationRequested(); return result; } catch { if (result is IEnumerable reads) foreach (var item in reads) item.Dispose(); throw; } } catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException) { failure = ex; RecordFailure(ex); } } ProbeFailed(); throw new InvalidOperationException("No ready authenticated data endpoint.", failure); } finally { if (admitted) _unaryCapacity.Release(); ExitWork(); } } private static bool SupportsWrites(DataCapabilities caps) => caps.ProtocolMinor >= 3 && caps.WriteServingGenerationEnforced; private static DataMetadata ExposeMetadata(DataMetadata metadata, ServingIdentity serving, DataCapabilities caps) => SupportsWrites(caps) ? metadata with { Serving = serving } : metadata with { Serving = serving, Writable = false, AllowedOperations = metadata.AllowedOperations & ~DataOperations.Write }; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => QueryAsync(budget, (selected, _, _) => Task.FromResult(SupportsWrites(selected.Capabilities) ? selected.Capabilities : selected.Capabilities with { Operations = selected.Capabilities.Operations & ~DataOperations.Write }), cancellationToken); public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => QueryAsync(request.Budget, async (selected, budget, options) => { var browseStarted = Clock.GetTimestamp(); var wire = await selected.Channel.Client.BrowseAsync(DataProtoMapper.EncodeBrowseRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false); Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeBrowseResponse(wire, Limits(budget, selected.Capabilities)); if (result.Lease is { } lease && (lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch || lease.AuthorityEpoch != selected.Capabilities.Serving.AuthorityEpoch || lease.Duration > selected.Capabilities.Limits.MaxMetadataLease)) throw new InvalidOperationException("Browse lease has unexpected authority or duration."); if (result.Parent != request.Parent || result.Items.Any(x => x.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch || !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase))) throw new InvalidOperationException("Browse response has unexpected provenance."); Verify(wire.Serving, selected); lock (_sync) _metadataLeaseExpiresAtUtc = result.Lease is { } observed ? Clock.GetUtcNow().UtcDateTime + TimeSpan.FromTicks(Math.Max(0, (observed.Duration - Clock.GetElapsedTime(browseStarted)).Ticks)) : null; var serving = DataProtoMapper.DecodeServing(wire.Serving); return result with { Serving = serving, Items = result.Items.Select(x => ExposeMetadata(x, serving, selected.Capabilities)).ToArray() }; }, cancellationToken); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => QueryAsync(request.Budget, async (selected, budget, options) => { var wire = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false); Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeMetadataResponse(wire, Limits(budget, selected.Capabilities)); if (result.Count != request.Views.Count || result.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) || x.Value is not null && (x.Value.View.Address != request.Views[i].Address || x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch)).Any()) throw new InvalidOperationException("Metadata response has unexpected items."); Verify(wire.Serving, selected); var serving = DataProtoMapper.DecodeServing(wire.Serving); return (IReadOnlyList>)result.Select(x => x.Value is null ? x : x with { Value = ExposeMetadata(x.Value, serving, selected.Capabilities) }).ToArray(); }, cancellationToken); public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) { var start = Clock.GetTimestamp(); return QueryAsync(request.Budget, async (selected, budget, options) => { var wire = await selected.Channel.Client.ReadAsync(DataProtoMapper.EncodeReadRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false); Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeReadResponse(wire, Limits(budget, selected.Capabilities), Clock.GetElapsedTime(start)); try { if (result.Count != request.Items.Count || !result.Select(x => x.CorrelationId).SequenceEqual(request.Items.Select(x => x.CorrelationId)) || result.Any(x => x.Sample is not null && x.Sample.Serving != selected.Capabilities.Serving)) throw new InvalidOperationException("Read response has unexpected items or serving identity."); Verify(wire.Serving, selected); if (result.LastOrDefault(x => x.Sample is not null) is { } observed) RecordSampleAge(observed.AgeBounds); return result; } catch { foreach (var item in result) item.Dispose(); throw; } }, cancellationToken); } public async Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) { request.Budget.Validate(); var admissionStart = Clock.GetTimestamp(); EnterWork(); var admitted = false; try { using var admission = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, _shutdown.Token); admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false); if (!admitted) { var rejected = request.Items.Select(x => new WriteItemResult(x.CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Unary capacity exhausted."))).ToArray(); RecordWrites(rejected); return rejected; } var elapsed = Clock.GetElapsedTime(admissionStart); var remaining = Remaining(admissionStart, request.Budget); var reduced = request with { Budget = request.Budget with { Timeout = remaining }, Items = request.Items.Select(x => x with { RemainingBudget = x.RemainingBudget - elapsed }).ToArray() }; var outcomes = await WriteCoreAsync(reduced, cancellationToken).ConfigureAwait(false); RecordWrites(outcomes); return outcomes; } finally { if (admitted) _unaryCapacity.Release(); ExitWork(); } } private async Task> WriteCoreAsync(WriteBatch request, CancellationToken cancellationToken) { request.Budget.Validate(); ArgumentNullException.ThrowIfNull(request.Items); var start = Clock.GetTimestamp(); var results = request.Items.Select(x => new WriteItemResult(x.CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "No ready endpoint."))).ToArray(); if (!ProbeAllowed()) return results; var eligible = Enumerable.Range(0, request.Items.Count).ToArray(); var attempted = false; foreach (var endpoint in _endpoints) { if (eligible.Length == 0) break; cancellationToken.ThrowIfCancellationRequested(); Selected selected; try { selected = await SelectAsync(endpoint, start, request.Budget, true, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); } catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException) { continue; } using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); // Caller-bound generations are strict: never replace any supplied precondition or rebind. var strictMismatch = eligible.Where(i => request.Items[i].ExpectedServingGeneration is { } generation && (generation <= 0 || generation != selected.Capabilities.Serving.ServingGeneration || request.Items[i].ExpectedCatalogRevision != selected.Capabilities.Serving.CatalogEpoch || request.Items[i].ExpectedServingIncarnation != selected.Capabilities.Serving.Incarnation)).ToArray(); foreach (var index in strictMismatch) results[index] = new(request.Items[index].CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Serving precondition mismatch.")); eligible = eligible.Except(strictMismatch).ToArray(); if (eligible.Length == 0) { eligible = strictMismatch; continue; } var items = eligible.Select(i => request.Items[i]).ToArray(); var deferred = strictMismatch.ToList(); if (attempted) { // Only legacy retries require fresh metadata. A failed lookup must not suppress // independently matching, not-yet-dispatched strict items on this endpoint. var legacy = Enumerable.Range(0, items.Length) .Where(i => request.Items[eligible[i]].ExpectedServingGeneration is null).ToArray(); var metadataValid = legacy.Length == 0; if (legacy.Length > 0) { try { var remaining = Remaining(start, request.Budget); var budget = request.Budget with { Timeout = remaining }; var metadataRequest = new MetadataRequest(legacy.Select(i => items[i].View).ToArray(), budget); var wireMetadata = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(metadataRequest), Options(selected.Channel, start, request.Budget, linked.Token)).ResponseAsync.ConfigureAwait(false); Verify(wireMetadata.Serving, selected); var metadata = DataProtoMapper.DecodeMetadataResponse(wireMetadata, Limits(budget, selected.Capabilities)); metadataValid = metadata.Count == legacy.Length && !metadata.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) || x.Status != DataItemStatus.Good || x.Value is null || x.Value.View != items[legacy[i]].View || x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch || !x.Value.Writable || (x.Value.AllowedOperations & DataOperations.Write) == 0).Any(); if (metadataValid) { linked.Token.ThrowIfCancellationRequested(); Verify(wireMetadata.Serving, selected); for (var i = 0; i < legacy.Length; i++) items[legacy[i]] = items[legacy[i]] with { ExpectedCatalogRevision = metadata[i].Value!.CatalogRevision, ExpectedServingIncarnation = selected.Capabilities.Serving.Incarnation }; } } catch (Exception ex) when (ex is RpcException or HttpRequestException or InvalidOperationException or ArgumentException or TimeoutException or OperationCanceledException) { if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested) break; } } if (!metadataValid) { deferred.AddRange(legacy.Select(i => eligible[i])); var strict = Enumerable.Range(0, items.Length).Except(legacy).ToArray(); eligible = strict.Select(i => eligible[i]).ToArray(); items = strict.Select(i => items[i]).ToArray(); if (eligible.Length == 0) { eligible = deferred.ToArray(); continue; } } } items = items.Select(x => x.ExpectedServingGeneration is null ? x with { ExpectedServingGeneration = selected.Capabilities.Serving.ServingGeneration } : x).ToArray(); var elapsed = Clock.GetElapsedTime(start); var live = Enumerable.Range(0, items.Length).Where(i => items[i].RemainingBudget > elapsed).ToArray(); foreach (var i in Enumerable.Range(0, items.Length).Except(live)) results[eligible[i]] = new(request.Items[eligible[i]].CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Item budget expired before dispatch.")); eligible = live.Select(i => eligible[i]).ToArray(); items = live.Select(i => items[i] with { RemainingBudget = items[i].RemainingBudget - elapsed }).ToArray(); if (eligible.Length == 0) { eligible = deferred.ToArray(); continue; } var dispatchStarted = false; try { var remaining = Remaining(start, request.Budget); var batch = new WriteBatch(items.Select(x => x with { RemainingBudget = x.RemainingBudget < remaining ? x.RemainingBudget : remaining }).ToArray(), request.Budget with { Timeout = remaining }); var options = Options(selected.Channel, start, request.Budget, linked.Token); var encoded = DataProtoMapper.EncodeWriteRequest(batch); linked.Token.ThrowIfCancellationRequested(); dispatchStarted = true; var wire = await selected.Channel.Client.WriteAsync(encoded, options).ResponseAsync.ConfigureAwait(false); var decoded = DataProtoMapper.DecodeWriteResponse(wire, Limits(batch.Budget, selected.Capabilities)); if (decoded.Count != items.Length || !decoded.Select(x => x.CorrelationId).SequenceEqual(items.Select(x => x.CorrelationId))) throw new InvalidOperationException("Invalid write result sequence."); VerifyWriteEnvelope(wire.Serving, selected, decoded); linked.Token.ThrowIfCancellationRequested(); for (var i = 0; i < eligible.Length; i++) results[eligible[i]] = decoded[i]; eligible = deferred.Concat(eligible.Where((index, i) => request.Items[index].ExpectedServingGeneration is null && decoded[i].Outcome.State == DataWriteState.RejectedBeforeDispatch)).ToArray(); attempted = true; } catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException or ArgumentException or TimeoutException) { if (dispatchStarted) foreach (var index in eligible) results[index] = new(request.Items[index].CorrelationId, new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown.")); if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested) break; eligible = dispatchStarted ? deferred.ToArray() : deferred.Concat(eligible).ToArray(); } } if (!attempted && eligible.Length > 0) ProbeFailed(); return results; } private static void VerifyWriteEnvelope(W.Serving? serving, Selected selected, IReadOnlyList results) { if (serving is null) throw new InvalidOperationException("Missing write serving identity."); var actual = DataProtoMapper.DecodeServing(serving); var expected = selected.Capabilities.Serving; if (!AcceptWriteServing(expected, actual, results)) throw new InvalidOperationException("Write serving identity changed."); selected.Channel.Retired.Token.ThrowIfCancellationRequested(); } internal static bool AcceptWriteServing(ServingIdentity expected, ServingIdentity actual, IReadOnlyList results) => actual == expected || actual.NodeId == expected.NodeId && actual.Incarnation == expected.Incarnation && results.Count > 0 && results.All(x => x.Outcome.State == DataWriteState.RejectedBeforeDispatch); public async Task SubscribeAsync(CancellationToken cancellationToken) { EnterWork(); var reserved = false; try { if (!ProbeAllowed()) throw new InvalidOperationException("Data endpoint discovery is backing off."); while (true) { var count = Volatile.Read(ref _activeStreams); if (count >= _maxStreams) throw new InvalidOperationException("Stream capacity exhausted."); if (Interlocked.CompareExchange(ref _activeStreams, count + 1, count) == count) { reserved = true; break; } } var budget = new DataBudget(TimeSpan.FromSeconds(5), 1000, _maxMessageBytes); var start = Clock.GetTimestamp(); Exception? failure = null; foreach (var endpoint in _endpoints) { try { var selected = await SelectAsync(endpoint, start, budget, false, cancellationToken).ConfigureAwait(false); if ((selected.Capabilities.Operations & DataOperations.Subscribe) == 0 || Volatile.Read(ref _activeStreams) > selected.Capabilities.Limits.MaxStreams) throw new InvalidOperationException("Subscriptions unavailable or peer stream capacity exhausted."); ProbeSucceeded(); var lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); RemoteSubscription? subscription = null; var transferred = false; try { var call = selected.Channel.Client.Subscribe(Headers(selected.Channel), cancellationToken: lifetime.Token); subscription = new RemoteSubscription(this, call, selected, lifetime, _maxMessageBytes, Math.Min(_maxMonitoredItems, selected.Capabilities.Limits.MaxMonitoredItems), _maxPendingCommands, _maxCommandTimeout, _commandBudget, ClaimStreamEpoch, PendingIdentityObserverForTests, AfterTimerCancelledForTests, () => { lock (_sync) { _streams.Remove(subscription!); Interlocked.Decrement(ref _activeStreams); CheckDrainedLocked(); } }); if (BeforeStreamInstallForTests is { } pause) await pause().ConfigureAwait(false); lock (_sync) { _streams.Add(subscription); reserved = false; transferred = true; if (_disposed) throw new ObjectDisposedException(nameof(GrpcDataConnection)); } subscription.ObserveLifetime(); return subscription; } catch { if (subscription is null) lifetime.Dispose(); else { // Once a call exists, even a failed install owns a raw-send receipt. // Transfer its slot first; cleanup and the receipt run outside this lock. if (!transferred) { lock (_sync) { _streams.Add(subscription); reserved = false; } } _ = subscription.DisposeAsync(); } throw; } } catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException) { failure = ex; RecordFailure(ex); } } ProbeFailed(); throw new InvalidOperationException("No ready subscription endpoint.", failure); } finally { if (reserved) { lock (_sync) { Interlocked.Decrement(ref _activeStreams); CheckDrainedLocked(); } } ExitWork(); } } private sealed class RemoteSubscription(GrpcDataConnection owner, AsyncDuplexStreamingCall call, Selected selected, CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands, TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func claimEpoch, Action? observePending, Func? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance { public ServingIdentity Serving { get; } = selected.Capabilities.Serving; private readonly SemaphoreSlim _send = new(1, 1); private readonly Task _headersReceipt = call.ResponseHeadersAsync; private Dictionary _handles = new(); private Dictionary _clientHandles = new(StringComparer.Ordinal); private HashSet _usedHandles = new(); private Dictionary _versions = new(); private sealed record PendingCommand(string Id, string[]? ClientIds, DataItemHandle[]? Removed, bool IsModify, TimeSpan Timeout, long Bytes, CancellationTokenSource Timer); private readonly Dictionary _pending = new(StringComparer.Ordinal); private long _pendingBytes, _usedCommandBytes; private readonly HashSet _usedCommands = new(StringComparer.Ordinal); private string? _id; private long _epoch, _sequence; private int _disposed, _reading, _operations; private bool _physicalClosed, _released; private readonly object _lifecycle = new(); private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously); private CancellationTokenRegistration _retirementRegistration; internal void ObserveLifetime() => _retirementRegistration = lifetime.Token.Register(() => { _ = Task.Run(async () => await DisposeAsync()); }); private void EnterOperation() { lock (_lifecycle) { ObjectDisposedException.ThrowIf(_disposed != 0, this); _operations++; } } private void ExitOperation() { bool finish; lock (_lifecycle) { _operations--; finish = TryFinishLocked(); } if (finish) Finish(); } private bool TryFinishLocked() { if (_disposed == 0 || !_physicalClosed || _operations != 0 || _released) return false; _released = true; return true; } private void Finish() { _retirementRegistration.Dispose(); lock (_pending) { foreach (var pending in _pending.Values) { pending.Timer.Cancel(); pending.Timer.Dispose(); } _pending.Clear(); commandBudget.Release(checked(_pendingBytes + _usedCommandBytes)); _pendingBytes = 0; _usedCommandBytes = 0; } lifetime.Dispose(); release(); _closed.TrySetResult(); } public async Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) { EnterOperation(); try { ArgumentNullException.ThrowIfNull(command); if (command.AcknowledgementTimeout <= TimeSpan.Zero || command.AcknowledgementTimeout > maxCommandTimeout) throw new ArgumentOutOfRangeException(nameof(command)); using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lifetime.Token); linked.CancelAfter(command.AcknowledgementTimeout); if (!await _send.WaitAsync(0, linked.Token).ConfigureAwait(false)) throw new InvalidOperationException("A command is already being sent."); try { if (_id is null) { if (command is not OpenSubscription) throw new InvalidOperationException("First command must open the stream."); if (!claimEpoch(command.SubscriptionId, command.StreamEpoch)) throw new InvalidOperationException("Subscription epoch was already used or history capacity exhausted."); _id = command.SubscriptionId; _epoch = command.StreamEpoch; } if (command.SubscriptionId != _id || command.StreamEpoch != _epoch || command.StreamEpoch <= 0) throw new InvalidOperationException("Command belongs to another stream epoch."); var count = command switch { OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count, ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, _ => maxItems + 1 }; if (count > maxItems) throw new InvalidOperationException("Command item capacity exceeded."); var encoded = DataProtoMapper.EncodeCommand(command); if (encoded.CalculateSize() > Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes)) throw new InvalidOperationException("Command byte capacity exceeded."); string[]? ids = command switch { OpenSubscription => encoded.Open.Items.Select(x => x.ClientItemId).ToArray(), AddSubscriptionItems => encoded.Add.Items.Select(x => x.ClientItemId).ToArray(), ModifySubscriptionItems => encoded.Modify.Items.Select(x => x.ClientItemId).ToArray(), _ => null }; var removed = command is RemoveSubscriptionItems ? encoded.Remove.Items.Select(DataProtoMapper.DecodeHandle).ToArray() : null; long charge = checked(256L + 2L * encoded.CommandId.Length + (ids?.Sum(x => 64L + 2L * x.Length) ?? 0L) + (removed?.Sum(x => 96L + 2L * x.SubscriptionId.Length) ?? 0L)); var pending = new PendingCommand(encoded.CommandId, ids, removed, command is ModifySubscriptionItems, command.AcknowledgementTimeout, charge, CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token)); lock (_pending) { var commandLimit = (int)Math.Min(100_000L, Math.Max(1024L, 4L * maxItems)); long usedCharge = checked(64L + 2L * pending.Id.Length); if (_pending.Count >= maxPendingCommands || _usedCommands.Count >= commandLimit || _usedCommands.Contains(pending.Id) || !commandBudget.TryReserve(checked(charge + usedCharge))) { pending.Timer.Dispose(); throw new InvalidOperationException("Command capacity or duplicate command."); } _usedCommands.Add(pending.Id); _pending.Add(pending.Id, pending); _pendingBytes += charge; _usedCommandBytes += usedCharge; } if (pending.ClientIds is not null) observePending?.Invoke(new WeakReference(pending.ClientIds)); _ = ExpireUnacknowledgedAsync(pending.Id, pending.Timeout, pending.Timer); try { await call.RequestStream.WriteAsync(encoded, linked.Token).ConfigureAwait(false); } catch { await lifetime.CancelAsync().ConfigureAwait(false); throw; } } finally { _send.Release(); } } finally { ExitOperation(); } } private async Task ExpireUnacknowledgedAsync(string commandId, TimeSpan timeout, CancellationTokenSource timer) { try { await Task.Delay(timeout, timer.Token).ConfigureAwait(false); Task? cancellation = null; lock (_pending) if (_pending.TryGetValue(commandId, out var current) && ReferenceEquals(current.Timer, timer)) cancellation = lifetime.CancelAsync(); if (cancellation is not null) await cancellation.ConfigureAwait(false); } catch (OperationCanceledException) { if (afterTimerCancelled is not null) await afterTimerCancelled().ConfigureAwait(false); } catch (ObjectDisposedException) { } } internal int DiagnosticRegistrationCount; public async IAsyncEnumerable ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken) { if (Interlocked.Exchange(ref _reading, 1) != 0) throw new InvalidOperationException("A stream has one reader."); using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lifetime.Token); try { while (true) { bool more; EnterOperation(); try { more = await call.ResponseStream.MoveNext(linked.Token).ConfigureAwait(false); } finally { ExitOperation(); } if (!more) break; var wire = call.ResponseStream.Current; Verify(wire.Serving, selected); if (_id is null || wire.SubscriptionId != _id || wire.StreamEpoch != _epoch || wire.Sequence != _sequence + 1) throw new InvalidOperationException("Unexpected stream epoch or sequence."); DataSubscriptionFrame frame; if (wire.Values is not null || wire.CompactValues is not null) frame = DataProtoMapper.DecodeValues(wire, _handles, maxItems, Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes), selected.Capabilities.Serving, selected.Capabilities.Limits.MaxValueElements, selected.Capabilities.SubscriptionAgeReadiness); else frame = DataProtoMapper.DecodeControlOrAck(wire, new DataDecodeLimits(maxItems, Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes), selected.Capabilities.Limits.MaxValueElements)); try { Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); if (frame is DataSubscriptionAck ack) { PendingCommand pending; lock (_pending) { if (!_pending.TryGetValue(ack.CommandId, out pending!)) throw new InvalidOperationException("Unknown acknowledgement."); } var requested = pending.ClientIds ?? pending.Removed!.Select(_ => (string?)null).ToArray(); if (ack.Items.Count != requested.Length) throw new InvalidOperationException("Unexpected acknowledgement count."); var next = new Dictionary(_handles); var nextClients = new Dictionary(_clientHandles, StringComparer.Ordinal); var nextUsed = new HashSet(_usedHandles); var nextVersions = new Dictionary(_versions); for (var i = 0; i < ack.Items.Count; i++) { var item = ack.Items[i]; if (requested[i] is { } clientId && item.ClientItemId != clientId) throw new InvalidOperationException("Unexpected acknowledgement item."); if (item.Status != DataItemStatus.Good) continue; var handle = item.Handle ?? throw new InvalidOperationException("Successful acknowledgement has no handle."); if (pending.Removed is { } removedItems) { if (removedItems[i] != handle || !next.Remove(handle.Handle) || !nextClients.Remove(item.ClientItemId, out var removed) || removed != handle.Handle) throw new InvalidOperationException("Unexpected removed handle."); nextVersions.Remove(handle.Handle); } else { DataItemHandle? prior = null; if (pending.IsModify) { if (!nextClients.TryGetValue(item.ClientItemId, out var previous) || !next.Remove(previous, out prior)) throw new InvalidOperationException("Unknown modified item."); if (previous != handle.Handle) nextVersions.Remove(previous); } else if (nextClients.ContainsKey(item.ClientItemId)) throw new InvalidOperationException("Duplicate item."); var unchanged = prior == handle; if ((!unchanged && nextUsed.Contains(handle.Handle)) || next.Count >= maxItems || next.ContainsKey(handle.Handle)) throw new InvalidOperationException("Handle capacity or identity conflict."); if (!unchanged && nextUsed.Count >= Math.Min(100_000L, Math.Max(1024L, 4L * maxItems))) throw new InvalidOperationException("Handle history capacity exhausted; reset the stream."); nextUsed.Add(handle.Handle); next[handle.Handle] = handle; nextClients[item.ClientItemId] = handle.Handle; } } Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); lock (_pending) { linked.Token.ThrowIfCancellationRequested(); if (!_pending.Remove(ack.CommandId)) throw new InvalidOperationException("Acknowledgement expired."); _pendingBytes -= pending.Bytes; commandBudget.Release(pending.Bytes); pending.Timer.Cancel(); pending.Timer.Dispose(); _handles = next; _clientHandles = nextClients; _usedHandles = nextUsed; _versions = nextVersions; Volatile.Write(ref DiagnosticRegistrationCount, next.Count); } } if (frame is DataSubscriptionValues values) { var nextVersions = new Dictionary(_versions); var seen = new HashSet(); foreach (var item in values.Items) { if (!seen.Add(item.Handle.Handle) || nextVersions.TryGetValue(item.Handle.Handle, out var previous) && item.Sample.Version < previous) throw new InvalidOperationException("Duplicate handle or sample version regression."); nextVersions[item.Handle.Handle] = item.Sample.Version; } Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); _versions = nextVersions; } _sequence = wire.Sequence; } catch { if (frame is IDisposable owned) owned.Dispose(); throw; } if (frame is DataSubscriptionValues { Items.Count: > 0 } observedValues) owner.RecordSampleAge(observedValues.Items[^1].AgeBounds); if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset }) Interlocked.Increment(ref owner._resetCount); if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Coalesced }) Interlocked.Increment(ref owner._coalescedCount); yield return frame; if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset }) { await lifetime.CancelAsync().ConfigureAwait(false); yield break; } } } finally { await DisposeAsync().ConfigureAwait(false); } } public ValueTask DisposeAsync() { lock (_lifecycle) { if (_disposed == 0) { _disposed = 1; _ = ClosePhysicalAsync(); } return new(_closed.Task); } } private async Task ClosePhysicalAsync() { await Task.Yield(); try { await Task.Run(() => { lifetime.Cancel(); call.Dispose(); }).ConfigureAwait(false); } catch (Exception) { } // Unlike MoveNext's pre-header task, this receipt settles only after the raw HTTP send does. try { await _headersReceipt.ConfigureAwait(false); } catch (Exception) { } bool finish; lock (_lifecycle) { _physicalClosed = true; finish = TryFinishLocked(); } if (finish) Finish(); } } public ValueTask DisposeAsync() { lock (_sync) { if (_disposeTask is not null) return new(_disposeTask); _disposed = true; _security.Changed -= SecurityChanged; _shutdownCancellation = _shutdown.CancelAsync(); RetireAll(); foreach (var stream in _streams.ToArray()) _ = stream.DisposeAsync(); CheckDrainedLocked(); _disposeTask = FinishDisposeAsync(); return new(_disposeTask); } } private async Task FinishDisposeAsync() { await _drained.Task.ConfigureAwait(false); try { if (_shutdownCancellation is not null) await _shutdownCancellation.ConfigureAwait(false); } finally { _scope.Dispose(); _shutdown.Dispose(); } } }