feat(grpc-data): A2a — origin condition streaming: root-scoped items over the A1 hub, priority queue, host negotiation, consumer decode
This commit is contained in:
@@ -21,7 +21,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
/// 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;
|
||||
internal static DataFeatures SupportedFeatures => DataFeatures.History | DataFeatures.Conditions;
|
||||
|
||||
/// <summary>
|
||||
/// Whether this call negotiated history against <paramref name="caps"/>. Refines the recorded effective set: an
|
||||
@@ -36,6 +36,33 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
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)
|
||||
{
|
||||
@@ -79,6 +106,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
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
|
||||
@@ -98,6 +126,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
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));
|
||||
@@ -112,6 +141,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
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));
|
||||
@@ -252,9 +282,16 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
using (var initial = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken))
|
||||
{
|
||||
initial.CancelAfter(_options.UnaryTimeout);
|
||||
caps = await Ready(connection, DataOperations.Subscribe, initial.Token).ConfigureAwait(false);
|
||||
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"))
|
||||
@@ -267,7 +304,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
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));
|
||||
() => 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); }
|
||||
@@ -285,6 +322,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
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;
|
||||
@@ -312,8 +350,19 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
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) : IDataSubscriptionDeliverySink
|
||||
DataCapabilities caps, int maximumBytes, bool compact, Func<bool> hostGuard, bool conditions = false) : IDataSubscriptionDeliverySink
|
||||
{
|
||||
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
|
||||
CancellationToken cancellationToken)
|
||||
@@ -328,12 +377,23 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
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 is DataSubscriptionValues valuesFrame
|
||||
? DataProtoMapper.EncodeValues(valuesFrame, compactNegotiated: compact && valuesFrame.Items.Count > 0, subscriptionAgeReadiness: true)
|
||||
: DataProtoMapper.EncodeControlOrAck(frame);
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user