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
@@ -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) { }
@@ -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) { }
@@ -62,6 +62,60 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
return handle;
}
/// <inheritdoc />
public async Task<IReadOnlyList<MonitoredItemResult>> AddDataChangeMonitoredItemsAsync(
IReadOnlyList<NodeId> nodeIds, int samplingIntervalMs, Action<string, DataValue> onDataChange,
CancellationToken ct)
{
var items = new List<MonitoredItem>(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;
}
/// <inheritdoc />
public async Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct)
{
@@ -2,6 +2,11 @@ using Opc.Ua;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
/// <summary>The outcome of one item of a batched monitored-item add: its client handle, or the per-item error.</summary>
/// <param name="Handle">The client handle when the item was created.</param>
/// <param name="Error">Why the server rejected this item, or <see langword="null"/> when it was created.</param>
internal readonly record struct MonitoredItemResult(uint Handle, Exception? Error);
/// <summary>
/// Abstracts OPC UA subscription and monitored item management.
/// </summary>
@@ -23,6 +28,18 @@ internal interface ISubscriptionAdapter : IDisposable
Task<uint> AddDataChangeMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs,
Action<string, DataValue> onDataChange, CancellationToken ct = default);
/// <summary>
/// Adds one data-change monitored item per node with a SINGLE server round trip (#1000 S-12: one
/// <c>CreateMonitoredItems</c> for N nodes instead of N sequential requests).
/// </summary>
/// <param name="nodeIds">The nodes to monitor.</param>
/// <param name="samplingIntervalMs">The sampling interval in milliseconds, shared by every item.</param>
/// <param name="onDataChange">Callback when data changes. Receives (nodeIdString, DataValue).</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>One result per input node, in order; a rejected item carries its error and is not tracked.</returns>
Task<IReadOnlyList<MonitoredItemResult>> AddDataChangeMonitoredItemsAsync(IReadOnlyList<NodeId> nodeIds,
int samplingIntervalMs, Action<string, DataValue> onDataChange, CancellationToken ct = default);
/// <summary>
/// Removes a previously added monitored item by its client handle.
/// </summary>
@@ -90,6 +90,25 @@ public interface IOpcUaClientService : IDisposable
/// <returns>A task that represents the asynchronous operation.</returns>
Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default);
/// <summary>
/// Subscribes to live data changes for many nodes at once. The default implementation subscribes one node at a
/// time; <see cref="OpcUaClientService"/> 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.
/// </summary>
/// <param name="nodeIds">The nodes whose value changes should be monitored.</param>
/// <param name="intervalMs">The monitored-item sampling and publishing interval in milliseconds.</param>
/// <param name="ct">The cancellation token that aborts subscription creation.</param>
/// <returns>One entry per input node, in order: <see langword="null"/> when subscribed, otherwise why that node failed.</returns>
async Task<IReadOnlyList<Exception?>> SubscribeManyAsync(IReadOnlyList<NodeId> 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;
}
/// <summary>
/// Removes a previously created live-data subscription for a node.
/// </summary>
@@ -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();
/// <summary>First backoff between failover passes; doubles per pass up to <see cref="FailoverBackoffCap"/> (S-4).</summary>
internal static readonly TimeSpan FailoverBackoffStart = TimeSpan.FromSeconds(1);
/// <summary>Cap of the failover backoff (S-4).</summary>
internal static readonly TimeSpan FailoverBackoffCap = TimeSpan.FromSeconds(15);
/// <summary>Delay seam between failover passes (test hook; production waits on the clock, cancelled by the epoch).</summary>
internal Func<TimeSpan, CancellationToken, Task> FailoverDelay { get; set; } = Task.Delay;
/// <summary>The backoff before failover retry pass <paramref name="pass"/> (1-based): 1 s, 2 s, 4 s, ... capped at 15 s.</summary>
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));
}
/// <summary>Starts a new connection epoch (caller holds <see cref="_subscriptionLock"/>) and wakes any sleeping failover.</summary>
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;
}
/// <summary>
/// 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).
/// </summary>
private void ClearSubscriptionState()
{
lock (_subscriptionLock)
{
_activeDataSubscriptions.Clear();
_activeAlarmSubscription = null;
}
}
/// <summary>The most recent keep-alive-triggered failover task (test seam: lets a test await it).</summary>
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);
}
/// <inheritdoc />
public async Task<IReadOnlyList<Exception?>> SubscribeManyAsync(IReadOnlyList<NodeId> 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<string>(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();
}
}
/// <inheritdoc />
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();
}
}
}
/// <summary>
/// One pass over the endpoint list, under the subscription gate.
/// </summary>
/// <returns>
/// <see langword="true"/> when the failover is finished (connected, or abandoned because the epoch moved on);
/// <see langword="false"/> when every endpoint failed and another pass should follow.
/// </returns>
private async Task<bool> 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;
}
/// <summary>Re-creates the recorded subscriptions on <paramref name="session"/>. Runs under the subscription gate.</summary>
@@ -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)