test: validate grpc data connections with local docker and opcua cli
This commit is contained in:
@@ -34,6 +34,9 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
internal readonly CancellationTokenSource Retired = new();
|
||||
}
|
||||
private sealed record Selected(ChannelEntry Channel, DataCapabilities Capabilities);
|
||||
// Capability discovery is a protocol envelope, not an operation result page.
|
||||
// Bound its advertised kinds by the locally understood finite enum.
|
||||
private static readonly int MaxCapabilityKinds = Enum.GetValues<DataValueKind>().Length - 1;
|
||||
private readonly object _sync = new();
|
||||
private readonly string _id;
|
||||
private readonly Uri[] _endpoints;
|
||||
@@ -42,6 +45,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
private readonly DataConnectionScopeLease _scope;
|
||||
private readonly int _maxMessageBytes, _maxChannels, _maxStreams, _maxMonitoredItems, _maxPendingCommands;
|
||||
private readonly TimeSpan _maxCommandTimeout;
|
||||
private readonly bool _enableCompactBatches;
|
||||
private readonly SemaphoreSlim _unaryCapacity;
|
||||
private readonly CommandStateBudget _commandBudget;
|
||||
private readonly Dictionary<DataConnectionChannelIdentity, ChannelEntry> _channels = new();
|
||||
@@ -66,7 +70,8 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
IDataConnectionSecurityProvider security, DataConnectionScopeLease scope, int maxMessageBytes,
|
||||
int maxChannels, TimeProvider? clock = null, IReadOnlySet<string>? eligibleNodeIds = null,
|
||||
int maxStreams = 16, int maxMonitoredItems = 10_000, int maxPendingCommands = 256,
|
||||
int maxConcurrentUnaryCalls = 64, TimeSpan? maxCommandTimeout = null, long maxPendingCommandBytes = 4 * 1024 * 1024)
|
||||
int maxConcurrentUnaryCalls = 64, TimeSpan? maxCommandTimeout = null, long maxPendingCommandBytes = 4 * 1024 * 1024,
|
||||
bool enableCompactBatches = true)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(connectionId);
|
||||
ArgumentNullException.ThrowIfNull(target); target.Validate();
|
||||
@@ -80,6 +85,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
_maxCommandTimeout = maxCommandTimeout ?? TimeSpan.FromSeconds(30);
|
||||
if (_maxCommandTimeout <= TimeSpan.Zero || _maxCommandTimeout > TimeSpan.FromDays(1)) throw new ArgumentOutOfRangeException(nameof(maxCommandTimeout));
|
||||
_maxStreams = maxStreams; _maxMonitoredItems = maxMonitoredItems; _maxPendingCommands = maxPendingCommands;
|
||||
_enableCompactBatches = enableCompactBatches;
|
||||
_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)))
|
||||
@@ -227,9 +233,11 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
{
|
||||
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 },
|
||||
var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 5 },
|
||||
Options(channel, start, budget, linked.Token)).ResponseAsync.ConfigureAwait(false);
|
||||
var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(budget.MaxItems, _maxMessageBytes));
|
||||
if (response.ValueKinds.Count > MaxCapabilityKinds || response.ValueKinds.Distinct().Count() != response.ValueKinds.Count)
|
||||
throw new ArgumentException("Invalid capability value kinds.");
|
||||
var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(MaxCapabilityKinds, _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.");
|
||||
@@ -299,18 +307,31 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
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<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
|
||||
QueryAsync(request.Budget, async (selected, budget, options) =>
|
||||
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Covers endpoint selection, dispatch, transport and decoding, never a peer-supplied clock.
|
||||
var started = Clock.GetTimestamp();
|
||||
return 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())
|
||||
x.Value is not null && (x.Value.View.Address != request.Views[i].Address || x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch) ||
|
||||
selected.Capabilities.MetadataItemLeases && x.Lease is { } lease &&
|
||||
(lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch || lease.AuthorityEpoch != selected.Capabilities.Serving.AuthorityEpoch ||
|
||||
lease.Duration > selected.Capabilities.Limits.MaxMetadataLease)).Any())
|
||||
throw new InvalidOperationException("Metadata response has unexpected items.");
|
||||
Verify(wire.Serving, selected);
|
||||
var serving = DataProtoMapper.DecodeServing(wire.Serving);
|
||||
return (IReadOnlyList<DataItemResult<DataMetadata>>)result.Select(x => x.Value is null ? x : x with { Value = ExposeMetadata(x.Value, serving, selected.Capabilities) }).ToArray();
|
||||
return (IReadOnlyList<DataItemResult<DataMetadata>>)result.Select((x, i) => x with
|
||||
{
|
||||
Value = x.Value is null ? null : ExposeMetadata(x.Value, serving, selected.Capabilities),
|
||||
Lease = selected.Capabilities.MetadataItemLeases && x.Value?.View == request.Views[i] ? x.Lease : null,
|
||||
LeaseRequestStartedTimestamp = selected.Capabilities.MetadataItemLeases && x.Value?.View == request.Views[i] && x.Lease is not null
|
||||
? started : null,
|
||||
}).ToArray();
|
||||
}, cancellationToken);
|
||||
}
|
||||
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var start = Clock.GetTimestamp();
|
||||
@@ -318,7 +339,8 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
{
|
||||
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));
|
||||
var observedAt = Clock.GetTimestamp();
|
||||
var result = DataProtoMapper.DecodeReadResponse(wire, Limits(budget, selected.Capabilities), Clock.GetElapsedTime(start, observedAt));
|
||||
try
|
||||
{
|
||||
if (result.Count != request.Items.Count || !result.Select(x => x.CorrelationId).SequenceEqual(request.Items.Select(x => x.CorrelationId)) ||
|
||||
@@ -326,7 +348,8 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
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;
|
||||
// The decoded results transfer their owned leases to these stamped copies.
|
||||
return (IReadOnlyList<ReadResult>)result.Select(item => item with { FreshnessObservedTimestamp = observedAt }).ToArray();
|
||||
}
|
||||
catch { foreach (var item in result) item.Dispose(); throw; }
|
||||
}, cancellationToken);
|
||||
@@ -366,14 +389,22 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
if (!ProbeAllowed()) return results;
|
||||
var eligible = Enumerable.Range(0, request.Items.Count).ToArray();
|
||||
var attempted = false;
|
||||
var readReadyButWriteIneligible = 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(); }
|
||||
try { selected = await SelectAsync(endpoint, start, request.Budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
|
||||
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException)
|
||||
{ continue; }
|
||||
if (!SupportsWrites(selected.Capabilities) || !ClusterEndpointSelector.IsEligible(Target, selected.Capabilities, true))
|
||||
{
|
||||
// A read-ready endpoint can be intentionally ineligible for writes. Do not
|
||||
// turn that policy decision into discovery backoff for subsequent reads.
|
||||
readReadyButWriteIneligible = true;
|
||||
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 &&
|
||||
@@ -467,7 +498,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
eligible = dispatchStarted ? deferred.ToArray() : deferred.Concat(eligible).ToArray();
|
||||
}
|
||||
}
|
||||
if (!attempted && eligible.Length > 0) ProbeFailed();
|
||||
if (!attempted && eligible.Length > 0 && !readReadyButWriteIneligible) ProbeFailed();
|
||||
return results;
|
||||
}
|
||||
private static void VerifyWriteEnvelope(W.Serving? serving, Selected selected, IReadOnlyList<WriteItemResult> results)
|
||||
@@ -512,8 +543,11 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
var transferred = false;
|
||||
try
|
||||
{
|
||||
var call = selected.Channel.Client.Subscribe(Headers(selected.Channel), cancellationToken: lifetime.Token);
|
||||
subscription = new RemoteSubscription(this, call, selected, lifetime, _maxMessageBytes,
|
||||
var compact = _enableCompactBatches && DataProtoMapper.NegotiateCompact(selected.Capabilities);
|
||||
var headers = Headers(selected.Channel);
|
||||
if (compact) headers.Add(DataConnectionProtoContract.CompactCodecHeader, DataConnectionProtoContract.CompactCodecVersion.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
var call = selected.Channel.Client.Subscribe(headers, cancellationToken: lifetime.Token);
|
||||
subscription = new RemoteSubscription(this, call, selected, lifetime, compact, _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);
|
||||
@@ -556,11 +590,16 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
|
||||
private sealed class RemoteSubscription(GrpcDataConnection owner,
|
||||
AsyncDuplexStreamingCall<W.SubscriptionCommand, W.SubscriptionFrame> call, Selected selected,
|
||||
CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands,
|
||||
CancellationTokenSource lifetime, bool compactNegotiated, int maxBytes, int maxItems, int maxPendingCommands,
|
||||
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func<string, long, bool> claimEpoch, Action<WeakReference>? observePending,
|
||||
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance
|
||||
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance, IDataSubscriptionFreshnessSupport
|
||||
{
|
||||
public ServingIdentity Serving { get; } = selected.Capabilities.Serving;
|
||||
public bool SupportsFreshnessChallenges => selected.Capabilities.SubscriptionFreshnessChallenges && selected.Capabilities.SubscriptionAgeReadiness;
|
||||
public int FreshnessMaxItems => selected.Capabilities.Limits.MaxBatchItems;
|
||||
private readonly Dictionary<string, long> _freshnessStarts = new(StringComparer.Ordinal);
|
||||
private readonly Queue<string> _freshnessOrder = new();
|
||||
private long _lastFreshnessSequence;
|
||||
private readonly SemaphoreSlim _send = new(1, 1);
|
||||
private readonly Task _headersReceipt = call.ResponseHeadersAsync;
|
||||
private Dictionary<ulong, DataItemHandle> _handles = new();
|
||||
@@ -568,7 +607,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
private HashSet<ulong> _usedHandles = new();
|
||||
private Dictionary<ulong, long> _versions = new();
|
||||
private sealed record PendingCommand(string Id, string[]? ClientIds, DataItemHandle[]? Removed,
|
||||
bool IsModify, TimeSpan Timeout, long Bytes, CancellationTokenSource Timer);
|
||||
bool IsModify, bool IsChallenge, TimeSpan Timeout, long Bytes, CancellationTokenSource Timer);
|
||||
private readonly Dictionary<string, PendingCommand> _pending = new(StringComparer.Ordinal);
|
||||
private long _pendingBytes, _usedCommandBytes;
|
||||
private readonly HashSet<string> _usedCommands = new(StringComparer.Ordinal);
|
||||
@@ -630,8 +669,9 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
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 };
|
||||
ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, ChallengeSubscriptionFreshness c => c.Items.Count, _ => maxItems + 1 };
|
||||
if (count > maxItems) throw new InvalidOperationException("Command item capacity exceeded.");
|
||||
if (command is ChallengeSubscriptionFreshness && !SupportsFreshnessChallenges) throw new InvalidOperationException("Peer did not negotiate freshness challenges.");
|
||||
var encoded = DataProtoMapper.EncodeCommand(command);
|
||||
if (encoded.CalculateSize() > Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes))
|
||||
throw new InvalidOperationException("Command byte capacity exceeded.");
|
||||
@@ -642,23 +682,41 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
ModifySubscriptionItems => encoded.Modify.Items.Select(x => x.ClientItemId).ToArray(),
|
||||
_ => null
|
||||
};
|
||||
var removed = command is RemoveSubscriptionItems ? encoded.Remove.Items.Select(DataProtoMapper.DecodeHandle).ToArray() : null;
|
||||
var removed = command switch { RemoveSubscriptionItems => encoded.Remove.Items.Select(DataProtoMapper.DecodeHandle).ToArray(),
|
||||
ChallengeSubscriptionFreshness => encoded.FreshnessChallenge.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));
|
||||
command is ChallengeSubscriptionFreshness, 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) ||
|
||||
long sequence = 0;
|
||||
if (pending.IsChallenge && (pending.Id.Length > 32 || !pending.Id.StartsWith("freshness-", StringComparison.Ordinal) ||
|
||||
!long.TryParse(pending.Id.AsSpan("freshness-".Length), System.Globalization.NumberStyles.None,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out sequence) || sequence <= _lastFreshnessSequence))
|
||||
{ pending.Timer.Dispose(); throw new InvalidOperationException("Freshness challenge sequence is invalid."); }
|
||||
if (!pending.IsChallenge && pending.Id.StartsWith("freshness-", StringComparison.Ordinal))
|
||||
{ pending.Timer.Dispose(); throw new InvalidOperationException("Reserved command identifier."); }
|
||||
long usedCharge = pending.IsChallenge ? 0 : checked(64L + 2L * pending.Id.Length);
|
||||
if (_pending.Count >= maxPendingCommands || (!pending.IsChallenge && (_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);
|
||||
if (pending.IsChallenge) _lastFreshnessSequence = sequence;
|
||||
else _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);
|
||||
if (pending.IsChallenge)
|
||||
{
|
||||
lock (_pending)
|
||||
{
|
||||
_freshnessStarts.Add(pending.Id, owner.Clock.GetTimestamp()); _freshnessOrder.Enqueue(pending.Id);
|
||||
while (_freshnessOrder.Count > 16) _freshnessStarts.Remove(_freshnessOrder.Dequeue());
|
||||
}
|
||||
}
|
||||
try { await call.RequestStream.WriteAsync(encoded, linked.Token).ConfigureAwait(false); }
|
||||
catch { await lifetime.CancelAsync().ConfigureAwait(false); throw; }
|
||||
}
|
||||
@@ -699,6 +757,8 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
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.CompactValues is not null && !compactNegotiated)
|
||||
throw new InvalidOperationException("Unnegotiated compact subscription 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,
|
||||
@@ -730,10 +790,19 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
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);
|
||||
if (removedItems[i] != handle) throw new InvalidOperationException("Unexpected acknowledged handle.");
|
||||
if (pending.IsChallenge)
|
||||
{
|
||||
if (!next.TryGetValue(handle.Handle, out var currentHandle) || currentHandle != handle ||
|
||||
!nextClients.TryGetValue(item.ClientItemId, out var currentClient) || currentClient != handle.Handle)
|
||||
throw new InvalidOperationException("Unexpected challenged handle.");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!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
|
||||
{
|
||||
@@ -776,11 +845,40 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
nextVersions[item.Handle.Handle] = item.Sample.Version;
|
||||
}
|
||||
Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); _versions = nextVersions;
|
||||
if (SupportsFreshnessChallenges)
|
||||
{
|
||||
var bounded = new List<DataSubscriptionValue>(values.Items.Count);
|
||||
try
|
||||
{
|
||||
foreach (var item in values.Items)
|
||||
{
|
||||
long start;
|
||||
lock (_pending) start = item.FreshnessChallengeId is { } nonce && _freshnessStarts.TryGetValue(nonce, out var known) ? known : -1;
|
||||
var bounds = item.AgeBounds;
|
||||
long? observed = null;
|
||||
if (start >= 0 && bounds.Lower is { } lower)
|
||||
{
|
||||
observed = owner.Clock.GetTimestamp();
|
||||
bounds = new(bounds.Lower, lower + owner.Clock.GetElapsedTime(start, observed.Value));
|
||||
}
|
||||
bounded.Add(item with { Sample = item.Sample with { Value = item.Sample.Value.Retain() }, AgeBounds = bounds,
|
||||
FreshnessObservedTimestamp = observed });
|
||||
}
|
||||
frame = new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot, bounded, values);
|
||||
}
|
||||
catch { foreach (var item in bounded) item.Sample.Dispose(); throw; }
|
||||
}
|
||||
}
|
||||
_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 DataSubscriptionValues observedValues)
|
||||
{
|
||||
if (wire.CompactValues is not null) Interlocked.Increment(ref owner._compactFrameCount);
|
||||
else Interlocked.Increment(ref owner._fallbackFrameCount);
|
||||
Interlocked.Add(ref owner._serializedValueFrameBytes, wire.CalculateSize());
|
||||
if (observedValues.Items.Count > 0) 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;
|
||||
|
||||
Reference in New Issue
Block a user