0ccfd88a23
#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.
315 lines
16 KiB
C#
315 lines
16 KiB
C#
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>
|
|
/// Review 2026-10-21 R06:O-8 — <c>AcknowledgeAsync</c> 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 returns normally unless it carries a per-ack
|
|
/// refusal, which (#947) throws the breaker-exempt <see cref="DriverOperationRefusedException"/> so the host's #760
|
|
/// revert fires. <c>BadConditionBranchAlreadyAcked</c> is the requested end state and stays a success.
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class OpcUaClientAcknowledgeFailureTests
|
|
{
|
|
private const string Condition = "ns=2;s=Pump17";
|
|
|
|
private static Mock<ISession> NewSession()
|
|
{
|
|
var mock = new Mock<ISession>(MockBehavior.Loose);
|
|
mock.SetupGet(s => s.MessageContext).Returns(ServiceMessageContext.Create(SdkTelemetry.Context));
|
|
mock.SetupGet(s => s.NamespaceUris).Returns(new NamespaceTable());
|
|
return mock;
|
|
}
|
|
|
|
private static AlarmAcknowledgeRequest[] Ack() => [new(Condition, Condition, "operator ack")];
|
|
|
|
/// <summary>A transport failure on the Acknowledge call reaches the caller with the transport status.</summary>
|
|
[Fact]
|
|
public async Task A_transport_failure_propagates_with_its_status()
|
|
{
|
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-o8");
|
|
var session = NewSession();
|
|
session.Setup(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()))
|
|
.ThrowsAsync(new ServiceResultException(StatusCodes.BadConnectionClosed));
|
|
drv.SetSessionForTest(session.Object);
|
|
|
|
var ex = await Should.ThrowAsync<ServiceResultException>(() =>
|
|
drv.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken));
|
|
|
|
ex.StatusCode.ShouldBe(StatusCodes.BadConnectionClosed);
|
|
}
|
|
|
|
/// <summary>Positive control: a reply returns normally and the call reached the wire.</summary>
|
|
[Fact]
|
|
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();
|
|
session.Setup(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()))
|
|
.ReturnsAsync(new CallResponse
|
|
{
|
|
ResponseHeader = new ResponseHeader(),
|
|
Results = [new CallMethodResult { StatusCode = StatusCodes.BadConditionBranchAlreadyAcked }],
|
|
DiagnosticInfos = [],
|
|
});
|
|
drv.SetSessionForTest(session.Object);
|
|
|
|
await drv.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken);
|
|
|
|
session.Verify(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()),
|
|
Times.Once);
|
|
}
|
|
|
|
private static Mock<ISession> SessionAnswering(params StatusCode[] statuses)
|
|
{
|
|
var session = NewSession();
|
|
session.Setup(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()))
|
|
.ReturnsAsync(new CallResponse
|
|
{
|
|
ResponseHeader = new ResponseHeader(),
|
|
Results = statuses.Select(c => new CallMethodResult { StatusCode = c }).ToArray(),
|
|
DiagnosticInfos = [],
|
|
});
|
|
return session;
|
|
}
|
|
|
|
/// <summary>#947: an upstream per-ack refusal throws the breaker-exempt refusal (the #760 revert depends on it).</summary>
|
|
public static TheoryData<uint> 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<DriverOperationRefusedException>(() =>
|
|
drv.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken));
|
|
|
|
ex.Message.ShouldContain(Condition);
|
|
ex.Message.ShouldContain(status.ToString("X8"));
|
|
}
|
|
|
|
/// <summary>A refusal is the server ANSWERING: health stays Healthy, not Degraded.</summary>
|
|
[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<DriverOperationRefusedException>(() =>
|
|
drv.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken));
|
|
|
|
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
|
|
}
|
|
|
|
/// <summary>
|
|
/// #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.
|
|
/// </summary>
|
|
[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<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()))
|
|
.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<DriverOperationRefusedException>(() => 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");
|
|
}
|
|
|
|
/// <summary>A batch: results are index-aligned with the SENT calls — the refusal names the right condition.</summary>
|
|
[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<DriverOperationRefusedException>(() => 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");
|
|
}
|
|
|
|
/// <summary>An unresolvable id alongside a resolvable one: the resolvable one is still sent, then the refusal is thrown.</summary>
|
|
[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<DriverOperationRefusedException>(() => 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<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()),
|
|
Times.Once);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Acknowledge_encodes_EventId_as_scalar_ByteString_and_never_retries_a_transport_failure()
|
|
{
|
|
using var driver = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-ack-types");
|
|
var session = NewSession();
|
|
ArrayOf<CallMethodRequest> sent = default;
|
|
session.Setup(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()))
|
|
.Callback<RequestHeader, ArrayOf<CallMethodRequest>, CancellationToken>((_, calls, _) => sent = calls)
|
|
.ThrowsAsync(new ServiceResultException(StatusCodes.BadConnectionClosed));
|
|
driver.SetSessionForTest(session.Object);
|
|
await Should.ThrowAsync<ServiceResultException>(() => driver.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken));
|
|
var arguments = sent[0].InputArguments;
|
|
arguments[0].TypeInfo.BuiltInType.ShouldBe(BuiltInType.ByteString);
|
|
arguments[0].TypeInfo.ValueRank.ShouldBe(ValueRanks.Scalar);
|
|
arguments[0].GetByteString().IsEmpty.ShouldBeTrue();
|
|
arguments[1].TypeInfo.BuiltInType.ShouldBe(BuiltInType.LocalizedText);
|
|
arguments[1].GetLocalizedText().Text.ShouldBe("operator ack");
|
|
session.Verify(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()), Times.Once);
|
|
}
|
|
|
|
/// <summary>A session lost while the ack queued on the gate fails the ack rather than reporting it applied.</summary>
|
|
[Fact]
|
|
public async Task A_session_lost_while_queued_fails_the_ack()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-o8-lost");
|
|
drv.SetSessionForTest(NewSession().Object);
|
|
|
|
await drv.Gate.WaitAsync(ct);
|
|
var call = drv.AcknowledgeAsync(Ack(), ct);
|
|
drv.SetSessionForTest(null);
|
|
drv.Gate.Release();
|
|
|
|
await Should.ThrowAsync<ServiceResultException>(() => call);
|
|
}
|
|
|
|
private sealed class ListLogger : Microsoft.Extensions.Logging.ILogger<OpcUaClientDriver>
|
|
{
|
|
public List<(Microsoft.Extensions.Logging.LogLevel Level, string Message)> Entries { get; } = [];
|
|
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
|
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
|
|
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId,
|
|
TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
|
{
|
|
lock (Entries) Entries.Add((logLevel, formatter(state, exception)));
|
|
}
|
|
}
|
|
|
|
private static AlarmAcknowledgeRequest[] Unresolvable() =>
|
|
[new("nsu=urn:not-in-table;s=X", "nsu=urn:not-in-table;s=X", "ack")];
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
[Fact]
|
|
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 Should.ThrowAsync<DriverOperationRefusedException>(() =>
|
|
drv.AcknowledgeAsync(Unresolvable(), TestContext.Current.CancellationToken));
|
|
|
|
session.Verify(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()),
|
|
Times.Never);
|
|
lock (logger.Entries)
|
|
logger.Entries.ShouldContain(e => e.Level == Microsoft.Extensions.Logging.LogLevel.Warning && e.Message.Contains("resolved none"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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 (they now THROW the exempt refusal, #947) — a genuine
|
|
/// ack that follows is still delivered upstream (the positive control).
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Unresolvable_acks_do_not_open_the_ack_breaker_for_real_acks()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-n1");
|
|
var session = NewSession();
|
|
session.Setup(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()))
|
|
.ReturnsAsync(new CallResponse
|
|
{
|
|
ResponseHeader = new ResponseHeader(),
|
|
Results = [new CallMethodResult { StatusCode = 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-n1", () => options, "OpcUaClient");
|
|
|
|
// 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
|
|
{
|
|
await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host",
|
|
async c => await drv.AcknowledgeAsync(Unresolvable(), c), ct);
|
|
}
|
|
catch (DriverOperationRefusedException) { }
|
|
}
|
|
|
|
await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host",
|
|
async c => await drv.AcknowledgeAsync(Ack(), c), ct);
|
|
|
|
session.Verify(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()),
|
|
Times.Once, "the genuine ack must still reach the server");
|
|
}
|
|
|
|
/// <summary>Review m4: an ack with no reply is a comms fault like a read or write — Degraded, stamp preserved.</summary>
|
|
[Fact]
|
|
public async Task An_ack_transport_failure_degrades_and_preserves_the_stamp()
|
|
{
|
|
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-m4");
|
|
var stamp = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
|
drv.SetHealthForTest(new DriverHealth(DriverState.Healthy, stamp, null));
|
|
var session = NewSession();
|
|
session.Setup(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()))
|
|
.ThrowsAsync(new ServiceResultException(StatusCodes.BadConnectionClosed));
|
|
drv.SetSessionForTest(session.Object);
|
|
|
|
await Should.ThrowAsync<ServiceResultException>(() => drv.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken));
|
|
|
|
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
|
|
drv.GetHealth().LastSuccessfulRead.ShouldBe(stamp);
|
|
}
|
|
}
|