using System.Buffers.Binary; using System.IO.Pipelines; using System.Net; using System.Threading.Channels; using Google.Protobuf; using Opc.Ua; using Opc.Ua.Client; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.OpcUaServer; 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; public sealed partial class GrpcDataConfiguredDiscoveryWireTests { [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] public async Task Framed_grpc_pinned_sdk_item_never_substitutes_healthy_other_node_and_old_republish_is_denied() { var ct = TestContext.Current.CancellationToken; var capacityA = new SubscriptionTransportCapacity(4, 2, 1_000_000); var capacityB = new SubscriptionTransportCapacity(4, 2, 1_000_000); var demandA = new DeferredSubscriptionDemand(); demandA.Accept(); var demandB = new DeferredSubscriptionDemand(); demandB.Accept(); var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); LocalDataFixture? peerA = null, peerB = null; using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => new LocalSubscriptionService(peerA!.Services, context, target, demandA, limits, capacityA)); peerA = originA; originA.Publish(7); using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (context, target) => new LocalSubscriptionService(peerB!.Services, context, target, demandB, limits, capacityB), clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2"); peerB = originB; originB.Publish(8); using var connections = new FramedClusterConnections(originA, originB, pinnedToFirst: true); var published = Channel.CreateUnbounded(); await WithComposedServer(originA, originA.Raw, async (session, sink, resolver, applier, access, placements, anchor) => { var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); var configured = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, originA.Raw.Address), ct); configured.ShouldNotBeNull(); (await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).Node.ShouldBe("node-a"); await configured.DisposeAsync(); (await connections.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBe("node-a"); while (published.Reader.TryRead(out _)) { } var client = (SessionClient)session; var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); var physicalA = await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); physicalA.Node.ShouldBe("node-a"); var old = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); (Opc.Ua.DataValue Value, uint Sequence) initial; do { initial = await PublishComposedNotification(client, 1, ct); } while (!StatusCode.IsGood(initial.Value.StatusCode)); initial.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7); connections.Select(originB); await physicalA.Session.DisposeAsync(); (await connections.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBe("node-a"); // Two node-b capability probes prove that at least one full retry rejected the // other node's otherwise healthy primary identity and proceeded to retry. await connections.NodeBProbed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); await connections.NodeBProbed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); old.SourceProof.IsValid.ShouldBeFalse(); connections.Opened.Reader.TryRead(out var replacement).ShouldBeFalse($"a pinned node must not open {replacement.Node}"); while (published.Reader.TryRead(out var update)) update.Route.Serving.NodeId.ShouldNotBe("node-b"); var replay = await client.RepublishAsync(new RequestHeader(), subscriptionId, initial.Sequence, ct); StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) .ShouldBeFalse("a pinned item's old notification cannot remain good after its source stream is lost"); }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections, localPermissions: 4); } [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] public async Task Framed_grpc_new_primary_rebinds_same_subscribe_only_sdk_item_and_rejects_old_republish() { var ct = TestContext.Current.CancellationToken; var capacityA = new SubscriptionTransportCapacity(4, 2, 1_000_000); var capacityB = new SubscriptionTransportCapacity(4, 2, 1_000_000); var demandA = new DeferredSubscriptionDemand(); demandA.Accept(); var demandB = new DeferredSubscriptionDemand(); demandB.Accept(); var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); LocalDataFixture? peerA = null, peerB = null; using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => new LocalSubscriptionService(peerA!.Services, context, target, demandA, limits, capacityA)); peerA = originA; originA.Publish(7); using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (context, target) => new LocalSubscriptionService(peerB!.Services, context, target, demandB, limits, capacityB), clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2"); peerB = originB; originB.Publish(8); using var connections = new FramedClusterConnections(originA, originB); var published = Channel.CreateUnbounded(); await WithComposedServer(originA, originA.Raw, async (session, sink, resolver, applier, access, placements, anchor) => { // The configured, deployment-owned interest materializes the node before the // restricted SDK caller appears. The caller itself has Subscribe only. var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); var configured = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, originA.Raw.Address), ct); configured.ShouldNotBeNull(); var configuredStream = await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); configuredStream.Node.ShouldBe("node-a"); await configured.DisposeAsync(); (await connections.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBe("node-a"); while (published.Reader.TryRead(out _)) { } var client = (SessionClient)session; var deniedBrowse = await client.BrowseAsync(new RequestHeader(), null, 10, [new BrowseDescription { NodeId = anchor, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All, }], ct); StatusCode.IsGood(deniedBrowse.Results[0].StatusCode).ShouldBeFalse(); var deniedRead = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Neither, [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); deniedRead.Results[0].StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); var physicalA = await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); physicalA.Node.ShouldBe("node-a"); var old = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); old.Route.Serving.ShouldBe(originA.Serving); (Opc.Ua.DataValue Value, uint Sequence) initial; do { initial = await PublishComposedNotification(client, 1, ct); } while (!StatusCode.IsGood(initial.Value.StatusCode)); initial.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7); var browseCalls = connections.BrowseCalls; connections.Select(originB); await physicalA.Session.DisposeAsync(); // End the actual origin stream, leaving the SDK monitored item alive. (await connections.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBe("node-a"); var physicalB = await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); physicalB.Node.ShouldBe("node-b"); var next = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, 8), ct); next.SourceProof.IsValid.ShouldBeTrue(); old.SourceProof.IsValid.ShouldBeFalse("the ended serving incarnation cannot revive old evidence"); connections.MetadataCallsOnB.ShouldBeGreaterThan(0, "new-primary renewal must validate metadata through gRPC"); connections.BrowseCalls.ShouldBe(browseCalls, "recovery must not depend on a new browse grant or request"); Opc.Ua.DataValue current; do { current = await PublishComposedValue(client, 1, ct); } while (!StatusCode.IsGood(current.StatusCode)); current.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); var oldReplay = await client.RepublishAsync(new RequestHeader(), subscriptionId, initial.Sequence, ct); StatusCode.IsGood(ComposedChanges(oldReplay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) .ShouldBeFalse("the same monitored item must not make its old notification valid under the new serving identity"); }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections, localPermissions: 4); } /// Two independently authenticated local origins behind an HTTP/2 framed gRPC client. private sealed class FramedClusterConnections : IGrpcDataAdapterConnectionSource, IDisposable { private readonly LocalDataFixture _first, _second; private readonly bool _pinnedToFirst; private LocalDataFixture _current; private readonly DataConnectionManager _manager = new("consumer", 1); private int _browseCalls, _metadataCallsOnB; internal readonly Channel<(string Node, DataSubscriptionSession Session)> Opened = Channel.CreateUnbounded<(string, DataSubscriptionSession)>(); internal readonly Channel Closed = Channel.CreateUnbounded(); internal readonly Channel NodeBProbed = Channel.CreateUnbounded(); internal int BrowseCalls => Volatile.Read(ref _browseCalls); internal int MetadataCallsOnB => Volatile.Read(ref _metadataCallsOnB); internal FramedClusterConnections(LocalDataFixture first, LocalDataFixture second, bool pinnedToFirst = false) { _first = first; _second = second; _current = first; _pinnedToFirst = pinnedToFirst; _manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); } internal void Select(LocalDataFixture current) => Volatile.Write(ref _current, current); public ValueTask AcquireAsync(string id, CancellationToken ct) { if (id != "link") return ValueTask.FromResult(null); var target = _pinnedToFirst ? new DataTarget(DataTargetMode.Node, "cluster", "node-a") : new DataTarget(DataTargetMode.Cluster, "cluster", null); var connection = new GrpcDataConnection("link", target, [new Uri("https://node-a.test"), new Uri("https://node-b.test")], new Security(this), _manager.Acquire("link"), 1_000_000, 2, _first.Clock, eligibleNodeIds: _pinnedToFirst ? null : new HashSet { "node-a", "node-b" }); return ValueTask.FromResult(new Lease(connection)); } public void Dispose() => _manager.Dispose(); private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease { public IDataConnection Connection => connection; public CancellationToken CancellationToken => CancellationToken.None; public ValueTask DisposeAsync() => connection.DisposeAsync(); } private sealed class Security(FramedClusterConnections owner) : IDataConnectionSecurityProvider { public event Action? Changed { add { } remove { } } public ValueTask ResolveAsync(string id, Uri endpoint, CancellationToken ct) { var origin = endpoint.Host == "node-a.test" ? owner._first : owner._second; return ValueTask.FromResult(new("v1", "ca", "key", () => new Handler(owner, origin))); } } private sealed class Handler(FramedClusterConnections owner, LocalDataFixture origin) : HttpMessageHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) { if (!ReferenceEquals(Volatile.Read(ref owner._current), origin)) throw new HttpRequestException("Endpoint is not the selected primary."); if (request.RequestUri!.AbsolutePath.EndsWith("/Subscribe", StringComparison.Ordinal)) { var incoming = new Pipe(); var outgoing = new Pipe(); _ = CopyRequestAsync(request.Content!, incoming.Writer, ct); _ = ServeAsync(incoming.Reader.AsStream(), outgoing.Writer.AsStream(), ct); return Response(new StreamContent(outgoing.Reader.AsStream())); } await using var local = origin.Services.Create(origin.Context, new(DataTargetMode.Cluster, "cluster", null)); IMessage message; if (request.RequestUri.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) { var caps = await local.GetCapabilitiesAsync(LocalDataFixture.Budget, ct); if (ReferenceEquals(origin, owner._second)) owner.NodeBProbed.Writer.TryWrite(true); message = DataProtoMapper.EncodeCapabilities(caps with { SubscriptionAgeReadiness = true, ResponseServingIdentity = true, SubscriptionFreshnessChallenges = true }); } else { var bytes = await request.Content!.ReadAsByteArrayAsync(ct); var payload = bytes.AsSpan(5).ToArray(); if (request.RequestUri.AbsolutePath.EndsWith("/Browse", StringComparison.Ordinal)) { Interlocked.Increment(ref owner._browseCalls); var result = await local.BrowseAsync(DataProtoMapper.DecodeBrowseRequest(W.BrowseRequest.Parser.ParseFrom(payload)), ct); var wire = DataProtoMapper.EncodeBrowseResponse(result); wire.Serving = DataProtoMapper.EncodeServing(origin.Serving); message = wire; } else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal)) { if (ReferenceEquals(origin, owner._second)) Interlocked.Increment(ref owner._metadataCallsOnB); var result = await local.GetMetadataAsync(DataProtoMapper.DecodeMetadataRequest(W.MetadataRequest.Parser.ParseFrom(payload)), ct); var wire = DataProtoMapper.EncodeMetadataResponse(result); wire.Serving = DataProtoMapper.EncodeServing(origin.Serving); message = wire; } else throw new InvalidOperationException("Unexpected RPC in lifecycle test."); } return Response(new ByteArrayContent(Frame(message))); } private static async Task CopyRequestAsync(HttpContent content, PipeWriter writer, CancellationToken ct) { try { await content.CopyToAsync(writer.AsStream(), ct); } catch (Exception) { } finally { await writer.CompleteAsync(); } } private async Task ServeAsync(Stream input, Stream output, CancellationToken ct) { using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct); try { await using var local = origin.Services.Create(origin.Context, new(DataTargetMode.Cluster, "cluster", null)); await using var stream = await local.SubscribeAsync(lifetime.Token); var session = stream.ShouldBeOfType(); owner.Opened.Writer.TryWrite((origin.Serving.NodeId, session)); var reader = Task.Run(async () => { while (true) { var prefix = new byte[5]; await input.ReadExactlyAsync(prefix, lifetime.Token); var bytes = new byte[BinaryPrimitives.ReadInt32BigEndian(prefix.AsSpan(1))]; await input.ReadExactlyAsync(bytes, lifetime.Token); await stream.SendAsync(DataProtoMapper.DecodeCommand(W.SubscriptionCommand.Parser.ParseFrom(bytes)), lifetime.Token); } }, lifetime.Token); try { await foreach (var frame in stream.ReadAllAsync(lifetime.Token)) { try { var wire = frame is DataSubscriptionValues values ? DataProtoMapper.EncodeValues(values, false, true) : DataProtoMapper.EncodeControlOrAck(frame); wire.Serving = DataProtoMapper.EncodeServing(origin.Serving); await output.WriteAsync(Frame(wire), lifetime.Token); await output.FlushAsync(lifetime.Token); } finally { (frame as IDisposable)?.Dispose(); } } } finally { lifetime.Cancel(); try { await reader; } catch (Exception) { } } } catch (Exception) { } finally { await output.DisposeAsync(); owner.Closed.Writer.TryWrite(origin.Serving.NodeId); } } private static byte[] Frame(IMessage message) { var payload = message.ToByteArray(); var bytes = new byte[payload.Length + 5]; BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(1, 4), payload.Length); payload.CopyTo(bytes, 5); return bytes; } private static HttpResponseMessage Response(HttpContent content) { var result = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = content }; content.Headers.ContentType = new("application/grpc"); result.TrailingHeaders.Add("grpc-status", "0"); return result; } } } }