feat: author and inspect grpc data connections

This commit is contained in:
Joseph Doherty
2026-11-16 20:58:43 -05:00
parent 8ad03e9c5d
commit 1df29a3124
31 changed files with 1246 additions and 141 deletions
@@ -23,7 +23,7 @@ public interface IDataConnectionSecurityProvider
public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endpoint, string CredentialVersion, string TrustFingerprint);
/// <summary>Caller-bound remote facade. All channels and requests are bounded by configured local limits.</summary>
public sealed class GrpcDataConnection : IDataConnection
public sealed partial class GrpcDataConnection : IDataConnection
{
private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer)
{
@@ -141,6 +141,8 @@ public sealed class GrpcDataConnection : IDataConnection
lock (_sync)
{
_securityGeneration++;
_diagnosticState = "connecting"; _diagnosticEndpoint = null; _diagnosticServing = null;
_lastSampleAtUtc = null; _metadataLeaseExpiresAtUtc = null; _lastVerifiedAtUtc = null; _sampleAgeUpper = null;
foreach (var item in _channels.Values)
{
_retiringChannels++;
@@ -232,6 +234,7 @@ public sealed class GrpcDataConnection : IDataConnection
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)
@@ -265,7 +268,7 @@ public sealed class GrpcDataConnection : IDataConnection
catch { if (result is IEnumerable<ReadResult> reads) foreach (var item in reads) item.Dispose(); throw; }
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; }
{ failure = ex; RecordFailure(ex); }
}
ProbeFailed();
throw new InvalidOperationException("No ready authenticated data endpoint.", failure);
@@ -282,6 +285,7 @@ public sealed class GrpcDataConnection : IDataConnection
public Task<DataBrowseBranch> 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 ||
@@ -290,6 +294,8 @@ public sealed class GrpcDataConnection : IDataConnection
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);
@@ -318,7 +324,9 @@ public sealed class GrpcDataConnection : IDataConnection
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); return result;
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);
@@ -333,13 +341,18 @@ public sealed class GrpcDataConnection : IDataConnection
{
using var admission = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, _shutdown.Token);
admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false);
if (!admitted) return request.Items.Select(x => new WriteItemResult(x.CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Unary capacity exhausted."))).ToArray();
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() };
return await WriteCoreAsync(reduced, cancellationToken).ConfigureAwait(false);
var outcomes = await WriteCoreAsync(reduced, cancellationToken).ConfigureAwait(false);
RecordWrites(outcomes); return outcomes;
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
}
@@ -500,7 +513,7 @@ public sealed class GrpcDataConnection : IDataConnection
try
{
var call = selected.Channel.Client.Subscribe(Headers(selected.Channel), cancellationToken: lifetime.Token);
subscription = new RemoteSubscription(call, selected, lifetime, _maxMessageBytes,
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);
@@ -529,7 +542,7 @@ public sealed class GrpcDataConnection : IDataConnection
}
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; }
{ failure = ex; RecordFailure(ex); }
}
ProbeFailed();
throw new InvalidOperationException("No ready subscription endpoint.", failure);
@@ -541,7 +554,7 @@ public sealed class GrpcDataConnection : IDataConnection
}
}
private sealed class RemoteSubscription(
private sealed class RemoteSubscription(GrpcDataConnection owner,
AsyncDuplexStreamingCall<W.SubscriptionCommand, W.SubscriptionFrame> call, Selected selected,
CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands,
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func<string, long, bool> claimEpoch, Action<WeakReference>? observePending,
@@ -667,6 +680,7 @@ public sealed class GrpcDataConnection : IDataConnection
catch (OperationCanceledException) { if (afterTimerCancelled is not null) await afterTimerCancelled().ConfigureAwait(false); }
catch (ObjectDisposedException) { }
}
internal int DiagnosticRegistrationCount;
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
if (Interlocked.Exchange(ref _reading, 1) != 0) throw new InvalidOperationException("A stream has one reader.");
@@ -748,6 +762,7 @@ public sealed class GrpcDataConnection : IDataConnection
_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)
@@ -765,6 +780,9 @@ public sealed class GrpcDataConnection : IDataConnection
_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; }