diff --git a/docs/drivers/OpcUaClient.md b/docs/drivers/OpcUaClient.md index 0db6e2377..8a159f623 100644 --- a/docs/drivers/OpcUaClient.md +++ b/docs/drivers/OpcUaClient.md @@ -427,11 +427,22 @@ initialise (the AdminUI form drops them on the next save). Pinned by |------------|------|-------| | `ITagDiscovery` | `DiscoverAsync` (recursive browse) | Mirrors the upstream tree from `BrowseRoot` (default `ObjectsFolder` i=85), bounded by `MaxDiscoveredNodes` / `MaxBrowseDepth` | | `IReadable` | `ReadAsync` → `Session.ReadAsync` | Upstream `StatusCode`s pass through verbatim (cascading-quality rule) | -| `IWritable` | `WriteAsync` → `Session.WriteAsync` | Passthrough write | +| `IWritable` | `WriteAsync` → `Session.WriteAsync` | Passthrough write. A failure that can occur AFTER the request was sent (`ServiceResultException` `BadRequestTimeout`/`BadTimeout`/`BadSecureChannelClosed`/`BadConnectionClosed`/`BadRequestInterrupted`, `TimeoutException`) reports `BadTimeout` ("outcome unknown"), like a cancelled wait; any other failure is the pre-wire `BadCommunicationError`. Health is `Degraded` in both (no reply arrived) — #992 G-14 | | `ISubscribable` | native OPC UA subscriptions / monitored items | The remote server pushes data changes | | `IHostConnectivityProbe` | session keep-alive | Host key is the endpoint URL actually connected to after the failover sweep | | `IAlarmSource` | `SubscribeAlarmsAsync` (EventFilter) + `AcknowledgeAsync` | Subscribes to upstream alarm/condition events and forwards acks | +> **Subscribe-time refusals and unsubscribe ordering (#992).** A subscribed ref that gets no monitored item — it does not +> resolve to an upstream node id (`BadNodeIdInvalid`, no wire call) or the server refused the create (`BadNodeIdUnknown`, +> `BadAttributeIdInvalid`, … — `CreateItemsAsync` reports these on the item's status, it does not throw) — is published +> **Bad once with that code** and counted in ONE summarised Warning (G-12); it used to sit silently at the host's last +> stamp, `BadNoCommunication`, pointing at comms rather than the address. (It is not added to the skipped-tag report, which +> is an init-time snapshot.) The recovery / reconcile re-publish finds a ref's subscriptions through a per-subscription ref +> set, not a scan of every monitored item under the delivery lock (G-10: 20k refs went from ~6 s to ~1 s). `UnsubscribeAsync` / +> `UnsubscribeAlarmsAsync` leave the subscription tracked until they hold the subscription gate; if the wait is **cancelled** +> (the host's 5 s unsubscribe token vs a slow `ConditionRefresh`), the handlers are detached synchronously — nothing more is +> delivered, even to the re-subscribed set — and the wire delete is queued until the gate frees (G-11). + > **Native alarms (#619).** An alarm raw tag is `TagConfig` `{ "nodeId": "", "alarm": {...} }`. > The host subscribes with RawPaths and routes on (driver, RawPath), so the driver matches each > event's `ConditionId` (then its `SourceNode`) against the tag's authored `nodeId` and reports the **RawPath** as @@ -447,7 +458,7 @@ initialise (the AdminUI form drops them on the next save). Pinned by > condition after a start or deploy respawn is flagged `IsRestatement` and states the upstream condition so it lands > from whatever the host retained: an inactive+acked one goes out as `Clear` + `Acknowledge` (#657; it used to be an > `Unspecified` the host wrote as "Activated", and a retained-Active host condition stayed Active). So the host writes no -> duplicate row when its condition already shows that state (see `docs/AlarmTracking.md`). Condition **branch** events (non-null `BranchId`) are ignored. +> duplicate row when its condition already shows that state (see `docs/AlarmTracking.md`). Condition **branch** events (non-null `BranchId`) are ignored. An event from an authored alarm source that is **not a condition** (no `ConditionId`, no `ActiveState`/`AckedState` — audit/system events on the same node, #992 G-13) is dropped, never forwarded as `Unspecified` (it replaced the condition's message and wrote an "Activated" row); pass-through mode (no authored refs) still forwards everything. > **`ConditionRefresh`** is called after the event item is created, after a keep-alive outage the session survived, and on a > `RefreshRequired` event, so a condition already active upstream is reported at subscribe. The `RefreshStart`/`RefreshEnd` > markers are never projected as alarms. A server without ConditionRefresh (`BadNotSupported`/`BadMethodInvalid`/…) is logged once and tolerated. diff --git a/docs/drivers/TestConnectProbes.md b/docs/drivers/TestConnectProbes.md index 71e8f73d7..91cbfd015 100644 --- a/docs/drivers/TestConnectProbes.md +++ b/docs/drivers/TestConnectProbes.md @@ -42,7 +42,7 @@ with a human-readable explanation rather than a false-green TCP-open tick. | Driver | Handshake | Ok message | Dev-rig target | |--------|-----------|------------|----------------| | **Modbus** | FC03 (Read Holding Registers, qty 1 @ addr 0) via `ModbusTcpTransport`. A Modbus exception PDU still proves a real Modbus device → `Ok`. A non-MBAP reply → handshake fail. | `"Modbus FC03 OK"` | `10.100.0.35:5020` (Modbus sim) | -| **OpcUaClient** | `DiscoveryClient.GetEndpointsAsync` — no session, no app-cert, no auth. ≥ 1 endpoint → `Ok`. A non-OPC-UA TCP server throws or times out → handshake fail. | `"OPC UA: N endpoint(s)"` | `opc.tcp://10.100.0.35:50000` (opc-plc) | +| **OpcUaClient** | `DiscoveryClient.GetEndpointsAsync` — no session, no app-cert, no auth. ≥ 1 endpoint → `Ok`. A non-OPC-UA TCP server throws or times out → handshake fail. The TCP preflight (here and in the Galaxy probe) uses a dual-mode socket, so an IPv6 literal / AAAA-only host reaches the handshake (#992 G-15; it was IPv4-only). | `"OPC UA: N endpoint(s)"` | `opc.tcp://10.100.0.35:50000` (opc-plc) | | **S7** | `Plc.OpenAsync` (COTP CR/CC + S7 setup-communication), check `IsConnected`, then `Close`. Wrong rack/slot or a non-S7 server causes `OpenAsync` to throw → handshake fail. | `"S7 connected (CPU …)"` | `10.100.0.35:1102` (python-snap7 sim) | | **AbCip** | `libplctag` Tag `InitializeAsync` (EIP session + CIP Forward Open). A CIP-level error such as tag-not-found still proves the controller answered CIP → `Ok`. A session/ForwardOpen/connect error → handshake fail. | `"CIP session OK"` | `10.100.0.35:44818` (CIP sim) | | **AbLegacy** | Same `libplctag` `InitializeAsync` handshake as AbCip, PCCC protocol family. | `"CIP session OK"` (PCCC family) | Deferred — no PLC5/SLC sim | diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverProbe.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverProbe.cs index cfa757b89..78023c713 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverProbe.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverProbe.cs @@ -64,7 +64,7 @@ public sealed class GalaxyDriverProbe : IDriverProbe var sw = Stopwatch.StartNew(); try { - using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) /* G-15: dual-mode, so an IPv6 literal / AAAA-only host connects */; await socket.ConnectAsync(host, port, probeCts.Token); } catch (SocketException ex) diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs index 8cbe357ad..d946b1d77 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs @@ -236,6 +236,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit return handle; } + /// Test-only seam: the SDK monitored items registered for a data subscription. + /// The subscription handle. + internal IReadOnlyList MonitoredItemsForTest(ISubscriptionHandle handle) => + _subscriptions.TryGetValue(((OpcUaSubscriptionHandle)handle).Id, out var rs) + ? [.. rs.ItemHandlers.Select(p => p.Item)] + : []; + /// Test-only seam: deliver one data notification as the SDK publish thread would. /// The subscription handle. /// The RawPath. @@ -1618,22 +1625,48 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit // retry") is more honest than BadCommunicationError ("definitely did not // happen"). Downstream callers that need retry semantics check for BadTimeout // and can decide whether to re-issue. - const uint StatusBadTimeout = 0x800A0000u; for (var w = 0; w < indexMap.Count; w++) - results[indexMap[w]] = new WriteResult(StatusBadTimeout); + results[indexMap[w]] = new WriteResult(StatusBadTimeoutCode); // No reply arrived. Only a timeout is a comms fault — a caller that cancelled says nothing about upstream. if (!cancellationToken.IsCancellationRequested) RecordCommsFault(generation, $"write: {ex.Message}"); } catch (Exception ex) { - // Pre-wire transport failure — the write definitely did not reach the server. + // G-14: a failure that can occur AFTER the request was sent (the SDK's own request timeout, a channel + // that closed under it) leaves the outcome unknown: BadTimeout, like a cancelled wait — never the + // "definitely did not happen" BadCommunicationError, which would tell the operator a setpoint that + // may have taken effect did not. Any other failure is a pre-wire transport fault. + var code = IsPossiblyDispatchedWriteFailure(ex) ? StatusBadTimeoutCode : StatusBadCommunicationError; for (var w = 0; w < indexMap.Count; w++) - results[indexMap[w]] = new WriteResult(StatusBadCommunicationError); + results[indexMap[w]] = new WriteResult(code); RecordCommsFault(generation, $"write: {ex.Message}"); } return results; } + /// OPC UA BadTimeout — "outcome unknown" for a write. + private const uint StatusBadTimeoutCode = 0x800A0000u; + + /// + /// G-14: whether a write failure is one that can occur after the request reached the wire — a + /// carrying the SDK's request timeout, a closed channel/connection or an + /// interrupted request (or a ). Such a write may have taken effect. + /// + /// The exception the write call threw. + internal static bool IsPossiblyDispatchedWriteFailure(Exception ex) + { + if (ex is TimeoutException) return true; + for (Exception? e = ex; e is not null; e = e.InnerException) + { + if (e is not ServiceResultException sre) continue; + var c = sre.StatusCode; + return c == StatusCodes.BadRequestTimeout.Code || c == StatusCodes.BadTimeout.Code + || c == StatusCodes.BadSecureChannelClosed.Code || c == StatusCodes.BadConnectionClosed.Code + || c == StatusCodes.BadRequestInterrupted.Code; + } + return false; + } + /// /// (v3) Resolve a tag's RawPath reference to a live against the /// 's current namespace table. Two stages: @@ -2012,6 +2045,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit }); long subscribeGeneration = 0; + // G-12: refs the upstream cannot serve (unresolvable here, or the server refused the monitored item). + var rejected = new List(); await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false); try { @@ -2052,6 +2087,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit } finally { _subscriptionGate.Release(); } + if (rejected.Count > 0) ReportRejectedItems(handle, rejected); return handle; async Task CreateDataItemsAsync(ISession session, List itemHandlers) @@ -2059,7 +2095,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit await subscription.CreateAsync(cancellationToken).ConfigureAwait(false); foreach (var fullRef in fullReferences) { - if (!TryResolveTagNode(session, fullRef, out var nodeId)) continue; + if (!TryResolveTagNode(session, fullRef, out var nodeId)) + { + rejected.Add(new RejectedItem(fullRef, StatusBadNodeIdInvalid, "the reference does not resolve to an upstream node id")); + continue; + } // The RawPath (v3 tag identity) is routed through MonitoredItem.Handle so the // Notification handler reports the change under the same reference the runtime // subscribed with — StartNodeId is the resolved upstream node, Handle stays the RawPath. @@ -2085,9 +2125,59 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit await subscription.CreateItemsAsync(cancellationToken).ConfigureAwait(false); ThrowIfSubscribeSuperseded(subscribeGeneration); + foreach (var pair in itemHandlers) + if (RejectedMonitoredItemStatus(pair.Item) is { } refused) + rejected.Add(new RejectedItem(RefOf(pair.Item), refused, $"the server refused the monitored item (0x{refused:X8})")); } } + /// One ref a subscribe could not establish a monitored item for. + /// The RawPath. + /// The status to publish for it. + /// The operator-facing reason. + internal readonly record struct RejectedItem(string Ref, uint Status, string Why); + + /// + /// G-12: the status the server refused with at create time, or null when it was created. + /// CreateItemsAsync does not throw for a per-item refusal (BadNodeIdUnknown, + /// BadAttributeIdInvalid, ...); the failure is only on the item's status. + /// + /// The monitored item after CreateItemsAsync. + internal static uint? RejectedMonitoredItemStatus(MonitoredItem item) + { + var error = item.Status?.Error; + if (error is null || !ServiceResult.IsBad(error)) return null; + return error.StatusCode.Code; + } + + /// + /// G-12: a ref with no monitored item gets one Bad publish with the real code (it used to sit at the host's last + /// stamp, BadNoCommunication, pointing the operator at comms rather than the address) and the subscribe + /// logs ONE summarised Warning. + /// + /// The subscription the refs were asked for on. + /// The refs that got no monitored item. + internal void ReportRejectedItems(ISubscriptionHandle handle, IReadOnlyList rejected) + { + var now = Clock.GetUtcNow().UtcDateTime; + lock (_deliveryLock) + { + foreach (var r in rejected) + { + var snapshot = new DataValueSnapshot(null, r.Status, null, now); + _lastValues[r.Ref] = snapshot; + _deliverySeq.AddOrUpdate(r.Ref, 1, (_, n) => n + 1); + RaiseDataChange(new DataChangeEventArgs(handle, r.Ref, snapshot)); + } + } + _logger.LogWarning( + "OpcUaClientDriver '{DriverInstanceId}': {Count} of the subscribed references have no upstream monitored item " + + "and were published Bad: {Sample}{More}", + _driverInstanceId, rejected.Count, + string.Join("; ", rejected.Take(5).Select(r => $"{r.Ref} (0x{r.Status:X8}: {r.Why})")), + rejected.Count > 5 ? $"; and {rejected.Count - 5} more" : string.Empty); + } + /// /// Review m10: a subscribe that a shutdown / re-initialise overtook must not register its subscription — the /// teardown has already enumerated the registry, so the entry would outlive it and the next session's stall @@ -2105,12 +2195,28 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) { if (handle is not OpcUaSubscriptionHandle h) return; - if (!_subscriptions.TryRemove(h.Id, out var rs)) return; - var emptied = NoteSubscriptionDeleted(); + if (!_subscriptions.ContainsKey(h.Id)) return; - await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false); + // G-11: the registry entry is removed only once the gate is held (or, on a cancelled wait, with its + // handlers detached synchronously and the delete queued) - removing it first and then losing the wait + // orphaned a live, still-delivering SDK subscription the driver no longer tracked. + try { await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false); } + catch (OperationCanceledException) + { + if (_subscriptions.TryRemove(h.Id, out var orphan)) + { + var orphanEmptied = NoteSubscriptionDeleted(); + DetachNotificationHandlers(orphan.ItemHandlers); + QueueDeferredDelete(orphan.Subscription, orphanEmptied); + } + throw; + } + + var emptied = false; try { + if (!_subscriptions.TryRemove(h.Id, out var rs)) return; // a concurrent unsubscribe / teardown got there first + emptied = NoteSubscriptionDeleted(); // Detach Notification handlers BEFORE deleting the subscription so the SDK's // MonitoredItem.Notification multicast invocation list no longer holds a // closure that captures the driver instance. The delegate stored on @@ -2118,7 +2224,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit // cleanly. DetachNotificationHandlers(rs.ItemHandlers); try { await DeleteSubscriptionAsync(rs.Subscription, cancellationToken).ConfigureAwait(false); } - catch { /* best-effort — the subscription may already be gone on reconnect */ } + catch { /* best-effort - the subscription may already be gone on reconnect */ } } finally { @@ -2128,6 +2234,46 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit } } + /// + /// G-11: an unsubscribe whose wait for was cancelled has already detached the + /// subscription's handlers (so nothing more is delivered, even to a re-subscribed set); the wire delete is + /// still owed. Issue it best-effort once the gate frees, bounded by the session's work token (a shutdown / + /// re-initialise closes the session, which deletes the subscription server-side anyway) and + /// . + /// + /// The detached SDK subscription. + /// True when its removal emptied the set (restarts the stale-NoSubscription window after the delete). + private void QueueDeferredDelete(Subscription subscription, bool emptied) + { + var work = _sessionWorkCts.Token; + var task = Task.Run(async () => + { + try + { + await _subscriptionGate.WaitAsync(work).ConfigureAwait(false); + } + catch (Exception) { return; } // session released / driver disposed - the session close deletes it + try + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(work); + cts.CancelAfter(SessionCloseTimeout); + try { await DeleteSubscriptionAsync(subscription, cts.Token).ConfigureAwait(false); } + catch { /* best-effort */ } + } + finally + { + if (emptied) NoteSubscriptionDeleted(force: true); + try { _subscriptionGate.Release(); } catch (ObjectDisposedException) { } + } + }); + Interlocked.Exchange(ref _deferredDeleteForTest, task); + } + + private Task _deferredDeleteForTest = Task.CompletedTask; + + /// Test seam: the most recent deferred delete of a subscription whose unsubscribe wait was cancelled. + internal Task DeferredDeleteForTest => Volatile.Read(ref _deferredDeleteForTest); + private static void DetachNotificationHandlers(IReadOnlyList items) { for (var i = 0; i < items.Count; i++) @@ -2410,7 +2556,19 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit private sealed record RemoteSubscription( Subscription Subscription, OpcUaSubscriptionHandle Handle, - IReadOnlyList ItemHandlers); + IReadOnlyList ItemHandlers) + { + /// + /// G-10: the RawPaths this subscription carries, built once. The recovery / reconcile re-publish asks + /// "does this subscription carry that ref" once per recovered ref under _deliveryLock; a scan of + /// made it O(refs x items). is fixed at registration. + /// + private readonly HashSet _refs = new(ItemHandlers.Select(p => RefOf(p.Item)), StringComparer.Ordinal); + + /// True when one of this subscription's monitored items is bound to . + /// The RawPath. + public bool Carries(string fullRef) => _refs.Contains(fullRef); + } /// /// One (MonitoredItem, handler-delegate-instance) pair captured at subscribe time so @@ -2649,22 +2807,42 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit public async Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken) { if (handle is not OpcUaAlarmSubscriptionHandle h) return; - RemoteAlarmSubscription? rs; - // #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it. - lock (_alarmStateLock) - if (!_alarmSubscriptions.TryRemove(h.Id, out rs)) return; - var emptied = NoteSubscriptionDeleted(); + if (!_alarmSubscriptions.ContainsKey(h.Id)) return; - await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false); + // G-11: same ordering as UnsubscribeAsync - a cancelled gate wait must not leave a live, untracked + // subscription still delivering events. + try { await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false); } + catch (OperationCanceledException) + { + RemoteAlarmSubscription? orphan; + // #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it. + lock (_alarmStateLock) + _alarmSubscriptions.TryRemove(h.Id, out orphan); + if (orphan is not null) + { + var orphanEmptied = NoteSubscriptionDeleted(); + try { orphan.EventItem.Notification -= orphan.Handler; } + catch { /* best-effort */ } + QueueDeferredDelete(orphan.Subscription, orphanEmptied); + } + throw; + } + + var emptied = false; try { + RemoteAlarmSubscription? rs; + // #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it. + lock (_alarmStateLock) + if (!_alarmSubscriptions.TryRemove(h.Id, out rs)) return; + emptied = NoteSubscriptionDeleted(); // Detach the Notification handler before deleting the subscription so the SDK's // multicast invocation list no longer holds the driver instance through the // closure. try { rs.EventItem.Notification -= rs.Handler; } catch { /* best-effort */ } try { await DeleteSubscriptionAsync(rs.Subscription, cancellationToken).ConfigureAwait(false); } - catch { /* best-effort — session may already be gone across a reconnect */ } + catch { /* best-effort - session may already be gone across a reconnect */ } } finally { @@ -3633,6 +3811,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit else { upstreamCondition = conditionField is NodeId cn && !cn.IsNull ? keyOf(cn) : string.Empty; + // G-13: the alarm item is an unfiltered event subscription on the Server object, so an authored source + // also receives every NON-condition event naming it (audit / system events: no ConditionId, no + // ActiveState/AckedState). Forwarded as Unspecified they overwrote the condition's message/severity and + // wrote an "Activated" history row; they are not alarm state, so they are dropped here (the + // pass-through mode, with no authored refs, keeps forwarding them). + if (state is null && upstreamCondition.Length == 0) return null; var sourceKey = sourceField is NodeId sn && !sn.IsNull ? keyOf(sn) : string.Empty; if (!(upstreamCondition.Length > 0 && sourceIndex.TryGetValue(upstreamCondition, out reported!)) && !(sourceKey.Length > 0 && sourceIndex.TryGetValue(sourceKey, out reported!))) @@ -4188,7 +4372,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit && Interlocked.Read(ref _replayGuardUntilTicks) != 0) _replayGuard.AddOrUpdate(fullRef, readAt.Ticks, (_, prior) => Math.Max(prior, readAt.Ticks)); foreach (var rs in _subscriptions.Values) - if (rs.ItemHandlers.Any(p => RefOf(p.Item) == fullRef)) + if (rs.Carries(fullRef)) RaiseDataChange(new DataChangeEventArgs(rs.Handle, fullRef, value)); } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriverProbe.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriverProbe.cs index 5bae05471..4272be60a 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriverProbe.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriverProbe.cs @@ -60,7 +60,7 @@ public sealed class OpcUaClientDriverProbe : IDriverProbe var sw = Stopwatch.StartNew(); try { - using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) /* G-15: dual-mode, so an IPv6 literal / AAAA-only host connects */; await socket.ConnectAsync(host, port, cts.Token); } catch (SocketException ex) diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverProbeTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverProbeTests.cs index 48d7cd2fe..764780579 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverProbeTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverProbeTests.cs @@ -160,4 +160,36 @@ public sealed class GalaxyDriverProbeTests message.ShouldContain("DeadlineExceeded"); message.ShouldContain("host:5120"); } + + // ── #992 G-15: the TCP preflight is dual-mode (IPv6 literal / AAAA-only hosts) ──────────────── + + /// + /// An IPv6 literal endpoint must pass the TCP preflight (it used to fail "Connect failed" on an IPv4-only + /// socket before any gRPC traffic). A listener that accepts then closes proves the preflight connected: the + /// failure is then the gRPC ping, never "Connect failed". + /// + [Fact] + public async Task An_IPv6_literal_endpoint_passes_the_tcp_preflight() + { + if (!Socket.OSSupportsIPv6) Assert.Skip("IPv6 is not available on this host."); + var listener = new TcpListener(IPAddress.IPv6Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var testCt = TestContext.Current.CancellationToken; + var accepted = Task.Run(async () => + { + try { using var c = await listener.AcceptTcpClientAsync(testCt); return true; } + catch { return false; } + }, testCt); + try + { + var result = await _probe.ProbeAsync( + ConfigJson($"http://[::1]:{port}"), TimeSpan.FromSeconds(5), testCt); + + result.Ok.ShouldBeFalse("the listener is not a gateway"); + result.Message.ShouldNotBeNull().ShouldNotContain("Connect failed", Case.Insensitive); + (await accepted.WaitAsync(TimeSpan.FromSeconds(5), testCt)).ShouldBeTrue("the preflight reached the IPv6 listener"); + } + finally { listener.Stop(); } + } } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientSmokeTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientSmokeTests.cs index b1d3cc1b8..3ae2f6f75 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientSmokeTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientSmokeTests.cs @@ -93,6 +93,55 @@ public sealed class OpcUaClientSmokeTests(OpcPlcFixture sim) await drv.UnsubscribeAsync(handle, TestContext.Current.CancellationToken); } + /// + /// #992 G-12 through the real SDK: a ref whose upstream node does not exist (the server refuses the monitored + /// item with BadNodeIdUnknown in the create RESULT, not an exception) used to get no publish, no log and + /// no status. It now gets exactly one Bad publish carrying the upstream's code, while the good ref beside it + /// still delivers values. + /// + [Fact] + public async Task A_subscribed_ref_the_server_refuses_gets_one_Bad_publish_with_the_upstream_code() + { + if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason); + var ct = TestContext.Current.CancellationToken; + const string missingRef = "Sim/OpcUaClient/plc/DoesNotExist"; + var options = OpcPlcProfile.BuildOptions(sim.EndpointUrl) with + { + RawTags = + [ + .. OpcPlcProfile.RawTags, + new RawTagEntry(missingRef, System.Text.Json.JsonSerializer.Serialize(new { nodeId = "ns=3;s=DoesNotExist" }), WriteIdempotent: true), + ], + }; + await using var drv = new OpcUaClientDriver(options, driverInstanceId: "opcua-smoke-refused"); + await drv.InitializeAsync("{}", ct); + + var observed = new List(); + drv.OnDataChange += (_, e) => { lock (observed) observed.Add(e); }; + + var handle = await drv.SubscribeAsync( + [OpcPlcProfile.FastUInt1Ref, missingRef], TimeSpan.FromMilliseconds(250), ct); + + // Positive control: the good ref beside the refused one is live. + var deadline = DateTime.UtcNow.AddSeconds(5); + while (DateTime.UtcNow < deadline) + { + lock (observed) + if (observed.Any(o => o.FullReference == OpcPlcProfile.FastUInt1Ref && o.Snapshot.StatusCode == 0u)) break; + await Task.Delay(100, ct); + } + DataChangeEventArgs[] snapshot; + lock (observed) snapshot = [.. observed]; + snapshot.ShouldContain(o => o.FullReference == OpcPlcProfile.FastUInt1Ref && o.Snapshot.StatusCode == 0u); + + var refused = snapshot.Where(o => o.FullReference == missingRef).ToList(); + refused.Count.ShouldBe(1, "exactly one Bad publish for the refused ref"); + refused[0].Snapshot.StatusCode.ShouldBe(Opc.Ua.StatusCodes.BadNodeIdUnknown.Code); + refused[0].SubscriptionHandle.ShouldBe(handle); + + await drv.UnsubscribeAsync(handle, ct); + } + /// /// Review 2026-10-21 O-9 + lifecycle generation, through the real SDK: a shutdown with several live /// subscriptions completes inside the one teardown budget, lands Unknown, and a re-initialise of the same diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientDriverProbeTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientDriverProbeTests.cs index 971c85b7e..55a4e0c97 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientDriverProbeTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientDriverProbeTests.cs @@ -157,4 +157,36 @@ public sealed class OpcUaClientDriverProbeTests message.ShouldNotContain("invalid", Case.Insensitive); message.ShouldContain("Connect failed", Case.Insensitive); } + + // ── #992 G-15: the TCP preflight is dual-mode (IPv6 literal / AAAA-only hosts) ──────────────── + + /// + /// An IPv6 literal endpoint must pass the TCP preflight (it used to fail "Connect failed" on an IPv4-only + /// socket before any OPC UA traffic). A listener that accepts then closes proves the preflight connected: the + /// failure is then the discovery handshake, never "Connect failed". + /// + [Fact] + public async Task An_IPv6_literal_endpoint_passes_the_tcp_preflight() + { + if (!Socket.OSSupportsIPv6) Assert.Skip("IPv6 is not available on this host."); + var listener = new TcpListener(IPAddress.IPv6Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var testCt = TestContext.Current.CancellationToken; + var accepted = Task.Run(async () => + { + try { using var c = await listener.AcceptTcpClientAsync(testCt); return true; } + catch { return false; } + }, testCt); + try + { + var result = await _probe.ProbeAsync( + $$"""{"EndpointUrl":"opc.tcp://[::1]:{{port}}"}""", TimeSpan.FromSeconds(5), testCt); + + result.Ok.ShouldBeFalse("the listener is not an OPC UA server"); + result.Message.ShouldNotBeNull().ShouldNotContain("Connect failed", Case.Insensitive); + (await accepted.WaitAsync(TimeSpan.FromSeconds(5), testCt)).ShouldBeTrue("the preflight reached the IPv6 listener"); + } + finally { listener.Stop(); } + } } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientReview1202FindingsTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientReview1202FindingsTests.cs new file mode 100644 index 000000000..6900821cd --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientReview1202FindingsTests.cs @@ -0,0 +1,254 @@ +using System.Text.Json; +using Microsoft.Extensions.Logging; +using Moq; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests; + +/// +/// #992 / review 2026-12-02 G-11 .. G-14 on the OpcUaClient driver (G-10 is in +/// , G-15 in the probe tests, G-12's wire half in the +/// integration suite). +/// +[Trait("Category", "Unit")] +public sealed class OpcUaClientReview1202FindingsTests +{ + private const string SpeedRef = "Plant/dev/Speed"; + + private static readonly IReadOnlyList Tags = + [new(SpeedRef, JsonSerializer.Serialize(new { nodeId = "ns=0;s=Speed" }), WriteIdempotent: true)]; + + private sealed class ListLogger : ILogger + { + public List<(LogLevel Level, string Message)> Entries { get; } = []; + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) + { + lock (Entries) Entries.Add((logLevel, formatter(state, exception))); + } + } + + private static (OpcUaClientDriver Driver, Mock Session) NewConnectedDriver(ILogger? log = null) + { + var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions { RawTags = Tags }, "opcua-g11", log); + var session = new Mock(MockBehavior.Loose); + session.SetupGet(s => s.MessageContext).Returns(ServiceMessageContext.Create(SdkTelemetry.Context)); + session.SetupGet(s => s.NamespaceUris).Returns(new NamespaceTable()); + drv.SetSessionForTest(session.Object); + drv.SetNamespaceMapForTest(NamespaceMap.FromTable(new NamespaceTable(), Tags)); + drv.SetHealthForTest(new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null)); + return (drv, session); + } + + private static void RaiseGoodNotification(MonitoredItem item, int value) => + item.SaveValueInCache(new MonitoredItemNotification + { + Value = new DataValue(VariantHelper.CastFrom(value), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow), + }); + + // ── G-11 ───────────────────────────────────────────────────────────────────────────────────────────────────── + + /// + /// An unsubscribe whose gate wait is cancelled must not orphan a live subscription: nothing more is delivered + /// for it (the host re-subscribes the new set in that window) and the wire delete is still issued once the + /// gate frees. Positive control: the notification path demonstrably delivers before the unsubscribe. + /// + [Fact] + public async Task A_cancelled_unsubscribe_wait_detaches_the_subscription_and_still_deletes_it() + { + var (drv, _) = NewConnectedDriver(); + using var _ = drv; + var handle = drv.AddSubscriptionForTest([SpeedRef]); + var item = drv.MonitoredItemsForTest(handle).Single(); + var delivered = 0; + drv.OnDataChange += (_, _) => Interlocked.Increment(ref delivered); + var deleted = new List(); + drv.DeleteSubscriptionAsync = (sub, _) => { lock (deleted) deleted.Add(sub); return Task.CompletedTask; }; + + RaiseGoodNotification(item, 1); + delivered.ShouldBe(1, "positive control: the registered handler delivers"); + + await drv.SubscriptionGate.WaitAsync(TestContext.Current.CancellationToken); // e.g. a slow ConditionRefresh holds it + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + await Should.ThrowAsync(() => drv.UnsubscribeAsync(handle, cts.Token)); + + RaiseGoodNotification(item, 2); + delivered.ShouldBe(1, "the orphan must not keep delivering after its unsubscribe was cancelled"); + lock (deleted) deleted.Count.ShouldBe(0, "the gate is still held, so the delete is queued, not issued"); + + drv.SubscriptionGate.Release(); + await drv.DeferredDeleteForTest.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + lock (deleted) deleted.Count.ShouldBe(1, "the wire delete was still issued once the gate freed"); + + await drv.UnsubscribeAsync(handle, TestContext.Current.CancellationToken); // a retry is a quiet no-op + lock (deleted) deleted.Count.ShouldBe(1); + } + + /// + /// While the unsubscribe waits for the gate (token still live) the subscription stays tracked; once the gate + /// frees it is removed, detached and deleted exactly once. + /// + [Fact] + public async Task An_unsubscribe_waiting_for_the_gate_keeps_the_subscription_tracked_until_it_holds_it() + { + var (drv, _) = NewConnectedDriver(); + using var _ = drv; + var handle = drv.AddSubscriptionForTest([SpeedRef]); + var deleted = new List(); + drv.DeleteSubscriptionAsync = (sub, _) => { lock (deleted) deleted.Add(sub); return Task.CompletedTask; }; + + await drv.SubscriptionGate.WaitAsync(TestContext.Current.CancellationToken); + var unsub = drv.UnsubscribeAsync(handle, TestContext.Current.CancellationToken); + await Task.Delay(100, TestContext.Current.CancellationToken); + + unsub.IsCompleted.ShouldBeFalse("it is waiting for the gate"); + drv.MonitoredItemsForTest(handle).Count.ShouldBe(1, "still tracked until the gate is held"); + + drv.SubscriptionGate.Release(); + await unsub.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + drv.MonitoredItemsForTest(handle).Count.ShouldBe(0); + lock (deleted) deleted.Count.ShouldBe(1); + } + + /// The alarm unsubscribe has the same ordering: a cancelled gate wait still deletes the subscription. + [Fact] + public async Task A_cancelled_alarm_unsubscribe_wait_still_deletes_the_subscription() + { + var (drv, _) = NewConnectedDriver(); + using var _ = drv; + var handle = drv.AddAlarmSubscriptionForTest([SpeedRef]); + var deleted = new List(); + drv.DeleteSubscriptionAsync = (sub, _) => { lock (deleted) deleted.Add(sub); return Task.CompletedTask; }; + + await drv.SubscriptionGate.WaitAsync(TestContext.Current.CancellationToken); + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + await Should.ThrowAsync(() => drv.UnsubscribeAlarmsAsync(handle, cts.Token)); + drv.SubscriptionGate.Release(); + + await drv.DeferredDeleteForTest.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + lock (deleted) deleted.Count.ShouldBe(1); + } + + // ── G-12 ───────────────────────────────────────────────────────────────────────────────────────────────────── + + /// + /// A ref with no monitored item is published Bad with the real code (it used to be silent), once each, and one + /// summarised Warning is logged. The accepted ref is not touched. + /// + [Fact] + public void Refs_with_no_monitored_item_are_published_Bad_with_their_code_and_warned_once() + { + var log = new ListLogger(); + var (drv, _) = NewConnectedDriver(log); + using var _ = drv; + var handle = drv.AddSubscriptionForTest([SpeedRef]); + var seen = new List(); + drv.OnDataChange += (_, e) => seen.Add(e); + + drv.ReportRejectedItems(handle, + [ + new OpcUaClientDriver.RejectedItem("Plant/dev/Gone", 0x80340000u, "the server refused the monitored item"), + new OpcUaClientDriver.RejectedItem("Plant/dev/Unresolved", 0x80330000u, "the reference does not resolve"), + ]); + + seen.Select(e => (e.FullReference, e.Snapshot.StatusCode)).ShouldBe( + [("Plant/dev/Gone", 0x80340000u), ("Plant/dev/Unresolved", 0x80330000u)]); + seen.ShouldAllBe(e => ReferenceEquals(e.SubscriptionHandle, handle)); + lock (log.Entries) + log.Entries.Where(e => e.Level == LogLevel.Warning).ShouldHaveSingleItem().Message.ShouldContain("2 of the subscribed"); + } + + // ── G-13 ───────────────────────────────────────────────────────────────────────────────────────────────────── + + private static readonly Dictionary TripIndex = new() { ["ns=3;s=Alarms.Trip1"] = "Plant/opc/plc/Trip1" }; + + private static List Fields(NodeId eventType, Variant conditionId, string message) => + [ + Variant.From(new byte[] { 1 }.ToByteString()), + new Variant(eventType), + new Variant(NodeId.Parse("ns=3;s=Alarms.Trip1")), + new Variant(new LocalizedText(message)), + new Variant((ushort)100), + new Variant(DateTime.UtcNow), + conditionId, + ]; + + private sealed class Handle : IAlarmSubscriptionHandle + { + public string DiagnosticId => "g13"; + } + + /// + /// An audit event (no ConditionId, no ActiveState/AckedState) naming an authored alarm source is not alarm + /// state: it must not reach the host as an Unspecified transition (which wrote an "Activated" row and replaced + /// the condition's message). Positive control: a real condition event for the same source still flows. + /// + [Fact] + public void A_non_condition_event_from_an_authored_source_is_dropped_but_a_condition_event_flows() + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-g13"); + var seen = new List(); + drv.OnAlarmEvent += (_, e) => seen.Add(e); + var handle = new Handle(); + + drv.RouteAlarmEvent(Fields(ObjectTypeIds.AuditWriteUpdateEventType, Variant.Null, "Write by user"), TripIndex, handle); + seen.ShouldBeEmpty("an audit event is not an alarm"); + + drv.RouteAlarmEvent( + Fields(new NodeId("TripAlarmType", 3), new Variant(NodeId.Parse("ns=3;s=Alarms.Trip1.Cond")), "tripped"), + TripIndex, handle); + seen.Count.ShouldBe(1, "positive control: a condition event for the same source flows"); + seen[0].Message.ShouldBe("tripped"); + } + + // ── G-14 ───────────────────────────────────────────────────────────────────────────────────────────────────── + + public static TheoryData PostDispatchFailures => + [ + StatusCodes.BadRequestTimeout.Code, + StatusCodes.BadTimeout.Code, + StatusCodes.BadSecureChannelClosed.Code, + StatusCodes.BadConnectionClosed.Code, + StatusCodes.BadRequestInterrupted.Code, + ]; + + /// + /// A write that failed after it may have been sent (the SDK's request timeout, a channel closed under it) + /// reports BadTimeout ("outcome unknown"), not "did not reach the server". Health is still degraded: + /// no reply arrived, which is a comms fault. + /// + [Theory] + [MemberData(nameof(PostDispatchFailures))] + public async Task A_write_failing_after_dispatch_reports_BadTimeout(uint status) + { + var (drv, session) = NewConnectedDriver(); + using var _ = drv; + session.Setup(s => s.WriteAsync(It.IsAny(), It.IsAny>(), It.IsAny())) + .ThrowsAsync(new ServiceResultException(new StatusCode(status))); + + var results = await drv.WriteAsync([new Core.Abstractions.WriteRequest(SpeedRef, 7)], TestContext.Current.CancellationToken); + + results.Single().StatusCode.ShouldBe(0x800A0000u); + drv.GetHealth().State.ShouldBe(DriverState.Degraded); + } + + /// Positive control: a failure that cannot have been sent stays BadCommunicationError. + [Fact] + public async Task A_write_failing_before_dispatch_stays_BadCommunicationError() + { + var (drv, session) = NewConnectedDriver(); + using var _ = drv; + session.Setup(s => s.WriteAsync(It.IsAny(), It.IsAny>(), It.IsAny())) + .ThrowsAsync(new ServiceResultException(StatusCodes.BadNotConnected)); + + var results = await drv.WriteAsync([new Core.Abstractions.WriteRequest(SpeedRef, 7)], TestContext.Current.CancellationToken); + + results.Single().StatusCode.ShouldBe(0x80050000u); + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientReview1202RecoveryTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientReview1202RecoveryTests.cs new file mode 100644 index 000000000..586d74dfb --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientReview1202RecoveryTests.cs @@ -0,0 +1,67 @@ +using System.Diagnostics; +using System.Text.Json; +using Moq; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests; + +/// +/// #992 / review 2026-12-02 G-10 — the in-place recovery re-publish scanned every monitored item of every +/// subscription per recovered ref (O(refs x items)) while holding the delivery lock. +/// +[Trait("Category", "Unit")] +public sealed class OpcUaClientReview1202RecoveryTests +{ + private const int RefCount = 20_000; + + /// + /// 20k refs on one subscription: a bad then a good keep-alive must re-publish every ref promptly. Before the + /// per-subscription ref index this was ~2 x 10^8 string compares under the delivery lock. + /// + [Fact] + public async Task Recovery_republish_of_20k_refs_is_not_quadratic() + { + var refs = Enumerable.Range(0, RefCount).Select(i => $"Plant/dev/T{i}").ToList(); + var tags = refs.Select((r, i) => + new RawTagEntry(r, JsonSerializer.Serialize(new { nodeId = $"ns=0;s=T{i}" }), WriteIdempotent: true)).ToList(); + var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions { RawTags = tags }, "opcua-g10"); + using var _ = drv; + var session = new Mock(MockBehavior.Loose); + session.SetupGet(s => s.MessageContext).Returns(ServiceMessageContext.Create(SdkTelemetry.Context)); + session.SetupGet(s => s.NamespaceUris).Returns(new NamespaceTable()); + drv.SetSessionForTest(session.Object); + drv.SetNamespaceMapForTest(NamespaceMap.FromTable(new NamespaceTable(), tags)); + drv.SetHealthForTest(new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null)); + drv.PostRecoveryReconcileDelay = () => TimeSpan.FromDays(1); // keep the trailing read out of this test + session.Setup(s => s.ReadAsync( + It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny>(), It.IsAny())) + .ReturnsAsync((RequestHeader _, double _, TimestampsToReturn _, ArrayOf nodes, CancellationToken _) => + new ReadResponse + { + ResponseHeader = new ResponseHeader(), + Results = [.. nodes.ToList().Select(_ => new DataValue(VariantHelper.CastFrom(1), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow))], + DiagnosticInfos = [], + }); + drv.AddSubscriptionForTest(refs); + var goodPublishes = 0; + drv.OnDataChange += (_, e) => + { + if (e.Snapshot.StatusCode == 0u) Interlocked.Increment(ref goodPublishes); + }; + + drv.RaiseKeepAliveForTest(StatusCodes.BadNoCommunication); + var sw = Stopwatch.StartNew(); + drv.RaiseKeepAliveForTest(StatusCodes.Good); + await drv.RecoveryTaskForTest; + sw.Stop(); + + goodPublishes.ShouldBe(RefCount, "positive control: every awaiting ref was re-published"); + sw.Elapsed.ShouldBeLessThan(TimeSpan.FromMilliseconds(1500), + $"recovery of {RefCount} refs took {sw.ElapsedMilliseconds} ms — the per-ref scan is O(refs x items)"); + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientWriteHealthTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientWriteHealthTests.cs index 3fcfb0ae2..6621a8989 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientWriteHealthTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientWriteHealthTests.cs @@ -68,7 +68,7 @@ public sealed class OpcUaClientWriteHealthTests var (drv, session) = NewConnectedDriver(new DriverHealth(DriverState.Healthy, Stale, null)); using var _ = drv; session.Setup(s => s.WriteAsync(It.IsAny(), It.IsAny>(), It.IsAny())) - .ThrowsAsync(new ServiceResultException(StatusCodes.BadConnectionClosed)); + .ThrowsAsync(new ServiceResultException(StatusCodes.BadNotConnected)); // pre-wire: nothing was sent (G-14: BadConnectionClosed may be post-dispatch) var results = await drv.WriteAsync(Write(), TestContext.Current.CancellationToken);