feat: expose mapped raw and uns data through grpc adapters
This commit is contained in:
@@ -225,10 +225,10 @@ public sealed 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 = 2 },
|
||||
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 || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) ||
|
||||
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();
|
||||
@@ -272,8 +272,13 @@ public sealed class GrpcDataConnection : IDataConnection
|
||||
}
|
||||
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<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) =>
|
||||
QueryAsync(budget, (selected, _, _) => Task.FromResult(selected.Capabilities), cancellationToken);
|
||||
QueryAsync(budget, (selected, _, _) => Task.FromResult(SupportsWrites(selected.Capabilities) ? selected.Capabilities :
|
||||
selected.Capabilities with { Operations = selected.Capabilities.Operations & ~DataOperations.Write }), cancellationToken);
|
||||
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) =>
|
||||
QueryAsync(request.Budget, async (selected, budget, options) =>
|
||||
{
|
||||
@@ -282,9 +287,11 @@ public sealed class GrpcDataConnection : IDataConnection
|
||||
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 => !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)))
|
||||
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); return result;
|
||||
Verify(wire.Serving, selected);
|
||||
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) =>
|
||||
@@ -292,9 +299,11 @@ public sealed class GrpcDataConnection : IDataConnection
|
||||
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).Any())
|
||||
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); return result;
|
||||
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();
|
||||
}, cancellationToken);
|
||||
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -353,30 +362,61 @@ public sealed class GrpcDataConnection : IDataConnection
|
||||
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)
|
||||
{
|
||||
// A retry needs fresh, authenticated metadata from the new primary. Never infer a
|
||||
// catalog revision from its serving epoch or reuse the old node incarnation.
|
||||
try
|
||||
// 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)
|
||||
{
|
||||
var remaining = Remaining(start, request.Budget);
|
||||
var budget = request.Budget with { Timeout = remaining };
|
||||
var metadataRequest = new MetadataRequest(items.Select(x => x.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));
|
||||
if (metadata.Count != items.Length || metadata.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) ||
|
||||
x.Status != DataItemStatus.Good || x.Value is null || x.Value.View.Address != items[i].View.Address ||
|
||||
!x.Value.Writable || (x.Value.AllowedOperations & DataOperations.Write) == 0).Any()) continue;
|
||||
linked.Token.ThrowIfCancellationRequested(); Verify(wireMetadata.Serving, selected);
|
||||
items = items.Select((x, i) => x with { ExpectedCatalogRevision = metadata[i].Value!.CatalogRevision,
|
||||
ExpectedServingIncarnation = selected.Capabilities.Serving.Incarnation }).ToArray();
|
||||
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; }
|
||||
}
|
||||
catch (Exception ex) when (ex is RpcException or InvalidOperationException or ArgumentException or TimeoutException or OperationCanceledException)
|
||||
{ if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested) break; 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))
|
||||
@@ -384,7 +424,7 @@ public sealed class GrpcDataConnection : IDataConnection
|
||||
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) break;
|
||||
if (eligible.Length == 0) { eligible = deferred.ToArray(); continue; }
|
||||
var dispatchStarted = false;
|
||||
try
|
||||
{
|
||||
@@ -402,7 +442,7 @@ public sealed class GrpcDataConnection : IDataConnection
|
||||
VerifyWriteEnvelope(wire.Serving, selected, decoded);
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
for (var i = 0; i < eligible.Length; i++) results[eligible[i]] = decoded[i];
|
||||
eligible = eligible.Where((_, i) => decoded[i].Outcome.State == DataWriteState.RejectedBeforeDispatch).ToArray();
|
||||
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)
|
||||
@@ -410,7 +450,8 @@ public sealed class GrpcDataConnection : IDataConnection
|
||||
if (dispatchStarted)
|
||||
foreach (var index in eligible) results[index] = new(request.Items[index].CorrelationId,
|
||||
new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown."));
|
||||
break;
|
||||
if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested) break;
|
||||
eligible = dispatchStarted ? deferred.ToArray() : deferred.Concat(eligible).ToArray();
|
||||
}
|
||||
}
|
||||
if (!attempted && eligible.Length > 0) ProbeFailed();
|
||||
@@ -504,8 +545,9 @@ public sealed class GrpcDataConnection : IDataConnection
|
||||
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,
|
||||
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription
|
||||
Func<Task>? 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<ulong, DataItemHandle> _handles = new();
|
||||
|
||||
Reference in New Issue
Block a user