From 3279a7f9db1b072a7daa07468876f6c38041b328 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 17:11:59 -0500 Subject: [PATCH] test(grpc-data): X0 recorded-v1-client compatibility gate, goldens captured on pre-X0 master 2e4e4063 --- .../GrpcDataV1CompatibilityTests.cs | 272 ++++++++++++++++++ .../DataConnections/GrpcDataV1Goldens.cs | 29 ++ 2 files changed, 301 insertions(+) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1Goldens.cs diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs new file mode 100644 index 000000000..7106c9d2c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs @@ -0,0 +1,272 @@ +using Google.Protobuf; +using Grpc.Core; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Host.Grpc; +using ZB.MOM.WW.OtOpcUa.Host.OpcUa; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +/// +/// Recorded-v1-client compatibility gate (plan test "C/H", exit gate of X0, H2, A2 and A3). +/// A v1 client's requests are replayed byte-for-byte against the server, and every response +/// must serialize to the golden bytes captured from the pre-X0 server (master 2e4e4063). +/// The origin facade is deterministic, so no field is time-varying and nothing is normalised: +/// is the single place a later phase may list a genuinely varying field. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")] +public sealed class GrpcDataV1CompatibilityTests +{ + /// Every RPC of the v1 service, in the order records them. + internal static readonly string[] RpcNames = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe"]; + public static TheoryData Rpcs => new(RpcNames); + + [Fact] + public void Recorded_v1_requests_are_unchanged() + { + foreach (var rpc in RpcNames) + Hex(V1Requests.Bytes(rpc)).ShouldBe(GrpcDataV1Goldens.Requests[rpc], $"recorded {rpc} request"); + } + + [Theory] + [MemberData(nameof(Rpcs))] + public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string rpc) + { + var actual = await V1CompatibilityHarness.DriveAsync(rpc, new Metadata()); + actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response diverged from the recorded v1 bytes"); + } + + [Theory] + [MemberData(nameof(Rpcs))] + public async Task Feature_header_changes_nothing_while_the_server_supports_no_feature(string rpc) + { + var headers = new Metadata { { "x-otopcua-data-features", "history,conditions" } }; + var actual = await V1CompatibilityHarness.DriveAsync(rpc, headers); + actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response must not change in X0 when features are requested"); + } + + internal static string Hex(byte[] bytes) => Convert.ToHexString(bytes); + + /// X0: no field varies. Add explicit, listed normalisations here only if a later phase needs one. + internal static IMessage Normalise(IMessage message) => message; +} + +/// The recorded v1 client requests. Changing any value here invalidates the goldens. +internal static class V1Requests +{ + internal static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65_536); + internal static readonly DataView Raw = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Speed"), + DataRealm.Raw, null, 0, "Plant/Speed"); + internal static readonly DataView Folder = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant"), + DataRealm.Raw, null, 0, "Plant"); + internal static readonly DataView Array = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Array"), + DataRealm.Raw, null, 0, "Plant/Array"); + internal static readonly DataView Missing = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Missing"), + DataRealm.Raw, null, 0, "Plant/Missing"); + + internal static IMessage Message(string rpc) => rpc switch + { + "GetCapabilities" => new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 5 }, + "Browse" => DataProtoMapper.EncodeBrowseRequest(new BrowseRequest(Folder, null, null, Budget)), + "GetMetadata" => DataProtoMapper.EncodeMetadataRequest(new MetadataRequest([Raw, Missing], Budget)), + "Read" => DataProtoMapper.EncodeReadRequest(new ReadRequest([new("r1", Raw, TimeSpan.FromSeconds(2)), new("r2", Missing, null)], Budget)), + "Write" => WriteRequest(), + "Subscribe" => DataProtoMapper.EncodeCommand(new OpenSubscription("sub-1", 1, "open-1", TimeSpan.FromSeconds(5), + [new("item-1", Raw, new(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null))], + false, TimeSpan.FromMinutes(5), Budget)), + _ => throw new ArgumentOutOfRangeException(nameof(rpc)), + }; + + private static W.WriteRequest WriteRequest() + { + using var first = DataValue.FromScalar(DataValueKind.Int32, 17); + using var second = DataValue.FromScalar(DataValueKind.String, "abc"); + return DataProtoMapper.EncodeWriteRequest(new WriteBatch( + [ + new("w1", "op-1", Raw, first, 1, "boot", TimeSpan.FromSeconds(4), 1), + new("w2", "op-2", Missing, second, 1, "boot", TimeSpan.FromSeconds(4), 1), + ], Budget)); + } + + internal static byte[] Bytes(string rpc) => Message(rpc).ToByteArray(); +} + +/// +/// Drives the real in-process with a recorded request and a +/// deterministic origin facade. Reusable by H2/A2/A3: pass the headers a client of that phase sends. +/// +internal static class V1CompatibilityHarness +{ + internal static async Task DriveAsync(string rpc, Metadata headers) + { + var (service, context) = Create(rpc, headers); + var bytes = V1Requests.Bytes(rpc); + IMessage response = rpc switch + { + "GetCapabilities" => await service.GetCapabilities(W.CapabilitiesRequest.Parser.ParseFrom(bytes), context), + "Browse" => await service.Browse(W.BrowseRequest.Parser.ParseFrom(bytes), context), + "GetMetadata" => await service.GetMetadata(W.MetadataRequest.Parser.ParseFrom(bytes), context), + "Read" => await service.Read(W.ReadRequest.Parser.ParseFrom(bytes), context), + "Write" => await service.Write(W.WriteRequest.Parser.ParseFrom(bytes), context), + "Subscribe" => null!, + _ => throw new ArgumentOutOfRangeException(nameof(rpc)), + }; + if (rpc != "Subscribe") + return GrpcDataV1CompatibilityTests.Hex(GrpcDataV1CompatibilityTests.Normalise(response).ToByteArray()); + var writer = new Writer(); + await service.Subscribe(new Reader(W.SubscriptionCommand.Parser.ParseFrom(bytes)), writer, context); + return string.Join("|", writer.Frames.Select(f => GrpcDataV1CompatibilityTests.Hex(GrpcDataV1CompatibilityTests.Normalise(f).ToByteArray()))); + } + + internal static (DataConnectionGrpcService Service, CallContext Context) Create(string rpc, Metadata headers) + { + var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); + var authority = new DataPlaneAuthorityState(); + authority.Apply("cluster", "v1", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }], + [], new Dictionary>()); + var authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System); + var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" }; + var context = new CallContext(rpc, headers); + var http = new DefaultHttpContext(); + http.Connection.LocalPort = 9443; http.Request.Protocol = "HTTP/2"; http.Request.Scheme = "https"; http.Request.Method = "POST"; + http.Request.Host = new HostString("source.local", 9443); http.Request.Path = context.Method; + http.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(bearer); + http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node"); + context.UserState["__HttpContext"] = http; + return (new DataConnectionGrpcService(new Factory(), Options.Create(options), authenticator), context); + } + + internal static HttpContext Http(ServerCallContext context) => (HttpContext)context.UserState["__HttpContext"]; + + private sealed class Factory : IDataConnectionFactory + { + public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => new Origin(target); + } + + /// A deterministic v1 origin exercising every optional v1 field the encoders emit. + private sealed class Origin(DataTarget target) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate + { + internal static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); + private static readonly DateTimeOffset Source = new(2026, 11, 23, 12, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset Server = Source.AddMilliseconds(250); + public DataTarget Target => target; + public TimeProvider Clock => TimeProvider.System; + public bool CanPublish(ServingIdentity expectedServing) => expectedServing == Serving; + public bool CanPublishCapabilities(DataCapabilities expected) => true; + + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities( + 1, 3, Serving, DataReadiness.Ready, + DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, + new HashSet { DataValueKind.Int32, DataValueKind.String, DataValueKind.Array }, + new(16, 16, 65_536, 16, 4, 65_536, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(10), TimeSpan.FromSeconds(5), 1000), + false, 0, "cluster", true, true, true, true, true)); + + private static DataMetadata Scalar => new(V1Requests.Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, + DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, + 1, "src-1", "rpm", false); + private static DataMetadata ArrayItem => new(V1Requests.Array, "Array", "Variable", DataValueKind.Array, 1, [3], false, + DataOperations.Browse | DataOperations.Metadata | DataOperations.Read, 1, null, null, true, DataValueKind.UInt8); + + public Task BrowseAsync(BrowseRequest request, CancellationToken token) => Task.FromResult(new DataBrowseBranch( + request.Parent, DataItemStatus.Good, [Scalar, ArrayItem], false, "next-page", new MetadataLease(1, 1, TimeSpan.FromSeconds(30)))); + + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken token) => + Task.FromResult>>( + [ + new("0", DataItemStatus.Good, Scalar, null, new MetadataLease(1, 1, TimeSpan.FromSeconds(30))), + new("1", DataItemStatus.NotFound, null, "No such node."), + ]); + + public Task> ReadAsync(ReadRequest request, CancellationToken token) => + Task.FromResult>( + [ + new("r1", DataItemStatus.Good, DataReadiness.Ready, TimeSpan.FromMilliseconds(120), + new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, Source, Server, Serving, 7), null, new Lease()), + new("r2", DataItemStatus.Denied, DataReadiness.Unavailable, null, null, "Denied."), + ]); + + public Task> WriteAsync(WriteBatch request, CancellationToken token) => + Task.FromResult>( + [ + new("w1", new(DataWriteState.DriverConfirmedSuccess, 0, null)), + new("w2", new(DataWriteState.RejectedBeforeDispatch, 0x80340000u, "Unknown node.")), + ]); + + public Task SubscribeAsync(CancellationToken token) => Task.FromResult(new Subscription()); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + + private sealed class Lease : IDataPublicationLease { public bool IsValid => true; public void Dispose() { } } + + private sealed class Subscription : IDataSubscriptionTransport + { + private readonly TaskCompletionSource _opened = new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task SendAsync(DataSubscriptionCommand command, CancellationToken token) { _opened.TrySetResult(command); return Task.CompletedTask; } + public IAsyncEnumerable ReadAllAsync(CancellationToken token) => throw new NotSupportedException(); + public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken token) + { + var open = (OpenSubscription)await _opened.Task.WaitAsync(token); + var handle = new DataItemHandle(open.SubscriptionId, open.StreamEpoch, 1, 1); + await Emit(sink, new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId, + [new("item-1", DataItemStatus.Good, handle, open.Items[0].Settings, null)]), token); + await Emit(sink, new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 2, DataStreamControlKind.SnapshotBegin, + [new(0, 3)], 1, 1, null), token); + using (var values = new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, 3, true, + [new(handle, new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, Source, Server, Serving, 7), + new(TimeSpan.Zero, TimeSpan.FromMilliseconds(120)), DataReadiness.Ready)])) + await Emit(sink, values, token); + await Emit(sink, new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 4, DataStreamControlKind.SnapshotEnd, + [new(0, 3)], 1, 1, "done"), token); + } + private static async Task Emit(IDataSubscriptionDeliverySink sink, DataSubscriptionFrame frame, CancellationToken token) + { + using var prepared = await sink.PrepareAsync(frame, 65_536, token); + ((IDataPreparedSubscriptionPublication)prepared).SetPublicationGuard(() => true); + await sink.WriteAsync(prepared, token); + } + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + } + + internal sealed class Reader(W.SubscriptionCommand open) : IAsyncStreamReader + { + private int _read; + public W.SubscriptionCommand Current { get; private set; } = null!; + public async Task MoveNext(CancellationToken token) + { + if (Interlocked.Exchange(ref _read, 1) == 0) { Current = open; return true; } + await Task.Delay(Timeout.Infinite, token); return false; + } + } + + internal sealed class Writer : IServerStreamWriter + { + public List Frames { get; } = []; + public WriteOptions? WriteOptions { get; set; } + public Task WriteAsync(W.SubscriptionFrame frame) { Frames.Add(frame); return Task.CompletedTask; } + public Task WriteAsync(W.SubscriptionFrame frame, CancellationToken cancellationToken) => WriteAsync(frame); + } + + internal sealed class CallContext(string rpc, Metadata headers) : ServerCallContext + { + protected override string MethodCore => DataConnectionEndpoints.ServicePrefix + rpc; + protected override string HostCore => "source.local"; + protected override string PeerCore => "ipv4:127.0.0.1:0"; + protected override DateTime DeadlineCore => DateTime.MaxValue; + protected override Metadata RequestHeadersCore => headers; + protected override CancellationToken CancellationTokenCore => TestContext.Current.CancellationToken; + protected override Metadata ResponseTrailersCore { get; } = []; + protected override Status StatusCore { get; set; } + protected override WriteOptions? WriteOptionsCore { get; set; } + protected override AuthContext AuthContextCore => new(null, new Dictionary>()); + protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException(); + protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1Goldens.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1Goldens.cs new file mode 100644 index 000000000..8de49bb8b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1Goldens.cs @@ -0,0 +1,29 @@ +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +/// +/// Golden bytes recorded from the pre-X0 server (master 2e4e4063) by . +/// Uppercase hex of ToByteArray(); Subscribe frames are joined with '|'. Never re-record these to make a +/// later phase pass: a difference is a v1 wire regression. +/// +internal static class GrpcDataV1Goldens +{ + internal static readonly IReadOnlyDictionary Requests = new Dictionary + { + ["GetCapabilities"] = "08011005", + ["Browse"] = "0A3A0A2F0A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A01732205506C616E7410012A05506C616E74220B0880E1EB17101018808004", + ["GetMetadata"] = "0A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F53706565640A4A0A370A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220D506C616E742F4D697373696E6710012A0D506C616E742F4D697373696E67120B0880E1EB17101018808004", + ["Read"] = "0A510A02723112460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F53706565641880DAC4090A500A027232124A0A370A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220D506C616E742F4D697373696E6710012A0D506C616E742F4D697373696E67120B0880E1EB17101018808004", + ["Write"] = "0A670A02773112046F702D311A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F537065656422040805182228013204626F6F743880B4891340010A6E0A02773212046F702D321A4A0A370A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220D506C616E742F4D697373696E6710012A0D506C616E742F4D697373696E672207080D3A0361626328013204626F6F743880B489134001120B0880E1EB17101018808004", + ["Subscribe"] = "0A057375622D3110011A066F70656E2D312080E1EB172A730A5E0A066974656D2D3112460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F53706565641A0C08C096B1021080ADE20418021880BCC1960B220B0880E1EB17101018808004", + }; + + internal static readonly IReadOnlyDictionary Responses = new Dictionary + { + ["GetCapabilities"] = "080110031A1B0A046E6F64651204626F6F741A075072696D6172792001280130012001281F3203050D113A24081010101880800420102804308080043880C6868F014080F882AD164880E1EB1750E8075207636C757374657258016001680170017801", + ["Browse"] = "0A3A0A2F0A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A01732205506C616E7410012A05506C616E7410011A780A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F5370656564120553706565641A085661726961626C65200528FFFFFFFFFFFFFFFFFF013801401F480152057372632D315A0372706D1A680A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F417272617910012A0B506C616E742F4172726179120541727261791A085661726961626C652011280132010340074801600168072A096E6578742D70616765320A080110011880C6868F013A1B0A046E6F64651204626F6F741A075072696D617279200128013001", + ["GetMetadata"] = "0A8B010A013010011A780A460A350A07636C7573746572121A68747470733A2F2F7A622E636F6D2F6F746F706375612F7261771A0173220B506C616E742F537065656410012A0B506C616E742F5370656564120553706565641A085661726961626C65200528FFFFFFFFFFFFFFFFFF013801401F480152057372632D315A0372706D2A0A080110011880C6868F010A140A01311003220D4E6F2073756368206E6F64652E121B0A046E6F64651204626F6F741A075072696D617279200128013001", + ["Read"] = "0A480A0272311001180120809F492A3A0A04080518541A0608C0D590D806220B08C0D590D8061080E59A772A1B0A046E6F64651204626F6F741A075072696D61727920012801300130070A110A02723210021803320744656E6965642E121B0A046E6F64651204626F6F741A075072696D617279200128013001", + ["Write"] = "0A060A02773110020A1B0A0277321001188080D08108220D556E6B6E6F776E206E6F64652E121B0A046E6F64651204626F6F741A075072696D617279200128013001", + ["Subscribe"] = "0A057375622D311001180122310A066F70656E2D3112270A066974656D2D3110011A0D0A057375622D31100118012001220C08C096B1021080ADE2041802421B0A046E6F64651204626F6F741A075072696D617279200128013001|0A057375622D31100118022A0A08011202100318012001421B0A046E6F64651204626F6F741A075072696D617279200128013001|0A057375622D311001180332530801124F0A0D0A057375622D31100118012001123A0A04080518541A0608C0D590D806220B08C0D590D8061080E59A772A1B0A046E6F64651204626F6F741A075072696D617279200128013001300718002001421B0A046E6F64651204626F6F741A075072696D617279200128013001|0A057375622D31100118042A10080212021003180120012A04646F6E65421B0A046E6F64651204626F6F741A075072696D617279200128013001", + }; +}