Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs
T

471 lines
31 KiB
C#

using Google.Protobuf;
using Grpc.Core;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Commons.Protos;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Host.Grpc;
/// <summary>Dedicated authenticated transport over the caller-bound origin-local ports.</summary>
[BindServiceMethod(typeof(DataConnectionGrpcBinding), nameof(DataConnectionGrpcBinding.BindService))]
public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IOptions<DataConnectionOptions> options,
DataConnectionAuthenticator authenticator) : W.DataConnectionService.DataConnectionServiceBase
{
private readonly DataConnectionOptions _options = options.Value;
/// <summary>
/// The optional features this server honours on a call that requests them (H2: history). A feature is effective on
/// a call only when the header asked for it, this server supports it AND the origin can serve it (history: the
/// connection's capabilities carry <see cref="DataCapabilities.History"/>). A header-less call keeps v1 shapes exactly.
/// </summary>
internal static DataFeatures SupportedFeatures => DataFeatures.History | DataFeatures.Conditions;
/// <summary>
/// Whether this call negotiated history against <paramref name="caps"/>. Refines the recorded effective set: an
/// origin that cannot serve history drops it, so the call stays v1-shaped.
/// </summary>
internal static bool HistoryNegotiated(ServerCallContext context, DataCapabilities caps)
{
var features = CallFeatures(context);
var negotiated = (features.Effective & DataFeatures.History) != 0 && caps.History is not null;
if (!negotiated && (features.Effective & DataFeatures.History) != 0)
context.UserState[typeof(DataCallFeatures)] = features with { Effective = features.Effective & ~DataFeatures.History };
return negotiated;
}
/// <summary>
/// A2: whether this call negotiated conditions against <paramref name="caps"/> (the origin serves them: the connection's
/// capabilities carry <see cref="DataCapabilities.Conditions"/>). Refines the recorded effective set like history.
/// </summary>
internal static bool ConditionsNegotiated(ServerCallContext context, DataCapabilities caps)
{
var features = CallFeatures(context);
var negotiated = (features.Effective & DataFeatures.Conditions) != 0 && caps.Conditions is not null;
if (!negotiated && (features.Effective & DataFeatures.Conditions) != 0)
context.UserState[typeof(DataCallFeatures)] = features with { Effective = features.Effective & ~DataFeatures.Conditions };
return negotiated;
}
/// <summary>A2: the v1 shape of a capabilities response with respect to conditions: no field 17, no AlarmSubscribe bit.</summary>
internal static void StripConditions(W.CapabilitiesResponse response)
{
response.Conditions = null;
response.Operations &= ~(uint)DataOperations.AlarmSubscribe;
}
/// <summary>A2: a metadata item never carries AlarmSubscribe on a call without conditions (it is a root-scope grant).</summary>
internal static void StripConditions(W.Metadata? metadata)
{
if (metadata is null) return;
metadata.AllowedOperations &= ~(uint)DataOperations.AlarmSubscribe;
}
/// <summary>The v1 shape of a capabilities response: no history field and no HistoryRead bit.</summary>
internal static void StripHistory(W.CapabilitiesResponse response)
{
response.History = null;
response.Operations &= ~(uint)DataOperations.HistoryRead;
}
/// <summary>The v1 shape of a metadata item: no history info and no HistoryRead bit.</summary>
internal static void StripHistory(W.Metadata? metadata)
{
if (metadata is null) return;
metadata.History = null;
metadata.AllowedOperations &= ~(uint)DataOperations.HistoryRead;
}
private static RpcException NotNegotiated() => new(new Status(StatusCode.FailedPrecondition, "feature not negotiated"));
/// <summary>The feature set recorded for this call by <see cref="NegotiateFeatures"/> (v1 when absent).</summary>
internal static DataCallFeatures CallFeatures(ServerCallContext context) =>
context.UserState.TryGetValue(typeof(DataCallFeatures), out var value) && value is DataCallFeatures features
? features : DataCallFeatures.None;
/// <summary>
/// Parses <see cref="DataConnectionProtoContract.FeaturesHeader"/> on every RPC (after authentication) and records
/// requested ∩ supported. A binary or oversized value is an <see cref="ArgumentException"/> ⇒ InvalidArgument.
/// </summary>
private static DataCallFeatures NegotiateFeatures(ServerCallContext context)
{
var requested = DataFeatureHeader.Parse(context.RequestHeaders);
var features = requested == DataFeatures.None ? DataCallFeatures.None : new DataCallFeatures(requested, requested & SupportedFeatures);
context.UserState[typeof(DataCallFeatures)] = features;
return features;
}
public override Task<W.CapabilitiesResponse> GetCapabilities(W.CapabilitiesRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
if (request.ProtocolMajor != 1) throw new RpcException(new Status(StatusCode.Unimplemented, "Incompatible protocol major."));
var budget = new DataBudget(_options.UnaryTimeout, 1, _options.MaxMessageBytes);
var capabilities = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false);
var response = DataProtoMapper.EncodeCapabilities(capabilities with
{ ProtocolMinor = Math.Max(3, capabilities.ProtocolMinor), ResponseServingIdentity = true, SubscriptionAgeReadiness = true });
if (!HistoryNegotiated(context, capabilities)) StripHistory(response);
if (!ConditionsNegotiated(context, capabilities)) StripConditions(response);
CheckSize(response);
var current = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false);
if (!authenticator.IsCurrent(caller) || current.Serving != capabilities.Serving
|| current.Readiness != capabilities.Readiness || current.Operations != capabilities.Operations)
throw Unavailable();
Register(context, response, () => authenticator.IsCurrent(caller)
&& !token.IsCancellationRequested
&& connection is IDataConnectionDiscoveryGate gate && gate.CanPublishCapabilities(capabilities));
return response;
});
public override Task<W.BrowseResponse> Browse(W.BrowseRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
var caps = await Ready(connection, DataOperations.Browse, token).ConfigureAwait(false);
var decoded = DataProtoMapper.DecodeBrowseRequest(request, DecodeLimits(caps));
var result = await connection.BrowseAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false);
var response = DataProtoMapper.EncodeBrowseResponse(result);
if (!HistoryNegotiated(context, caps)) foreach (var item in response.Items) StripHistory(item);
if (!ConditionsNegotiated(context, caps)) foreach (var item in response.Items) StripConditions(item);
response.Serving = DataProtoMapper.EncodeServing(caps.Serving);
CheckSize(response);
Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving));
return response;
});
public override Task<W.MetadataResponse> GetMetadata(W.MetadataRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
var caps = await Ready(connection, DataOperations.Metadata, token).ConfigureAwait(false);
var decoded = DataProtoMapper.DecodeMetadataRequest(request, DecodeLimits(caps));
var result = await connection.GetMetadataAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false);
var response = DataProtoMapper.EncodeMetadataResponse(result);
if (!HistoryNegotiated(context, caps)) foreach (var item in response.Items) StripHistory(item.Value);
if (!ConditionsNegotiated(context, caps)) foreach (var item in response.Items) StripConditions(item.Value);
response.Serving = DataProtoMapper.EncodeServing(caps.Serving);
CheckSize(response);
Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving));
return response;
});
public override Task<W.ReadResponse> Read(W.ReadRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
var caps = await Ready(connection, DataOperations.Read, token).ConfigureAwait(false);
HistoryNegotiated(context, caps); // records the effective set; Read carries no history shape
var decoded = DataProtoMapper.DecodeReadRequest(request, DecodeLimits(caps));
var results = await connection.ReadAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false);
foreach (var result in results) context.GetHttpContext().Response.RegisterForDispose(result);
var response = DataProtoMapper.EncodeReadResponse(results);
response.Serving = DataProtoMapper.EncodeServing(caps.Serving);
CheckSize(response);
Register(context, response, () => !token.IsCancellationRequested
&& CanPublish(connection, caller, caps.Serving)
&& results.All(result => result.Sample is null || result.ResourceLease is IDataPublicationLease { IsValid: true }));
return response;
});
public override Task<W.WriteResponse> Write(W.WriteRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
var caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false);
HistoryNegotiated(context, caps); // records the effective set; Write carries no history shape
var limits = DecodeLimits(caps);
var decoded = DataProtoMapper.DecodeWriteRequest(request, limits.MaxItems, limits.MaxBytes, limits.MaxValueElements);
try
{
var results = caps.Readiness == DataReadiness.Ready && caps.Operations.HasFlag(DataOperations.Write)
? await connection.WriteAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false)
: decoded.Items.Select(item => new WriteItemResult(item.CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write unavailable before dispatch."))).ToArray();
var serving = caps.Serving;
DataCapabilities? rejectionCaps = null;
if (results.All(result => result.Outcome.State == DataWriteState.RejectedBeforeDispatch))
{
var current = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false);
if (current.Serving.NodeId != serving.NodeId || current.Serving.Incarnation != serving.Incarnation) throw Unavailable();
rejectionCaps = current; serving = current.Serving;
}
var response = DataProtoMapper.EncodeWriteResponse(results);
response.Serving = DataProtoMapper.EncodeServing(serving);
CheckSize(response);
Register(context, response, () => !token.IsCancellationRequested && authenticator.IsCurrent(caller)
&& (rejectionCaps is { } negative
? connection is IDataConnectionDiscoveryGate discovery && discovery.CanPublishCapabilities(negative)
: CanPublish(connection, caller, serving)));
return response;
}
finally { foreach (var item in decoded.Items) item.Value.Dispose(); }
});
/// <summary>
/// H2 remote history. Order: the call negotiated history (header) and the origin can serve it, else
/// FAILED_PRECONDITION; then readiness and the HistoryRead operation (as every v1 RPC); then the origin facade applies,
/// per item, the export grant, the origin ACL and the tagname lookup — answering every refusal identically.
/// </summary>
public override Task<W.HistoryReadResponse> HistoryRead(W.HistoryReadRequest request, ServerCallContext context) =>
Execute(context, async (connection, caller, token) =>
{
if ((CallFeatures(context).Effective & DataFeatures.History) == 0
|| connection is not (IDataHistoryTransport or IDataHistoryService)) throw NotNegotiated();
var discovered = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false);
if (!HistoryNegotiated(context, discovered)) throw NotNegotiated();
var caps = await Ready(connection, DataOperations.HistoryRead, token).ConfigureAwait(false);
var (decoded, release) = DataHistoryProtoMapper.DecodeRequest(request, DecodeLimits(caps));
var channel = Channel(context);
IReadOnlyList<DataHistoryReadResult> results;
if (release)
{
var tokens = decoded.Items.Where(x => x.Continuation is not null).Select(x => x.Continuation!).ToArray();
if (connection is IDataHistoryTransport releasing) await releasing.ReleaseForTransportAsync(tokens, channel, token).ConfigureAwait(false);
else await ((IDataHistoryService)connection).ReleaseAsync(tokens, token).ConfigureAwait(false);
results = decoded.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, 0, [], null)).ToArray();
}
else
{
var bounded = decoded with { Budget = Clamp(decoded.Budget) };
results = connection is IDataHistoryTransport transport
? await transport.ReadForTransportAsync(bounded, channel, token).ConfigureAwait(false)
: await ((IDataHistoryService)connection).ReadAsync(bounded, token).ConfigureAwait(false);
}
foreach (var result in results) context.GetHttpContext().Response.RegisterForDispose(result);
if (results.Count != decoded.Items.Count) throw Unavailable();
var response = DataHistoryProtoMapper.EncodeResponse(results);
response.Serving = DataProtoMapper.EncodeServing(caps.Serving);
CheckSize(response);
Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving));
return response;
});
/// <summary>
/// The transport channel of this call: its HTTP/2 connection. Origin continuations are partitioned by it and cleared
/// when Kestrel reports the connection closed (idle expiry is the backstop where the feature is absent).
/// </summary>
private static DataHistoryChannel Channel(ServerCallContext context) => ChannelOf(context.GetHttpContext());
/// <summary>The history channel of an HTTP request: its connection id, closed when Kestrel closes the connection.</summary>
internal static DataHistoryChannel ChannelOf(Microsoft.AspNetCore.Http.HttpContext http)
{
var closed = http.Features.Get<Microsoft.AspNetCore.Connections.Features.IConnectionLifetimeFeature>()?.ConnectionClosed
?? CancellationToken.None;
return new DataHistoryChannel("http:" + (http.Connection.Id ?? "unknown"), closed);
}
private DataBudget DiscoveryBudget => new(_options.UnaryTimeout, 1, _options.MaxMessageBytes);
private DataBudget Clamp(DataBudget budget) => budget with
{ Timeout = budget.Timeout <= _options.UnaryTimeout ? budget.Timeout : _options.UnaryTimeout,
MaxBytes = Math.Min(budget.MaxBytes, _options.MaxMessageBytes) };
private DataDecodeLimits DecodeLimits(DataCapabilities caps) => new(caps.Limits.MaxBatchItems,
Math.Min(caps.Limits.MaxMessageBytes, _options.MaxMessageBytes), caps.Limits.MaxValueElements);
private async Task<DataCapabilities> Ready(IDataConnection connection, DataOperations operation, CancellationToken token)
{
var caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false);
if (caps.Readiness != DataReadiness.Ready) throw Unavailable();
if (!caps.Operations.HasFlag(operation)) throw new RpcException(new Status(StatusCode.PermissionDenied, "Data operation denied."));
return caps;
}
private bool CanPublish(IDataConnection connection, DataAuthenticatedContext caller, ServingIdentity expected) =>
authenticator.IsCurrent(caller) && connection is IDataConnectionPublicationGate gate && gate.CanPublish(expected);
public override async Task Subscribe(IAsyncStreamReader<W.SubscriptionCommand> requests,
IServerStreamWriter<W.SubscriptionFrame> responses, ServerCallContext context)
{
try
{
context.WriteOptions = new(WriteFlags.NoCompress);
responses.WriteOptions = new(WriteFlags.NoCompress);
var (caller, target) = AuthenticateCall(context);
NegotiateFeatures(context);
await using var connection = factory.Create(caller, target);
DataCapabilities caps;
IDataSubscription subscription;
using (var initial = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken))
{
initial.CancelAfter(_options.UnaryTimeout);
caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, initial.Token).ConfigureAwait(false);
if (caps.Readiness != DataReadiness.Ready) throw Unavailable();
}
HistoryNegotiated(context, caps); // records the effective set; no stream frame carries history in H2
// A2: condition items (frame arm 9) exist only on a stream that negotiated `conditions`. A stream that did not
// has every condition_scope stripped before decode, so the session can never produce arm 9 for it.
var conditions = ConditionsNegotiated(context, caps);
if (!caps.Operations.HasFlag(DataOperations.Subscribe)
&& !(conditions && caps.Operations.HasFlag(DataOperations.AlarmSubscribe)))
throw new RpcException(new Status(StatusCode.PermissionDenied, "Data operation denied."));
var codecHeaders = context.RequestHeaders.Where(entry => string.Equals(entry.Key, DataConnectionProtoContract.CompactCodecHeader, StringComparison.OrdinalIgnoreCase)).ToArray();
if (codecHeaders.Length > 1 || codecHeaders.Length == 1 &&
(codecHeaders[0].IsBinary || codecHeaders[0].Value != "1"))
throw new RpcException(new Status(StatusCode.InvalidArgument, "Invalid compact codec negotiation."));
var compact = codecHeaders.Length == 1 && DataProtoMapper.NegotiateCompact(caps);
subscription = await connection.SubscribeAsync(context.CancellationToken).ConfigureAwait(false);
await using (subscription)
{
if (subscription is not IDataSubscriptionTransport transport)
throw new RpcException(new Status(StatusCode.Unavailable, "Subscription transport is unavailable."));
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken);
var sink = new GrpcDeliverySink(responses, context, caps, _options.MaxMessageBytes, compact,
() => CanPublish(connection, caller, caps.Serving), conditions);
var delivery = transport.RunDeliveryAsync(sink, stop.Token);
var commands = ReceiveCommands();
try { await await Task.WhenAny(delivery, commands).ConfigureAwait(false); }
finally
{
await stop.CancelAsync().ConfigureAwait(false);
await subscription.DisposeAsync().ConfigureAwait(false);
try { await Task.WhenAll(delivery, commands).ConfigureAwait(false); }
catch (OperationCanceledException) when (stop.IsCancellationRequested) { }
}
async Task ReceiveCommands()
{
var limits = DecodeLimits(caps) with { MaxItems = caps.Limits.MaxMonitoredItems };
while (await requests.MoveNext(stop.Token).ConfigureAwait(false))
{
if (!CanPublish(connection, caller, caps.Serving)) throw Unavailable();
if (!conditions) StripConditionScopes(requests.Current);
var command = DataProtoMapper.DecodeCommand(requests.Current, limits);
var ack = command.AcknowledgementTimeout <= _options.StreamCommandTimeout
? command.AcknowledgementTimeout : _options.StreamCommandTimeout;
command = command switch
{
OpenSubscription open => open with { AcknowledgementTimeout = ack, SnapshotBudget = Clamp(open.SnapshotBudget) },
AddSubscriptionItems add => add with { AcknowledgementTimeout = ack },
ModifySubscriptionItems modify => modify with { AcknowledgementTimeout = ack },
RemoveSubscriptionItems remove => remove with { AcknowledgementTimeout = ack },
ChallengeSubscriptionFreshness challenge when caps.SubscriptionFreshnessChallenges && caps.SubscriptionAgeReadiness =>
challenge with { AcknowledgementTimeout = ack },
_ => throw new ArgumentException("Unsupported stream command.")
};
using var commandDeadline = CancellationTokenSource.CreateLinkedTokenSource(stop.Token);
commandDeadline.CancelAfter(_options.StreamCommandTimeout);
await subscription.SendAsync(command, commandDeadline.Token).ConfigureAwait(false);
}
}
}
}
catch (RpcException) { throw; }
catch (UnauthorizedAccessException) { throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed.")); }
catch (ArgumentException) { throw new RpcException(new Status(StatusCode.InvalidArgument, "Invalid stream command.")); }
catch (InvalidOperationException) { throw Unavailable(); }
catch (OperationCanceledException) { throw new RpcException(new Status(StatusCode.Cancelled, "Data stream canceled.")); }
}
/// <summary>
/// A2: a header-less stream keeps the v1 shape — a v1 server ignores the unknown field 4 of SubscriptionItem, so the
/// item is decoded as the plain value item it would be on v1.
/// </summary>
internal static void StripConditionScopes(W.SubscriptionCommand command)
{
var items = command.Open?.Items ?? command.Add?.Items ?? command.Modify?.Items;
if (items is null) return;
foreach (var item in items) item.ConditionScope = null;
}
private sealed class GrpcDeliverySink(IServerStreamWriter<W.SubscriptionFrame> writer, ServerCallContext context,
DataCapabilities caps, int maximumBytes, bool compact, Func<bool> hostGuard, bool conditions = false) : IDataSubscriptionDeliverySink
{
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Reserve conservatively before allocating protobuf payload copies or serialized bytes.
long charge = checked(2048L + 4L * frame.SubscriptionId.Length);
charge = frame switch
{
DataSubscriptionValues values => values.Items.Aggregate(charge, (sum, item) => checked(sum
+ 4 * item.Sample.Value.EstimatedRetainedBytes + 2048L)),
DataSubscriptionAck ack => ack.Items.Aggregate(charge, (sum, item) => checked(sum + 2048L
+ 4L * (item.ClientItemId.Length + (item.Diagnostic?.Length ?? 0)))),
DataSubscriptionControl control => checked(charge + 128L * control.Watermarks.Count + 4L * (control.Diagnostic?.Length ?? 0)),
// A2: never on a stream that did not negotiate conditions (v1 clients fault on an unknown arm).
DataSubscriptionConditions states when conditions => states.Items.Aggregate(charge, (sum, item) => checked(sum + 2048L
+ 4L * (item.ConditionKey.Length + item.Message.Length + (item.Comment?.Length ?? 0) + (item.ClientUserId?.Length ?? 0)
+ (item.Activation?.Incarnation.Length ?? 0)
+ (item.Info is { } info ? info.ConditionType.Length + info.ConditionName.Length
+ info.Placements.Sum(p => 256 + p.Subject.Length + p.Address.Identifier.Length + p.Address.NamespaceUri.Length
+ p.Address.OriginClusterId.Length) : 0)))),
_ => throw new ArgumentException("Unsupported subscription frame.")
};
if (charge > reservedBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Prepared frame exceeds its reservation."));
var wire = frame switch
{
DataSubscriptionValues valuesFrame =>
DataProtoMapper.EncodeValues(valuesFrame, compactNegotiated: compact && valuesFrame.Items.Count > 0, subscriptionAgeReadiness: true),
DataSubscriptionConditions states => DataConditionProtoMapper.EncodeFrame(states),
_ => DataProtoMapper.EncodeControlOrAck(frame),
};
wire.Serving = DataProtoMapper.EncodeServing(caps.Serving);
if (wire.CalculateSize() > maximumBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Stream message exceeds transport limits."));
var payload = wire.ToByteArray();
if (charge < payload.Length) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Prepared frame exceeds its reservation."));
return ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new PreparedDataSubscription(wire, payload, charge,
maximumBytes, hostGuard, cancellationToken, () => !context.CancellationToken.IsCancellationRequested
&& context.WriteOptions is { Flags: var flags } && (flags & WriteFlags.NoCompress) != 0));
}
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) =>
await writer.WriteAsync(((PreparedDataSubscription)prepared).Frame, cancellationToken).ConfigureAwait(false);
}
private (DataAuthenticatedContext Caller, DataTarget Target) AuthenticateCall(ServerCallContext context)
{
var http = context.GetHttpContext();
if (!DataConnectionEndpoints.IsDataRequest(http, _options)
|| http.Items[typeof(DataAuthenticatedContext)] is not DataAuthenticatedContext caller
|| !authenticator.IsCurrent(caller))
throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed."));
if (http.Items[typeof(DataTarget)] is not DataTarget target) throw new ArgumentException("Missing target policy.");
target.Validate();
return (caller, target);
}
private async Task<T> Execute<T>(ServerCallContext context,
Func<IDataConnection, DataAuthenticatedContext, CancellationToken, Task<T>> operation)
{
try
{
// ASP.NET discovers generated bindings with a null service instance and creates its
// invoker by reflection. The real execution path must own this flag, not a binder delegate.
context.WriteOptions = new(WriteFlags.NoCompress);
var http = context.GetHttpContext();
var (caller, target) = AuthenticateCall(context);
NegotiateFeatures(context);
if (!http.Items.ContainsKey(typeof(DataConnectionUnaryLifetime)))
http.Items[typeof(DataConnectionUnaryLifetime)] = new DataConnectionUnaryLifetime(TimeProvider.System, _options.UnaryTimeout);
var timeout = new CancellationTokenSource(_options.UnaryTimeout);
http.Response.RegisterForDispose(timeout);
var linked = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken, timeout.Token);
http.Response.RegisterForDispose(linked);
http.Items[typeof(DataConnectionGrpcService)] = linked.Token;
var connection = factory.Create(caller, target);
http.Response.RegisterForDisposeAsync(connection);
return await operation(connection, caller, linked.Token).ConfigureAwait(false);
}
catch (RpcException) { throw; }
catch (UnauthorizedAccessException) { throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed.")); }
catch (ArgumentException) { throw new RpcException(new Status(StatusCode.InvalidArgument, "Invalid data request.")); }
catch (InvalidOperationException) { throw Unavailable(); }
catch (OperationCanceledException) { throw new RpcException(new Status(StatusCode.Cancelled, "Data request canceled.")); }
}
private void CheckSize(IMessage response)
{
if (response.CalculateSize() > _options.MaxMessageBytes)
throw new RpcException(new Status(StatusCode.ResourceExhausted, "Data response exceeds transport limits."));
}
private void Register(ServerCallContext context, IMessage response, Func<bool> guard)
{
var http = context.GetHttpContext();
var operationToken = http.Items[typeof(DataConnectionGrpcService)] is CancellationToken token ? token : context.CancellationToken;
var deadline = (DataConnectionUnaryLifetime)http.Items[typeof(DataConnectionUnaryLifetime)]!;
http.Response.RegisterForDispose(DataConnectionPublication.RegisterUnary(response, () =>
{
var allowed = guard();
// Publication validation may block; cancellation/deadline and compression flags are
// observed again afterwards, immediately before the marshaller's final state read.
return allowed && !operationToken.IsCancellationRequested && !context.CancellationToken.IsCancellationRequested
&& context.WriteOptions is { Flags: var flags } && (flags & WriteFlags.NoCompress) != 0;
}, _options.MaxMessageBytes, deadline));
}
private static RpcException Unavailable() => new(new Status(StatusCode.Unavailable, "Data serving identity or authority is unavailable."));
}