Merge #992: OpcUaClient indexed recovery re-publish, safe unsubscribe ordering, Bad publish for refused refs, post-dispatch BadTimeout, IPv6 probe preflight
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user