using Opc.Ua; using Shouldly; using Xunit; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; /// The SDK's notification-payload pool is process-wide; the recycled-payload test must not race another /// test renting from it. [CollectionDefinition(Name, DisableParallelization = true)] public sealed class SdkPayloadPoolCollection { /// The collection name. public const string Name = "sdk-payload-pool"; } /// /// Gitea #717 T7, the payload matrix the D4 rewrite meets at delivery: SDK 2.0.1 hands each Publish and Republish a /// CoreUtils.Clone of the cached message, which may carry several s (with /// s), an and a /// side by side. Every payload kind must survive the clone, only marked ordinary-tag values may change, nothing the /// SDK owns may be mutated, and the result must still encode. The stale-marker case is driven through the SDK's real /// payload pool. /// [Collection(SdkPayloadPoolCollection.Name)] public sealed class WarmStandbyCloneMatrixTests { private static readonly DateTimeUtc Source = (DateTimeUtc)new DateTime(2026, 11, 13, 8, 0, 0, DateTimeKind.Utc); private static readonly DateTimeUtc Server = (DateTimeUtc)new DateTime(2026, 11, 13, 8, 0, 1, DateTimeKind.Utc); private static DataValue Good(double v) => new(new Variant(v), StatusCodes.Good, Source, Server); private static MonitoredItemNotification Marked(uint handle, double v) { var n = new MonitoredItemNotification { ClientHandle = handle, Value = Good(v) }; n.Message = new OrdinaryTagMarker(handle, n.Value); return n; } /// The cached message as the SDK builds it: two data-change payloads (the first with per-item diagnostics), /// an event list and a status change, in that order. private static NotificationMessage Cached() => new() { SequenceNumber = 42, PublishTime = Server, NotificationData = new List { new(new DataChangeNotification { MonitoredItems = new List { Marked(1, 1.5), new() { ClientHandle = 2, Value = Good(2.5) }, // i=2267 or a condition child: unmarked }, DiagnosticInfos = new List { new() { SymbolicId = 11, AdditionalInfo = "first" }, new() { SymbolicId = 12, AdditionalInfo = "second" }, }, }), new(new EventNotificationList { Events = new List { new() { ClientHandle = 9, EventFields = new List { new("event-id"), new("message") } }, }, }), new(new StatusChangeNotification { Status = StatusCodes.BadTimeout }), new(new DataChangeNotification { MonitoredItems = new List { Marked(3, 3.5) }, }), }, }; private static T Body(NotificationMessage m, int index) where T : class, IEncodeable { m.NotificationData[index].TryGetValue(out var body).ShouldBeTrue($"payload {index} is a {typeof(T).Name}"); return body!; } private static MonitoredItemNotification Item(NotificationMessage m, int payload, int item) => Body(m, payload).MonitoredItems[item]; private static byte[] Encode(NotificationMessage m) => BinaryEncoder.EncodeMessage(m, ServiceMessageContext.Create(DefaultTelemetry.Create(_ => { }))); [Fact] public void Every_payload_kind_survives_the_delivery_clone_and_only_marked_values_are_rewritten() { var cached = Cached(); var cachedBytes = Encode(cached); var delivered = CoreUtils.Clone(cached)!; var deliveredBytes = Encode(delivered); // The clone carries every marker, each still valid against its own (cloned) notification. OrdinaryTagMarker.IsOrdinaryTag(Item(delivered, 0, 0)).ShouldBeTrue(); OrdinaryTagMarker.IsOrdinaryTag(Item(delivered, 0, 1)).ShouldBeFalse(); OrdinaryTagMarker.IsOrdinaryTag(Item(delivered, 3, 0)).ShouldBeTrue(); var projected = StandbyNotificationRewriter.Project(delivered, out var rewritten); rewritten.ShouldBe(2, "both marked values, across both data-change payloads"); projected.SequenceNumber.ShouldBe(42u); projected.PublishTime.ShouldBe(Server); projected.NotificationData.Count.ShouldBe(4, "no payload is dropped or added"); Item(projected, 0, 0).Value.StatusCode.ShouldBe(StatusCodes.BadOutOfService); Item(projected, 0, 0).Value.WrappedValue.IsNull.ShouldBeTrue(); Item(projected, 0, 0).Value.SourceTimestamp.ShouldBe(DateTimeUtc.MinValue); Item(projected, 0, 0).Value.ServerTimestamp.ShouldBe(Server); Item(projected, 0, 0).ClientHandle.ShouldBe(1u); Item(projected, 0, 1).Value.ShouldBe(Good(2.5)); Item(projected, 3, 0).Value.StatusCode.ShouldBe(StatusCodes.BadOutOfService); var diagnostics = Body(projected, 0).DiagnosticInfos; diagnostics.Count.ShouldBe(2, "per-item diagnostics stay aligned with the items"); diagnostics[0].AdditionalInfo.ShouldBe("first"); diagnostics[1].AdditionalInfo.ShouldBe("second"); Body(projected, 1).IsEqual(Body(cached, 1)).ShouldBeTrue("events pass through"); Body(projected, 2).Status.ShouldBe(StatusCodes.BadTimeout); // Nothing the SDK owns moved: neither the per-delivery clone handed in nor the cached original. Encode(delivered).ShouldBe(deliveredBytes, "the delivered clone is not mutated"); Encode(cached).ShouldBe(cachedBytes, "the cached message is not mutated"); OrdinaryTagMarker.IsOrdinaryTag(Item(cached, 0, 0)).ShouldBeTrue("the cached original keeps its marker for a later Republish"); // The projected message is wire-valid and the marker never reaches the wire. var decoded = BinaryDecoder.DecodeMessage(Encode(projected), ServiceMessageContext.Create(DefaultTelemetry.Create(_ => { })))!; decoded.NotificationData.Count.ShouldBe(4); Item(decoded, 0, 0).Value.StatusCode.ShouldBe(StatusCodes.BadOutOfService); Item(decoded, 0, 0).Message.ShouldBeNull(); Body(decoded, 0).DiagnosticInfos.Count.ShouldBe(2); } /// A Republish is a second clone of the same cached message: projecting it gives the same bytes. [Fact] public void Projecting_two_delivery_clones_of_one_cached_message_gives_identical_payloads() { var cached = Cached(); var first = StandbyNotificationRewriter.Project(CoreUtils.Clone(cached)!, out var a); var second = StandbyNotificationRewriter.Project(CoreUtils.Clone(cached)!, out var b); a.ShouldBe(b); Encode(second).ShouldBe(Encode(first)); } /// A message with no marked value comes back as the same instance (nothing rebuilt, nothing counted). [Fact] public void A_message_with_only_events_status_and_unmarked_values_is_returned_as_is() { var cached = Cached(); cached.NotificationData = new List { cached.NotificationData[1], cached.NotificationData[2] }; var delivered = CoreUtils.Clone(cached)!; ReferenceEquals(StandbyNotificationRewriter.Project(delivered, out var rewritten), delivered).ShouldBeTrue(); rewritten.ShouldBe(0); } /// /// The SDK's own pool, not a hand-made stale marker: a payload stamped for an ordinary tag and returned (as /// SentMessageQueue does on acknowledge) comes back out with its marker, here even reusing the SAME /// ClientHandle. With a different value it is not an ordinary-tag notification and is never rewritten. /// [Fact] public void A_payload_recycled_through_the_sdk_pool_keeps_its_stale_marker_which_never_validates() { var stamped = (MonitoredItemNotification)MonitoredItemNotificationActivator.Instance.CreateInstance(); stamped.ClientHandle = 7; stamped.Value = Good(1.0); stamped.Message = new OrdinaryTagMarker(7, stamped.Value); stamped.Reuse(); // Rent until the stamped payload comes back (other pooled payloads may sit ahead of it), then return the rest. var others = new List(); MonitoredItemNotification? recycled = null; for (var i = 0; i <= PooledEncodeableType.DefaultMaximumRetained && recycled is null; i++) { var rented = (MonitoredItemNotification)MonitoredItemNotificationActivator.Instance.CreateInstance(); if (ReferenceEquals(rented, stamped)) recycled = rented; else others.Add(rented); } foreach (var other in others) other.Reuse(); recycled.ShouldNotBeNull("precondition: the pool hands the stamped payload back out"); try { recycled.Message.ShouldBeOfType("precondition: Initialize() does not clear the helper"); recycled.ClientHandle = 7; // the client reused the handle for a non-ordinary item recycled.Value = new DataValue(new Variant((byte)90), StatusCodes.Good, Source, Server); OrdinaryTagMarker.IsOrdinaryTag(recycled).ShouldBeFalse(); var message = new NotificationMessage { SequenceNumber = 1, NotificationData = new List { new(new DataChangeNotification { MonitoredItems = new List { recycled } }), }, }; var projected = StandbyNotificationRewriter.Project(CoreUtils.Clone(message)!, out var rewritten); rewritten.ShouldBe(0); Item(projected, 0, 0).Value.StatusCode.ShouldBe(StatusCodes.Good); } finally { recycled.Message = null!; recycled.Reuse(); } } }