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.
This commit is contained in:
Joseph Doherty
2026-12-03 10:46:13 -05:00
parent 2f6f41441a
commit 291be3c55c
13 changed files with 738 additions and 83 deletions
@@ -109,4 +109,34 @@ public class SubscribeCommandTests
// the single-node form the original test asserted — the command supports multi-node now.
output.ShouldContain("Subscribed to 1/1 nodes (interval: 2000ms)");
}
}
/// <summary>#1000 S-4: a connection drop / recovery is printed instead of the run going silent.</summary>
[Fact]
public async Task Execute_PrintsConnectionStateTransitions()
{
var fakeService = new FakeOpcUaClientService();
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar"
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Connected,
Shared.Models.ConnectionState.Reconnecting, "opc.tcp://localhost:4840");
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Reconnecting,
Shared.Models.ConnectionState.Connected, "opc.tcp://backup:4840");
// The drain loop is asynchronous: poll for the last line instead of sleeping a fixed time.
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!TestConsoleHelper.GetOutput(console).Contains("Reconnecting -> Connected") && DateTime.UtcNow < deadline)
await Task.Delay(20, TestContext.Current.CancellationToken);
console.RequestCancellation();
await task;
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("CONNECTION Connected -> Reconnecting (opc.tcp://localhost:4840)");
output.ShouldContain("CONNECTION Reconnecting -> Connected (opc.tcp://backup:4840)");
}
}
@@ -0,0 +1,198 @@
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);
}
}
@@ -76,6 +76,38 @@ internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter
}
}
/// <summary>Gets the number of server round trips (apply-changes) the batched add made; the single-item add is not counted.</summary>
public int BatchApplyCount { get; private set; }
/// <summary>Node ids whose batched add the fake server rejects (string form).</summary>
public HashSet<string> RejectedNodes { get; } = [];
/// <inheritdoc />
public Task<IReadOnlyList<MonitoredItemResult>> AddDataChangeMonitoredItemsAsync(IReadOnlyList<NodeId> nodeIds,
int samplingIntervalMs, Action<string, DataValue> onDataChange, CancellationToken ct)
{
lock (_itemsLock)
{
BatchApplyCount++;
var results = new List<MonitoredItemResult>(nodeIds.Count);
foreach (var nodeId in nodeIds)
{
if (RejectedNodes.Contains(nodeId.ToString()))
{
results.Add(new MonitoredItemResult(0, new ServiceResultException(StatusCodes.BadNodeIdUnknown)));
continue;
}
AddDataChangeCount++;
var handle = _nextHandle++;
_items[handle] = (nodeId, onDataChange, null);
results.Add(new MonitoredItemResult(handle, null));
}
return Task.FromResult<IReadOnlyList<MonitoredItemResult>>(results);
}
}
/// <inheritdoc />
public Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct)
{
@@ -1637,22 +1637,31 @@ public class OpcUaClientServiceTests : IDisposable
}
/// <summary>
/// Verifies that the client falls back to disconnected when every failover endpoint is unreachable.
/// Verifies that when every failover endpoint is unreachable the client is not connected but keeps trying (#1000
/// S-4: it used to land permanently Disconnected after one pass). The retry loop itself is covered in
/// <see cref="FailoverRetryTests"/>; here the backoff is held open so the state can be observed.
/// </summary>
[Fact]
public async Task KeepAliveFailure_AllEndpointsFail_TransitionsToDisconnected()
public async Task KeepAliveFailure_AllEndpointsFail_StaysReconnectingAndRetries()
{
var session1 = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session1);
var states = new List<ConnectionState>();
_service.ConnectionStateChanged += (_, e) => { lock (states) states.Add(e.NewState); };
var backoff = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_service.FailoverDelay = (_, token) => backoff.Task.WaitAsync(token);
await _service.ConnectAsync(ValidSettings(), TestContext.Current.CancellationToken);
// After the first session, make factory fail
_sessionFactory.ThrowOnCreate = true;
session1.SimulateKeepAlive(false);
await Task.Delay(200, TestContext.Current.CancellationToken);
var failover = _service.LastFailover.ShouldNotBeNull();
while (_sessionFactory.CreateCallCount < 2) await Task.Delay(10, TestContext.Current.CancellationToken);
_service.IsConnected.ShouldBeFalse();
failover.IsCompleted.ShouldBeFalse();
lock (states) states.ShouldNotContain(ConnectionState.Disconnected);
}
/// <summary>
@@ -0,0 +1,111 @@
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-12: subscribing N nodes (and replaying them after a failover) costs one server round trip, not N.</summary>
public sealed class SubscribeManyTests : IDisposable
{
private const string Primary = "opc.tcp://primary:4840";
private const string Backup = "opc.tcp://backup:4840";
private readonly FakeSessionFactory _factory = new();
private readonly OpcUaClientService _service;
public SubscribeManyTests()
{
_service = new OpcUaClientService(new FakeApplicationConfigurationFactory(), new FakeEndpointDiscovery(), _factory);
}
public void Dispose() => _service.Dispose();
private static List<NodeId> Nodes(int count) =>
Enumerable.Range(0, count).Select(i => NodeId.Parse($"ns=2;s=Plant/Dev/Tag{i}")).ToList();
private static ConnectionSettings Settings() => new()
{
EndpointUrl = Primary, FailoverUrls = [Backup], SessionTimeoutSeconds = 60
};
[Fact]
public async Task Subscribing_100_nodes_through_the_batch_path_makes_one_apply()
{
var ct = TestContext.Current.CancellationToken;
var session = new FakeSessionAdapter();
_factory.EnqueueSession(session);
await _service.ConnectAsync(Settings(), ct);
var results = await _service.SubscribeManyAsync(Nodes(100), 250, ct);
results.ShouldAllBe(e => e == null);
var sub = session.CreatedSubscriptions.ShouldHaveSingleItem();
sub.BatchApplyCount.ShouldBe(1);
sub.AddDataChangeCount.ShouldBe(100);
sub.ActiveHandles.Count.ShouldBe(100);
}
/// <summary>A per-item server rejection is reported for that node only; the rest are subscribed and recorded, and
/// the rejected node can be subscribed again later (it was not recorded).</summary>
[Fact]
public async Task A_per_item_rejection_is_reported_for_that_node_only()
{
var ct = TestContext.Current.CancellationToken;
var nodes = Nodes(5);
var sub = new FakeSubscriptionAdapter();
sub.RejectedNodes.Add(nodes[2].ToString());
_factory.EnqueueSession(new FakeSessionAdapter { NextSubscription = sub });
await _service.ConnectAsync(Settings(), ct);
var results = await _service.SubscribeManyAsync(nodes, 250, ct);
results.Select((e, i) => (e, i)).Where(t => t.e != null).Select(t => t.i).ShouldBe([2]);
sub.AddDataChangeCount.ShouldBe(4);
// Positive control: the accepted nodes are recorded as subscribed (a repeat makes no new apply) ...
await _service.SubscribeManyAsync(nodes.Where(n => n != nodes[2]).ToList(), 250, ct);
sub.BatchApplyCount.ShouldBe(1);
// ... while the rejected one was not recorded and is retried.
sub.RejectedNodes.Clear();
(await _service.SubscribeManyAsync([nodes[2]], 250, ct)).ShouldHaveSingleItem().ShouldBeNull();
sub.BatchApplyCount.ShouldBe(2);
sub.AddDataChangeCount.ShouldBe(5);
}
[Fact]
public async Task Duplicate_and_already_subscribed_nodes_are_not_added_twice()
{
var ct = TestContext.Current.CancellationToken;
var nodes = Nodes(3);
var session = new FakeSessionAdapter();
_factory.EnqueueSession(session);
await _service.ConnectAsync(Settings(), ct);
await _service.SubscribeAsync(nodes[0], 250, ct);
await _service.SubscribeManyAsync([nodes[0], nodes[1], nodes[1], nodes[2]], 250, ct);
session.CreatedSubscriptions.ShouldHaveSingleItem().AddDataChangeCount.ShouldBe(3);
}
/// <summary>The failover replay re-creates every recorded subscription in one batched apply.</summary>
[Fact]
public async Task Failover_replay_recreates_all_subscriptions_in_one_apply()
{
var ct = TestContext.Current.CancellationToken;
var s1 = new FakeSessionAdapter();
var s2 = new FakeSessionAdapter();
_factory.EnqueueSession(s1);
_factory.EnqueueSession(s2);
await _service.ConnectAsync(Settings(), ct);
await _service.SubscribeManyAsync(Nodes(50), 250, ct);
s1.SimulateKeepAlive(false);
await _service.LastFailover.ShouldNotBeNull().WaitAsync(TimeSpan.FromSeconds(10), ct);
var replayed = s2.CreatedSubscriptions.ShouldHaveSingleItem();
replayed.BatchApplyCount.ShouldBe(1);
replayed.AddDataChangeCount.ShouldBe(50);
}
}