Files
lmxopcua/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/FailoverRetryTests.cs
T
Joseph Doherty 291be3c55c fix(client): #1000 failover retries with backoff, reconnect clears the subscription map, subscriptions batch into one round trip
S-4: a failover that finds every endpoint down stays Reconnecting and cycles the endpoints with a
1s..15s capped backoff until it connects or the connection epoch moves on; the backoff is woken by
the epoch so it never pins the failover slot. S-3: ConnectAsync/DisconnectAsync/landing Disconnected
clear the recorded subscriptions, so a re-subscribe of the same node creates a monitored item.
S-12: SubscribeManyAsync + ISubscriptionAdapter batch add (one CreateMonitoredItems), used by the CLI
subscribe and the failover replay. CLI subscribe/alarms print connection transitions.
2026-12-03 10:46:13 -05:00

199 lines
9.0 KiB
C#

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;
/// <summary>
/// #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 <see cref="OpcUaClientService.FailoverDelay"/>, which
/// the tests gate, so nothing here sleeps on the wall clock.
/// </summary>
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<ConnectionState> _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];
}
/// <summary>Puts the service in the pre-fix terminal shape (Disconnected, no session, map still populated) via reflection.</summary>
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);
}
/// <summary>The documented schedule: 1 s doubling to a 15 s cap.</summary>
[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]);
}
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>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.</summary>
[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);
}
/// <summary>
/// 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).
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
[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);
}
}