fix(client): #1048 Client.UI recursive subscribe + restore batch through SubscribeManyAsync; CLI subscribe/alarms exit 3 when a failover never recovers
- SubscriptionsViewModel collects the subtree's variables first (deduped, already-subscribed skipped) and creates them in one SubscribeManyAsync; per-node failures are named in StatusMessage, a whole-batch failure adds nothing. RestoreSubscriptionsAsync batches too. - CLI: ConnectionLossWatch ends subscribe/alarms when the service lands Disconnected on its own, or stays out of Connected past --reconnect-timeout (default 300 s, 0 = no limit): WARNING line, summary (subscribe adds 'Connection: LOST'), exit code 3. A recovery inside the window re-arms the watch.
This commit is contained in:
@@ -38,12 +38,22 @@ public class AlarmsCommand : CommandBase
|
||||
[CommandOption("refresh", Description = "Request a ConditionRefresh after subscribing")]
|
||||
public bool Refresh { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets how long, in seconds, a lost connection may stay unrecovered before the command warns and exits with
|
||||
/// <see cref="SubscribeCommand.ConnectionLostExitCode" /> (#1048). <c>0</c> waits indefinitely; the service giving
|
||||
/// up (<c>Disconnected</c>) always ends the run.
|
||||
/// </summary>
|
||||
[CommandOption("reconnect-timeout", Description = "Exit non-zero (code 3) if a lost connection has not recovered after N seconds (0 = wait indefinitely)")]
|
||||
public int ReconnectTimeoutSeconds { get; init; } = SubscribeCommand.DefaultReconnectTimeoutSeconds;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
ConfigureLogging();
|
||||
if (Interval <= 0)
|
||||
throw new CommandException($"--interval must be greater than 0 (was {Interval}).");
|
||||
if (ReconnectTimeoutSeconds < 0)
|
||||
throw new CommandException($"--reconnect-timeout must be 0 or a positive number (was {ReconnectTimeoutSeconds}).");
|
||||
|
||||
NodeId? sourceNodeId;
|
||||
try
|
||||
@@ -96,10 +106,15 @@ 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) =>
|
||||
// restart is distinguishable from a server that simply stopped publishing. #1048: and end the run when
|
||||
// the connection is lost for good.
|
||||
using var lossWatch = new ConnectionLossWatch(TimeSpan.FromSeconds(ReconnectTimeoutSeconds));
|
||||
void ConnectionHandler(object? sender, ConnectionStateChangedEventArgs e)
|
||||
{
|
||||
outputChannel.Writer.TryWrite(
|
||||
$"[{DateTime.UtcNow:O}] CONNECTION {e.OldState} -> {e.NewState} ({e.EndpointUrl})");
|
||||
lossWatch.Observe(e);
|
||||
}
|
||||
|
||||
service.ConnectionStateChanged += ConnectionHandler;
|
||||
|
||||
@@ -128,15 +143,10 @@ public class AlarmsCommand : CommandBase
|
||||
await console.Output.WriteLineAsync(line);
|
||||
}, CancellationToken.None);
|
||||
|
||||
// Wait until cancellation
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Expected on Ctrl+C
|
||||
}
|
||||
// Wait until cancellation (Ctrl+C) or a connection lost for good (#1048).
|
||||
var lostReason = await ConnectionLossWatch.WaitAsync(lossWatch, Timeout.InfiniteTimeSpan, ct);
|
||||
if (lostReason is not null)
|
||||
outputChannel.Writer.TryWrite($"[{DateTime.UtcNow:O}] WARNING: {lostReason}; stopping.");
|
||||
|
||||
// Stop accepting new notifications before writing final output.
|
||||
service.AlarmEvent -= AlarmEventHandler;
|
||||
@@ -145,6 +155,12 @@ public class AlarmsCommand : CommandBase
|
||||
await drainCts.CancelAsync();
|
||||
try { await drainTask; } catch (OperationCanceledException) { }
|
||||
|
||||
if (lostReason is not null)
|
||||
{
|
||||
// No unsubscribe over a dead connection; the finally block disconnects.
|
||||
throw new CommandException($"Connection lost: {lostReason}.", SubscribeCommand.ConnectionLostExitCode);
|
||||
}
|
||||
|
||||
await service.UnsubscribeAlarmsAsync();
|
||||
await console.Output.WriteLineAsync("Unsubscribed.");
|
||||
}
|
||||
|
||||
@@ -68,6 +68,20 @@ public class SubscribeCommand : CommandBase
|
||||
[CommandOption("summary-file", Description = "Write summary to this file path on exit (in addition to stdout)")]
|
||||
public string? SummaryFile { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets how long, in seconds, a lost connection may stay unrecovered before the command prints a warning, its
|
||||
/// summary, and exits with <see cref="ConnectionLostExitCode" /> (#1048). <c>0</c> waits indefinitely for the
|
||||
/// failover to reconnect; the service giving up (<c>Disconnected</c>) always ends the run.
|
||||
/// </summary>
|
||||
[CommandOption("reconnect-timeout", Description = "Exit non-zero (code 3) if a lost connection has not recovered after N seconds (0 = wait indefinitely)")]
|
||||
public int ReconnectTimeoutSeconds { get; init; } = DefaultReconnectTimeoutSeconds;
|
||||
|
||||
/// <summary>Default for <see cref="ReconnectTimeoutSeconds" />: comfortably longer than a server restart.</summary>
|
||||
public const int DefaultReconnectTimeoutSeconds = 300;
|
||||
|
||||
/// <summary>Process exit code when the run ends because its connection was lost for good (#1048).</summary>
|
||||
public const int ConnectionLostExitCode = 3;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -79,6 +93,8 @@ public class SubscribeCommand : CommandBase
|
||||
throw new CommandException($"--max-depth must be greater than 0 (was {MaxDepth}).");
|
||||
if (DurationSeconds < 0)
|
||||
throw new CommandException($"--duration must be 0 or a positive number (was {DurationSeconds}).");
|
||||
if (ReconnectTimeoutSeconds < 0)
|
||||
throw new CommandException($"--reconnect-timeout must be 0 or a positive number (was {ReconnectTimeoutSeconds}).");
|
||||
|
||||
NodeId rootNodeId;
|
||||
try
|
||||
@@ -142,10 +158,15 @@ 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) =>
|
||||
// restart is distinguishable from a server that simply stopped publishing. #1048: and end the run when
|
||||
// the connection is lost for good.
|
||||
using var lossWatch = new ConnectionLossWatch(TimeSpan.FromSeconds(ReconnectTimeoutSeconds));
|
||||
void ConnectionHandler(object? sender, ConnectionStateChangedEventArgs e)
|
||||
{
|
||||
outputChannel.Writer.TryWrite(
|
||||
$"[{DateTime.UtcNow:O}] CONNECTION {e.OldState} -> {e.NewState} ({e.EndpointUrl})");
|
||||
lossWatch.Observe(e);
|
||||
}
|
||||
|
||||
service.ConnectionStateChanged += ConnectionHandler;
|
||||
|
||||
@@ -180,16 +201,10 @@ public class SubscribeCommand : CommandBase
|
||||
await console.Output.WriteLineAsync(line);
|
||||
}, CancellationToken.None);
|
||||
|
||||
try
|
||||
{
|
||||
if (DurationSeconds > 0)
|
||||
await Task.Delay(TimeSpan.FromSeconds(DurationSeconds), ct);
|
||||
else
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
var lostReason = await ConnectionLossWatch.WaitAsync(
|
||||
lossWatch, DurationSeconds > 0 ? TimeSpan.FromSeconds(DurationSeconds) : Timeout.InfiniteTimeSpan, ct);
|
||||
if (lostReason is not null)
|
||||
outputChannel.Writer.TryWrite($"[{DateTime.UtcNow:O}] WARNING: {lostReason}; stopping.");
|
||||
|
||||
// Stop accepting new notifications before writing the summary.
|
||||
service.DataChanged -= DataChangedHandler;
|
||||
@@ -231,6 +246,8 @@ public class SubscribeCommand : CommandBase
|
||||
summary.Add($" Last status GOOD: {good.Count}");
|
||||
summary.Add($" Last status NOT-GOOD: {bad.Count}");
|
||||
summary.Add($" No update received at all: {never.Count}");
|
||||
if (lostReason is not null)
|
||||
summary.Add($"Connection: LOST — {lostReason}. Last values above predate the loss.");
|
||||
|
||||
if (neverWentBad.Count > 0 && neverWentBad.Count < targets.Count)
|
||||
{
|
||||
@@ -252,6 +269,12 @@ public class SubscribeCommand : CommandBase
|
||||
catch (Exception ex) { await console.Output.WriteLineAsync($"Failed to write summary file: {ex.Message}"); }
|
||||
}
|
||||
|
||||
if (lostReason is not null)
|
||||
{
|
||||
// No per-node unsubscribe over a dead connection; the finally block disconnects.
|
||||
throw new CommandException($"Connection lost: {lostReason}.", ConnectionLostExitCode);
|
||||
}
|
||||
|
||||
foreach (var (nodeId, _) in targets)
|
||||
{
|
||||
try { await service.UnsubscribeAsync(nodeId); } catch { /* ignore */ }
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Watches a long-running command's connection for a loss that never recovers (#1048). The shared service keeps
|
||||
/// a failover in <see cref="ConnectionState.Reconnecting" />, cycling the endpoints with a capped backoff, until it
|
||||
/// connects or is disconnected (#1000) — so without this a <c>subscribe</c>/<c>alarms</c> run across an outage
|
||||
/// that never ends just sits there, and its summary reports the last values seen before the drop as final.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para><see cref="Lost" /> completes, with the reason, when either:</para>
|
||||
/// <list type="bullet">
|
||||
/// <item>the service lands <see cref="ConnectionState.Disconnected" /> on its own — it will not retry; or</item>
|
||||
/// <item>the connection stays out of <see cref="ConnectionState.Connected" /> for longer than the timeout
|
||||
/// (<c>--reconnect-timeout</c>; <see cref="TimeSpan.Zero" /> = wait indefinitely for a reconnect).</item>
|
||||
/// </list>
|
||||
/// <para>A return to <see cref="ConnectionState.Connected" /> before the timeout re-arms the watch.</para>
|
||||
/// </remarks>
|
||||
internal sealed class ConnectionLossWatch : IDisposable
|
||||
{
|
||||
private readonly TimeSpan _timeout;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly object _gate = new();
|
||||
private readonly TaskCompletionSource<string> _lost = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private CancellationTokenSource? _pending;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Creates the watch.</summary>
|
||||
/// <param name="timeout">How long a loss may last before it counts as unrecovered; zero or less = no limit.</param>
|
||||
/// <param name="clock">Clock for the timeout (tests); null = the system clock.</param>
|
||||
public ConnectionLossWatch(TimeSpan timeout, TimeProvider? clock = null)
|
||||
{
|
||||
_timeout = timeout;
|
||||
_clock = clock ?? TimeProvider.System;
|
||||
}
|
||||
|
||||
/// <summary>Completes with a human-readable reason once the connection is lost for good; never faults.</summary>
|
||||
public Task<string> Lost => _lost.Task;
|
||||
|
||||
/// <summary>
|
||||
/// A long-running command's main wait: returns when <paramref name="ct" /> fires (Ctrl+C), when
|
||||
/// <paramref name="duration" /> elapses, or when the connection is lost for good.
|
||||
/// </summary>
|
||||
/// <param name="watch">The command's watch.</param>
|
||||
/// <param name="duration">How long to run; <see cref="Timeout.InfiniteTimeSpan" /> = until cancelled.</param>
|
||||
/// <param name="ct">The command's cancellation token.</param>
|
||||
/// <returns>The loss reason when the connection was lost for good, otherwise <see langword="null" />.</returns>
|
||||
public static async Task<string?> WaitAsync(ConnectionLossWatch watch, TimeSpan duration, CancellationToken ct)
|
||||
{
|
||||
using var waitCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var wait = Task.Delay(duration, waitCts.Token);
|
||||
var first = await Task.WhenAny(wait, watch.Lost).ConfigureAwait(false);
|
||||
if (first == watch.Lost && !ct.IsCancellationRequested)
|
||||
{
|
||||
await waitCts.CancelAsync().ConfigureAwait(false);
|
||||
try { await wait.ConfigureAwait(false); } catch (OperationCanceledException) { }
|
||||
return await watch.Lost.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
try { await wait.ConfigureAwait(false); } catch (OperationCanceledException) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Feeds one connection transition. Safe to call from the SDK's notification threads.</summary>
|
||||
/// <param name="e">The transition.</param>
|
||||
public void Observe(ConnectionStateChangedEventArgs e)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || _lost.Task.IsCompleted) return;
|
||||
switch (e.NewState)
|
||||
{
|
||||
case ConnectionState.Connected:
|
||||
CancelPending();
|
||||
return;
|
||||
case ConnectionState.Disconnected:
|
||||
CancelPending();
|
||||
_lost.TrySetResult($"the client gave up and disconnected from {e.EndpointUrl}");
|
||||
return;
|
||||
default: // Reconnecting / Connecting: start the clock once per outage.
|
||||
if (_pending is not null || _timeout <= TimeSpan.Zero) return;
|
||||
var cts = new CancellationTokenSource();
|
||||
_pending = cts;
|
||||
var endpoint = e.EndpointUrl;
|
||||
_ = ExpireAsync(cts, endpoint);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExpireAsync(CancellationTokenSource cts, string endpoint)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(_timeout, _clock, cts.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (!ReferenceEquals(_pending, cts) || _disposed) return;
|
||||
_lost.TrySetResult(
|
||||
$"the connection was lost (last endpoint {endpoint}) and did not recover within {_timeout.TotalSeconds:0} s");
|
||||
}
|
||||
}
|
||||
|
||||
private void CancelPending()
|
||||
{
|
||||
var pending = _pending;
|
||||
_pending = null;
|
||||
if (pending is null) return;
|
||||
pending.Cancel();
|
||||
pending.Dispose();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
CancelPending();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -215,19 +215,27 @@ public partial class SubscriptionsViewModel : ObservableObject
|
||||
/// <param name="nodeClass">The node class of the starting node so variables can be subscribed immediately.</param>
|
||||
/// <param name="intervalMs">The monitored-item interval, in milliseconds, used for created subscriptions.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs = 1000)
|
||||
{
|
||||
return AddSubscriptionRecursiveAsync(nodeIdStr, nodeClass, intervalMs, maxDepth: 10, currentDepth: 0);
|
||||
}
|
||||
|
||||
private async Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs, int maxDepth, int currentDepth)
|
||||
public async Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs = 1000)
|
||||
{
|
||||
if (!IsConnected || string.IsNullOrWhiteSpace(nodeIdStr)) return;
|
||||
if (currentDepth >= maxDepth) return;
|
||||
|
||||
// #1048 (#1000 S-12): collect the whole subtree's variables first, then create every monitored item in ONE
|
||||
// batched SubscribeManyAsync — a recursive subscribe over thousands of variables used to be one server round
|
||||
// trip per node.
|
||||
var targets = new List<string>();
|
||||
await CollectVariablesAsync(nodeIdStr, nodeClass, maxDepth: 10, currentDepth: 0, targets,
|
||||
new HashSet<string>(StringComparer.Ordinal));
|
||||
await SubscribeManyNodesAsync(targets, intervalMs);
|
||||
}
|
||||
|
||||
private async Task CollectVariablesAsync(
|
||||
string nodeIdStr, string nodeClass, int maxDepth, int currentDepth, List<string> targets, HashSet<string> seen)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(nodeIdStr) || currentDepth >= maxDepth) return;
|
||||
|
||||
if (nodeClass == "Variable")
|
||||
{
|
||||
await AddSubscriptionForNodeAsync(nodeIdStr, intervalMs);
|
||||
if (seen.Add(nodeIdStr)) targets.Add(nodeIdStr);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -238,7 +246,7 @@ public partial class SubscriptionsViewModel : ObservableObject
|
||||
var children = await _service.BrowseAsync(nodeId);
|
||||
|
||||
foreach (var child in children)
|
||||
await AddSubscriptionRecursiveAsync(child.NodeId, child.NodeClass, intervalMs, maxDepth, currentDepth + 1);
|
||||
await CollectVariablesAsync(child.NodeId, child.NodeClass, maxDepth, currentDepth + 1, targets, seen);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -247,6 +255,61 @@ public partial class SubscriptionsViewModel : ObservableObject
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes <paramref name="nodeIdStrs" /> in one batched <see cref="IOpcUaClientService.SubscribeManyAsync" />
|
||||
/// (#1048), skipping nodes already subscribed. Nodes that subscribed are added as rows; per-node failures and a
|
||||
/// whole-batch failure are surfaced through <see cref="StatusMessage" />.
|
||||
/// </summary>
|
||||
private async Task SubscribeManyNodesAsync(IReadOnlyList<string> nodeIdStrs, int intervalMs)
|
||||
{
|
||||
var pending = new List<(string Text, NodeId Id)>();
|
||||
var failures = new List<string>();
|
||||
foreach (var text in nodeIdStrs.Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text) || _rowsByNodeId.ContainsKey(text)) continue;
|
||||
try { pending.Add((text, NodeId.Parse(text))); }
|
||||
catch (Exception ex) { failures.Add($"{text}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
var subscribed = new List<string>();
|
||||
if (pending.Count > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
var outcomes = await _service.SubscribeManyAsync(pending.Select(p => p.Id).ToList(), intervalMs);
|
||||
for (var i = 0; i < pending.Count; i++)
|
||||
{
|
||||
var error = i < outcomes.Count ? outcomes[i] : null;
|
||||
if (error is null) subscribed.Add(pending[i].Text);
|
||||
else
|
||||
{
|
||||
Logger.Warning(error, "Subscribe failed for {NodeId}", pending[i].Text);
|
||||
failures.Add($"{pending[i].Text}: {error.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Batched subscribe of {Count} node(s) failed", pending.Count);
|
||||
_dispatcher.Post(() => StatusMessage = $"Subscribe failed for {pending.Count} node(s): {ex.Message}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var failedCount = failures.Count;
|
||||
var total = subscribed.Count + failedCount;
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
foreach (var text in subscribed)
|
||||
ActiveSubscriptions.Add(new SubscriptionItemViewModel(text, intervalMs));
|
||||
SubscriptionCount = ActiveSubscriptions.Count;
|
||||
StatusMessage = failedCount == 0
|
||||
? null
|
||||
: $"Subscribe failed for {failedCount} of {total} node(s): {string.Join("; ", failures.Take(5))}"
|
||||
+ (failedCount > 5 ? $"; … and {failedCount - 5} more" : string.Empty);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the node IDs of all active subscriptions for persistence.
|
||||
/// </summary>
|
||||
@@ -263,8 +326,9 @@ public partial class SubscriptionsViewModel : ObservableObject
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task RestoreSubscriptionsAsync(IEnumerable<string> nodeIds)
|
||||
{
|
||||
foreach (var nodeId in nodeIds)
|
||||
await AddSubscriptionForNodeAsync(nodeId);
|
||||
if (!IsConnected) return;
|
||||
// #1048: one batched round trip for the whole saved set (it can be a recursive subscribe's thousands of nodes).
|
||||
await SubscribeManyNodesAsync(nodeIds.ToList(), intervalMs: 1000);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in New Issue
Block a user