fix(opcuaclient): review r0 minors m1-m10

- m1: the form hint now says ProbeTimeoutSeconds can only shorten Test Connect's
  10 s budget (passing the configured value as the button's budget is shared code -
  follow-up).
- m2: a superseded init no longer overwrites _options (generation-checked under
  _probeLock) or the cert-validation handler (handed back and published with the
  session; detached when not installed; a previous one detached on replace).
- m3: an ack none of whose condition ids resolves throws BadNodeIdUnknown + Warning.
- m4: an ack with no reply (transport failure / non-caller timeout) degrades.
- m5: no session before the gate is the same ServiceResultException(BadNotConnected).
- m6: the caller-cancelled-write deviation is documented.
- m7: a reply during a published outage advances the stamp but does not write
  Healthy; the keep-alive recovery ends the outage.
- m8: test for a non-caller OperationCanceledException write -> Degraded.
- m9: the browse session owns and disposes the user certificate it loaded
  (OpcUaUserIdentityFactory.LoadCertificate; a key-less cert is disposed before the
  throw); AdminUI-host certificate path documented.
- m10: a subscribe overtaken by a shutdown / re-init removes its half-built
  subscription instead of registering it (data and alarm).
- Sync Dispose drains each gate for 500 ms (was 2 s).

Refs #743

Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
Joseph Doherty
2026-10-22 16:42:29 -04:00
parent edd2e23b7a
commit f0d807e7b7
10 changed files with 293 additions and 61 deletions
@@ -100,4 +100,27 @@ public sealed class OpcUaClientBrowseSessionAttributesTests
await Should.ThrowAsync<ArgumentException>(() =>
session.AttributesAsync("nsu=urn:not-in-table;s=X", TestContext.Current.CancellationToken));
}
private sealed class TrackingCredential : IDisposable
{
public int Disposed { get; private set; }
public void Dispose() => Disposed++;
}
/// <summary>Review m9: the browse session disposes the user certificate it was handed, with itself.</summary>
[Fact]
public async Task The_session_disposes_the_credential_it_owns()
{
var mock = SessionReturning(NodeClass.Variable, DataTypeIds.Int32, -1, 1);
var credential = new TrackingCredential();
var session = new OpcUaClientBrowseSession(
mock.Object, NamespaceMap.FromTable(new NamespaceTable()), ObjectIds.ObjectsFolder, credential);
credential.Disposed.ShouldBe(0, "positive control: still owned while the session is open");
await session.DisposeAsync();
await session.DisposeAsync();
credential.Disposed.ShouldBe(1);
}
}
@@ -80,4 +80,39 @@ public sealed class OpcUaClientAcknowledgeFailureTests
await Should.ThrowAsync<ServiceResultException>(() => call);
}
/// <summary>Review m3: an ack none of whose condition ids resolves sent nothing upstream — that fails, it is not "applied".</summary>
[Fact]
public async Task An_ack_with_no_resolvable_condition_fails_with_BadNodeIdUnknown()
{
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-m3");
var session = NewSession();
drv.SetSessionForTest(session.Object);
var ex = await Should.ThrowAsync<ServiceResultException>(() => drv.AcknowledgeAsync(
[new AlarmAcknowledgeRequest("nsu=urn:not-in-table;s=X", "nsu=urn:not-in-table;s=X", "ack")],
TestContext.Current.CancellationToken));
ex.StatusCode.ShouldBe(StatusCodes.BadNodeIdUnknown);
session.Verify(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<CallMethodRequestCollection>(), It.IsAny<CancellationToken>()),
Times.Never);
}
/// <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<CallMethodRequestCollection>(), 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);
}
}
@@ -51,15 +51,17 @@ public sealed class OpcUaClientAlarmTests
await drv.UnsubscribeAlarmsAsync(new FakeAlarmHandle(), TestContext.Current.CancellationToken);
}
/// <summary>Verifies that AcknowledgeAsync without initialize throws InvalidOperationException.</summary>
/// <summary>Verifies that AcknowledgeAsync without initialize throws ServiceResultException(BadNotConnected).</summary>
[Fact]
public async Task AcknowledgeAsync_without_initialize_throws_InvalidOperationException()
public async Task AcknowledgeAsync_without_initialize_throws_BadNotConnected()
{
// Review m5: the same status as a session lost while the ack queued (one "no session" answer).
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-ack-uninit");
await Should.ThrowAsync<InvalidOperationException>(async () =>
var ex = await Should.ThrowAsync<Opc.Ua.ServiceResultException>(async () =>
await drv.AcknowledgeAsync(
[new AlarmAcknowledgeRequest("ns=2;s=Src", "ns=2;s=Cond", "operator ack")],
TestContext.Current.CancellationToken));
ex.StatusCode.ShouldBe(Opc.Ua.StatusCodes.BadNotConnected);
}
/// <summary>Verifies that AcknowledgeAsync with empty batch is noop even without init.</summary>
@@ -117,4 +117,47 @@ public sealed class OpcUaClientWriteHealthTests
h.LastSuccessfulRead.ShouldNotBeNull().ShouldBeGreaterThan(Stale);
h.LastError.ShouldBeNull();
}
/// <summary>
/// Review m8: a write that TIMED OUT (an OperationCanceledException the caller did not cause) is a call with no
/// reply — Degraded, stamp preserved. The genuine positive control for the caller-cancelled test above (same
/// catch branch, the caller's token is the only difference).
/// </summary>
[Fact]
public async Task A_write_that_timed_out_without_caller_cancellation_degrades()
{
var (drv, session) = NewConnectedDriver(new DriverHealth(DriverState.Healthy, Stale, null));
using var _ = drv;
session.Setup(s => s.WriteAsync(It.IsAny<RequestHeader>(), It.IsAny<WriteValueCollection>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new OperationCanceledException("SDK request timeout"));
var results = await drv.WriteAsync(Write(), TestContext.Current.CancellationToken);
results.Single().StatusCode.ShouldBe(0x800A0000u); // BadTimeout
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
drv.GetHealth().LastSuccessfulRead.ShouldBe(Stale);
}
/// <summary>
/// Review m7: a reply that was in flight across a bad keep-alive advances the stamp (it is evidence) but does not
/// declare the published outage over — health stays Degraded until the keep-alive recovers.
/// </summary>
[Fact]
public async Task A_reply_during_a_published_outage_advances_the_stamp_but_keeps_degraded()
{
var (drv, session) = NewConnectedDriver(new DriverHealth(DriverState.Healthy, Stale, null));
using var _ = drv;
drv.RaiseKeepAliveForTest(StatusCodes.BadNoCommunication);
drv.GetHealth().State.ShouldBe(DriverState.Degraded, "positive control: the outage is published");
session.Setup(s => s.WriteAsync(It.IsAny<RequestHeader>(), It.IsAny<WriteValueCollection>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new WriteResponse { ResponseHeader = new ResponseHeader(), Results = [StatusCodes.Good], DiagnosticInfos = [] });
await drv.WriteAsync(Write(), TestContext.Current.CancellationToken);
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
drv.GetHealth().LastSuccessfulRead.ShouldNotBeNull().ShouldBeGreaterThan(Stale);
drv.RaiseKeepAliveForTest(StatusCodes.Good);
drv.GetHealth().State.ShouldBe(DriverState.Healthy, "the keep-alive recovery is what ends the outage");
}
}