diff --git a/docs/drivers/OpcUaClient.md b/docs/drivers/OpcUaClient.md index 9441a47c8..12fb0d8a7 100644 --- a/docs/drivers/OpcUaClient.md +++ b/docs/drivers/OpcUaClient.md @@ -289,10 +289,10 @@ The session keep-alive (`KeepAliveInterval`, default 5 s) is the liveness signal no health — including a write the host cancelled at its own write deadline against a hung upstream; the session keep-alive owns liveness and reports that outage itself. A reply that was in flight across a bad keep-alive advances the stamp but does not write `Healthy` while the outage is published — the keep-alive recovery ends the outage. - An ack none of whose condition ids resolves sends nothing and logs a Warning — it does **not** throw (a deterministic - per-ack refusal must not count toward the host's AlarmAcknowledge circuit breaker, or five re-acks of one - unresolvable condition would block every genuine ack). Only a call with no reply throws; with no session an ack - fails `BadNotConnected` (before or inside the gate alike). + An ack none of whose condition ids resolves sends nothing, logs a Warning and **throws the breaker-exempt + `DriverOperationRefusedException`** (#947 — it used to return silently; see "A refused ack is refused" below). A call + with no reply throws a `ServiceResultException`; with no session an ack fails `BadNotConnected` (before or inside the + gate alike). - **Bad keep-alive** ⇒ health `Degraded` (`LastError = "keep-alive: "`, read stamp preserved), host status `Stopped`, and — **once per outage**, not per keep-alive — every subscribed ref is published `BadNoCommunication` with its last value retained and **source + server timestamp = the detection time** (live-gate F1: stamped with the @@ -473,7 +473,11 @@ initialise (the AdminUI form drops them on the next save). Pinned by > consumer), keeps them out of the backstop, and diagnoses them if no signal follows. > - **Retry bounds:** at most 3 re-refreshes run per episode, backing off 2 s, 4 s and 8 s. A clean RefreshEnd resets > the budget. Once the budget is spent, a further loss gets a new budget only after a 5-minute cool-down. -> - **RefreshRequired:** its sweeps are coalesced while one is queued. The alarm event item asks for a +> - **RefreshRequired:** its sweeps are coalesced while one is queued **and rate-limited (#946)**: at least +> `alarmRefreshRequiredMinInterval` (default 10 s, start to start; `00:00:00` disables) separates two sweeps on one +> session. A request inside the window is **deferred** to the window's end, never dropped, and everything arriving +> meanwhile coalesces into that one sweep; a new session starts a fresh window. Reconnect / re-subscribe / loss-retry +> refreshes (own 3-attempt budget) are not subject to it. The alarm event item asks for a > queue of 10,000 (previously 1,000); the server may revise it down. Counters on `otopcua.driver.opcuaclient.events`: > `alarm_event_queue_overflow` and `alarm_refresh_lossy`. > Last-told state survives a re-initialise (the host re-subscribes the same set over nodes it did not rebuild) and is @@ -484,8 +488,20 @@ initialise (the AdminUI form drops them on the next save). Pinned by > **An ack that never got a reply fails (review 2026-10-21 O-8).** A transport failure on the `Acknowledge` call > (closed channel, faulted session) — or a session lost while the ack queued — now throws with its status > (`ServiceResultException`, e.g. `BadConnectionClosed` / `BadNotConnected`), so the host logs the ack as failed -> instead of applied. A *reply* still returns normally, including per-ack refusals such as -> `BadConditionBranchAlreadyAcked` (logged per ack): a refusal is the server answering. +> instead of applied. +> +> **A refused ack is refused (#947, reverses the O-8 decision).** A *reply* carrying a Bad per-ack status +> (`BadUserAccessDenied`, `BadNodeIdUnknown`, `BadEventIdUnknown`, `BadInvalidState`, …) — or a condition id that does +> not resolve against the live session — used to be logged and swallowed, so the host never saw a failure, the #760 +> revert never fired, and the node kept showing an ack upstream had refused. It now throws +> `DriverOperationRefusedException` (one per call, naming each refused condition + status). That type is exempt from the +> resilience pipeline's retry **and** circuit breaker, which is the reason the earlier decision gave for *not* throwing +> (five refused re-acks opening the AlarmAcknowledge breaker); with it gone the reason is gone. The refusal is a reply, +> so it neither degrades health nor counts as a comms fault. Results are matched to the acks actually sent (an +> unresolvable id in a batch is refused after the resolvable ones are sent). **`BadConditionBranchAlreadyAcked` is +> success** (logged at Information): the condition is already in the requested end state, and reverting would un-ack +> a condition that IS acked. Part 9 defines no other already-acked status. This driver implements no Confirm / Shelve / +> Enable / Disable — `AcknowledgeAsync` is the only upstream condition method it calls, so there is no sibling path. > This driver does **not** implement `IRediscoverable` — there is no > push-driven rediscovery signal from a remote OPC UA server in this driver. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Contracts/OpcUaClientDriverOptions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Contracts/OpcUaClientDriverOptions.cs index 93ff57e8d..c25fcbbbf 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Contracts/OpcUaClientDriverOptions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Contracts/OpcUaClientDriverOptions.cs @@ -112,6 +112,15 @@ public sealed record OpcUaClientDriverOptions /// Client-side keep-alive interval. public TimeSpan KeepAliveInterval { get; init; } = TimeSpan.FromSeconds(5); + /// + /// Minimum time between two RefreshRequired-triggered ConditionRefresh sweeps on one session (#946). An + /// upstream that raises RefreshRequired 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 + /// deferred to the window's end (and coalesced with any others), never dropped. + /// disables the limit; default 10 s. Reconnect / re-subscribe / loss-retry refreshes are not limited by this. + /// + public TimeSpan AlarmRefreshRequiredMinInterval { get; init; } = TimeSpan.FromSeconds(10); + /// /// When true, the driver accepts any self-signed / untrusted server certificate. /// Dev-only — must be false in production so MITM attacks against the opc.tcp 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 fe9d23324..8cbe357ad 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs @@ -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(); + // #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(); + List? 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(); } + 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(); } } + /// + /// #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 BadConditionBranchAlreadyAcked for this. + /// + /// The per-ack status. + /// Whether the status says the condition was already acknowledged. + internal static bool IsAckAlreadyApplied(StatusCode code) => + code.Code == StatusCodes.BadConditionBranchAlreadyAcked; + private void OnEventNotification( OpcUaAlarmSubscriptionHandle handle, IReadOnlyDictionary 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); + }); } + /// UTC ticks at which the last RefreshRequired-triggered sweep started (0 = none). + private long _lastRefreshRequiredSweepTicks; + + /// The session that sweep ran on — a new session starts a fresh window. + private object? _lastRefreshRequiredSweepSession; + + /// #946: how long a RefreshRequired sweep requested now must wait to respect the per-session minimum interval. + /// The session the sweep would run on. + /// Zero when it may start immediately. + 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; + } + + /// Test seam (#946): invoked each time an alarm ConditionRefresh sweep starts. + internal Action? RefreshSweepStartedForTest { get; set; } + + /// Test seam (#946): request a RefreshRequired-triggered sweep exactly as an upstream RefreshRequired event does. + internal void RequestRefreshRequiredSweepForTest() => RequestRefreshRequiredSweep(); + /// True for a RefreshRequiredEventType event (the server asks the client to ConditionRefresh). /// The event's fields. /// Whether the event is a RefreshRequired marker. @@ -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 { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientAcknowledgeFailureTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientAcknowledgeFailureTests.cs index acdd5b88c..3b0617be5 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientAcknowledgeFailureTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientAcknowledgeFailureTests.cs @@ -10,8 +10,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests; /// /// Review 2026-10-21 R06:O-8 — AcknowledgeAsync swallowed every non-cancellation transport failure, so /// the host logged the Part 9 ack as applied while upstream still showed the condition unacknowledged. A -/// transport failure (no reply) now propagates with its status; a reply — even one carrying per-ack refusals — -/// still returns normally (that is the server answering, logged per ack). +/// transport failure (no reply) now propagates with its status; a reply returns normally unless it carries a per-ack +/// refusal, which (#947) throws the breaker-exempt so the host's #760 +/// revert fires. BadConditionBranchAlreadyAcked is the requested end state and stays a success. /// [Trait("Category", "Unit")] public sealed class OpcUaClientAcknowledgeFailureTests @@ -46,7 +47,7 @@ public sealed class OpcUaClientAcknowledgeFailureTests /// Positive control: a reply returns normally and the call reached the wire. [Fact] - public async Task Positive_control_a_reply_returns_normally() + public async Task Positive_control_a_reply_returns_normally_and_already_acked_is_success() { using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-o8-ok"); var session = NewSession(); @@ -65,6 +66,120 @@ public sealed class OpcUaClientAcknowledgeFailureTests Times.Once); } + private static Mock SessionAnswering(params StatusCode[] statuses) + { + var session = NewSession(); + session.Setup(s => s.CallAsync(It.IsAny(), It.IsAny>(), It.IsAny())) + .ReturnsAsync(new CallResponse + { + ResponseHeader = new ResponseHeader(), + Results = statuses.Select(c => new CallMethodResult { StatusCode = c }).ToArray(), + DiagnosticInfos = [], + }); + return session; + } + + /// #947: an upstream per-ack refusal throws the breaker-exempt refusal (the #760 revert depends on it). + public static TheoryData RefusalStatuses => new() + { + StatusCodes.BadUserAccessDenied.Code, StatusCodes.BadNodeIdUnknown.Code, + StatusCodes.BadEventIdUnknown.Code, StatusCodes.BadInvalidState.Code, + }; + + [Theory] + [MemberData(nameof(RefusalStatuses))] + public async Task A_bad_per_ack_status_throws_the_breaker_exempt_refusal(uint status) + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947"); + drv.SetSessionForTest(SessionAnswering(new StatusCode(status)).Object); + + var ex = await Should.ThrowAsync(() => + drv.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken)); + + ex.Message.ShouldContain(Condition); + ex.Message.ShouldContain(status.ToString("X8")); + } + + /// A refusal is the server ANSWERING: health stays Healthy, not Degraded. + [Fact] + public async Task A_refused_ack_does_not_degrade_health() + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947-health"); + drv.SetHealthForTest(new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null)); + drv.SetSessionForTest(SessionAnswering(StatusCodes.BadUserAccessDenied).Object); + + await Should.ThrowAsync(() => + drv.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken)); + + drv.GetHealth().State.ShouldBe(DriverState.Healthy); + } + + /// + /// #947 through the host's real resilience pipeline: six refused acks (above the AlarmAcknowledge breaker's + /// threshold of five) must not open the breaker — a genuine ack that follows still reaches the server. + /// + [Fact] + public async Task Refused_acks_do_not_open_the_ack_breaker_and_are_not_retried() + { + var ct = TestContext.Current.CancellationToken; + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947-breaker"); + var calls = 0; + var session = NewSession(); + session.Setup(s => s.CallAsync(It.IsAny(), It.IsAny>(), It.IsAny())) + .ReturnsAsync(() => new CallResponse + { + ResponseHeader = new ResponseHeader(), + Results = [new CallMethodResult { StatusCode = Interlocked.Increment(ref calls) <= 6 ? StatusCodes.BadUserAccessDenied : StatusCodes.Good }], + DiagnosticInfos = [], + }); + drv.SetSessionForTest(session.Object); + var options = new ZB.MOM.WW.OtOpcUa.Core.Resilience.DriverResilienceOptions { Tier = DriverTier.A }; + var invoker = new ZB.MOM.WW.OtOpcUa.Core.Resilience.CapabilityInvoker( + new ZB.MOM.WW.OtOpcUa.Core.Resilience.DriverResiliencePipelineBuilder(), "opcua-947-breaker", () => options, "OpcUaClient"); + + for (var i = 0; i < 6; i++) + await Should.ThrowAsync(() => invoker.ExecuteAsync( + DriverCapability.AlarmAcknowledge, "host", async c => await drv.AcknowledgeAsync(Ack(), c), ct).AsTask()); + + calls.ShouldBe(6, "a refusal is not retried"); + await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host", async c => await drv.AcknowledgeAsync(Ack(), c), ct); + calls.ShouldBe(7, "the genuine ack still reaches the server"); + } + + /// A batch: results are index-aligned with the SENT calls — the refusal names the right condition. + [Fact] + public async Task A_refusal_in_a_batch_names_the_refused_condition_and_ignores_already_acked() + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947-batch"); + drv.SetSessionForTest(SessionAnswering( + StatusCodes.BadConditionBranchAlreadyAcked, StatusCodes.BadUserAccessDenied, StatusCodes.Good).Object); + + var ex = await Should.ThrowAsync(() => drv.AcknowledgeAsync( + [new("ns=2;s=A", "ns=2;s=A", null), new("ns=2;s=B", "ns=2;s=B", null), new("ns=2;s=C", "ns=2;s=C", null)], + TestContext.Current.CancellationToken)); + + ex.Message.ShouldContain("ns=2;s=B"); + ex.Message.ShouldNotContain("ns=2;s=A"); + ex.Message.ShouldNotContain("ns=2;s=C"); + } + + /// An unresolvable id alongside a resolvable one: the resolvable one is still sent, then the refusal is thrown. + [Fact] + public async Task A_partly_unresolvable_batch_sends_the_rest_then_refuses() + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947-partial"); + var session = SessionAnswering(StatusCodes.Good); + drv.SetSessionForTest(session.Object); + + var ex = await Should.ThrowAsync(() => drv.AcknowledgeAsync( + [new("ns=2;s=A", "ns=2;s=A", null), new("nsu=urn:not-in-table;s=X", "nsu=urn:not-in-table;s=X", null)], + TestContext.Current.CancellationToken)); + + ex.Message.ShouldContain("urn:not-in-table"); + session.Verify(s => s.CallAsync(It.IsAny(), It.IsAny>(), It.IsAny()), + Times.Once); + } + [Fact] public async Task Acknowledge_encodes_EventId_as_scalar_ByteString_and_never_retries_a_transport_failure() { @@ -117,18 +232,19 @@ public sealed class OpcUaClientAcknowledgeFailureTests [new("nsu=urn:not-in-table;s=X", "nsu=urn:not-in-table;s=X", "ack")]; /// - /// Review m3 / r1 N-1: an ack none of whose condition ids resolves sends nothing upstream and says so at Warning — - /// but does NOT throw (a deterministic per-ack refusal must not count toward the AlarmAcknowledge breaker). + /// Review m3 / r1 N-1 / #947: an ack none of whose condition ids resolves sends nothing upstream, says so at Warning + /// and throws the breaker-exempt refusal (it used to return silently, so the host never reverted the node). /// [Fact] - public async Task An_ack_with_no_resolvable_condition_warns_and_does_not_throw() + public async Task An_ack_with_no_resolvable_condition_warns_and_is_refused() { var logger = new ListLogger(); using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-m3", logger); var session = NewSession(); drv.SetSessionForTest(session.Object); - await drv.AcknowledgeAsync(Unresolvable(), TestContext.Current.CancellationToken); + await Should.ThrowAsync(() => + drv.AcknowledgeAsync(Unresolvable(), TestContext.Current.CancellationToken)); session.Verify(s => s.CallAsync(It.IsAny(), It.IsAny>(), It.IsAny()), Times.Never); @@ -138,8 +254,8 @@ public sealed class OpcUaClientAcknowledgeFailureTests /// /// r1 N-1 through the host's real resilience pipeline: six unresolvable acks (more than the AlarmAcknowledge - /// breaker's threshold of five) must not open the breaker — a genuine ack that follows is still delivered - /// upstream (the positive control). + /// breaker's threshold of five) must not open the breaker (they now THROW the exempt refusal, #947) — a genuine + /// ack that follows is still delivered upstream (the positive control). /// [Fact] public async Task Unresolvable_acks_do_not_open_the_ack_breaker_for_real_acks() @@ -159,8 +275,8 @@ public sealed class OpcUaClientAcknowledgeFailureTests var invoker = new ZB.MOM.WW.OtOpcUa.Core.Resilience.CapabilityInvoker( new ZB.MOM.WW.OtOpcUa.Core.Resilience.DriverResiliencePipelineBuilder(), "opcua-n1", () => options, "OpcUaClient"); - // Failures are tolerated here on purpose (the host logs and drops them): what is asserted is that the six do - // not trip the breaker — a driver that THREW for them would fail the genuine ack below with an open circuit. + // Refusals are tolerated here on purpose: what is asserted is that the six do not trip the breaker — a + // non-exempt exception would fail the genuine ack below with an open circuit. for (var i = 0; i < 6; i++) { try @@ -168,7 +284,7 @@ public sealed class OpcUaClientAcknowledgeFailureTests await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host", async c => await drv.AcknowledgeAsync(Unresolvable(), c), ct); } - catch (ServiceResultException) { } + catch (DriverOperationRefusedException) { } } await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host", diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshRequiredRateLimitTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshRequiredRateLimitTests.cs new file mode 100644 index 000000000..6adaf4615 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshRequiredRateLimitTests.cs @@ -0,0 +1,172 @@ +using Moq; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests; + +/// +/// #946 — RefreshRequired sweeps were coalesced but not rate-limited: an upstream raising RefreshRequired +/// continuously got back-to-back ConditionRefresh sweeps of every alarm subscription. A minimum interval per +/// session now spaces them; a request inside the window is DEFERRED to the window's end, never dropped. +/// +[Trait("Category", "Unit")] +[Trait("Issue", "946")] +public sealed class OpcUaClientRefreshRequiredRateLimitTests +{ + /// A TimeProvider whose time and timers move only when the test says so. + private sealed class ManualTimeProvider(DateTimeOffset start) : TimeProvider + { + private readonly object _lock = new(); + private readonly List _timers = []; + private DateTimeOffset _now = start; + + public override DateTimeOffset GetUtcNow() { lock (_lock) return _now; } + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + var t = new ManualTimer(this, callback, state); + t.Change(dueTime, period); + return t; + } + + public void Advance(TimeSpan by) + { + List due; + lock (_lock) + { + _now += by; + due = _timers.Where(t => t.Due is { } d && d <= _now).ToList(); + foreach (var t in due) t.Due = null; + } + foreach (var t in due) t.Fire(); + } + + private sealed class ManualTimer(ManualTimeProvider owner, TimerCallback cb, object? state) : ITimer + { + public DateTimeOffset? Due { get; set; } + public void Fire() => cb(state); + + public bool Change(TimeSpan dueTime, TimeSpan period) + { + lock (owner._lock) + { + owner._timers.Remove(this); + if (dueTime == Timeout.InfiniteTimeSpan) { Due = null; return true; } + Due = owner._now + dueTime; + owner._timers.Add(this); + } + return true; + } + + public void Dispose() { lock (owner._lock) owner._timers.Remove(this); } + public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; } + } + } + + private static (OpcUaClientDriver Drv, ManualTimeProvider Clock, Func Sweeps) NewDriver( + string id, OpcUaClientDriverOptions? options = null) + { + var drv = new OpcUaClientDriver(options ?? new OpcUaClientDriverOptions(), id); + var clock = new ManualTimeProvider(new DateTimeOffset(2026, 11, 28, 12, 0, 0, TimeSpan.Zero)); + drv.Clock = clock; + var session = new Mock(MockBehavior.Loose); + drv.SetSessionForTest(session.Object); + drv.AddAlarmSubscriptionForTest(["Plant/opc/plc/Trip1"]); + var sweeps = 0; + drv.RefreshSweepStartedForTest = () => Interlocked.Increment(ref sweeps); + return (drv, clock, () => Volatile.Read(ref sweeps)); + } + + private static async Task Eventually(Func condition) + { + for (var i = 0; i < 200 && !condition(); i++) await Task.Delay(10, TestContext.Current.CancellationToken); + condition().ShouldBeTrue(); + } + + /// The default is a real limit (10 s), and zero is the opt-out. + [Fact] + public void Default_minimum_interval_is_ten_seconds() + => new OpcUaClientDriverOptions().AlarmRefreshRequiredMinInterval.ShouldBe(TimeSpan.FromSeconds(10)); + + /// + /// The first sweep runs at once; a request inside the window waits for the window's end (and runs — deferred, + /// not dropped); however many requests arrive during the wait they coalesce into ONE sweep. + /// + [Fact] + public async Task A_request_inside_the_window_is_deferred_to_its_end_and_coalesced() + { + var (drv, clock, sweeps) = NewDriver("opcua-946-defer"); + using var _ = drv; + + drv.RequestRefreshRequiredSweepForTest(); + await Eventually(() => sweeps() == 1); + + clock.Advance(TimeSpan.FromSeconds(1)); + drv.RequestRefreshRequiredSweepForTest(); + drv.RequestRefreshRequiredSweepForTest(); + drv.RequestRefreshRequiredSweepForTest(); + + // Absence is only meaningful with a positive control (below): the window has not elapsed, so nothing runs. + clock.Advance(TimeSpan.FromSeconds(8)); + await Task.Delay(150, TestContext.Current.CancellationToken); + sweeps().ShouldBe(1, "9 s into a 10 s window"); + + // Positive control: the window's end releases exactly one deferred sweep. + clock.Advance(TimeSpan.FromSeconds(1)); + await Eventually(() => sweeps() == 2); + await Task.Delay(150, TestContext.Current.CancellationToken); + sweeps().ShouldBe(2, "three coalesced requests are one sweep"); + } + + /// The window then restarts from the deferred sweep: a later request is deferred again. + [Fact] + public async Task The_window_restarts_from_each_sweep() + { + var (drv, clock, sweeps) = NewDriver("opcua-946-restart"); + using var _ = drv; + + drv.RequestRefreshRequiredSweepForTest(); + await Eventually(() => sweeps() == 1); + clock.Advance(TimeSpan.FromSeconds(10)); + + drv.RequestRefreshRequiredSweepForTest(); // exactly at the end of the first window: runs at once + await Eventually(() => sweeps() == 2); + + drv.RequestRefreshRequiredSweepForTest(); // inside the second window + await Task.Delay(150, TestContext.Current.CancellationToken); + sweeps().ShouldBe(2); + clock.Advance(TimeSpan.FromSeconds(10)); + await Eventually(() => sweeps() == 3); + } + + /// Zero disables the limit: back-to-back requests each sweep. + [Fact] + public async Task Zero_interval_disables_the_limit() + { + var (drv, _, sweeps) = NewDriver("opcua-946-off", + new OpcUaClientDriverOptions { AlarmRefreshRequiredMinInterval = TimeSpan.Zero }); + using var _d = drv; + + drv.RequestRefreshRequiredSweepForTest(); + await Eventually(() => sweeps() == 1); + drv.RequestRefreshRequiredSweepForTest(); + await Eventually(() => sweeps() == 2); + } + + /// A new session starts a fresh window (its first RefreshRequired must not wait on the old session's). + [Fact] + public async Task A_new_session_starts_a_fresh_window() + { + var (drv, _, sweeps) = NewDriver("opcua-946-session"); + using var _d = drv; + + drv.RequestRefreshRequiredSweepForTest(); + await Eventually(() => sweeps() == 1); + + drv.SetSessionForTest(new Mock(MockBehavior.Loose).Object); + drv.RequestRefreshRequiredSweepForTest(); + await Eventually(() => sweeps() == 2); + } +}