fix: preserve SDK 2 driver value and credential lifetimes

This commit is contained in:
Joseph Doherty
2026-11-10 10:17:03 -05:00
parent b583840fbc
commit 62c3ba6c37
5 changed files with 73 additions and 48 deletions
@@ -280,6 +280,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private Func<Opc.Ua.Security.Certificates.Certificate, ServiceResult, bool>? _certValidationHandler;
/// <summary>The <see cref="ICertificateManager"/> that owns <see cref="_certValidationHandler"/>.</summary>
private ICertificateManager? _certValidatorRef;
private ApplicationInstance? _ownedApplication;
/// <summary>
/// 1 while the CURRENT session's keep-alive is bad (an outage is in progress), else 0. The
/// 0→1 edge publishes the outage once (Bad per subscribed ref + a quality-only alarm annotation); the 1→0
@@ -565,6 +566,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
string? connectedUrl = null;
foreach (var url in candidates)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
session = OpenSessionForTest is { } open
@@ -572,9 +574,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
: await OpenSessionOnEndpointAsync(
appConfig, url, _options.SecurityPolicy, _options.SecurityMode,
identity, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
connectedUrl = url;
break;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception ex)
{
attemptErrors.Add($"{url} -> {ex.GetType().Name}: {ex.Message}");
@@ -622,6 +626,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
DetachCertValidation(_certValidatorRef, _certValidationHandler);
_certValidationHandler = certValidation.Handler;
_certValidatorRef = certValidation.Validator;
_ownedApplication = certValidation.Application;
installed = true;
}
}
@@ -642,7 +647,12 @@ 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 (!installed)
{
DetachCertValidation(certValidation.Validator, certValidation.Handler);
if (certValidation.Application is { } application)
await application.DisposeAsync().ConfigureAwait(false);
}
if (Volatile.Read(ref _lifecycleGeneration) == generation)
{
if (installed)
@@ -659,6 +669,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
{
public Func<Opc.Ua.Security.Certificates.Certificate, ServiceResult, bool>? Handler { get; set; }
public ICertificateManager? Validator { get; set; }
public ApplicationInstance? Application { get; set; }
}
private static void DetachCertValidation(ICertificateManager? validator, Func<Opc.Ua.Security.Certificates.Certificate, ServiceResult, bool>? handler)
@@ -735,11 +746,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
ApplicationType = ApplicationType.Client,
};
certValidation.Application = app;
var pkiRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"OtOpcUa", "pki");
var config = new ApplicationConfiguration
var config = new ApplicationConfiguration(_sdkTelemetry)
{
ApplicationName = _options.SessionName,
ApplicationType = ApplicationType.Client,
@@ -782,6 +794,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
DisableHiResClock = true,
};
app.ApplicationConfiguration = config;
await config.ValidateAsync(ApplicationType.Client, ct).ConfigureAwait(false);
// AutoAccept=true is a dev-only escape hatch. Emit a prominent warning so a
@@ -821,7 +834,6 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
// Ensure an application certificate exists. The SDK auto-generates one if missing.
app.ApplicationConfiguration = config;
await app.CheckApplicationInstanceCertificatesAsync(silent: true, lifeTimeInMonths: null, ct)
.ConfigureAwait(false);
@@ -1181,10 +1193,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// Take the session reference under _probeLock and clear Session to null so any concurrent caller that
// checks inside _gate sees null immediately after release begins.
ISession? sessionToClose;
ApplicationInstance? applicationToDispose;
lock (_probeLock)
{
if (Volatile.Read(ref _lifecycleGeneration) != generation) return;
sessionToClose = Session;
applicationToDispose = _ownedApplication;
_ownedApplication = null;
if (_keepAliveHandler is not null && sessionToClose is not null)
{
try { sessionToClose.KeepAlive -= _keepAliveHandler; } catch { }
@@ -1209,6 +1224,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
catch { /* best-effort */ }
try { sessionToClose?.Dispose(); } catch { }
if (applicationToDispose is not null)
{
try { await applicationToDispose.DisposeAsync().ConfigureAwait(false); } catch { }
}
Interlocked.Exchange(ref _sessionLost, 0);
Interlocked.Exchange(ref _subscriptionLost, 0);
Interlocked.Exchange(ref _publishingStoppedSinceTicks, 0);
@@ -1732,11 +1751,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// the release fails silently and the cursor times out server-side anyway.
try
{
using var release = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await session.BrowseNextAsync(
requestHeader: null,
releaseContinuationPoints: true,
continuationPoints: [continuationPoint],
ct: CancellationToken.None).ConfigureAwait(false);
ct: release.Token).AsTask().WaitAsync(release.Token).ConfigureAwait(false);
}
catch { /* best-effort — server may have already cleaned up */ }
throw;
@@ -2630,7 +2650,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
ObjectId = conditionId,
MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [
new Variant(eventId), // Part 9 §5.7.3: the EventId being acknowledged (empty only when none seen)
Variant.From(eventId.ToByteString()), // Part 9 §5.7.3: the EventId being acknowledged (empty only when none seen)
new Variant(new LocalizedText(ack.Comment ?? string.Empty)),
],
});
@@ -3702,8 +3722,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// hook synchronously (no async work on this hot path), then fires the cert-validation
/// handler detach. The async session-close is intentionally skipped — it requires a
/// live session + network round-trip and is unsafe to block-on from a potentially
/// single-threaded context (OPC UA stack thread). The session will be cleaned up by
/// the SDK's own finalizer on GC (no sync-over-async).
/// single-threaded context (OPC UA stack thread). Local session and certificate-manager
/// resources are disposed synchronously.
/// </summary>
public void Dispose()
{
@@ -3721,7 +3741,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
try { Session.KeepAlive -= _keepAliveHandler; } catch { }
}
_keepAliveHandler = null;
var session = Session;
Session = null;
if (session is not null) DetachDiagnostics(session);
try { session?.Dispose(); } catch { }
try { (_ownedApplication?.ApplicationConfiguration?.CertificateManager as IDisposable)?.Dispose(); } catch { }
_ownedApplication = null;
}
// Detach the cert-validation handler registered during InitializeAsync so the