using Moq; using Opc.Ua; using Opc.Ua.Client; using Shouldly; using Xunit; namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests; /// /// #946 — RefreshRequired sweeps were coalesced but not rate-limited: an upstream raising RefreshRequired /// continuously got back-to-back ConditionRefresh sweeps of every alarm subscription. A minimum interval per /// session now spaces them; a request inside the window is DEFERRED to the window's end, never dropped. /// [Trait("Category", "Unit")] [Trait("Issue", "946")] public sealed class OpcUaClientRefreshRequiredRateLimitTests { /// A TimeProvider whose time and timers move only when the test says so. private sealed class ManualTimeProvider(DateTimeOffset start) : TimeProvider { private readonly object _lock = new(); private readonly List _timers = []; private DateTimeOffset _now = start; public override DateTimeOffset GetUtcNow() { lock (_lock) return _now; } public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) { var t = new ManualTimer(this, callback, state); t.Change(dueTime, period); return t; } public void Advance(TimeSpan by) { List due; lock (_lock) { _now += by; due = _timers.Where(t => t.Due is { } d && d <= _now).ToList(); foreach (var t in due) t.Due = null; } foreach (var t in due) t.Fire(); } private sealed class ManualTimer(ManualTimeProvider owner, TimerCallback cb, object? state) : ITimer { public DateTimeOffset? Due { get; set; } public void Fire() => cb(state); public bool Change(TimeSpan dueTime, TimeSpan period) { lock (owner._lock) { owner._timers.Remove(this); if (dueTime == Timeout.InfiniteTimeSpan) { Due = null; return true; } Due = owner._now + dueTime; owner._timers.Add(this); } return true; } public void Dispose() { lock (owner._lock) owner._timers.Remove(this); } public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; } } } private static (OpcUaClientDriver Drv, ManualTimeProvider Clock, Func Sweeps) NewDriver( string id, OpcUaClientDriverOptions? options = null) { var drv = new OpcUaClientDriver(options ?? new OpcUaClientDriverOptions(), id); var clock = new ManualTimeProvider(new DateTimeOffset(2026, 11, 28, 12, 0, 0, TimeSpan.Zero)); drv.Clock = clock; var session = new Mock(MockBehavior.Loose); drv.SetSessionForTest(session.Object); drv.AddAlarmSubscriptionForTest(["Plant/opc/plc/Trip1"]); var sweeps = 0; drv.RefreshSweepStartedForTest = () => Interlocked.Increment(ref sweeps); return (drv, clock, () => Volatile.Read(ref sweeps)); } private static async Task Eventually(Func condition) { for (var i = 0; i < 200 && !condition(); i++) await Task.Delay(10, TestContext.Current.CancellationToken); condition().ShouldBeTrue(); } /// The default is a real limit (10 s), and zero is the opt-out. [Fact] public void Default_minimum_interval_is_ten_seconds() => new OpcUaClientDriverOptions().AlarmRefreshRequiredMinInterval.ShouldBe(TimeSpan.FromSeconds(10)); /// /// The first sweep runs at once; a request inside the window waits for the window's end (and runs — deferred, /// not dropped); however many requests arrive during the wait they coalesce into ONE sweep. /// [Fact] public async Task A_request_inside_the_window_is_deferred_to_its_end_and_coalesced() { var (drv, clock, sweeps) = NewDriver("opcua-946-defer"); using var _ = drv; drv.RequestRefreshRequiredSweepForTest(); await Eventually(() => sweeps() == 1); clock.Advance(TimeSpan.FromSeconds(1)); drv.RequestRefreshRequiredSweepForTest(); drv.RequestRefreshRequiredSweepForTest(); drv.RequestRefreshRequiredSweepForTest(); // Absence is only meaningful with a positive control (below): the window has not elapsed, so nothing runs. clock.Advance(TimeSpan.FromSeconds(8)); await Task.Delay(150, TestContext.Current.CancellationToken); sweeps().ShouldBe(1, "9 s into a 10 s window"); // Positive control: the window's end releases exactly one deferred sweep. clock.Advance(TimeSpan.FromSeconds(1)); await Eventually(() => sweeps() == 2); await Task.Delay(150, TestContext.Current.CancellationToken); sweeps().ShouldBe(2, "three coalesced requests are one sweep"); } /// The window then restarts from the deferred sweep: a later request is deferred again. [Fact] public async Task The_window_restarts_from_each_sweep() { var (drv, clock, sweeps) = NewDriver("opcua-946-restart"); using var _ = drv; drv.RequestRefreshRequiredSweepForTest(); await Eventually(() => sweeps() == 1); clock.Advance(TimeSpan.FromSeconds(10)); drv.RequestRefreshRequiredSweepForTest(); // exactly at the end of the first window: runs at once await Eventually(() => sweeps() == 2); drv.RequestRefreshRequiredSweepForTest(); // inside the second window await Task.Delay(150, TestContext.Current.CancellationToken); sweeps().ShouldBe(2); clock.Advance(TimeSpan.FromSeconds(10)); await Eventually(() => sweeps() == 3); } /// Zero disables the limit: back-to-back requests each sweep. [Fact] public async Task Zero_interval_disables_the_limit() { var (drv, _, sweeps) = NewDriver("opcua-946-off", new OpcUaClientDriverOptions { AlarmRefreshRequiredMinInterval = TimeSpan.Zero }); using var _d = drv; drv.RequestRefreshRequiredSweepForTest(); await Eventually(() => sweeps() == 1); drv.RequestRefreshRequiredSweepForTest(); await Eventually(() => sweeps() == 2); } /// A new session starts a fresh window (its first RefreshRequired must not wait on the old session's). [Fact] public async Task A_new_session_starts_a_fresh_window() { var (drv, _, sweeps) = NewDriver("opcua-946-session"); using var _d = drv; drv.RequestRefreshRequiredSweepForTest(); await Eventually(() => sweeps() == 1); drv.SetSessionForTest(new Mock(MockBehavior.Loose).Object); drv.RequestRefreshRequiredSweepForTest(); await Eventually(() => sweeps() == 2); } }