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:
Joseph Doherty
2026-12-03 15:07:30 -05:00
parent 65212dd471
commit 9496db9357
10 changed files with 471 additions and 37 deletions
+6
View File
@@ -71,6 +71,10 @@ When `-F` is provided, the shared service tries the primary URL first, then each
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 <old> -> <new> (<endpoint>)` 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.
The commands themselves do not wait forever, though (#1048): if the connection stays out of `Connected` for
`--reconnect-timeout` seconds (default 300) they print a `WARNING`, the summary and exit with code **3**, so a
scripted live gate across an outage that never ends fails instead of hanging and reporting pre-outage values as final.
```bash
otopcua-cli connect -u opc.tcp://localhost:4840/OtOpcUa -F opc.tcp://localhost:4841/OtOpcUa
```
@@ -193,6 +197,7 @@ otopcua-cli subscribe -u opc.tcp://localhost:4840 -n "ns=3;s=ZB" -r --max-depth
| `-q` / `--quiet` | Suppress per-update output; only print the final summary |
| `--duration` | Auto-exit after N seconds and print the summary (0 = run until Ctrl+C, default: 0) |
| `--summary-file` | Also write the summary to this file path on exit |
| `--reconnect-timeout` | Seconds a lost connection may stay unrecovered before the command prints `WARNING: … did not recover …`, its summary (with a `Connection: LOST` line — the last values predate the loss) and exits with code **3** (default: 300; `0` = wait indefinitely). The service giving up (`Disconnected`) always ends the run with code 3 (#1048). |
#### Summary buckets
@@ -384,6 +389,7 @@ otopcua-cli alarms -u opc.tcp://localhost:4840/OtOpcUa \
| `-n` / `--node` | Node ID to monitor for events (default: Server node) |
| `-i` / `--interval` | Publishing interval in milliseconds (default: 1000) |
| `--refresh` | Request a `ConditionRefresh` after subscribing to get current retained alarm states |
| `--reconnect-timeout` | Same as `subscribe`: exit with code 3 and a `WARNING` line when a lost connection has not recovered after N seconds (default: 300; `0` = wait indefinitely), or at once if the service gives up (#1048) |
The active/acknowledged columns come from the standard `ActiveState/Id`, `AckedState/Id` and
`EnabledState/Id` event fields. Before the 2026-10 fix the client's filter selected them with a single
+1 -1
View File
@@ -85,7 +85,7 @@ Right-click on tree nodes to access:
| Action | Description |
|--------|-------------|
| **Subscribe** | Subscribe to data changes on the selected node(s). For Object nodes, recursively subscribes all Variable descendants (up to 10 levels deep). Switches to the Subscriptions tab. |
| **Subscribe** | Subscribe to data changes on the selected node(s). For Object nodes, recursively subscribes all Variable descendants (up to 10 levels deep) — the subtree is browsed first and every monitored item is then created in one batched request (#1048), with per-node failures named in the status bar. Restoring saved subscriptions at connect is batched the same way. Switches to the Subscriptions tab. |
| **View History** | Set the selected Variable node as the target in the History tab and switch to it. Only enabled for Variable nodes. |
| **Monitor Alarms** | Stop any active alarm subscription and subscribe to alarm events on the selected node. Switches to the Alarms tab with automatic condition refresh. |
@@ -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>
@@ -202,4 +202,28 @@ public class AlarmsCommandTests
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
/// <summary>#1048: an outage that outlasts --reconnect-timeout ends the alarm watch non-zero, with a WARNING.</summary>
[Fact]
public async Task Execute_ExitsNonZero_WhenTheConnectionNeverRecovers()
{
var fakeService = new FakeOpcUaClientService();
var command = new AlarmsCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
ReconnectTimeoutSeconds = 1,
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
await fakeService.SubscribeAlarmsInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Connected,
Shared.Models.ConnectionState.Reconnecting, "opc.tcp://localhost:4840");
var ex = await Should.ThrowAsync<CliFx.Exceptions.CommandException>(
() => task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken));
ex.ExitCode.ShouldNotBe(0);
TestConsoleHelper.GetOutput(console).ShouldContain("WARNING");
fakeService.DisconnectCalled.ShouldBeTrue();
}
}
@@ -1,3 +1,4 @@
using CliFx.Exceptions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
@@ -139,4 +140,98 @@ public class SubscribeCommandTests
output.ShouldContain("CONNECTION Connected -> Reconnecting (opc.tcp://localhost:4840)");
output.ShouldContain("CONNECTION Reconnecting -> Connected (opc.tcp://backup:4840)");
}
/// <summary>
/// #1048: a connection that stays out of Connected past --reconnect-timeout ends the run with a WARNING, the
/// summary, and a non-zero exit — instead of waiting forever and reporting pre-outage values as final.
/// </summary>
[Fact]
public async Task Execute_ExitsNonZero_WhenTheConnectionNeverRecovers()
{
var fakeService = new FakeOpcUaClientService();
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
ReconnectTimeoutSeconds = 1,
};
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");
var ex = await Should.ThrowAsync<CommandException>(() => task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken));
ex.ExitCode.ShouldNotBe(0);
ex.Message.ShouldContain("did not recover within 1 s");
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("WARNING");
output.ShouldContain("==================== SUMMARY ====================");
output.ShouldContain("Connection:");
fakeService.DisconnectCalled.ShouldBeTrue();
}
/// <summary>#1048 positive control: a recovery inside the window re-arms the watch and the run continues.</summary>
[Fact]
public async Task Execute_KeepsRunning_WhenTheConnectionRecoversInsideTheTimeout()
{
var fakeService = new FakeOpcUaClientService();
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
ReconnectTimeoutSeconds = 2,
};
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");
await Task.Delay(TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
task.IsCompleted.ShouldBeFalse();
console.RequestCancellation();
await task; // a clean Ctrl+C exit: no exception
TestConsoleHelper.GetOutput(console).ShouldNotContain("WARNING");
}
/// <summary>#1048: the service landing Disconnected on its own is final — it will not retry — so exit at once.</summary>
[Fact]
public async Task Execute_ExitsNonZero_WhenTheServiceDisconnectsOnItsOwn()
{
var fakeService = new FakeOpcUaClientService();
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
ReconnectTimeoutSeconds = 0, // no time limit — Disconnected still ends the run
};
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.Reconnecting,
Shared.Models.ConnectionState.Disconnected, "opc.tcp://localhost:4840");
var ex = await Should.ThrowAsync<CommandException>(() => task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken));
ex.Message.ShouldContain("gave up");
}
[Fact]
public async Task Execute_RejectsNegativeReconnectTimeout()
{
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(new FakeOpcUaClientService()))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
ReconnectTimeoutSeconds = -1,
};
using var console = TestConsoleHelper.CreateConsole();
var ex = await Should.ThrowAsync<CommandException>(async () => await command.ExecuteAsync(console));
ex.Message.ShouldContain("--reconnect-timeout");
}
}
@@ -217,6 +217,32 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
return Task.CompletedTask;
}
/// <summary>Number of batched <see cref="SubscribeManyAsync" /> calls (#1048).</summary>
public int SubscribeManyCallCount { get; private set; }
/// <summary>The node lists each <see cref="SubscribeManyAsync" /> call carried, in call order.</summary>
public List<List<string>> SubscribeManyBatches { get; } = [];
/// <summary>Nodes whose entry in a batch should come back as a per-node failure.</summary>
public Dictionary<string, Exception> SubscribeManyNodeFailures { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Batched subscribe (#1000 S-12 / #1048): one call for the whole set, a per-node failure for the nodes in
/// <see cref="SubscribeManyNodeFailures" />, or <see cref="SubscribeException" /> for the whole batch.
/// </summary>
public Task<IReadOnlyList<Exception?>> SubscribeManyAsync(IReadOnlyList<NodeId> nodeIds, int intervalMs = 1000,
CancellationToken ct = default)
{
SubscribeManyCallCount++;
SubscribeManyBatches.Add(nodeIds.Select(n => n.ToString()).ToList());
LastSubscribeIntervalMs = intervalMs;
if (SubscribeException != null) throw SubscribeException;
IReadOnlyList<Exception?> results = nodeIds
.Select(n => SubscribeManyNodeFailures.TryGetValue(n.ToString(), out var ex) ? ex : null)
.ToList();
return Task.FromResult(results);
}
/// <inheritdoc />
public Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default)
{
@@ -272,7 +272,10 @@ public class SubscriptionsViewModelTests
await _vm.RestoreSubscriptionsAsync(["ns=2;s=A", "ns=2;s=B"]);
_vm.ActiveSubscriptions.Count.ShouldBe(2);
_service.SubscribeCallCount.ShouldBe(2);
// #1048: one batched round trip for the whole saved set.
_service.SubscribeManyCallCount.ShouldBe(1);
_service.SubscribeManyBatches[0].ShouldBe(["ns=2;s=A", "ns=2;s=B"]);
_service.SubscribeCallCount.ShouldBe(0);
}
/// <summary>Verifies that ValidateAndWriteAsync returns true on successful write.</summary>
@@ -359,7 +362,54 @@ public class SubscriptionsViewModelTests
await _vm.AddSubscriptionRecursiveAsync("ns=2;s=Folder", "Object");
_vm.ActiveSubscriptions.Count.ShouldBe(2);
_service.SubscribeCallCount.ShouldBe(2);
// #1048: the whole collected set is one batched SubscribeManyAsync, not a round trip per node.
_service.SubscribeManyCallCount.ShouldBe(1);
_service.SubscribeManyBatches[0].ShouldBe(["ns=2;s=Child1", "ns=2;s=Child2"]);
_service.SubscribeCallCount.ShouldBe(0);
}
/// <summary>
/// #1048: a per-node rejection inside the batch adds only the nodes that subscribed and names the failure;
/// nodes already subscribed and duplicates reached twice in the walk are not sent again.
/// </summary>
[Fact]
public async Task AddSubscriptionRecursiveAsync_BatchReportsPerNodeFailuresAndSkipsAlreadySubscribed()
{
_vm.IsConnected = true;
await _vm.AddSubscriptionForNodeAsync("ns=2;s=Already");
_service.BrowseResultsByParent["ns=2;s=Root"] =
[
new BrowseResult("ns=2;s=Already", "Already", "Variable", false),
new BrowseResult("ns=2;s=Good", "Good", "Variable", false),
new BrowseResult("ns=2;s=Bad", "Bad", "Variable", false),
new BrowseResult("ns=2;s=Sub", "Sub", "Object", true),
];
_service.BrowseResultsByParent["ns=2;s=Sub"] = [new BrowseResult("ns=2;s=Good", "Good", "Variable", false)];
_service.SubscribeManyNodeFailures["ns=2;s=Bad"] = new Exception("BadNodeIdUnknown");
await _vm.AddSubscriptionRecursiveAsync("ns=2;s=Root", "Object");
_service.SubscribeManyBatches.ShouldHaveSingleItem().ShouldBe(["ns=2;s=Good", "ns=2;s=Bad"]);
_vm.ActiveSubscriptions.Select(s => s.NodeId).ShouldBe(["ns=2;s=Already", "ns=2;s=Good"]);
_vm.SubscriptionCount.ShouldBe(2);
_vm.StatusMessage.ShouldNotBeNull();
_vm.StatusMessage.ShouldContain("1 of 2");
_vm.StatusMessage.ShouldContain("ns=2;s=Bad");
_vm.StatusMessage.ShouldContain("BadNodeIdUnknown");
}
/// <summary>#1048: a batch that fails as a whole adds nothing and surfaces the error.</summary>
[Fact]
public async Task AddSubscriptionRecursiveAsync_WholeBatchFailure_SurfacesStatusMessage()
{
_vm.IsConnected = true;
_service.BrowseResultsByParent["ns=2;s=Root"] = [new BrowseResult("ns=2;s=V", "V", "Variable", false)];
_service.SubscribeException = new Exception("session closed");
await _vm.AddSubscriptionRecursiveAsync("ns=2;s=Root", "Object");
_vm.ActiveSubscriptions.ShouldBeEmpty();
_vm.StatusMessage.ShouldNotBeNull().ShouldContain("session closed");
}
/// <summary>