fix(opcuaclient): #946 rate-limit RefreshRequired sweeps; #947 refused per-ack status throws DriverOperationRefusedException

#946: AlarmRefreshRequiredMinInterval (default 10 s, 0 disables) spaces RefreshRequired-triggered ConditionRefresh sweeps per session; a request inside the window is deferred to its end and coalesced, never dropped.
#947: AcknowledgeAsync throws the breaker-exempt DriverOperationRefusedException for Bad per-ack statuses and unresolvable condition ids (BadConditionBranchAlreadyAcked is success) so the #760 revert fires. Docs reverse the O-8 decision.
This commit is contained in:
Joseph Doherty
2026-12-01 19:24:01 -05:00
parent 6b60845931
commit 0ccfd88a23
5 changed files with 434 additions and 33 deletions
@@ -112,6 +112,15 @@ public sealed record OpcUaClientDriverOptions
/// <summary>Client-side keep-alive interval.</summary>
public TimeSpan KeepAliveInterval { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>
/// Minimum time between two <c>RefreshRequired</c>-triggered ConditionRefresh sweeps on one session (#946). An
/// upstream that raises <c>RefreshRequired</c> continuously (e.g. on every event-queue overflow during a replay)
/// would otherwise get back-to-back sweeps of every alarm subscription. A request inside the window is
/// <b>deferred</b> to the window's end (and coalesced with any others), never dropped. <see cref="TimeSpan.Zero"/>
/// disables the limit; default 10 s. Reconnect / re-subscribe / loss-retry refreshes are not limited by this.
/// </summary>
public TimeSpan AlarmRefreshRequiredMinInterval { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>
/// When <c>true</c>, the driver accepts any self-signed / untrusted server certificate.
/// Dev-only — must be <c>false</c> in production so MITM attacks against the opc.tcp
@@ -2707,6 +2707,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// condition node with EventId + Comment arguments. CallAsync accepts a batch —
// one CallMethodRequest per ack.
var callRequests = new List<CallMethodRequest>();
// #947: the ack behind each callRequests[i] (results come back index-aligned with the SENT calls, not with
// the batch), and the per-ack refusals collected for ONE breaker-exempt DriverOperationRefusedException.
var sentAcks = new List<AlarmAcknowledgeRequest>();
List<string>? refusals = null;
foreach (var ack in acknowledgements)
{
// the host acks by RawPath; Acknowledge must hit the upstream CONDITION node.
@@ -2718,15 +2722,24 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
byte[] eventId;
if (_alarmConditionByRawPath.TryGetValue(ack.ConditionId, out var seen))
{
if (!NamespaceMap.TryResolve(session, seen.ConditionRef, out conditionId)) continue;
if (!NamespaceMap.TryResolve(session, seen.ConditionRef, out conditionId))
{
(refusals ??= []).Add($"{ack.ConditionId}: condition id could not be resolved against the live session");
continue;
}
eventId = seen.EventId;
}
else
{
if (!TryResolveTagNode(session, ack.ConditionId, out conditionId)
&& !NamespaceMap.TryResolve(session, ack.ConditionId, out conditionId)) continue;
&& !NamespaceMap.TryResolve(session, ack.ConditionId, out conditionId))
{
(refusals ??= []).Add($"{ack.ConditionId}: condition id could not be resolved against the live session");
continue;
}
eventId = Array.Empty<byte>();
}
sentAcks.Add(ack);
callRequests.Add(new CallMethodRequest
{
ObjectId = conditionId,
@@ -2740,16 +2753,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
if (callRequests.Count == 0)
{
// Review m3 / r1 N-1: nothing resolved to a condition node, so nothing was sent — say so at Warning. NOT
// thrown: this is a deterministic per-ack refusal, and a throw would count toward the host's
// AlarmAcknowledge circuit breaker (5 failures), so an operator re-acking an unresolvable condition
// would block every genuine ack on this driver. Only a no-reply transport failure throws (F2 owns a
// per-ack result surface).
// Review m3 / r1 N-1 / #947: nothing resolved to a condition node, so nothing was sent — a deterministic
// per-ack refusal. It used to be logged and swallowed; a DriverOperationRefusedException is breaker-exempt
// (no retry, no circuit-breaker count), so it is thrown now — otherwise the host believes the ack took
// and the #760 revert never fires.
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync resolved none of {Count} condition id(s) " +
"against the live session; nothing was sent upstream and the acknowledgement was NOT applied.",
_driverInstanceId, acknowledgements.Count);
return;
throw new DriverOperationRefusedException(
"the OPC UA acknowledge was refused: " + string.Join("; ", refusals ?? []));
}
try
@@ -2770,14 +2783,24 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
for (var i = 0; i < resp.Results.Count; i++)
{
var result = resp.Results[i];
if (StatusCode.IsBad(result.StatusCode))
if (!StatusCode.IsBad(result.StatusCode)) continue;
// #947: "already acknowledged" is the outcome the operator asked for — upstream agrees with the
// node — so it is success, not a refusal (a revert would un-ack a condition that IS acked).
if (IsAckAlreadyApplied(result.StatusCode))
{
_logger.LogWarning(
_logger.LogInformation(
"OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync ack[{Index}] " +
"rejected by upstream server with StatusCode {StatusCode:X8}. " +
"The acknowledgement may not have been applied.",
"answered {StatusCode:X8}: the condition was already acknowledged upstream.",
_driverInstanceId, i, result.StatusCode.Code);
continue;
}
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync ack[{Index}] " +
"rejected by upstream server with StatusCode {StatusCode:X8}. " +
"The acknowledgement was NOT applied.",
_driverInstanceId, i, result.StatusCode.Code);
var target = i < sentAcks.Count ? sentAcks[i].ConditionId : $"ack[{i}]";
(refusals ??= []).Add($"{target}: upstream server rejected the acknowledge with {result.StatusCode.Code:X8}");
}
}
}
@@ -2803,10 +2826,26 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
RecordCommsFault(generation, $"ack: {ex.Message}");
throw;
}
// #947: a REPLY carrying refusals (or ids that never resolved) is not a comms fault, but it is not an applied
// ack either. DriverOperationRefusedException is exempt from the resilience retry + circuit breaker, so
// repeated refused acks cannot block genuine ones; the host reverts the node (#760).
if (refusals is { Count: > 0 })
throw new DriverOperationRefusedException(
"the OPC UA acknowledge was refused: " + string.Join("; ", refusals));
}
finally { _gate.Release(); }
}
/// <summary>
/// #947: a per-ack status meaning the condition is ALREADY acknowledged upstream — the requested end state — so the
/// ack is treated as applied. Part 9 defines only <c>BadConditionBranchAlreadyAcked</c> for this.
/// </summary>
/// <param name="code">The per-ack status.</param>
/// <returns>Whether the status says the condition was already acknowledged.</returns>
internal static bool IsAckAlreadyApplied(StatusCode code) =>
code.Code == StatusCodes.BadConditionBranchAlreadyAcked;
private void OnEventNotification(
OpcUaAlarmSubscriptionHandle handle,
IReadOnlyDictionary<string, string> sourceFilter,
@@ -3258,10 +3297,58 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh.
// r2 R2-1: bound to the session's work token, which a shutdown cancels first thing.
var sessionWork = _sessionWorkCts.Token;
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork,
onStart: () => Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0)));
// #946: rate-limit per session — a request inside the minimum interval is DEFERRED to the window's end (the queued
// flag stays set meanwhile, so everything arriving in the wait coalesces into this one sweep), never dropped.
var delay = RefreshRequiredSweepDelay(Session);
// The wait is armed HERE (not inside the pool task) so its due time is the request's, however late the pool runs.
var wait = delay > TimeSpan.Zero ? Task.Delay(delay, Clock, sessionWork) : null;
_ = Task.Run(async () =>
{
if (wait is not null)
{
try { await wait.ConfigureAwait(false); }
catch (OperationCanceledException)
{
// The session's work was cancelled (shutdown / re-init): the sweep it asked for is moot.
Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0);
return;
}
}
await RefreshAllAlarmSubscriptionsAsync(sessionWork, onStart: () =>
{
Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0);
// Stamp the START (the window runs start-to-start) against the session the sweep will run on.
Volatile.Write(ref _lastRefreshRequiredSweepTicks, Clock.GetUtcNow().UtcTicks);
Volatile.Write(ref _lastRefreshRequiredSweepSession, Session);
}).ConfigureAwait(false);
});
}
/// <summary>UTC ticks at which the last RefreshRequired-triggered sweep started (0 = none).</summary>
private long _lastRefreshRequiredSweepTicks;
/// <summary>The session that sweep ran on — a new session starts a fresh window.</summary>
private object? _lastRefreshRequiredSweepSession;
/// <summary>#946: how long a RefreshRequired sweep requested now must wait to respect the per-session minimum interval.</summary>
/// <param name="session">The session the sweep would run on.</param>
/// <returns>Zero when it may start immediately.</returns>
private TimeSpan RefreshRequiredSweepDelay(object? session)
{
var min = _options.AlarmRefreshRequiredMinInterval;
var last = Volatile.Read(ref _lastRefreshRequiredSweepTicks);
if (min <= TimeSpan.Zero || last == 0 || !ReferenceEquals(Volatile.Read(ref _lastRefreshRequiredSweepSession), session))
return TimeSpan.Zero;
var remaining = new DateTime(last, DateTimeKind.Utc) + min - Clock.GetUtcNow().UtcDateTime;
return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero;
}
/// <summary>Test seam (#946): invoked each time an alarm ConditionRefresh sweep starts.</summary>
internal Action? RefreshSweepStartedForTest { get; set; }
/// <summary>Test seam (#946): request a RefreshRequired-triggered sweep exactly as an upstream RefreshRequired event does.</summary>
internal void RequestRefreshRequiredSweepForTest() => RequestRefreshRequiredSweep();
/// <summary>True for a <c>RefreshRequiredEventType</c> event (the server asks the client to ConditionRefresh).</summary>
/// <param name="fields">The event's fields.</param>
/// <returns>Whether the event is a RefreshRequired marker.</returns>
@@ -3368,6 +3455,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken, Action? onStart = null)
{
onStart?.Invoke();
RefreshSweepStartedForTest?.Invoke();
if (_alarmSubscriptions.IsEmpty) return;
try
{