fix(opcuaclient): #992 G-10..G-15 recovery re-publish indexed, unsubscribe ordering, subscribe refusals published Bad, non-condition events dropped, post-dispatch write failures BadTimeout, dual-mode probe preflight

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 10:21:07 -05:00
parent be5641fc06
commit 888bc73c0d
11 changed files with 653 additions and 24 deletions
+13 -2
View File
@@ -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": "<upstream SourceNode>", "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.
+1 -1
View File
@@ -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 |
@@ -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)
@@ -236,6 +236,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
return handle;
}
/// <summary>Test-only seam: the SDK monitored items registered for a data subscription.</summary>
/// <param name="handle">The subscription handle.</param>
internal IReadOnlyList<MonitoredItem> MonitoredItemsForTest(ISubscriptionHandle handle) =>
_subscriptions.TryGetValue(((OpcUaSubscriptionHandle)handle).Id, out var rs)
? [.. rs.ItemHandlers.Select(p => p.Item)]
: [];
/// <summary>Test-only seam: deliver one data notification as the SDK publish thread would.</summary>
/// <param name="handle">The subscription handle.</param>
/// <param name="fullRef">The RawPath.</param>
@@ -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;
}
/// <summary>OPC UA <c>BadTimeout</c> — "outcome unknown" for a write.</summary>
private const uint StatusBadTimeoutCode = 0x800A0000u;
/// <summary>
/// G-14: whether a write failure is one that can occur after the request reached the wire — a
/// <see cref="ServiceResultException"/> carrying the SDK's request timeout, a closed channel/connection or an
/// interrupted request (or a <see cref="TimeoutException"/>). Such a write may have taken effect.
/// </summary>
/// <param name="ex">The exception the write call threw.</param>
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;
}
/// <summary>
/// (v3) Resolve a tag's <b>RawPath</b> reference to a live <see cref="NodeId"/> against the
/// <paramref name="session"/>'s <i>current</i> 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<RejectedItem>();
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<MonitoredItemNotificationHandle> 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})"));
}
}
/// <summary>One ref a subscribe could not establish a monitored item for.</summary>
/// <param name="Ref">The RawPath.</param>
/// <param name="Status">The status to publish for it.</param>
/// <param name="Why">The operator-facing reason.</param>
internal readonly record struct RejectedItem(string Ref, uint Status, string Why);
/// <summary>
/// G-12: the status the server refused <paramref name="item"/> with at create time, or null when it was created.
/// <c>CreateItemsAsync</c> does not throw for a per-item refusal (<c>BadNodeIdUnknown</c>,
/// <c>BadAttributeIdInvalid</c>, ...); the failure is only on the item's status.
/// </summary>
/// <param name="item">The monitored item after <c>CreateItemsAsync</c>.</param>
internal static uint? RejectedMonitoredItemStatus(MonitoredItem item)
{
var error = item.Status?.Error;
if (error is null || !ServiceResult.IsBad(error)) return null;
return error.StatusCode.Code;
}
/// <summary>
/// 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, <c>BadNoCommunication</c>, pointing the operator at comms rather than the address) and the subscribe
/// logs ONE summarised Warning.
/// </summary>
/// <param name="handle">The subscription the refs were asked for on.</param>
/// <param name="rejected">The refs that got no monitored item.</param>
internal void ReportRejectedItems(ISubscriptionHandle handle, IReadOnlyList<RejectedItem> 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);
}
/// <summary>
/// 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
}
}
/// <summary>
/// G-11: an unsubscribe whose wait for <see cref="_subscriptionGate"/> 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
/// <see cref="SessionCloseTimeout"/>.
/// </summary>
/// <param name="subscription">The detached SDK subscription.</param>
/// <param name="emptied">True when its removal emptied the set (restarts the stale-NoSubscription window after the delete).</param>
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;
/// <summary>Test seam: the most recent deferred delete of a subscription whose unsubscribe wait was cancelled.</summary>
internal Task DeferredDeleteForTest => Volatile.Read(ref _deferredDeleteForTest);
private static void DetachNotificationHandlers(IReadOnlyList<MonitoredItemNotificationHandle> 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<MonitoredItemNotificationHandle> ItemHandlers);
IReadOnlyList<MonitoredItemNotificationHandle> ItemHandlers)
{
/// <summary>
/// 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 <c>_deliveryLock</c>; a scan of
/// <see cref="ItemHandlers"/> made it O(refs x items). <see cref="ItemHandlers"/> is fixed at registration.
/// </summary>
private readonly HashSet<string> _refs = new(ItemHandlers.Select(p => RefOf(p.Item)), StringComparer.Ordinal);
/// <summary>True when one of this subscription's monitored items is bound to <paramref name="fullRef"/>.</summary>
/// <param name="fullRef">The RawPath.</param>
public bool Carries(string fullRef) => _refs.Contains(fullRef);
}
/// <summary>
/// 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));
}
@@ -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)
@@ -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) ────────────────
/// <summary>
/// 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".
/// </summary>
[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(); }
}
}
@@ -93,6 +93,55 @@ public sealed class OpcUaClientSmokeTests(OpcPlcFixture sim)
await drv.UnsubscribeAsync(handle, TestContext.Current.CancellationToken);
}
/// <summary>
/// #992 G-12 through the real SDK: a ref whose upstream node does not exist (the server refuses the monitored
/// item with <c>BadNodeIdUnknown</c> 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.
/// </summary>
[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<DataChangeEventArgs>();
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);
}
/// <summary>
/// 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
@@ -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) ────────────────
/// <summary>
/// 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".
/// </summary>
[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(); }
}
}
@@ -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;
/// <summary>
/// #992 / review 2026-12-02 G-11 .. G-14 on the OpcUaClient driver (G-10 is in
/// <see cref="OpcUaClientReview1202RecoveryTests"/>, G-15 in the probe tests, G-12's wire half in the
/// integration suite).
/// </summary>
[Trait("Category", "Unit")]
public sealed class OpcUaClientReview1202FindingsTests
{
private const string SpeedRef = "Plant/dev/Speed";
private static readonly IReadOnlyList<RawTagEntry> Tags =
[new(SpeedRef, JsonSerializer.Serialize(new { nodeId = "ns=0;s=Speed" }), WriteIdempotent: true)];
private sealed class ListLogger : ILogger<OpcUaClientDriver>
{
public List<(LogLevel Level, string Message)> Entries { get; } = [];
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
{
lock (Entries) Entries.Add((logLevel, formatter(state, exception)));
}
}
private static (OpcUaClientDriver Driver, Mock<ISession> Session) NewConnectedDriver(ILogger<OpcUaClientDriver>? log = null)
{
var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions { RawTags = Tags }, "opcua-g11", log);
var session = new Mock<ISession>(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 ─────────────────────────────────────────────────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
[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<Subscription>();
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<OperationCanceledException>(() => 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);
}
/// <summary>
/// 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.
/// </summary>
[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<Subscription>();
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);
}
/// <summary>The alarm unsubscribe has the same ordering: a cancelled gate wait still deletes the subscription.</summary>
[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<Subscription>();
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<OperationCanceledException>(() => 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 ─────────────────────────────────────────────────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
[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<DataChangeEventArgs>();
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<string, string> TripIndex = new() { ["ns=3;s=Alarms.Trip1"] = "Plant/opc/plc/Trip1" };
private static List<Variant> 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";
}
/// <summary>
/// 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.
/// </summary>
[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<AlarmEventArgs>();
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<uint> PostDispatchFailures =>
[
StatusCodes.BadRequestTimeout.Code,
StatusCodes.BadTimeout.Code,
StatusCodes.BadSecureChannelClosed.Code,
StatusCodes.BadConnectionClosed.Code,
StatusCodes.BadRequestInterrupted.Code,
];
/// <summary>
/// A write that failed after it may have been sent (the SDK's request timeout, a channel closed under it)
/// reports <c>BadTimeout</c> ("outcome unknown"), not "did not reach the server". Health is still degraded:
/// no reply arrived, which is a comms fault.
/// </summary>
[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<RequestHeader>(), It.IsAny<ArrayOf<WriteValue>>(), It.IsAny<CancellationToken>()))
.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);
}
/// <summary>Positive control: a failure that cannot have been sent stays <c>BadCommunicationError</c>.</summary>
[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<RequestHeader>(), It.IsAny<ArrayOf<WriteValue>>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new ServiceResultException(StatusCodes.BadNotConnected));
var results = await drv.WriteAsync([new Core.Abstractions.WriteRequest(SpeedRef, 7)], TestContext.Current.CancellationToken);
results.Single().StatusCode.ShouldBe(0x80050000u);
}
}
@@ -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;
/// <summary>
/// #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.
/// </summary>
[Trait("Category", "Unit")]
public sealed class OpcUaClientReview1202RecoveryTests
{
private const int RefCount = 20_000;
/// <summary>
/// 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.
/// </summary>
[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<ISession>(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<RequestHeader>(), It.IsAny<double>(), It.IsAny<TimestampsToReturn>(),
It.IsAny<ArrayOf<ReadValueId>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((RequestHeader _, double _, TimestampsToReturn _, ArrayOf<ReadValueId> 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)");
}
}
@@ -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<RequestHeader>(), It.IsAny<ArrayOf<WriteValue>>(), It.IsAny<CancellationToken>()))
.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);