From 291be3c55ca836bef3dcd167c04c7f89821051d2 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:46:13 -0500 Subject: [PATCH] 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. --- docs/Client.CLI.md | 2 + docs/Client.UI.md | 2 +- .../Commands/AlarmsCommand.cs | 9 + .../Commands/SubscribeCommand.cs | 29 +- .../Adapters/DefaultSubscriptionAdapter.cs | 54 ++++ .../Adapters/ISubscriptionAdapter.cs | 17 + .../IOpcUaClientService.cs | 19 ++ .../OpcUaClientService.cs | 301 ++++++++++++++---- .../SubscribeCommandTests.cs | 32 +- .../FailoverRetryTests.cs | 198 ++++++++++++ .../Fakes/FakeSubscriptionAdapter.cs | 32 ++ .../OpcUaClientServiceTests.cs | 15 +- .../SubscribeManyTests.cs | 111 +++++++ 13 files changed, 738 insertions(+), 83 deletions(-) create mode 100644 tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/FailoverRetryTests.cs create mode 100644 tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/SubscribeManyTests.cs diff --git a/docs/Client.CLI.md b/docs/Client.CLI.md index 3bf47cb3c..26eda8377 100644 --- a/docs/Client.CLI.md +++ b/docs/Client.CLI.md @@ -69,6 +69,8 @@ those, the CLI fails loudly if the server advertises an endpoint with no or an u When `-F` is provided, the shared service tries the primary URL first, then each failover URL in order. For long-running commands (`subscribe`, `alarms`), the service monitors the session via keep-alive and automatically reconnects to the next available server on failure. +If every endpoint is down when a failover starts (a restarting server, a redundant partner mid-switchover) the service stays in `Reconnecting` and cycles the endpoint list again with a capped backoff (1 s doubling to 15 s) until one connects or the user disconnects; it never gives up on its own (#1000). Both commands print `CONNECTION -> ()` lines for every transition, so a run across a restart shows the drop and the recovery. On recovery all recorded subscriptions are re-created in one batched request per sampling interval, and `subscribe` itself creates its monitored items for the whole target set (including `-r`) in one request instead of one round trip per node. + ```bash otopcua-cli connect -u opc.tcp://localhost:4840/OtOpcUa -F opc.tcp://localhost:4841/OtOpcUa ``` diff --git a/docs/Client.UI.md b/docs/Client.UI.md index 8a235facd..04fcc80bf 100644 --- a/docs/Client.UI.md +++ b/docs/Client.UI.md @@ -73,7 +73,7 @@ Connection settings are saved to `{LocalAppData}/OtOpcUaClient/settings.json` af ### Redundancy -When connected, the redundancy row displays the server's redundancy mode, service level, and application URI. The shared service handles automatic failover to backup endpoints if configured. +When connected, the redundancy row displays the server's redundancy mode, service level, and application URI. The shared service handles automatic failover to backup endpoints if configured. If no endpoint is reachable it stays `Reconnecting` and keeps retrying with a capped backoff (1 s to 15 s) until the user disconnects (#1000). ## Browse Tree diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/AlarmsCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/AlarmsCommand.cs index 5ef4bfba8..735c96641 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/AlarmsCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/AlarmsCommand.cs @@ -95,6 +95,14 @@ public class AlarmsCommand : CommandBase } } + // #1000 S-4: surface connection transitions (Reconnecting / Connected after a failover) so a run across a + // restart is distinguishable from a server that simply stopped publishing. + void ConnectionHandler(object? sender, ConnectionStateChangedEventArgs e) => + outputChannel.Writer.TryWrite( + $"[{DateTime.UtcNow:O}] CONNECTION {e.OldState} -> {e.NewState} ({e.EndpointUrl})"); + + service.ConnectionStateChanged += ConnectionHandler; + service.AlarmEvent += AlarmEventHandler; await service.SubscribeAlarmsAsync(sourceNodeId, Interval, ct); @@ -132,6 +140,7 @@ public class AlarmsCommand : CommandBase // Stop accepting new notifications before writing final output. service.AlarmEvent -= AlarmEventHandler; + service.ConnectionStateChanged -= ConnectionHandler; outputChannel.Writer.Complete(); await drainCts.CancelAsync(); try { await drainTask; } catch (OperationCanceledException) { } diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/SubscribeCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/SubscribeCommand.cs index 05bed3b86..541afb931 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/SubscribeCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/SubscribeCommand.cs @@ -141,21 +141,33 @@ public class SubscribeCommand : CommandBase } } + // #1000 S-4: surface connection transitions (Reconnecting / Connected after a failover) so a run across a + // restart is distinguishable from a server that simply stopped publishing. + void ConnectionHandler(object? sender, ConnectionStateChangedEventArgs e) => + outputChannel.Writer.TryWrite( + $"[{DateTime.UtcNow:O}] CONNECTION {e.OldState} -> {e.NewState} ({e.EndpointUrl})"); + + service.ConnectionStateChanged += ConnectionHandler; + service.DataChanged += DataChangedHandler; + // One batched CreateMonitoredItems for the whole target set (S-12) instead of one round trip per node; + // a per-node rejection is still reported for that node only. var subscribed = 0; - foreach (var (nodeId, _) in targets) + try { - try + var outcomes = await service.SubscribeManyAsync(targets.Select(t => t.nodeId).ToList(), Interval, ct); + for (var i = 0; i < targets.Count; i++) { - await service.SubscribeAsync(nodeId, Interval, ct); - subscribed++; - } - catch (Exception ex) - { - await console.Output.WriteLineAsync($" FAILED to subscribe {nodeId}: {ex.Message}"); + if (outcomes[i] is { } error) + await console.Output.WriteLineAsync($" FAILED to subscribe {targets[i].nodeId}: {error.Message}"); + else subscribed++; } } + catch (Exception ex) when (ex is not OperationCanceledException) + { + await console.Output.WriteLineAsync($" FAILED to subscribe {targets.Count} node(s): {ex.Message}"); + } await console.Output.WriteLineAsync( $"Subscribed to {subscribed}/{targets.Count} nodes (interval: {Interval}ms). Press Ctrl+C to stop and print summary."); @@ -181,6 +193,7 @@ public class SubscribeCommand : CommandBase // Stop accepting new notifications before writing the summary. service.DataChanged -= DataChangedHandler; + service.ConnectionStateChanged -= ConnectionHandler; outputChannel.Writer.Complete(); await drainCts.CancelAsync(); try { await drainTask; } catch (OperationCanceledException) { } diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSubscriptionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSubscriptionAdapter.cs index e44c3dc1f..23eceeaba 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSubscriptionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSubscriptionAdapter.cs @@ -62,6 +62,60 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter return handle; } + /// + public async Task> AddDataChangeMonitoredItemsAsync( + IReadOnlyList nodeIds, int samplingIntervalMs, Action onDataChange, + CancellationToken ct) + { + var items = new List(nodeIds.Count); + foreach (var nodeId in nodeIds) + { + var id = nodeId; + var item = new MonitoredItem(_subscription.DefaultItem) + { + StartNodeId = id, + DisplayName = id.ToString(), + SamplingInterval = samplingIntervalMs + }; + item.Notification += (_, e) => + { + if (Volatile.Read(ref _finishing) == 0 && e.NotificationValue is MonitoredItemNotification notification) + onDataChange(id.ToString(), notification.Value); + }; + items.Add(item); + _subscription.AddItem(item); + } + + try + { + await _subscription.ApplyChangesAsync(ct); + } + catch + { + // An interrupted batch tracks nothing; the SDK carries any required deletion on its next ApplyChanges. + foreach (var item in items) _subscription.RemoveItem(item); + throw; + } + + var results = new MonitoredItemResult[items.Count]; + for (var i = 0; i < items.Count; i++) + { + var item = items[i]; + if (item.Status.Error is { } error && StatusCode.IsBad(error.StatusCode)) + { + _subscription.RemoveItem(item); + results[i] = new MonitoredItemResult(0, new ServiceResultException(error.StatusCode)); + continue; + } + + _monitoredItems[item.ClientHandle] = item; + results[i] = new MonitoredItemResult(item.ClientHandle, null); + } + + Logger.Debug("Added {Count} data change monitored items in one round trip", items.Count); + return results; + } + /// public async Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct) { diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISubscriptionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISubscriptionAdapter.cs index afedf4c72..9fd9e844c 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISubscriptionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISubscriptionAdapter.cs @@ -2,6 +2,11 @@ using Opc.Ua; namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters; +/// The outcome of one item of a batched monitored-item add: its client handle, or the per-item error. +/// The client handle when the item was created. +/// Why the server rejected this item, or when it was created. +internal readonly record struct MonitoredItemResult(uint Handle, Exception? Error); + /// /// Abstracts OPC UA subscription and monitored item management. /// @@ -23,6 +28,18 @@ internal interface ISubscriptionAdapter : IDisposable Task AddDataChangeMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, Action onDataChange, CancellationToken ct = default); + /// + /// Adds one data-change monitored item per node with a SINGLE server round trip (#1000 S-12: one + /// CreateMonitoredItems for N nodes instead of N sequential requests). + /// + /// The nodes to monitor. + /// The sampling interval in milliseconds, shared by every item. + /// Callback when data changes. Receives (nodeIdString, DataValue). + /// Cancellation token. + /// One result per input node, in order; a rejected item carries its error and is not tracked. + Task> AddDataChangeMonitoredItemsAsync(IReadOnlyList nodeIds, + int samplingIntervalMs, Action onDataChange, CancellationToken ct = default); + /// /// Removes a previously added monitored item by its client handle. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs index 02b7aa453..89abcdf7f 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs @@ -90,6 +90,25 @@ public interface IOpcUaClientService : IDisposable /// A task that represents the asynchronous operation. Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default); + /// + /// Subscribes to live data changes for many nodes at once. The default implementation subscribes one node at a + /// time; overrides it to create every monitored item in a single server round + /// trip (#1000 S-12), which matters for a recursive subscribe over thousands of variables. + /// + /// The nodes whose value changes should be monitored. + /// The monitored-item sampling and publishing interval in milliseconds. + /// The cancellation token that aborts subscription creation. + /// One entry per input node, in order: when subscribed, otherwise why that node failed. + async Task> SubscribeManyAsync(IReadOnlyList nodeIds, int intervalMs = 1000, + CancellationToken ct = default) + { + var results = new Exception?[nodeIds.Count]; + for (var i = 0; i < nodeIds.Count; i++) + try { await SubscribeAsync(nodeIds[i], intervalMs, ct); } + catch (Exception ex) when (ex is not OperationCanceledException) { results[i] = ex; } + return results; + } + /// /// Removes a previously created live-data subscription for a node. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs index 026d48030..92b090fb8 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs @@ -41,6 +41,51 @@ public sealed class OpcUaClientService : IOpcUaClientService // failover is never undone by it. A keep-alive from a previous connection's session cannot start one either. private long _connectionEpoch; + // Cancelled whenever the epoch moves on (every epoch bump goes through AdvanceEpochLocked), so a failover asleep + // in its retry backoff wakes immediately and abandons itself instead of pinning _failoverInProgress for up to the + // backoff cap - which would swallow a bad keep-alive from the user's NEW connection. + private CancellationTokenSource _epochCts = new(); + + /// First backoff between failover passes; doubles per pass up to (S-4). + internal static readonly TimeSpan FailoverBackoffStart = TimeSpan.FromSeconds(1); + + /// Cap of the failover backoff (S-4). + internal static readonly TimeSpan FailoverBackoffCap = TimeSpan.FromSeconds(15); + + /// Delay seam between failover passes (test hook; production waits on the clock, cancelled by the epoch). + internal Func FailoverDelay { get; set; } = Task.Delay; + + /// The backoff before failover retry pass (1-based): 1 s, 2 s, 4 s, ... capped at 15 s. + internal static TimeSpan FailoverBackoff(int pass) + { + var seconds = FailoverBackoffStart.TotalSeconds * Math.Pow(2, Math.Max(0, pass - 1)); + return TimeSpan.FromSeconds(Math.Min(seconds, FailoverBackoffCap.TotalSeconds)); + } + + /// Starts a new connection epoch (caller holds ) and wakes any sleeping failover. + private long AdvanceEpochLocked() + { + var old = _epochCts; + _epochCts = new CancellationTokenSource(); + var epoch = ++_connectionEpoch; + try { old.Cancel(); } catch (Exception ex) { Logger.Warning(ex, "Cancelling the previous connection epoch"); } + return epoch; + } + + /// + /// Forgets every recorded subscription (the replay list AND the "already subscribed" guard). Must run wherever + /// the service lands without a session, or a later SubscribeAsync for the same node finds its key and silently + /// does nothing (#1000 S-3). + /// + private void ClearSubscriptionState() + { + lock (_subscriptionLock) + { + _activeDataSubscriptions.Clear(); + _activeAlarmSubscription = null; + } + } + /// The most recent keep-alive-triggered failover task (test seam: lets a test await it). internal Task? LastFailover { get; private set; } @@ -116,7 +161,10 @@ public sealed class OpcUaClientService : IOpcUaClientService $"Already {_state.ToString().ToLowerInvariant()}; call DisconnectAsync before connecting again."); long epoch; - lock (_subscriptionLock) epoch = ++_connectionEpoch; + lock (_subscriptionLock) epoch = AdvanceEpochLocked(); + + // A previous connection's recorded subscriptions are meaningless on a new session (S-3). + ClearSubscriptionState(); _settings = settings; _allEndpointUrls = FailoverUrlParser.Parse(settings.EndpointUrl, settings.FailoverUrls); @@ -150,10 +198,14 @@ public sealed class OpcUaClientService : IOpcUaClientService public async Task DisconnectAsync(CancellationToken ct = default) { if (_state == ConnectionState.Disconnected) + { + // Already down: nothing to close, but never leave a stale subscription map behind (S-3). + ClearSubscriptionState(); return; + } // A new epoch first: a failover still connecting abandons itself instead of resurrecting the connection. - lock (_subscriptionLock) _connectionEpoch++; + lock (_subscriptionLock) AdvanceEpochLocked(); // The SDK transport may already be disposed when teardown begins. var endpointUrl = CurrentConnectionInfo?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty; @@ -346,6 +398,66 @@ public sealed class OpcUaClientService : IOpcUaClientService Logger.Debug("Subscribed to data changes on {NodeId}", nodeId); } + /// + public async Task> SubscribeManyAsync(IReadOnlyList nodeIds, int intervalMs = 1000, + CancellationToken ct = default) + { + ThrowIfDisposed(); + ThrowIfNotConnected(); + + var results = new Exception?[nodeIds.Count]; + if (nodeIds.Count == 0) return results; + + await _subscriptionGate.WaitAsync(ct); + try + { + // A failover may have run (and failed) while this call waited for the gate. + ThrowIfNotConnected(); + + ISubscriptionAdapter? subscription; + ISessionAdapter session; + var pending = new List<(int Index, string Key, NodeId NodeId)>(); + lock (_subscriptionLock) + { + subscription = _dataSubscription; + session = _session!; + var seen = new HashSet(StringComparer.Ordinal); + for (var i = 0; i < nodeIds.Count; i++) + { + var key = nodeIds[i].ToString(); + if (_activeDataSubscriptions.ContainsKey(key) || !seen.Add(key)) continue; // already subscribed + pending.Add((i, key, nodeIds[i])); + } + } + + if (pending.Count == 0) return results; + + if (subscription == null) + { + subscription = await session.CreateSubscriptionAsync(intervalMs, ct); + lock (_subscriptionLock) _dataSubscription = subscription; + } + + var outcomes = await subscription.AddDataChangeMonitoredItemsAsync( + pending.Select(p => p.NodeId).ToList(), intervalMs, DataCallback(session, subscription), ct); + + lock (_subscriptionLock) + { + for (var i = 0; i < pending.Count; i++) + { + if (outcomes[i].Error is { } error) results[pending[i].Index] = error; + else _activeDataSubscriptions[pending[i].Key] = (pending[i].NodeId, intervalMs, outcomes[i].Handle); + } + } + + return results; + } + finally + { + _subscriptionGate.Release(); + } + } + /// public async Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default) { @@ -785,7 +897,7 @@ public sealed class OpcUaClientService : IOpcUaClientService { if (_disposed) return; _disposed = true; - _connectionEpoch++; // a failover still running abandons itself + AdvanceEpochLocked(); // a failover still running abandons itself } _dataSubscription?.Dispose(); @@ -925,14 +1037,16 @@ public sealed class OpcUaClientService : IOpcUaClientService } } - // The rest runs under the subscription gate (and its null-outs under _subscriptionLock): no subscribe can - // interleave with the teardown, the reconnect or the replay. + // Teardown runs under the subscription gate (and its null-outs under _subscriptionLock): no subscribe can + // interleave with it. The gate is then released between passes so a subscribe is never blocked behind a + // retry backoff - while Reconnecting it fails fast (ThrowIfNotConnected) instead. + ConnectionSettings? settings; + string[]? endpoints; + CancellationToken epochToken; await _subscriptionGate.WaitAsync(); try { // The user's settings / endpoint list as of THIS epoch: a Connect during the failover replaces the fields. - ConnectionSettings? settings; - string[]? endpoints; lock (_subscriptionLock) { if (_connectionEpoch != epoch || _disposed) return; // the user disconnected / reconnected meanwhile @@ -941,68 +1055,104 @@ public sealed class OpcUaClientService : IOpcUaClientService _alarmSubscription = null; settings = _settings; endpoints = _allEndpointUrls; + epochToken = _epochCts.Token; } - - if (settings == null || endpoints == null) - { - TransitionStateIfCurrent(epoch, ConnectionState.Disconnected, oldEndpoint); - return; - } - - // Try each endpoint - for (var attempt = 0; attempt < endpoints.Length; attempt++) - { - if (!IsCurrentEpoch(epoch)) return; // stop trying once the user has moved on (m5) - _currentEndpointIndex = (_currentEndpointIndex + 1) % endpoints.Length; - var url = endpoints[_currentEndpointIndex]; - - try - { - Logger.Information("Failover attempt to {EndpointUrl}", url); - var session = await ConnectToEndpointAsync(settings, url, CancellationToken.None); - - // A Disconnect / Connect / Dispose that ran while this attempt was connecting wins: never - // resurrect the old connection or overwrite the user's new session. Checked and installed - // atomically against the epoch. - bool installed; - lock (_subscriptionLock) - { - installed = _connectionEpoch == epoch && !_disposed; - if (installed) _session = session; - } - - if (!installed) - { - session.Dispose(); - return; - } - - session.RegisterKeepAliveHandler(isGood => - { - if (!isGood) OnKeepAliveFailed(epoch); - }); - - CurrentConnectionInfo = BuildConnectionInfo(session); - if (!TransitionStateIfCurrent(epoch, ConnectionState.Connected, url)) return; - Logger.Information("Failover succeeded to {EndpointUrl}", url); - - // Replay subscriptions - await ReplaySubscriptionsAsync(session); - return; - } - catch (Exception ex) - { - Logger.Warning(ex, "Failover to {EndpointUrl} failed", url); - } - } - - if (TransitionStateIfCurrent(epoch, ConnectionState.Disconnected, oldEndpoint)) - Logger.Error("All failover endpoints unreachable"); } finally { _subscriptionGate.Release(); } + + if (settings == null || endpoints == null) + { + // Landing Disconnected without a session: the recorded subscriptions are dead with it (S-3). + if (TransitionStateIfCurrent(epoch, ConnectionState.Disconnected, oldEndpoint)) ClearSubscriptionState(); + return; + } + + // Keep cycling the endpoint list with a capped backoff until a pass connects or the epoch moves on (a user + // Disconnect / Connect / Dispose). The state stays Reconnecting throughout: a server that is still restarting, + // or a redundant partner mid-switchover, is the NORMAL reason the first pass fails (S-4). + for (var pass = 0; ; pass++) + { + if (pass > 0) + { + var delay = FailoverBackoff(pass); + Logger.Information("All failover endpoints unreachable; retrying in {Delay}", delay); + try { await FailoverDelay(delay, epochToken); } + catch (OperationCanceledException) { return; } // the epoch moved on + } + + if (!IsCurrentEpoch(epoch)) return; + + await _subscriptionGate.WaitAsync(); + try + { + if (await TryFailoverPassAsync(epoch, settings, endpoints)) return; + } + finally + { + _subscriptionGate.Release(); + } + } + } + + /// + /// One pass over the endpoint list, under the subscription gate. + /// + /// + /// when the failover is finished (connected, or abandoned because the epoch moved on); + /// when every endpoint failed and another pass should follow. + /// + private async Task TryFailoverPassAsync(long epoch, ConnectionSettings settings, string[] endpoints) + { + for (var attempt = 0; attempt < endpoints.Length; attempt++) + { + if (!IsCurrentEpoch(epoch)) return true; // stop trying once the user has moved on (m5) + _currentEndpointIndex = (_currentEndpointIndex + 1) % endpoints.Length; + var url = endpoints[_currentEndpointIndex]; + + try + { + Logger.Information("Failover attempt to {EndpointUrl}", url); + var session = await ConnectToEndpointAsync(settings, url, CancellationToken.None); + + // A Disconnect / Connect / Dispose that ran while this attempt was connecting wins: never + // resurrect the old connection or overwrite the user's new session. Checked and installed + // atomically against the epoch. + bool installed; + lock (_subscriptionLock) + { + installed = _connectionEpoch == epoch && !_disposed; + if (installed) _session = session; + } + + if (!installed) + { + session.Dispose(); + return true; + } + + session.RegisterKeepAliveHandler(isGood => + { + if (!isGood) OnKeepAliveFailed(epoch); + }); + + CurrentConnectionInfo = BuildConnectionInfo(session); + if (!TransitionStateIfCurrent(epoch, ConnectionState.Connected, url)) return true; + Logger.Information("Failover succeeded to {EndpointUrl}", url); + + // Replay subscriptions + await ReplaySubscriptionsAsync(session); + return true; + } + catch (Exception ex) + { + Logger.Warning(ex, "Failover to {EndpointUrl} failed", url); + } + } + + return false; } /// Re-creates the recorded subscriptions on . Runs under the subscription gate. @@ -1021,29 +1171,40 @@ public sealed class OpcUaClientService : IOpcUaClientService _activeAlarmSubscription = null; } - // Replay data subscriptions + // Replay data subscriptions: one batched CreateMonitoredItems per distinct interval instead of one round trip + // per node (S-12), while notifications for already-replayed items are already flowing. ISubscriptionAdapter? dataSubscription = null; - foreach (var (nodeIdStr, (nodeId, intervalMs, _)) in subscriptions) + foreach (var group in subscriptions.GroupBy(s => s.Value.IntervalMs)) + { + var batch = group.ToList(); try { if (dataSubscription == null) { - dataSubscription = await session.CreateSubscriptionAsync(intervalMs, CancellationToken.None); + dataSubscription = await session.CreateSubscriptionAsync(group.Key, CancellationToken.None); lock (_subscriptionLock) _dataSubscription = dataSubscription; } - var handle = await dataSubscription.AddDataChangeMonitoredItemAsync( - nodeId, intervalMs, DataCallback(session, dataSubscription), CancellationToken.None); + var outcomes = await dataSubscription.AddDataChangeMonitoredItemsAsync( + batch.Select(b => b.Value.NodeId).ToList(), group.Key, + DataCallback(session, dataSubscription), CancellationToken.None); lock (_subscriptionLock) { - _activeDataSubscriptions[nodeIdStr] = (nodeId, intervalMs, handle); + for (var i = 0; i < batch.Count; i++) + { + if (outcomes[i].Error is { } error) + Logger.Warning(error, "Failed to replay data subscription for {NodeId}", batch[i].Key); + else + _activeDataSubscriptions[batch[i].Key] = (batch[i].Value.NodeId, group.Key, outcomes[i].Handle); + } } } catch (Exception ex) { - Logger.Warning(ex, "Failed to replay data subscription for {NodeId}", nodeIdStr); + Logger.Warning(ex, "Failed to replay {Count} data subscriptions at {IntervalMs} ms", batch.Count, group.Key); } + } // Replay alarm subscription if (alarmSubscription.HasValue) diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/SubscribeCommandTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/SubscribeCommandTests.cs index ed5270285..3b39c0308 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/SubscribeCommandTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/SubscribeCommandTests.cs @@ -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)"); } -} \ No newline at end of file + + /// #1000 S-4: a connection drop / recovery is printed instead of the run going silent. + [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)"); + } +} diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/FailoverRetryTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/FailoverRetryTests.cs new file mode 100644 index 000000000..092434e84 --- /dev/null +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/FailoverRetryTests.cs @@ -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; + +/// +/// #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); + } +} diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSubscriptionAdapter.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSubscriptionAdapter.cs index 120d9cef0..cc9ae53d4 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSubscriptionAdapter.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSubscriptionAdapter.cs @@ -76,6 +76,38 @@ internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter } } + /// Gets the number of server round trips (apply-changes) the batched add made; the single-item add is not counted. + public int BatchApplyCount { get; private set; } + + /// Node ids whose batched add the fake server rejects (string form). + public HashSet RejectedNodes { get; } = []; + + /// + public Task> AddDataChangeMonitoredItemsAsync(IReadOnlyList nodeIds, + int samplingIntervalMs, Action onDataChange, CancellationToken ct) + { + lock (_itemsLock) + { + BatchApplyCount++; + var results = new List(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>(results); + } + } + /// public Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct) { diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/OpcUaClientServiceTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/OpcUaClientServiceTests.cs index ef899f0b6..a54152a69 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/OpcUaClientServiceTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/OpcUaClientServiceTests.cs @@ -1637,22 +1637,31 @@ public class OpcUaClientServiceTests : IDisposable } /// - /// 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 + /// ; here the backoff is held open so the state can be observed. /// [Fact] - public async Task KeepAliveFailure_AllEndpointsFail_TransitionsToDisconnected() + public async Task KeepAliveFailure_AllEndpointsFail_StaysReconnectingAndRetries() { var session1 = new FakeSessionAdapter(); _sessionFactory.EnqueueSession(session1); + var states = new List(); + _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); } /// diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/SubscribeManyTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/SubscribeManyTests.cs new file mode 100644 index 000000000..e21fa833b --- /dev/null +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/SubscribeManyTests.cs @@ -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; + +/// #1000 S-12: subscribing N nodes (and replaying them after a failover) costs one server round trip, not N. +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 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); + } + + /// 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). + [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); + } + + /// The failover replay re-creates every recorded subscription in one batched apply. + [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); + } +}