feat(grpc-data): X0 tolerant metadata decode, feature header contract, proto field reservations with golden tests
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
using Grpc.Core;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Protos;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// The per-call feature set the server derived for one RPC: what the caller asked for, and what this server
|
||||
/// will actually honour (requested ∩ supported). A handler serves a feature only when it is in
|
||||
/// <see cref="Effective"/>; an empty effective set means exactly the v1 behaviour.
|
||||
/// </summary>
|
||||
public sealed record DataCallFeatures(DataFeatures Requested, DataFeatures Effective)
|
||||
{
|
||||
public static readonly DataCallFeatures None = new(DataFeatures.None, DataFeatures.None);
|
||||
}
|
||||
|
||||
/// <summary>Formats and parses <see cref="DataConnectionProtoContract.FeaturesHeader"/>.</summary>
|
||||
public static class DataFeatureHeader
|
||||
{
|
||||
public const string HistoryToken = "history";
|
||||
public const string ConditionsToken = "conditions";
|
||||
|
||||
/// <summary>The header value for <paramref name="features"/>, or null when nothing is requested (no header is sent).</summary>
|
||||
public static string? Format(DataFeatures features)
|
||||
{
|
||||
var tokens = new List<string>(2);
|
||||
if ((features & DataFeatures.History) != 0) tokens.Add(HistoryToken);
|
||||
if ((features & DataFeatures.Conditions) != 0) tokens.Add(ConditionsToken);
|
||||
return tokens.Count == 0 ? null : string.Join(',', tokens);
|
||||
}
|
||||
|
||||
/// <summary>Adds the header only for a non-empty feature set, so a v1-equivalent call stays byte-identical.</summary>
|
||||
public static void Apply(Metadata headers, DataFeatures features)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(headers);
|
||||
if (Format(features) is { } value) headers.Add(DataConnectionProtoContract.FeaturesHeader, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The union of every <see cref="DataConnectionProtoContract.FeaturesHeader"/> entry. Unknown, empty and
|
||||
/// whitespace tokens are ignored (forward compatibility). A binary (<c>-bin</c>) entry or a summed length over
|
||||
/// <see cref="DataConnectionProtoContract.MaxFeaturesHeaderLength"/> throws <see cref="ArgumentException"/>,
|
||||
/// which the server maps to <c>InvalidArgument</c>.
|
||||
/// </summary>
|
||||
public static DataFeatures Parse(Metadata? headers)
|
||||
{
|
||||
if (headers is null) return DataFeatures.None;
|
||||
var features = DataFeatures.None;
|
||||
var length = 0;
|
||||
foreach (var entry in headers)
|
||||
{
|
||||
if (!IsFeaturesKey(entry.Key)) continue;
|
||||
if (entry.IsBinary) throw new ArgumentException("Invalid data feature negotiation.");
|
||||
var value = entry.Value ?? string.Empty;
|
||||
length += value.Length;
|
||||
if (length > DataConnectionProtoContract.MaxFeaturesHeaderLength) throw new ArgumentException("Invalid data feature negotiation.");
|
||||
foreach (var token in value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (string.Equals(token, HistoryToken, StringComparison.OrdinalIgnoreCase)) features |= DataFeatures.History;
|
||||
else if (string.Equals(token, ConditionsToken, StringComparison.OrdinalIgnoreCase)) features |= DataFeatures.Conditions;
|
||||
}
|
||||
}
|
||||
return features;
|
||||
}
|
||||
|
||||
// gRPC lower-cases keys; "-bin" is the binary form of the same logical header.
|
||||
private static bool IsFeaturesKey(string key) =>
|
||||
string.Equals(key, DataConnectionProtoContract.FeaturesHeader, StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(key, DataConnectionProtoContract.FeaturesHeader + "-bin", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -281,7 +281,8 @@ public static class DataProtoMapper
|
||||
x.ValueRank,
|
||||
x.Dimensions.ToArray(),
|
||||
x.Writable,
|
||||
(DataOperations)x.AllowedOperations,
|
||||
// X0 tolerant reader: an operation bit this build does not understand is no grant.
|
||||
(DataOperations)(x.AllowedOperations & (uint)DataOperationSets.Understood),
|
||||
x.CatalogRevision,
|
||||
x.HasStableSourceId ? x.StableSourceId : null,
|
||||
x.HasEngineeringUnits ? x.EngineeringUnits : null,
|
||||
@@ -1051,16 +1052,7 @@ public static class DataProtoMapper
|
||||
x.ProtocolMinor,
|
||||
DecodeServing(x.Serving),
|
||||
r,
|
||||
(DataOperations)(
|
||||
x.Operations
|
||||
& (uint)(
|
||||
DataOperations.Browse
|
||||
| DataOperations.Metadata
|
||||
| DataOperations.Read
|
||||
| DataOperations.Write
|
||||
| DataOperations.Subscribe
|
||||
)
|
||||
),
|
||||
(DataOperations)(x.Operations & (uint)DataOperationSets.Understood),
|
||||
kinds,
|
||||
new DataLimits(
|
||||
l.MaxPageItems,
|
||||
|
||||
@@ -10,6 +10,26 @@ public static class DataConnectionProtoContract
|
||||
public const int CompactCodecVersion = 1;
|
||||
/// <summary>Optional, per-subscription client opt-in to a supported compact codec.</summary>
|
||||
public const string CompactCodecHeader = "x-data-compact-codec";
|
||||
/// <summary>
|
||||
/// Per-RPC feature request (comma list of <c>history</c>, <c>conditions</c>), sent by a consumer only for features
|
||||
/// the selected endpoint advertised. Absent ⇒ v1 behaviour on every RPC. See <see cref="DataConnections.DataFeatureHeader"/>.
|
||||
/// </summary>
|
||||
public const string FeaturesHeader = "x-otopcua-data-features";
|
||||
/// <summary>Cap on the summed length of every <see cref="FeaturesHeader"/> entry of one call.</summary>
|
||||
public const int MaxFeaturesHeaderLength = 256;
|
||||
|
||||
// X0 field reservations (history + alarm plan §4.2). Not protobuf `reserved`: each number is held for the
|
||||
// named field of a later phase. GrpcDataProtoReservationTests pins each as unused-or-that-field.
|
||||
/// <summary><c>CapabilitiesResponse.history</c> (H2).</summary>
|
||||
public const int CapabilitiesHistoryField = 16;
|
||||
/// <summary><c>CapabilitiesResponse.conditions</c> (A2).</summary>
|
||||
public const int CapabilitiesConditionsField = 17;
|
||||
/// <summary><c>Metadata.history</c> (H2).</summary>
|
||||
public const int MetadataHistoryField = 14;
|
||||
/// <summary><c>SubscriptionItem.condition_scope</c> (A2).</summary>
|
||||
public const int SubscriptionItemConditionScopeField = 4;
|
||||
/// <summary><c>SubscriptionFrame.condition_states</c> oneof arm (A2).</summary>
|
||||
public const int SubscriptionFrameConditionStatesArm = 9;
|
||||
|
||||
public static void Validate()
|
||||
{
|
||||
@@ -18,7 +38,16 @@ public static class DataConnectionProtoContract
|
||||
|| Sample.StatusCodeFieldNumber != 2
|
||||
|| SubscriptionFrame.CompactValuesFieldNumber != 7
|
||||
|| (int)ValueKind.Unspecified != 0
|
||||
|| !Reserved(CapabilitiesResponse.Descriptor, CapabilitiesHistoryField, "history")
|
||||
|| !Reserved(CapabilitiesResponse.Descriptor, CapabilitiesConditionsField, "conditions")
|
||||
|| !Reserved(Metadata.Descriptor, MetadataHistoryField, "history")
|
||||
|| !Reserved(SubscriptionItem.Descriptor, SubscriptionItemConditionScopeField, "condition_scope")
|
||||
|| !Reserved(SubscriptionFrame.Descriptor, SubscriptionFrameConditionStatesArm, "condition_states")
|
||||
)
|
||||
throw new InvalidOperationException("Data connection wire contract changed.");
|
||||
}
|
||||
|
||||
/// <summary>A reserved number is either still unused or carries exactly the field it was reserved for.</summary>
|
||||
public static bool Reserved(Google.Protobuf.Reflection.MessageDescriptor message, int number, string expectedName) =>
|
||||
message.FindFieldByNumber(number) is not { } field || field.Name == expectedName;
|
||||
}
|
||||
|
||||
@@ -119,6 +119,8 @@ message CapabilitiesResponse {
|
||||
bool subscription_freshness_challenges = 14;
|
||||
// Good GetMetadata results may include an exact-item authority lease.
|
||||
bool metadata_item_leases = 15;
|
||||
// X0 RESERVATION (not protobuf `reserved`: the numbers WILL be used): 16 = HistoryCapabilities history (H2),
|
||||
// 17 = ConditionCapabilities conditions (A2). Pinned by DataConnectionProtoContract + GrpcDataProtoReservationTests.
|
||||
}
|
||||
message Metadata {
|
||||
View view = 1;
|
||||
@@ -134,6 +136,7 @@ message Metadata {
|
||||
optional string engineering_units = 11;
|
||||
bool is_stale = 12;
|
||||
optional ValueKind array_element_kind = 13;
|
||||
// X0 RESERVATION: 14 = HistoryInfo history (H2). Pinned by GrpcDataProtoReservationTests.
|
||||
}
|
||||
message Lease {
|
||||
int64 catalog_epoch = 1;
|
||||
@@ -223,6 +226,7 @@ message SubscriptionItem {
|
||||
string client_item_id = 1;
|
||||
View view = 2;
|
||||
Settings settings = 3;
|
||||
// X0 RESERVATION: 4 = ConditionScope condition_scope (A2, header-gated). Pinned by GrpcDataProtoReservationTests.
|
||||
}
|
||||
message SubscriptionCommand {
|
||||
string subscription_id = 1;
|
||||
@@ -317,5 +321,7 @@ message SubscriptionFrame {
|
||||
Control control = 5;
|
||||
Values values = 6;
|
||||
CompactValues compact_values = 7;
|
||||
// X0 RESERVATION: oneof arm 9 = ConditionStates condition_states (A2). Only ever sent on a call that
|
||||
// negotiated `conditions` through x-otopcua-data-features: v1 clients fault on an unknown frame arm.
|
||||
}
|
||||
}
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
using Grpc.Core;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections;
|
||||
|
||||
/// <summary>X0: the feature header round-trips and is tolerant of what a newer peer may send.</summary>
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
|
||||
public sealed class GrpcDataFeatureHeaderTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(DataFeatures.None, null)]
|
||||
[InlineData(DataFeatures.History, "history")]
|
||||
[InlineData(DataFeatures.Conditions, "conditions")]
|
||||
[InlineData(DataFeatures.History | DataFeatures.Conditions, "history,conditions")]
|
||||
public void Format_emits_a_header_only_for_a_nonempty_set(DataFeatures features, string? expected)
|
||||
{
|
||||
DataFeatureHeader.Format(features).ShouldBe(expected);
|
||||
var headers = new Metadata();
|
||||
DataFeatureHeader.Apply(headers, features);
|
||||
if (expected is null) headers.ShouldBeEmpty();
|
||||
else
|
||||
{
|
||||
var entry = headers.ShouldHaveSingleItem();
|
||||
entry.Key.ShouldBe("x-otopcua-data-features");
|
||||
entry.Value.ShouldBe(expected);
|
||||
DataFeatureHeader.Parse(headers).ShouldBe(features);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("history", DataFeatures.History)]
|
||||
[InlineData(" history , conditions ", DataFeatures.History | DataFeatures.Conditions)]
|
||||
[InlineData("HISTORY", DataFeatures.History)]
|
||||
[InlineData("", DataFeatures.None)]
|
||||
[InlineData(",, ,", DataFeatures.None)]
|
||||
[InlineData("events,history,quantum", DataFeatures.History)]
|
||||
[InlineData("unknown", DataFeatures.None)]
|
||||
public void Unknown_empty_and_whitespace_tokens_are_ignored(string value, DataFeatures expected) =>
|
||||
DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features", value } }).ShouldBe(expected);
|
||||
|
||||
[Fact]
|
||||
public void Absent_header_is_none_and_multiple_entries_are_unioned()
|
||||
{
|
||||
DataFeatureHeader.Parse(null).ShouldBe(DataFeatures.None);
|
||||
DataFeatureHeader.Parse(new Metadata { { "authorization", "Bearer x" } }).ShouldBe(DataFeatures.None);
|
||||
DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features", "history" }, { "x-otopcua-data-features", "conditions" } })
|
||||
.ShouldBe(DataFeatures.History | DataFeatures.Conditions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Binary_or_oversized_values_are_rejected()
|
||||
{
|
||||
Should.Throw<ArgumentException>(() => DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features-bin", new byte[] { 1 } } }));
|
||||
Should.Throw<ArgumentException>(() => DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features", new string('h', 257) } }));
|
||||
// The cap is on the summed length, so splitting a long value across entries does not evade it.
|
||||
Should.Throw<ArgumentException>(() => DataFeatureHeader.Parse(new Metadata
|
||||
{ { "x-otopcua-data-features", new string(',', 200) }, { "x-otopcua-data-features", new string(',', 57) } }));
|
||||
Should.NotThrow(() => DataFeatureHeader.Parse(new Metadata { { "x-otopcua-data-features", new string(',', 256) } }));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>X0 tolerant decode: an operation bit this build does not understand is dropped, never thrown on.</summary>
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
|
||||
public sealed class GrpcDataTolerantDecodeTests
|
||||
{
|
||||
private static readonly DataView View = new(new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject");
|
||||
|
||||
[Fact]
|
||||
public void Metadata_decode_masks_unknown_allowed_operations()
|
||||
{
|
||||
var wire = DataProtoMapper.EncodeMetadata(new DataMetadata(View, "x", "Variable", DataValueKind.Int32, -1, [], true,
|
||||
DataOperations.Read | DataOperations.Subscribe, 1, null, null, false));
|
||||
wire.AllowedOperations |= 32u | 64u | 128u | 256u | 512u | (1u << 20) | 0x8000_0000u;
|
||||
var decoded = DataProtoMapper.DecodeMetadata(wire);
|
||||
decoded.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Subscribe);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Capabilities_decode_masks_with_the_shared_understood_set()
|
||||
{
|
||||
var caps = new DataCapabilities(1, 3, new ServingIdentity("n", "i", "Primary", 1, 1, 1), DataReadiness.Ready,
|
||||
DataOperations.Browse | DataOperations.Write, new HashSet<DataValueKind> { DataValueKind.Int32 },
|
||||
new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)), false, 0, "c");
|
||||
var wire = DataProtoMapper.EncodeCapabilities(caps);
|
||||
wire.Operations |= 32u | 512u | 0x8000_0000u;
|
||||
DataProtoMapper.DecodeCapabilities(wire).Operations.ShouldBe(DataOperations.Browse | DataOperations.Write);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Metadata_response_with_unknown_bits_decodes_whole()
|
||||
{
|
||||
var response = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, new DataMetadata(View, "x", "Variable",
|
||||
DataValueKind.Int32, -1, [], false, DataOperations.Read, 1, null, null, false), null)]);
|
||||
response.Items[0].Value.AllowedOperations |= 32u;
|
||||
var decoded = DataProtoMapper.DecodeMetadataResponse(response, new(16, 65536, 1000));
|
||||
decoded.ShouldHaveSingleItem().Value!.AllowedOperations.ShouldBe(DataOperations.Read);
|
||||
W.Metadata.Descriptor.FindFieldByName("allowed_operations").FieldNumber.ShouldBe(8);
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
using Google.Protobuf.Reflection;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Protos;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// X0 contract reservation. Each reserved number must stay unused until its phase adds it, and then carry exactly
|
||||
/// the planned field. These run against the generated descriptors, so a proto edit that takes a number for
|
||||
/// something else fails here.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
|
||||
public sealed class GrpcDataProtoReservationTests
|
||||
{
|
||||
public static TheoryData<string, int, string> Reservations => new()
|
||||
{
|
||||
{ nameof(CapabilitiesResponse), DataConnectionProtoContract.CapabilitiesHistoryField, "history" },
|
||||
{ nameof(CapabilitiesResponse), DataConnectionProtoContract.CapabilitiesConditionsField, "conditions" },
|
||||
{ nameof(Metadata), DataConnectionProtoContract.MetadataHistoryField, "history" },
|
||||
{ nameof(SubscriptionItem), DataConnectionProtoContract.SubscriptionItemConditionScopeField, "condition_scope" },
|
||||
{ nameof(SubscriptionFrame), DataConnectionProtoContract.SubscriptionFrameConditionStatesArm, "condition_states" },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Reservations))]
|
||||
public void Reserved_number_is_unused_or_carries_its_planned_field(string message, int number, string expected)
|
||||
{
|
||||
var descriptor = DataConnectionReflection.Descriptor.MessageTypes.Single(m => m.Name == message);
|
||||
var field = descriptor.FindFieldByNumber(number);
|
||||
if (field is not null) field.Name.ShouldBe(expected, $"{message} field {number} is reserved for '{expected}'");
|
||||
// The planned name is not squatted on another number either.
|
||||
var named = descriptor.FindFieldByName(expected);
|
||||
if (named is not null) named.FieldNumber.ShouldBe(number, $"{message}.{expected} must use its reserved number");
|
||||
DataConnectionProtoContract.Reserved(descriptor, number, expected).ShouldBeTrue();
|
||||
DataConnectionProtoContract.Reserved(descriptor, number, expected + "_other").ShouldBe(field is null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reserved_numbers_are_pinned()
|
||||
{
|
||||
DataConnectionProtoContract.CapabilitiesHistoryField.ShouldBe(16);
|
||||
DataConnectionProtoContract.CapabilitiesConditionsField.ShouldBe(17);
|
||||
DataConnectionProtoContract.MetadataHistoryField.ShouldBe(14);
|
||||
DataConnectionProtoContract.SubscriptionItemConditionScopeField.ShouldBe(4);
|
||||
DataConnectionProtoContract.SubscriptionFrameConditionStatesArm.ShouldBe(9);
|
||||
// The arm is a member of the frame oneof once it exists.
|
||||
var arm = SubscriptionFrame.Descriptor.FindFieldByNumber(DataConnectionProtoContract.SubscriptionFrameConditionStatesArm);
|
||||
if (arm is not null) arm.ContainingOneof?.Name.ShouldBe("frame");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void X0_adds_no_field_yet_so_the_server_advertises_nothing_new()
|
||||
{
|
||||
foreach (var (descriptor, number) in new (MessageDescriptor, int)[]
|
||||
{
|
||||
(CapabilitiesResponse.Descriptor, 16), (CapabilitiesResponse.Descriptor, 17), (Metadata.Descriptor, 14),
|
||||
(SubscriptionItem.Descriptor, 4), (SubscriptionFrame.Descriptor, 9),
|
||||
})
|
||||
descriptor.FindFieldByNumber(number).ShouldBeNull($"{descriptor.Name} field {number} must not exist before its phase");
|
||||
DataConnectionReflection.Descriptor.Services.Single().Methods.Count.ShouldBe(6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Header_names_are_pinned_and_contract_validation_includes_the_reservations()
|
||||
{
|
||||
DataConnectionProtoContract.FeaturesHeader.ShouldBe("x-otopcua-data-features");
|
||||
DataConnectionProtoContract.CompactCodecHeader.ShouldBe("x-data-compact-codec");
|
||||
DataConnectionProtoContract.MaxFeaturesHeaderLength.ShouldBe(256);
|
||||
Should.NotThrow(DataConnectionProtoContract.Validate);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user