diff --git a/docs/Client.CLI.md b/docs/Client.CLI.md index 26eda8377..735e1d9c7 100644 --- a/docs/Client.CLI.md +++ b/docs/Client.CLI.md @@ -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 -> ()` 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 diff --git a/docs/Client.UI.md b/docs/Client.UI.md index 04fcc80bf..398b085aa 100644 --- a/docs/Client.UI.md +++ b/docs/Client.UI.md @@ -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. | 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 735c96641..8b1f049de 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 @@ -38,12 +38,22 @@ public class AlarmsCommand : CommandBase [CommandOption("refresh", Description = "Request a ConditionRefresh after subscribing")] public bool Refresh { get; init; } + /// + /// Gets how long, in seconds, a lost connection may stay unrecovered before the command warns and exits with + /// (#1048). 0 waits indefinitely; the service giving + /// up (Disconnected) always ends the run. + /// + [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; + /// 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."); } 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 541afb931..a1675b675 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 @@ -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; } + /// + /// Gets how long, in seconds, a lost connection may stay unrecovered before the command prints a warning, its + /// summary, and exits with (#1048). 0 waits indefinitely for the + /// failover to reconnect; the service giving up (Disconnected) always ends the run. + /// + [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; + + /// Default for : comfortably longer than a server restart. + public const int DefaultReconnectTimeoutSeconds = 300; + + /// Process exit code when the run ends because its connection was lost for good (#1048). + public const int ConnectionLostExitCode = 3; + /// 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 */ } diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Helpers/ConnectionLossWatch.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Helpers/ConnectionLossWatch.cs new file mode 100644 index 000000000..7a4f907ab --- /dev/null +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Helpers/ConnectionLossWatch.cs @@ -0,0 +1,130 @@ +using ZB.MOM.WW.OtOpcUa.Client.Shared.Models; + +namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers; + +/// +/// Watches a long-running command's connection for a loss that never recovers (#1048). The shared service keeps +/// a failover in , cycling the endpoints with a capped backoff, until it +/// connects or is disconnected (#1000) — so without this a subscribe/alarms run across an outage +/// that never ends just sits there, and its summary reports the last values seen before the drop as final. +/// +/// +/// completes, with the reason, when either: +/// +/// the service lands on its own — it will not retry; or +/// the connection stays out of for longer than the timeout +/// (--reconnect-timeout; = wait indefinitely for a reconnect). +/// +/// A return to before the timeout re-arms the watch. +/// +internal sealed class ConnectionLossWatch : IDisposable +{ + private readonly TimeSpan _timeout; + private readonly TimeProvider _clock; + private readonly object _gate = new(); + private readonly TaskCompletionSource _lost = new(TaskCreationOptions.RunContinuationsAsynchronously); + private CancellationTokenSource? _pending; + private bool _disposed; + + /// Creates the watch. + /// How long a loss may last before it counts as unrecovered; zero or less = no limit. + /// Clock for the timeout (tests); null = the system clock. + public ConnectionLossWatch(TimeSpan timeout, TimeProvider? clock = null) + { + _timeout = timeout; + _clock = clock ?? TimeProvider.System; + } + + /// Completes with a human-readable reason once the connection is lost for good; never faults. + public Task Lost => _lost.Task; + + /// + /// A long-running command's main wait: returns when fires (Ctrl+C), when + /// elapses, or when the connection is lost for good. + /// + /// The command's watch. + /// How long to run; = until cancelled. + /// The command's cancellation token. + /// The loss reason when the connection was lost for good, otherwise . + public static async Task 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; + } + + /// Feeds one connection transition. Safe to call from the SDK's notification threads. + /// The transition. + 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(); + } + + /// + public void Dispose() + { + lock (_gate) + { + if (_disposed) return; + _disposed = true; + CancelPending(); + } + } +} diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/SubscriptionsViewModel.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/SubscriptionsViewModel.cs index 08bbbe9dd..e52e6ac1b 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/SubscriptionsViewModel.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/SubscriptionsViewModel.cs @@ -215,19 +215,27 @@ public partial class SubscriptionsViewModel : ObservableObject /// The node class of the starting node so variables can be subscribed immediately. /// The monitored-item interval, in milliseconds, used for created subscriptions. /// A task that represents the asynchronous operation. - 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(); + await CollectVariablesAsync(nodeIdStr, nodeClass, maxDepth: 10, currentDepth: 0, targets, + new HashSet(StringComparer.Ordinal)); + await SubscribeManyNodesAsync(targets, intervalMs); + } + + private async Task CollectVariablesAsync( + string nodeIdStr, string nodeClass, int maxDepth, int currentDepth, List targets, HashSet 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 } } + /// + /// Subscribes in one batched + /// (#1048), skipping nodes already subscribed. Nodes that subscribed are added as rows; per-node failures and a + /// whole-batch failure are surfaced through . + /// + private async Task SubscribeManyNodesAsync(IReadOnlyList nodeIdStrs, int intervalMs) + { + var pending = new List<(string Text, NodeId Id)>(); + var failures = new List(); + 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(); + 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); + }); + } + /// /// Returns the node IDs of all active subscriptions for persistence. /// @@ -263,8 +326,9 @@ public partial class SubscriptionsViewModel : ObservableObject /// A task that represents the asynchronous operation. public async Task RestoreSubscriptionsAsync(IEnumerable 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); } /// diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/AlarmsCommandTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/AlarmsCommandTests.cs index 51ac30fb2..0bd6d566d 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/AlarmsCommandTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/AlarmsCommandTests.cs @@ -202,4 +202,28 @@ public class AlarmsCommandTests fakeService.DisconnectCalled.ShouldBeTrue(); fakeService.DisposeCalled.ShouldBeTrue(); } + + /// #1048: an outage that outlasts --reconnect-timeout ends the alarm watch non-zero, with a WARNING. + [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( + () => task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken)); + ex.ExitCode.ShouldNotBe(0); + TestConsoleHelper.GetOutput(console).ShouldContain("WARNING"); + fakeService.DisconnectCalled.ShouldBeTrue(); + } } \ No newline at end of file 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 3b39c0308..caa1418b3 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 @@ -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)"); } + + /// + /// #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. + /// + [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(() => 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(); + } + + /// #1048 positive control: a recovery inside the window re-arms the watch and the run continues. + [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"); + } + + /// #1048: the service landing Disconnected on its own is final — it will not retry — so exit at once. + [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(() => 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(async () => await command.ExecuteAsync(console)); + ex.Message.ShouldContain("--reconnect-timeout"); + } } diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/Fakes/FakeOpcUaClientService.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/Fakes/FakeOpcUaClientService.cs index a8a94adff..335a08d25 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/Fakes/FakeOpcUaClientService.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/Fakes/FakeOpcUaClientService.cs @@ -217,6 +217,32 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService return Task.CompletedTask; } + /// Number of batched calls (#1048). + public int SubscribeManyCallCount { get; private set; } + + /// The node lists each call carried, in call order. + public List> SubscribeManyBatches { get; } = []; + + /// Nodes whose entry in a batch should come back as a per-node failure. + public Dictionary SubscribeManyNodeFailures { get; } = new(StringComparer.Ordinal); + + /// + /// Batched subscribe (#1000 S-12 / #1048): one call for the whole set, a per-node failure for the nodes in + /// , or for the whole batch. + /// + public Task> SubscribeManyAsync(IReadOnlyList nodeIds, int intervalMs = 1000, + CancellationToken ct = default) + { + SubscribeManyCallCount++; + SubscribeManyBatches.Add(nodeIds.Select(n => n.ToString()).ToList()); + LastSubscribeIntervalMs = intervalMs; + if (SubscribeException != null) throw SubscribeException; + IReadOnlyList results = nodeIds + .Select(n => SubscribeManyNodeFailures.TryGetValue(n.ToString(), out var ex) ? ex : null) + .ToList(); + return Task.FromResult(results); + } + /// public Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default) { diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/SubscriptionsViewModelTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/SubscriptionsViewModelTests.cs index 44ca937a0..c9709c2c3 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/SubscriptionsViewModelTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/SubscriptionsViewModelTests.cs @@ -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); } /// Verifies that ValidateAndWriteAsync returns true on successful write. @@ -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); + } + + /// + /// #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. + /// + [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"); + } + + /// #1048: a batch that fails as a whole adds nothing and surfaces the error. + [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"); } ///