using System.Collections.Concurrent; using System.Reflection; using Opc.Ua; using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms; using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters; namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters; /// /// Gitea #148: OtOpcUa emits RefreshRequiredEventType (SourceNode = Server, no condition /// fields) on an incomplete condition snapshot, a removed imported condition, or a resync that /// invalidates EventIds. Per OPC UA Part 9 the client must call ConditionRefresh and must NOT treat /// the event as an alarm. These tests pin the event branch in HandleAlarmEvent and the /// debounce/coalesce behaviour of . /// public class RealOpcUaRefreshRequiredTests { private static readonly MethodInfo Handler = typeof(RealOpcUaClient).GetMethod("HandleAlarmEvent", BindingFlags.Instance | BindingFlags.NonPublic)!; /// OtOpcUa's RefreshRequired shape: SourceNode = Server, SourceName "Server", Message "RefreshRequired". private static EventFieldList RefreshRequiredEvent() => new() { EventFields = new Variant[] { Variant.From(ObjectTypeIds.RefreshRequiredEventType), // 0 EventType Variant.From(ObjectIds.Server), // 1 SourceNode Variant.From("Server"), // 2 SourceName Variant.From(DateTime.UtcNow), // 3 Time Variant.From(new LocalizedText("RefreshRequired")), // 4 Message Variant.From((ushort)100), // 5 Severity Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null, } }; private static void Seed(RealOpcUaClient client, string handle) { var field = typeof(RealOpcUaClient).GetField("_alarmLastState", BindingFlags.Instance | BindingFlags.NonPublic)!; var map = (ConcurrentDictionary>)field.GetValue(client)!; map[handle] = new Dictionary(StringComparer.Ordinal); } private static async Task WaitUntilAsync(Func condition, TimeSpan timeout) { var deadline = DateTime.UtcNow + timeout; while (!condition()) { if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached"); await Task.Delay(10); } } /// A RefreshRequired event is never surfaced as a native alarm transition. [Fact] public async Task RefreshRequired_IsNotMappedAsAnAlarm_AndRequestsARefresh() { var client = new RealOpcUaClient(); Seed(client, "h1"); var batches = new ConcurrentQueue>(); client.RefreshRequiredCoalescer = new ConditionRefreshCoalescer( (handles, _) => { batches.Enqueue(handles.ToList()); return Task.CompletedTask; }, TimeSpan.FromMilliseconds(20)); var sink = new List(); Handler.Invoke(client, ["h1", "ns=2;s=Area", RefreshRequiredEvent(), (Action)sink.Add]); Assert.Empty(sink); // no phantom condition keyed "Server" await WaitUntilAsync(() => batches.Count == 1, TimeSpan.FromSeconds(5)); Assert.Equal(["h1"], batches.Single()); } /// /// The production executor tolerates a client with no live session: a RefreshRequired that /// lands after a disconnect is logged and dropped, never thrown on the publish thread. /// [Fact] public async Task RefreshRequired_WithNoSession_IsSwallowed() { var client = new RealOpcUaClient(); Seed(client, "h1"); var sink = new List(); Handler.Invoke(client, ["h1", "", RefreshRequiredEvent(), (Action)sink.Add]); await WaitUntilAsync(() => client.RefreshRequiredCoalescer.ExecutedBatches == 1, TimeSpan.FromSeconds(5)); Assert.Empty(sink); } /// A burst of RefreshRequired across several items costs ONE refresh carrying every handle. [Fact] public async Task Burst_CoalescesIntoOneRefresh() { var batches = new ConcurrentQueue>(); var coalescer = new ConditionRefreshCoalescer( (handles, _) => { batches.Enqueue(handles.ToList()); return Task.CompletedTask; }, TimeSpan.FromMilliseconds(100)); for (var i = 0; i < 50; i++) coalescer.Request(i % 2 == 0 ? "a" : "b"); await WaitUntilAsync(() => batches.Count >= 1, TimeSpan.FromSeconds(5)); await Task.Delay(300); // no trailing second refresh Assert.Single(batches); Assert.Equal(["a", "b"], batches.Single().OrderBy(h => h)); } /// /// A request arriving WHILE a refresh runs is not lost and does not overlap it: it is served by /// a second, sequential refresh. /// [Fact] public async Task RequestDuringRefresh_RunsASecondSequentialRefresh() { var release = new TaskCompletionSource(); var concurrent = 0; var maxConcurrent = 0; var batches = new ConcurrentQueue>(); var coalescer = new ConditionRefreshCoalescer(async (handles, _) => { var now = Interlocked.Increment(ref concurrent); maxConcurrent = Math.Max(maxConcurrent, now); batches.Enqueue(handles.ToList()); if (batches.Count == 1) await release.Task; Interlocked.Decrement(ref concurrent); }, TimeSpan.FromMilliseconds(20)); coalescer.Request("a"); await WaitUntilAsync(() => batches.Count == 1, TimeSpan.FromSeconds(5)); coalescer.Request("b"); // while the first refresh is still in flight await Task.Delay(100); Assert.Single(batches); release.SetResult(); await WaitUntilAsync(() => batches.Count == 2, TimeSpan.FromSeconds(5)); Assert.Equal(1, maxConcurrent); Assert.Equal(["b"], batches.ToArray()[1]); } /// An executor fault is logged, not thrown, and does not stop later refreshes. [Fact] public async Task ExecutorFailure_IsSwallowed_AndLaterRequestsStillRefresh() { var calls = 0; var coalescer = new ConditionRefreshCoalescer((_, _) => { if (Interlocked.Increment(ref calls) == 1) throw new ServiceResultException(StatusCodes.BadRefreshInProgress); return Task.CompletedTask; }, TimeSpan.FromMilliseconds(20)); coalescer.Request("a"); await WaitUntilAsync(() => Volatile.Read(ref calls) == 1, TimeSpan.FromSeconds(5)); await Task.Delay(50); coalescer.Request("a"); await WaitUntilAsync(() => Volatile.Read(ref calls) == 2, TimeSpan.FromSeconds(5)); } /// Clear() (disconnect) drops requests still debouncing — they belong to a dead session. [Fact] public async Task Clear_DropsPendingRequests() { var calls = 0; var coalescer = new ConditionRefreshCoalescer( (_, _) => { Interlocked.Increment(ref calls); return Task.CompletedTask; }, TimeSpan.FromMilliseconds(100)); coalescer.Request("a"); coalescer.Clear(); await Task.Delay(300); Assert.Equal(0, Volatile.Read(ref calls)); } /// /// RefreshStart/RefreshEnd stay framing sentinels, never alarms, and RefreshRequired arriving /// between them neither breaks the frame nor emits a condition. /// [Fact] public void RefreshRequiredInsideARefreshFrame_LeavesTheFrameIntact() { var client = new RealOpcUaClient(); Seed(client, "h1"); client.RefreshRequiredCoalescer = new ConditionRefreshCoalescer( (_, _) => Task.CompletedTask, TimeSpan.FromMilliseconds(10)); var sink = new List(); EventFieldList Boundary(NodeId type) => new() { EventFields = new Variant[] { Variant.From(type), Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null } }; Handler.Invoke(client, ["h1", "", Boundary(ObjectTypeIds.RefreshStartEventType), (Action)sink.Add]); Handler.Invoke(client, ["h1", "", RefreshRequiredEvent(), (Action)sink.Add]); Handler.Invoke(client, ["h1", "", Boundary(ObjectTypeIds.RefreshEndEventType), (Action)sink.Add]); Assert.Equal(["SnapshotStart", "SnapshotComplete"], sink.Select(t => t.Kind.ToString())); } }