119 lines
7.3 KiB
C#
119 lines
7.3 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
[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> { DataValueKind.Int32 }, Limits, true, 1, "c", true, true, true, true, true);
|
|
GrpcDataConnection.RequestedFeatures(everything).ShouldBe(DataFeatures.None);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Without_an_advertised_feature_only_the_capabilities_probe_carries_the_header()
|
|
{
|
|
var handler = new RecordingHandler();
|
|
using var manager = new DataConnectionManager("consumer", 1);
|
|
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "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));
|
|
// H2 (coordinator decision): the probe always asks for what this consumer understands (A2a: history and
|
|
// conditions); nothing else carries the header, because this origin advertised neither field.
|
|
handler.FeatureHeaders.ShouldNotBeEmpty();
|
|
handler.FeatureHeaders.ShouldAllBe(x => x == "history,conditions");
|
|
handler.FeatureHeaderPaths.ShouldAllBe(p => p.EndsWith("/GetCapabilities", StringComparison.Ordinal));
|
|
}
|
|
|
|
private sealed class RecordingHandler : HttpMessageHandler
|
|
{
|
|
public List<string> Paths { get; } = [];
|
|
public List<string> FeatureHeaders { get; } = [];
|
|
public List<string> FeatureHeaderPaths { get; } = [];
|
|
protected override async Task<HttpResponseMessage> 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); FeatureHeaderPaths.Add(path); }
|
|
}
|
|
IMessage message;
|
|
if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal))
|
|
{
|
|
var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, Serving, DataReadiness.Ready, DataOperationSets.V1,
|
|
new HashSet<DataValueKind> { 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 |= 64u | 128u; // 128 still reserved; 64 is never a node operation (A2a)
|
|
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<string>? Changed { add { } remove { } }
|
|
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
|
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca1", "key", () => handler));
|
|
}
|
|
}
|