diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs
index 2ffb7044f..17d669bc2 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs
@@ -211,12 +211,23 @@ public sealed partial class GrpcDataConnection : IDataConnection
catch { handler.Dispose(); throw; }
}
}
- private Metadata Headers(ChannelEntry channel)
+ ///
+ /// The optional features to request from the SELECTED endpoint: only what that endpoint advertised, re-derived on
+ /// every selection so a failover follows the new endpoint. X0 reserves the negotiation; no capability field
+ /// advertises a feature yet, so this is always empty and the header is never sent.
+ ///
+ internal static DataFeatures RequestedFeatures(DataCapabilities capabilities)
+ {
+ ArgumentNullException.ThrowIfNull(capabilities);
+ return DataFeatures.None;
+ }
+ private Metadata Headers(ChannelEntry channel, DataFeatures features = DataFeatures.None)
{
var headers = new Metadata { { "authorization", "Bearer " + channel.Bearer },
{ "x-data-target-mode", Target.Mode.ToString() }, { "x-data-consistency", Target.Consistency.ToString() },
{ "x-data-cluster-id", Target.ExpectedClusterId } };
if (Target.Mode == DataTargetMode.Node) headers.Add("x-data-node-id", Target.ExpectedNodeId!);
+ DataFeatureHeader.Apply(headers, features);
return headers;
}
private TimeSpan Remaining(long start, DataBudget budget)
@@ -227,6 +238,8 @@ public sealed partial class GrpcDataConnection : IDataConnection
}
private CallOptions Options(ChannelEntry channel, long start, DataBudget budget, CancellationToken ct) =>
new(Headers(channel), DateTime.UtcNow + Remaining(start, budget), ct);
+ private CallOptions Options(Selected selected, long start, DataBudget budget, CancellationToken ct) =>
+ new(Headers(selected.Channel, RequestedFeatures(selected.Capabilities)), DateTime.UtcNow + Remaining(start, budget), ct);
private DataDecodeLimits Limits(DataBudget budget, DataCapabilities caps) => new(Math.Min(budget.MaxItems, caps.Limits.MaxBatchItems),
(int)Math.Min(Math.Min(budget.MaxBytes, _maxMessageBytes), caps.Limits.MaxMessageBytes), caps.Limits.MaxValueElements);
private async Task SelectAsync(Uri endpoint, long start, DataBudget budget, bool write, CancellationToken ct)
@@ -271,7 +284,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
ProbeSucceeded();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token);
var remaining = budget with { Timeout = Remaining(start, budget) };
- var result = await call(selected, remaining, Options(selected.Channel, start, budget, linked.Token)).ConfigureAwait(false);
+ var result = await call(selected, remaining, Options(selected, start, budget, linked.Token)).ConfigureAwait(false);
try { linked.Token.ThrowIfCancellationRequested(); return result; }
catch { if (result is IEnumerable reads) foreach (var item in reads) item.Dispose(); throw; }
}
@@ -432,7 +445,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
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);
+ Options(selected, 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) =>
@@ -475,7 +488,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
var remaining = Remaining(start, request.Budget);
var batch = new WriteBatch(items.Select(x => x with { RemainingBudget = x.RemainingBudget < remaining ? x.RemainingBudget : remaining }).ToArray(),
request.Budget with { Timeout = remaining });
- var options = Options(selected.Channel, start, request.Budget, linked.Token);
+ var options = Options(selected, start, request.Budget, linked.Token);
var encoded = DataProtoMapper.EncodeWriteRequest(batch);
linked.Token.ThrowIfCancellationRequested();
dispatchStarted = true;
@@ -544,7 +557,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
try
{
var compact = _enableCompactBatches && DataProtoMapper.NegotiateCompact(selected.Capabilities);
- var headers = Headers(selected.Channel);
+ var headers = Headers(selected.Channel, RequestedFeatures(selected.Capabilities));
if (compact) headers.Add(DataConnectionProtoContract.CompactCodecHeader, DataConnectionProtoContract.CompactCodecVersion.ToString(System.Globalization.CultureInfo.InvariantCulture));
var call = selected.Channel.Client.Subscribe(headers, cancellationToken: lifetime.Token);
subscription = new RemoteSubscription(this, call, selected, lifetime, compact, _maxMessageBytes,
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs
new file mode 100644
index 000000000..65d1e8c37
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFeatureHeaderClientTests.cs
@@ -0,0 +1,113 @@
+using System.Buffers.Binary;
+using System.Net;
+using Google.Protobuf;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
+using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
+using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
+
+namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
+
+///
+/// X0 consumer side of the feature negotiation: the header is derived from the SELECTED endpoint's capabilities
+/// and sent only when non-empty. No capability advertises a feature yet, so an X0 consumer never sends it, even
+/// to an origin that advertises every v1 flag and unknown operation bits.
+///
+[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
+public sealed class GrpcDataFeatureHeaderClientTests
+{
+ private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5));
+ private static readonly ServingIdentity Serving = new("a", "boot", "Primary", 1, 1, 1);
+ private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x");
+ private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65536);
+
+ [Fact]
+ public void Requested_features_follow_the_selected_endpoint_and_are_empty_in_X0()
+ {
+ var everything = new DataCapabilities(1, 5, Serving, DataReadiness.Ready, DataOperationSets.V1 | DataOperationSets.Reserved,
+ new HashSet { DataValueKind.Int32 }, Limits, true, 1, "c", true, true, true, true, true);
+ GrpcDataConnection.RequestedFeatures(everything).ShouldBe(DataFeatures.None);
+ }
+
+ [Fact]
+ public async Task No_rpc_carries_the_feature_header_in_X0()
+ {
+ var handler = new RecordingHandler();
+ using var manager = new DataConnectionManager("consumer", 1);
+ manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } });
+ await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
+ [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1);
+ var ct = TestContext.Current.CancellationToken;
+
+ (await connection.GetCapabilitiesAsync(Budget, ct)).Operations.ShouldBe(DataOperationSets.V1);
+ (await connection.GetMetadataAsync(new MetadataRequest([View], Budget), ct)).ShouldHaveSingleItem().Value!.AllowedOperations
+ .ShouldBe(DataOperations.Read | DataOperations.Write);
+ foreach (var result in await connection.ReadAsync(new ReadRequest([new("r", View, null)], Budget), ct)) result.Dispose();
+ using (var value = DataValue.FromScalar(DataValueKind.Int32, 1))
+ (await connection.WriteAsync(new WriteBatch([new("w", "op", View, value, 1, "boot", TimeSpan.FromSeconds(4), 1)], Budget), ct))
+ .ShouldHaveSingleItem();
+
+ handler.Paths.ShouldContain(p => p.EndsWith("/GetMetadata", StringComparison.Ordinal));
+ handler.Paths.ShouldContain(p => p.EndsWith("/Read", StringComparison.Ordinal));
+ handler.Paths.ShouldContain(p => p.EndsWith("/Write", StringComparison.Ordinal));
+ handler.FeatureHeaders.ShouldBeEmpty();
+ }
+
+ private sealed class RecordingHandler : HttpMessageHandler
+ {
+ public List Paths { get; } = [];
+ public List FeatureHeaders { get; } = [];
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ var path = request.RequestUri!.AbsolutePath;
+ lock (Paths)
+ {
+ Paths.Add(path);
+ if (request.Headers.TryGetValues("x-otopcua-data-features", out var values)) FeatureHeaders.AddRange(values);
+ }
+ IMessage message;
+ if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal))
+ {
+ var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, Serving, DataReadiness.Ready, DataOperationSets.V1,
+ new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", true, true, true, true, true));
+ caps.Operations |= 32u | 64u | 128u | 256u | 512u; // a newer origin advertising reserved bits
+ message = caps;
+ }
+ else if (path.EndsWith("/GetMetadata", StringComparison.Ordinal))
+ {
+ var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good,
+ new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Write, 1, null, null, false), null)]);
+ wire.Items[0].Value.AllowedOperations |= 32u;
+ wire.Serving = DataProtoMapper.EncodeServing(Serving); message = wire;
+ }
+ else if (path.EndsWith("/Read", StringComparison.Ordinal))
+ {
+ var wire = DataProtoMapper.EncodeReadResponse([new ReadResult("r", DataItemStatus.Denied, DataReadiness.Unavailable, null, null, "no")]);
+ wire.Serving = DataProtoMapper.EncodeServing(Serving); message = wire;
+ }
+ else
+ {
+ var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
+ var write = W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray());
+ var result = new W.WriteResponse { Serving = DataProtoMapper.EncodeServing(Serving) };
+ foreach (var item in write.Items)
+ result.Items.Add(DataProtoMapper.EncodeWriteResult(new(item.CorrelationId, new(DataWriteState.DriverConfirmedSuccess, 0, null))));
+ message = result;
+ }
+ var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5];
+ BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5);
+ var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) };
+ response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0");
+ return response;
+ }
+ }
+
+ private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider
+ {
+ public event Action? Changed { add { } remove { } }
+ public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
+ ValueTask.FromResult(new("v1", "ca1", "key", () => handler));
+ }
+}