using System.Threading.Channels; using Opc.Ua; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Client.Shared.Models; using ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Fakes; namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests; /// /// #1000 S-3 / S-4: a failover that finds every endpoint down must keep retrying (with backoff) instead of ending /// permanently Disconnected, and a manual reconnect must never inherit a stale subscription map that turns a later /// SubscribeAsync into a silent no-op. Backoff waits go through , which /// the tests gate, so nothing here sleeps on the wall clock. /// public sealed class FailoverRetryTests : IDisposable { private const string Primary = "opc.tcp://primary:4840"; private const string Backup = "opc.tcp://backup:4840"; private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); private static readonly NodeId Node = NodeId.Parse("ns=2;s=Plant/Modbus/dev1/Speed"); private readonly FakeSessionFactory _factory = new(); private readonly OpcUaClientService _service; private readonly List _states = []; // Each failover backoff announces itself here and then waits for the test to release it (or the epoch to cancel it). private readonly Channel<(TimeSpan Delay, TaskCompletionSource Release)> _delays = Channel.CreateUnbounded<(TimeSpan, TaskCompletionSource)>(); public FailoverRetryTests() { _service = new OpcUaClientService(new FakeApplicationConfigurationFactory(), new FakeEndpointDiscovery(), _factory); _service.ConnectionStateChanged += (_, e) => { lock (_states) _states.Add(e.NewState); }; _service.FailoverDelay = async (delay, token) => { var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _delays.Writer.TryWrite((delay, release)); await release.Task.WaitAsync(token); }; } public void Dispose() => _service.Dispose(); private static ConnectionSettings Settings(params string[] failover) => new() { EndpointUrl = Primary, FailoverUrls = failover, SessionTimeoutSeconds = 60 }; private async Task<(TimeSpan Delay, TaskCompletionSource Release)> NextDelayAsync() => await _delays.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(Wait); private ConnectionState[] States() { lock (_states) return [.. _states]; } /// Puts the service in the pre-fix terminal shape (Disconnected, no session, map still populated) via reflection. private void ForceDisconnectedWithoutCleanup() { const System.Reflection.BindingFlags F = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; typeof(OpcUaClientService).GetField("_state", F)!.SetValue(_service, ConnectionState.Disconnected); typeof(OpcUaClientService).GetField("_session", F)!.SetValue(_service, null); typeof(OpcUaClientService).GetField("_dataSubscription", F)!.SetValue(_service, null); } /// The documented schedule: 1 s doubling to a 15 s cap. [Fact] public void Failover_backoff_doubles_from_one_second_to_a_fifteen_second_cap() { Enumerable.Range(1, 7).Select(p => OpcUaClientService.FailoverBackoff(p).TotalSeconds) .ShouldBe([1d, 2d, 4d, 8d, 15d, 15d, 15d]); } /// /// S-4 repro: the single pass used to land the service permanently Disconnected the moment the server was still /// down. It must stay Reconnecting, back off, retry, and reconnect (replaying subscriptions) once the server returns. /// [Fact] public async Task A_failover_that_finds_every_endpoint_down_retries_with_backoff_until_the_server_returns() { var ct = TestContext.Current.CancellationToken; var s1 = new FakeSessionAdapter(); _factory.EnqueueSession(s1); await _service.ConnectAsync(Settings(Backup), ct); await _service.SubscribeAsync(Node, 500, ct); _factory.ThrowOnCreate = true; s1.SimulateKeepAlive(false); var failover = _service.LastFailover.ShouldNotBeNull(); // Pass 1 fails (primary and backup both down) -> backoff 1 s, still Reconnecting. var (first, release1) = await NextDelayAsync(); first.ShouldBe(TimeSpan.FromSeconds(1)); _service.IsConnected.ShouldBeFalse(); States().ShouldNotContain(ConnectionState.Disconnected); failover.IsCompleted.ShouldBeFalse(); // Pass 2 still fails -> 2 s. release1.SetResult(); var (second, release2) = await NextDelayAsync(); second.ShouldBe(TimeSpan.FromSeconds(2)); States().ShouldNotContain(ConnectionState.Disconnected); // The server comes back: the next pass connects and replays the subscription. _factory.ThrowOnCreate = false; var s2 = new FakeSessionAdapter(); _factory.EnqueueSession(s2); release2.SetResult(); await failover.WaitAsync(Wait, ct); _service.IsConnected.ShouldBeTrue(); States().ShouldNotContain(ConnectionState.Disconnected); s2.CreatedSubscriptions.ShouldHaveSingleItem().AddDataChangeCount.ShouldBe(1); } /// A user Disconnect while the failover sleeps wakes it at once and frees the failover slot, so a bad /// keep-alive on the user's NEXT connection starts a fresh failover instead of being swallowed. [Fact] public async Task Disconnect_during_the_backoff_wakes_the_failover_and_a_later_connection_can_fail_over_again() { var ct = TestContext.Current.CancellationToken; var s1 = new FakeSessionAdapter(); _factory.EnqueueSession(s1); await _service.ConnectAsync(Settings(), ct); _factory.ThrowOnCreate = true; s1.SimulateKeepAlive(false); var failover = _service.LastFailover.ShouldNotBeNull(); await NextDelayAsync(); // asleep in the backoff await _service.DisconnectAsync(ct); await failover.WaitAsync(Wait, ct); // woken by the epoch, not by the (never released) delay _service.IsConnected.ShouldBeFalse(); _factory.ThrowOnCreate = false; var s2 = new FakeSessionAdapter(); _factory.EnqueueSession(s2); await _service.ConnectAsync(Settings(), ct); _factory.ThrowOnCreate = true; s2.SimulateKeepAlive(false); // would be ignored if the old failover still held the slot var second = _service.LastFailover.ShouldNotBeNull(); second.ShouldNotBeSameAs(failover); await NextDelayAsync(); States().Last().ShouldBe(ConnectionState.Reconnecting); } /// /// S-3 repro: subscribe, lose the server while it stays down, then reconnect manually and subscribe the SAME /// node: a monitored item must be created on the new session (not silently no-op'd by a stale map). /// [Fact] public async Task Resubscribing_the_same_node_after_a_failed_failover_and_manual_reconnect_creates_a_monitored_item() { var ct = TestContext.Current.CancellationToken; var s1 = new FakeSessionAdapter(); _factory.EnqueueSession(s1); await _service.ConnectAsync(Settings(), ct); await _service.SubscribeAsync(Node, 500, ct); _factory.ThrowOnCreate = true; s1.SimulateKeepAlive(false); var failover = _service.LastFailover.ShouldNotBeNull(); await NextDelayAsync(); // the failover has run against the dead server // The user's recovery: Disconnect (a no-op if the service already landed Disconnected) + Connect + Subscribe. _factory.ThrowOnCreate = false; await _service.DisconnectAsync(ct); await failover.WaitAsync(Wait, ct); var s2 = new FakeSessionAdapter(); _factory.EnqueueSession(s2); await _service.ConnectAsync(Settings(), ct); await _service.SubscribeAsync(Node, 500, ct); s2.CreatedSubscriptions.ShouldHaveSingleItem().AddDataChangeCount.ShouldBe(1); } /// /// S-3 defence in depth: ConnectAsync forgets whatever a previous connection recorded, so even a path that lands /// Disconnected without a DisconnectAsync cannot leave a stale "already subscribed" guard behind. /// [Fact] public async Task ConnectAsync_starts_with_an_empty_subscription_map() { var ct = TestContext.Current.CancellationToken; var s1 = new FakeSessionAdapter(); _factory.EnqueueSession(s1); await _service.ConnectAsync(Settings(), ct); await _service.SubscribeAsync(Node, 500, ct); ForceDisconnectedWithoutCleanup(); var s2 = new FakeSessionAdapter(); _factory.EnqueueSession(s2); await _service.ConnectAsync(Settings(), ct); await _service.SubscribeAsync(Node, 500, ct); s2.CreatedSubscriptions.ShouldHaveSingleItem().AddDataChangeCount.ShouldBe(1); } }