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
@@ -473,6 +473,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
WriteLifecycleHealth(generation, _ => new DriverHealth(DriverState.Initializing, null, null));
ISession? session = null;
KeepAliveEventHandler? keepAliveHandler = null;
var certValidation = new CertValidationHook();
var installed = false;
try
{
@@ -481,11 +482,18 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// with — the endpoint, security policy and tag set were all frozen at construction, and only
// secret rotation was picked up.
if (HasConfigBody(driverConfigJson))
_options = OpcUaClientDriverFactoryExtensions.ParseOptions(_driverInstanceId, driverConfigJson);
{
var parsed = OpcUaClientDriverFactoryExtensions.ParseOptions(_driverInstanceId, driverConfigJson);
// Review m2: a superseded init must not overwrite the options a newer one adopted.
lock (_probeLock)
{
if (Volatile.Read(ref _lifecycleGeneration) == generation) _options = parsed;
}
}
ValidateTuning(_options);
var appConfig = await BuildApplicationConfigurationAsync(cancellationToken).ConfigureAwait(false);
var appConfig = await BuildApplicationConfigurationAsync(certValidation, cancellationToken).ConfigureAwait(false);
// when a DiscoveryUrl is configured, FindServers/GetEndpoints on it first and try the
// discovered URLs ahead of the static list. Non-fatal — an LDS outage must not block init.
@@ -587,6 +595,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
Session = session;
_keepAliveHandler = keepAliveHandler;
_connectedEndpointUrl = connectedUrl;
// Review m2: the cert-validation handler is published with the session — a previous one (a
// re-initialise without shutdown) is detached first so it is not leaked on its validator.
DetachCertValidation(_certValidatorRef, _certValidationHandler);
_certValidationHandler = certValidation.Handler;
_certValidatorRef = certValidation.Validator;
installed = true;
}
}
@@ -607,6 +620,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// superseded check) does not orphan it and its keep-alive timer until GC.
if (session is not null && !installed)
await DiscardSessionAsync(session, keepAliveHandler).ConfigureAwait(false);
if (!installed) DetachCertValidation(certValidation.Validator, certValidation.Handler);
if (Volatile.Read(ref _lifecycleGeneration) == generation)
{
if (installed)
@@ -618,6 +632,19 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
}
/// <summary>The auto-accept certificate-validation handler one initialise attached, handed back to it (review m2).</summary>
private sealed class CertValidationHook
{
public CertificateValidationEventHandler? Handler { get; set; }
public CertificateValidator? Validator { get; set; }
}
private static void DetachCertValidation(CertificateValidator? validator, CertificateValidationEventHandler? handler)
{
if (validator is null || handler is null) return;
try { validator.CertificateValidation -= handler; } catch { /* best-effort */ }
}
/// <summary>
/// Test seam: opens the session for one endpoint URL in place of the real discovery + session create, so
/// the post-connect half of <see cref="InitializeAsync"/> (and its superseded / failure paths) can be driven
@@ -672,7 +699,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// — so multiple driver instances in the same OtOpcUa server process share one
/// certificate store without extra config.
/// </summary>
private async Task<ApplicationConfiguration> BuildApplicationConfigurationAsync(CancellationToken ct)
/// <param name="certValidation">Receives the auto-accept handler this build attached (if any) — published by the
/// caller only when its initialise is still current (review m2), detached otherwise.</param>
/// <param name="ct">Cancellation token.</param>
private async Task<ApplicationConfiguration> BuildApplicationConfigurationAsync(
CertValidationHook certValidation, CancellationToken ct)
{
// The ITelemetryContext overload is the non-obsolete ctor; SDK warnings reach the driver's
// logger when one was supplied.
@@ -762,10 +793,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
e.Accept = true;
};
config.CertificateValidator.CertificateValidation += handler;
// Store refs so ShutdownAsync + Dispose can detach the delegate and avoid
// leaking a closure on a potentially process-shared validator.
_certValidationHandler = handler;
_certValidatorRef = config.CertificateValidator;
// Handed back to the caller, which stores the refs (so ShutdownAsync + Dispose can detach the delegate)
// only while its initialise is the current lifecycle generation.
certValidation.Handler = handler;
certValidation.Validator = config.CertificateValidator;
}
// Ensure an application certificate exists. The SDK auto-generates one if missing.
@@ -1856,11 +1887,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
TimestampsToReturn = TimestampsToReturn.Both,
});
long subscribeGeneration = 0;
await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Re-read Session inside the critical section: a reconnect completing while we were
// blocked on _gate has already swapped in the new session via a re-initialise.
subscribeGeneration = Volatile.Read(ref _lifecycleGeneration);
var session = Session
?? throw new InvalidOperationException(
"OpcUaClient session was lost before the subscription could be created.");
@@ -1925,9 +1958,23 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
await subscription.CreateItemsAsync(cancellationToken).ConfigureAwait(false);
ThrowIfSubscribeSuperseded(subscribeGeneration);
}
}
/// <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
/// check would declare a dead subscription lost. Thrown inside the create's try, so the half-built
/// subscription is removed like any other failed create.
/// </summary>
private void ThrowIfSubscribeSuperseded(long subscribeGeneration)
{
if (Volatile.Read(ref _lifecycleGeneration) != subscribeGeneration)
throw new InvalidOperationException(
"OpcUaClient session was released (shutdown or re-initialise) while the subscription was being created.");
}
/// <inheritdoc />
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken)
{
@@ -2151,6 +2198,17 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private void RecordDeviceAnswered(long generation, DateTime now)
{
if (Volatile.Read(ref _subscriptionLost) == 1) return;
// Review m7: during a published outage (bad keep-alive) a reply that was in flight is evidence — the stamp
// advances — but it does not declare the outage over; the keep-alive recovery path does that (it also
// re-publishes the refs it published Bad), so Healthy is only written once the outage latch is clear.
if (Volatile.Read(ref _sessionLost) == 1)
{
UpdateHealth(generation, h => h.State is DriverState.Healthy or DriverState.Degraded
? h with { LastSuccessfulRead = now }
: null);
return;
}
UpdateHealth(generation, _ => new DriverHealth(DriverState.Healthy, now, null));
}
@@ -2336,11 +2394,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
MonitoredItem? eventItem = null;
MonitoredItemNotificationEventHandler? notifHandler = null;
long subscribeGeneration = 0;
await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Re-read Session inside the critical section: a reconnect completing while we were
// blocked on _gate has already swapped in the new session via a re-initialise.
subscribeGeneration = Volatile.Read(ref _lifecycleGeneration);
var session = Session
?? throw new InvalidOperationException(
"OpcUaClient session was lost before the alarm subscription could be created.");
@@ -2404,6 +2464,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
eventItem.Notification += notifHandler;
subscription.AddItem(eventItem);
await subscription.CreateItemsAsync(cancellationToken).ConfigureAwait(false);
ThrowIfSubscribeSuperseded(subscribeGeneration);
_alarmSubscriptions[id] = new RemoteAlarmSubscription(subscription, handle, eventItem, notifHandler);
}
@@ -2440,7 +2501,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// Fast-fail before queuing if the driver isn't connected, but do NOT bind the ack calls
// (or the namespace-relative ConditionId parse) to this reference — a reconnect can swap
// Session while we wait on _gate. The session actually used is re-read inside the gate.
_ = RequireSession();
// Review m5: the same BadNotConnected as the in-gate check, so "no session" is one status to the caller.
if (Session is null)
throw new ServiceResultException(StatusCodes.BadNotConnected,
"OpcUaClientDriver is not connected; the acknowledgement was not sent.");
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
@@ -2490,7 +2554,15 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
});
}
if (callRequests.Count == 0) return;
if (callRequests.Count == 0)
{
// Review m3: nothing resolved to a condition node, so nothing was sent — that is not an applied ack.
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync resolved none of {Count} condition id(s) " +
"against the live session; nothing was sent upstream.", _driverInstanceId, acknowledgements.Count);
throw new ServiceResultException(StatusCodes.BadNodeIdUnknown,
"None of the acknowledged condition ids resolved to an upstream condition node.");
}
try
{
@@ -2528,6 +2600,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
_logger.LogWarning(ex,
"OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync transport error.",
_driverInstanceId);
// Review m4: a timeout (not the caller cancelling) is a call with no reply, like a read or write.
if (!cancellationToken.IsCancellationRequested) RecordCommsFault(generation, $"ack: {ex.Message}");
throw;
}
catch (Exception ex)
@@ -2538,6 +2612,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
"OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync failed; " +
"acknowledgements were not applied.",
_driverInstanceId);
RecordCommsFault(generation, $"ack: {ex.Message}");
throw;
}
}
@@ -3524,7 +3599,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
{
try
{
if (gate.Wait(TimeSpan.FromSeconds(2)))
if (gate.Wait(TimeSpan.FromMilliseconds(500)))
gate.Release();
}
catch { /* timeout or already disposed — proceed */ }