docs: fill missing XML docs and strip tracking IDs from src comments

Clears CommentChecker findings in src/ (3,280 -> 209, the remainder being false
positives like PLC-5/IEEE-754/M0.0) by adding missing summaries/params/returns,
normalising inheritdoc usage, and removing Gitea/review tracking IDs while keeping
the rationale they annotated. Comment-only: comment-stripped sources are identical
to the parent commit.
This commit is contained in:
Joseph Doherty
2026-10-15 06:14:58 -04:00
parent ebcbd81fca
commit 826312befe
430 changed files with 4434 additions and 3923 deletions
@@ -24,7 +24,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient;
/// <para>
/// <b>Session lifetime</b>: a single <see cref="Session"/> per driver instance.
/// Subscriptions multiplex onto that session. A lost session is reported (health Degraded,
/// subscribed values BadNoCommunication — Gitea #670) and recovered by the host's comms-loss
/// subscribed values BadNoCommunication) and recovered by the host's comms-loss
/// watchdog re-initialising the driver and re-subscribing; a session whose keep-alive comes
/// back on its own recovers in place.
/// </para>
@@ -32,7 +32,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient;
public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IAlarmSource, ISkippedTagReporter, IDriverConnectionLossSource, IDisposable, IAsyncDisposable
{
/// <summary>Authored tags whose TagConfig carried no usable <c>nodeId</c>, so there is no upstream node
/// to dial (Gitea #541). This driver's skip path was the quietest of the twelve: <c>NamespaceMap</c>
/// to dial. This driver's skip path was the quietest of the twelve: <c>NamespaceMap</c>
/// drops such an entry with a bare <c>continue</c> and not even a log line.</summary>
private readonly SkippedTagLedger _skippedTags = new();
@@ -86,8 +86,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
PostRecoveryReconcileDelay = () => _options.Timeout + _options.KeepAliveInterval;
}
/// <summary>Mutable so <see cref="InitializeAsync"/> can adopt a re-parsed config on reinitialize
/// (#516). Only ever written on the init path, before any reader/session uses it.</summary>
/// <summary>Mutable so <see cref="InitializeAsync"/> can adopt a re-parsed config on reinitialize.
/// Only ever written on the init path, before any reader/session uses it.</summary>
private OpcUaClientDriverOptions _options;
private readonly ISecretResolver _secretResolver;
private readonly string _driverInstanceId;
@@ -95,23 +95,23 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private readonly System.Collections.Concurrent.ConcurrentDictionary<long, RemoteAlarmSubscription> _alarmSubscriptions = new();
/// <summary>#619: RawPath → the upstream condition NodeId last seen for it. The host acknowledges by
/// <summary>RawPath → the upstream condition NodeId last seen for it. The host acknowledges by
/// RawPath (its only identity for the condition) but Part 9 Acknowledge must be called on the CONDITION
/// node, which differs from the authored source node.</summary>
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, AlarmAckTarget> _alarmConditionByRawPath =
new(StringComparer.Ordinal);
/// <summary>#619 review: the (Active, Acked) state last told to the host per reported condition id, from
/// <summary>The (Active, Acked) state last told to the host per reported condition id, from
/// which <see cref="AlarmTransitions"/> picks the Kind sequence that moves the host's projector to the
/// upstream event's state.</summary>
private readonly Dictionary<string, AlarmToldState> _alarmStateByRawPath = new(StringComparer.Ordinal);
/// <summary>#619 re-review: serialises the read-compute-emit over <see cref="_alarmStateByRawPath"/>. Event
/// <summary>Serialises the read-compute-emit over <see cref="_alarmStateByRawPath"/>. Event
/// notifications arrive on SDK publish threads (and, across a resubscribe, from two subscriptions at once), so
/// a lock-free prior/target exchange could emit two kind sequences computed from the same prior.</summary>
private readonly object _alarmStateLock = new();
/// <summary>#619 re-review: the ref set the last <see cref="SubscribeAlarmsAsync"/> carried. Survives
/// <summary>The ref set the last <see cref="SubscribeAlarmsAsync"/> carried. Survives
/// <see cref="ShutdownAsync"/> deliberately — see <see cref="BeginAlarmSubscription"/>.</summary>
private HashSet<string>? _lastAlarmRefSet;
@@ -137,11 +137,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
public event EventHandler<HostStatusChangedEventArgs>? OnHostStatusChanged;
/// <inheritdoc />
/// <remarks>Gitea #676 — raised at most once per session, and only on a DEFINITIVE loss
/// (<see cref="IsDefinitiveSessionLoss"/>, or a tracked subscription the SERVER reported dropped — never the
/// publishing-stall heuristic). Re-armed when the session is released (re-initialise / shutdown). Known gap: the host
/// acts on it only while Connected, so a raise it receives before it has processed the successful initialise is
/// swallowed and that session falls back to the #527 watchdog.</remarks>
// Raised at most once per session, and only on a DEFINITIVE loss
// (IsDefinitiveSessionLoss, or a tracked subscription the SERVER reported dropped — never the
// publishing-stall heuristic). Re-armed when the session is released (re-initialise / shutdown). Known gap: the host
// acts on it only while Connected, so a raise it receives before it has processed the successful initialise is
// swallowed and that session falls back to the comms-loss watchdog.
public event EventHandler<DriverConnectionLossEventArgs>? ConnectionLost;
// OPC UA StatusCode constants the driver surfaces for local-side faults. Upstream-server
@@ -170,30 +170,30 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <param name="session">The session instance to install, or <c>null</c> to clear it.</param>
internal void SetSessionForTest(ISession? session) => Session = session;
/// <summary>Test-only seam (#670): the most recent in-place recovery task.</summary>
/// <summary>Test-only seam: the most recent in-place recovery task.</summary>
internal Task RecoveryTaskForTest => _recoveryTask;
/// <summary>Test seam (#676): the trailing reconcile read scheduled by the last in-place recovery.</summary>
/// <summary>Test seam: the trailing reconcile read scheduled by the last in-place recovery.</summary>
internal Task ReconcileTaskForTest => _reconcileTask;
/// <summary>Test-only seam (#670 review M1): raise the session's PublishError as the SDK publish loop does.</summary>
/// <summary>Test-only seam: raise the session's PublishError as the SDK publish loop does.</summary>
/// <param name="status">The publish error status.</param>
/// <param name="subscriptionId">The subscription id the error names (0 = none).</param>
internal void RaisePublishErrorForTest(StatusCode status, uint subscriptionId = 0) =>
HandlePublishError(Session, status, subscriptionId);
/// <summary>Test-only seam (#670): install a health snapshot as a completed connect would.</summary>
/// <summary>Test-only seam: install a health snapshot as a completed connect would.</summary>
/// <param name="health">The health to install.</param>
internal void SetHealthForTest(DriverHealth health) => _health = health;
/// <summary>Test-only seam (#670): raise the session keep-alive callback as the SDK timer does.</summary>
/// <summary>Test-only seam: raise the session keep-alive callback as the SDK timer does.</summary>
/// <param name="status">The keep-alive status.</param>
/// <param name="sender">The raising session; defaults to the current one.</param>
internal void RaiseKeepAliveForTest(StatusCode status, ISession? sender = null) =>
OnKeepAlive(sender ?? Session!, new KeepAliveEventArgs(new ServiceResult(status), ServerState.Running, DateTime.UtcNow));
/// <summary>
/// Test-only seam (#670): register a data subscription over <paramref name="refs"/> as
/// Test-only seam: register a data subscription over <paramref name="refs"/> as
/// <see cref="SubscribeAsync"/> would, without the wire create.
/// </summary>
/// <param name="refs">The RawPaths subscribed.</param>
@@ -215,14 +215,14 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
return handle;
}
/// <summary>Test-only seam (#670): deliver one data notification as the SDK publish thread would.</summary>
/// <summary>Test-only seam: deliver one data notification as the SDK publish thread would.</summary>
/// <param name="handle">The subscription handle.</param>
/// <param name="fullRef">The RawPath.</param>
/// <param name="value">The delivered value.</param>
internal void DeliverNotificationForTest(ISubscriptionHandle handle, string fullRef, DataValue value) =>
PublishNotification((OpcUaSubscriptionHandle)handle, fullRef, value);
/// <summary>Test-only seam (#670): register an alarm subscription over <paramref name="refs"/> as
/// <summary>Test-only seam: register an alarm subscription over <paramref name="refs"/> as
/// <see cref="SubscribeAlarmsAsync"/> would, without the wire create.</summary>
/// <param name="refs">The alarm RawPaths subscribed.</param>
internal void AddAlarmSubscriptionForTest(IReadOnlyList<string> refs)
@@ -245,12 +245,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <param name="map">The namespace map to install, or <c>null</c> to clear it.</param>
internal void SetNamespaceMapForTest(NamespaceMap? map) => _namespaceMap = map;
/// <summary>Test-only view of the diagnostics counters (#276).</summary>
/// <summary>Test-only view of the diagnostics counters.</summary>
internal OpcUaClientDiagnostics DiagnosticsForTest => _diag;
private DriverHealth _health = new(DriverState.Unknown, null, null);
/// <summary>Per-instance event counters published as OTel metrics (#276).</summary>
/// <summary>Per-instance event counters published as OTel metrics.</summary>
private readonly OpcUaClientDiagnostics _diag;
private NotificationEventHandler? _notificationHandler;
@@ -268,37 +268,37 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <summary>The <see cref="CertificateValidator"/> that owns <see cref="_certValidationHandler"/>.</summary>
private CertificateValidator? _certValidatorRef;
/// <summary>
/// Gitea #670 — 1 while the CURRENT session's keep-alive is bad (an outage is in progress), else 0. The
/// 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
/// edge on a good keep-alive recovers in place. Reset whenever the session is released, so a fresh session
/// reports its own loss. There is deliberately no in-driver reconnect any more: a session that never comes
/// back keeps health Degraded with <see cref="DriverHealth.LastSuccessfulRead"/> frozen, which is exactly what
/// the host's #527 comms-loss watchdog trips on (→ ShutdownAsync + InitializeAsync + re-subscribe).
/// the host's comms-loss watchdog trips on (→ ShutdownAsync + InitializeAsync + re-subscribe).
/// </summary>
private int _sessionLost;
/// <summary>
/// #670 review M1 — 1 once a tracked subscription is known dead while the SESSION lives (it stopped
/// 1 once a tracked subscription is known dead while the SESSION lives (it stopped
/// publishing past its keep-alive window, or the server said BadNoSubscription / BadSubscriptionIdInvalid —
/// e.g. an outage longer than the subscription lifetime but shorter than the session timeout). Sticky until
/// the session is released: health stays Degraded and NOTHING advances <see cref="DriverHealth.LastSuccessfulRead"/>
/// (good keep-alives would otherwise keep a driver whose data plane is dead looking alive forever), so the
/// host's #527 watchdog re-initialises the driver and the re-subscribe recreates the subscription.
/// host's comms-loss watchdog re-initialises the driver and the re-subscribe recreates the subscription.
/// </summary>
private int _subscriptionLost;
/// <summary>#670 review M1 — ticks of the first good keep-alive that saw a tracked subscription not publishing
/// <summary>Ticks of the first good keep-alive that saw a tracked subscription not publishing
/// (0 = none stalled). Only the keep-alive thread and the session release touch it.</summary>
private long _publishingStoppedSinceTicks;
/// <summary>The last in-place recovery started (#670). Test seam: lets a test await it deterministically.</summary>
/// <summary>The last in-place recovery started. Test seam: lets a test await it deterministically.</summary>
private Task _recoveryTask = Task.CompletedTask;
/// <summary>#676 — 1 once <see cref="ConnectionLost"/> has been raised for the CURRENT session (once per session);
/// <summary>1 once <see cref="ConnectionLost"/> has been raised for the CURRENT session (once per session);
/// cleared when the session is released, so a re-initialised driver reports its next loss.</summary>
private int _connectionLostRaised;
/// <summary>#676 live gate A1 — closed-channel keep-alive failures (<see cref="IsClosedChannel"/>) in the current
/// <summary>Closed-channel keep-alive failures (<see cref="IsClosedChannel"/>) in the current
/// outage; reset by a good keep-alive and when the session is released. Two make a closed channel "sustained".</summary>
private int _closedChannelFailures;
@@ -306,35 +306,35 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// transient that the next good keep-alive contradicts).</summary>
private const int SustainedClosedChannelFailures = 2;
/// <summary>#676 — the trailing reconcile read scheduled by the last in-place recovery. Test seam.</summary>
/// <summary>The trailing reconcile read scheduled by the last in-place recovery. Test seam.</summary>
private Task _reconcileTask = Task.CompletedTask;
/// <summary>#676 — late notifications the replay guard dropped since it was armed, and the refs they were for;
/// <summary>Late notifications the replay guard dropped since it was armed, and the refs they were for;
/// summarised in ONE Information line when the window disarms. Guarded by <see cref="_replayGuardLock"/>.</summary>
private int _replayDrops;
private readonly HashSet<string> _replayDropRefs = new(StringComparer.Ordinal);
/// <summary>
/// Test seam (#676): how long after an in-place recovery the trailing reconcile read runs. Production: the
/// Test seam: how long after an in-place recovery the trailing reconcile read runs. Production: the
/// operation timeout plus one keep-alive interval — by then every request that was in flight across the stall
/// (including the Publish responses whose notifications the SDK can lose) has completed or timed out.
/// </summary>
internal Func<TimeSpan> PostRecoveryReconcileDelay { get; set; }
/// <summary>Test seam (#670 review M1): whether a subscription has stopped publishing. Production asks the SDK.</summary>
/// <summary>Test seam: whether a subscription has stopped publishing. Production asks the SDK.</summary>
internal Func<Subscription, bool> IsPublishingStopped { get; set; } = static s => s.Created && s.PublishingStopped;
/// <summary>Test seam (#670 review M1): how long a subscription may keep reporting stopped (measured on the
/// <summary>Test seam: how long a subscription may keep reporting stopped (measured on the
/// driver's keep-alive cadence) before it is declared dead. Production: one more subscription keep-alive window
/// plus 5 s, on top of the window the SDK's own <c>PublishingStopped</c> already waits.</summary>
internal Func<Subscription, TimeSpan> PublishingStallGrace { get; set; } = static s =>
TimeSpan.FromMilliseconds(Math.Max(s.CurrentPublishingInterval, 1) * (s.CurrentKeepAliveCount + 1d))
+ TimeSpan.FromSeconds(5);
/// <summary>#670 — the last value delivered per subscribed RawPath, so an outage can publish
/// <summary>The last value delivered per subscribed RawPath, so an outage can publish
/// <c>BadNoCommunication</c> with the value retained (the same shape the host's own comms-loss fan uses).</summary>
/// <summary>
/// #670 follow-up F2 — per RawPath, the source time (ticks) of the last Good value ACCEPTED from upstream (a
/// per RawPath, the source time (ticks) of the last Good value ACCEPTED from upstream (a
/// notification, or the recovery read). Last, not max: in steady state it simply follows the upstream clock,
/// so a clock that steps backwards is tracked rather than remembered as a high-water mark. It only seeds the
/// replay guard below; nothing is ever dropped against it outside that guard's window.
@@ -343,7 +343,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
new(StringComparer.Ordinal);
/// <summary>
/// #670 follow-up F2 — the REPLAY guard. Armed only by a same-session recovery (keep-alive bad→good), when the
/// the REPLAY guard. Armed only by a same-session recovery (keep-alive bad→good), when the
/// SDK was observed delivering a missed notification seconds late with an older source time. Per ref it holds a
/// HIGH-WATER MARK: seeded with the last Good upstream source time at arming, raised by the recovery read, and
/// advanced by EVERY notification accepted while the window is open. A notification whose source time is at or
@@ -402,7 +402,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, DataValueSnapshot> _lastValues =
new(StringComparer.Ordinal);
/// <summary>#670 — refs published Bad by the current outage and not yet re-published Good. A notification
/// <summary>Refs published Bad by the current outage and not yet re-published Good. A notification
/// clears its ref (fresh data beats the recovery read); the recovery read publishes only what is left.</summary>
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, byte> _awaitingRecovery =
new(StringComparer.Ordinal);
@@ -411,12 +411,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// throttles the per-notification health write to at most one per second.</summary>
private long _lastEvidenceStampTicks;
/// <summary>Clock for liveness stamps. Test seam (#670); production uses <see cref="TimeProvider.System"/>.</summary>
/// <summary>Clock for liveness stamps. Test seam; production uses <see cref="TimeProvider.System"/>.</summary>
internal TimeProvider Clock { get; set; } = TimeProvider.System;
/// <summary>
/// SDK telemetry for this instance's sessions: SDK warnings (keep-alive / publish / channel errors) go to the
/// driver's own logger (#670 — the shared <see cref="SdkTelemetry.Context"/> has no provider, which made every
/// driver's own logger (the shared <see cref="SdkTelemetry.Context"/> has no provider, which made every
/// SDK-side session error invisible).
/// </summary>
private readonly ITelemetryContext _sdkTelemetry;
@@ -449,14 +449,14 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <inheritdoc />
public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
// #630: InitializeAsync is reachable on a live driver with no teardown first (the IDriver contract
// InitializeAsync is reachable on a live driver with no teardown first (the IDriver contract
// allows it, and a reconnect retry can overlap a running attempt); `Session = session` below would otherwise orphan the previous session,
// its keep-alive handler and any reconnect handler.
await ReleaseSessionAsync(cancellationToken).ConfigureAwait(false);
_health = new DriverHealth(DriverState.Initializing, null, null);
try
{
// #516: re-parse the supplied DriverConfig so a config change delivered through the IDriver
// re-parse the supplied DriverConfig so a config change delivered through the IDriver
// contract is honoured. Without this the driver keeps serving the options it was CONSTRUCTED
// with — the endpoint, security policy and tag set were all frozen at construction, and only
// secret rotation was picked up.
@@ -467,7 +467,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
var appConfig = await BuildApplicationConfigurationAsync(cancellationToken).ConfigureAwait(false);
// #278: when a DiscoveryUrl is configured, FindServers/GetEndpoints on it first and try the
// 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.
IReadOnlyList<string> discovered = [];
if (!string.IsNullOrWhiteSpace(_options.DiscoveryUrl))
@@ -536,7 +536,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
"Tried:\n " + string.Join("\n ", attemptErrors),
attemptErrors.Select(e => new InvalidOperationException(e)));
// Wire the session's keep-alive channel into HostState + health (#670). OPC UA keep-alives
// Wire the session's keep-alive channel into HostState + health. OPC UA keep-alives
// are authoritative for session liveness: the SDK pings on KeepAliveInterval. A good one is
// liveness evidence (advances LastSuccessfulRead); a bad one degrades health and publishes the
// outage. Recovery from a session that does not come back is the host's comms-loss watchdog
@@ -577,7 +577,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private async Task<ApplicationConfiguration> BuildApplicationConfigurationAsync(CancellationToken ct)
{
// The ITelemetryContext overload is the non-obsolete ctor; SDK warnings reach the driver's
// logger (#670) when one was supplied.
// logger when one was supplied.
var app = new ApplicationInstance(_sdkTelemetry)
{
ApplicationName = _options.SessionName,
@@ -609,7 +609,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
TrustedIssuerCertificates = new CertificateTrustList
{
StoreType = CertificateStoreType.Directory,
// #277: the issuer store's crl/ sub-folder is where the SDK reads issuer CRLs, so an
// the issuer store's crl/ sub-folder is where the SDK reads issuer CRLs, so an
// operator-supplied path is the CRL knob. Unset = the historical default.
StorePath = string.IsNullOrWhiteSpace(_options.CertificateValidation.IssuerStorePath)
? Path.Combine(pkiRoot, "issuers")
@@ -648,7 +648,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// fail with BadCertificateChainIncomplete, BadCertificateTimeInvalid, or
// BadCertificateHostNameInvalid, not only BadCertificateUntrusted. Only accepting
// the latter would silently fail for those certs. A REVOKED certificate is the one
// exception (#277): auto-accept is for dev self-signed certs, never for a cert its issuer
// exception: auto-accept is for dev self-signed certs, never for a cert its issuer
// has explicitly withdrawn.
CertificateValidationEventHandler handler = (_, e) =>
{
@@ -678,7 +678,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
return config;
}
/// <summary>True for the two hard "this certificate (or its issuer) is revoked" results (#277).</summary>
/// <summary>True for the two hard "this certificate (or its issuer) is revoked" results.</summary>
/// <param name="status">The SDK's certificate-validation status.</param>
/// <returns><c>true</c> when the status is Revoked / IssuerRevoked.</returns>
internal static bool IsRevocationFailure(StatusCode status) =>
@@ -695,7 +695,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
ResolveEndpointCandidates(opts, []);
/// <summary>
/// Resolve the ordered failover list with optional discovery results (#278). The configured
/// Resolve the ordered failover list with optional discovery results. The configured
/// endpoints always come FIRST — a discovered endpoint can only ever be a fallback, never outrank or
/// replace the server the operator named. Discovered URLs follow, de-duplicated case-insensitively.
/// With no discovered URLs the result is exactly the pre-discovery behaviour.
@@ -774,7 +774,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
internal readonly record struct DiscoveredEndpoint(string ApplicationUri, string Url);
/// <summary>
/// Decide which discovered endpoints may be used (#278). An LDS can register many servers (identical
/// Decide which discovered endpoints may be used. An LDS can register many servers (identical
/// line PLCs, a gateway plus a historian), and the first one that accepts a connection would be bound
/// silently — mis-attributing every value and write. So: with <paramref name="serverUri"/> set, only
/// that ApplicationUri's endpoints; unset and exactly one distinct server, that server; unset and
@@ -825,7 +825,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
};
/// <summary>
/// Range checks for the subscription-tuning and discovery options (#273/#278). Throws at
/// Range checks for the subscription-tuning and discovery options. Throws at
/// <see cref="InitializeAsync"/> so a bad config fails like the namespace-kind check does rather
/// than surfacing later as a server-side <c>BadInvalidArgument</c> on every subscribe.
/// </summary>
@@ -953,13 +953,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
$"No endpoint at '{endpointUrl}' matches SecurityPolicy={policy} + SecurityMode={mode}. " +
$"Server advertises: {advertised}");
}
// #676: connect where the operator pointed us, not where the server says it lives.
// connect where the operator pointed us, not where the server says it lives.
match.EndpointUrl = RewriteEndpointUrl(match.EndpointUrl, endpointUrl);
return match;
}
/// <summary>
/// Gitea #676 — the address to open the session on. A server reports its endpoints with ITS view of its own
/// the address to open the session on. A server reports its endpoints with ITS view of its own
/// address; behind NAT, a port map, a container port publish or a proxy that address is unreachable from here
/// (or bypasses the proxy). When the advertised URL's scheme matches the configured one, the configured host
/// AND port (when it names one) replace the advertised ones and the advertised path is kept — the SDK's own
@@ -1049,8 +1049,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <summary>
/// Detaches the keep-alive handler and closes + disposes the current session. The session part of
/// <see cref="ShutdownAsync"/>; also run at the top of <see cref="InitializeAsync"/> so a re-initialise on a
/// live driver (#630) does not orphan the previous session. Subscriptions are NOT touched here. Clears the
/// #670 outage latch, so the next session reports its own loss.
/// live driver does not orphan the previous session. Subscriptions are NOT touched here. Clears the
/// outage latch, so the next session reports its own loss.
/// </summary>
private async Task ReleaseSessionAsync(CancellationToken cancellationToken)
{
@@ -1069,7 +1069,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
Session = null;
}
// #670: bound the close — against a dead upstream (the comms-loss watchdog's whole use case) an unbounded
// bound the close — against a dead upstream (the comms-loss watchdog's whole use case) an unbounded
// CloseSession would sit out the full operation timeout on every reconnect attempt — and skip it outright
// when the keep-alive already says the session is unreachable (review L3).
var sessionKnownLost = Volatile.Read(ref _sessionLost) == 1;
@@ -1087,7 +1087,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
Interlocked.Exchange(ref _sessionLost, 0);
Interlocked.Exchange(ref _subscriptionLost, 0);
Interlocked.Exchange(ref _publishingStoppedSinceTicks, 0);
// #676: re-arm the definitive-loss signal for the next session.
// re-arm the definitive-loss signal for the next session.
Interlocked.Exchange(ref _connectionLostRaised, 0);
Interlocked.Exchange(ref _closedChannelFailures, 0);
// Review of 3b88056f: the released session's post-recovery timers must not outlive it.
@@ -1116,7 +1116,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// after close anyway. Before deleting each subscription we detach the Notification
// handlers we attached at subscribe time so the SDK's invocation list no longer
// holds the driver instance through the closure.
// #670: against a session already known lost (bad keep-alive) the wire deletes cannot succeed and would each
// against a session already known lost (bad keep-alive) the wire deletes cannot succeed and would each
// sit out the operation timeout — skip them; disposing the session releases the local objects.
var sessionAlive = Volatile.Read(ref _sessionLost) == 0;
foreach (var rs in _subscriptions.Values)
@@ -1145,7 +1145,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
_replayDropRefs.Clear();
}
_awaitingRecovery.Clear();
// #619 re-review: the last-told alarm states (and ack targets) deliberately SURVIVE a shutdown. A
// the last-told alarm states (and ack targets) deliberately SURVIVE a shutdown. A
// ReinitializeAsync (comms-loss watchdog / Force Reconnect) is followed by the host re-subscribing the
// same set over condition nodes it did NOT rebuild; forgetting here would make the post-subscribe
// ConditionRefresh re-raise every active+acked alarm (an un-ack flicker). BeginAlarmSubscription forgets
@@ -1199,7 +1199,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// The read itself, also used by the #670 in-place recovery. <c>TransportOk</c> is false when the wire read
/// The read itself, also used by the in-place recovery. <c>TransportOk</c> is false when the wire read
/// did not happen or threw (every result is then a local <c>BadCommunicationError</c>, not upstream data).
/// <paramref name="expectedSession"/>, when given, must still be the current session inside the gate — a
/// recovery overtaken by a re-initialise neither reads on, nor writes the health of, the new session.
@@ -1763,7 +1763,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// Floor the publishing interval at 50ms — OPC UA servers routinely negotiate
// minimum-supported intervals up anyway, but sending sub-50ms wastes negotiation
// bandwidth on every subscription create. #273: the options may pin the interval.
// bandwidth on every subscription create. the options may pin the interval.
var intervalMs = ResolvePublishingIntervalMs(_options, publishingInterval);
var subscription = new Subscription(telemetry: null!, new SubscriptionOptions
@@ -1875,7 +1875,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
{
_diag.Record(OpcUaClientDiagnostics.DataChange);
if (StatusCode.IsBad(dv.StatusCode)) _diag.Record(OpcUaClientDiagnostics.BadStatusValue);
// #670: a delivered notification is liveness evidence — the subscription path never calls ReadAsync, so
// a delivered notification is liveness evidence — the subscription path never calls ReadAsync, so
// without this a busy subscription-only driver's LastSuccessfulRead stayed at its connect time.
RecordLivenessEvidence();
var snapshot = new DataValueSnapshot(
@@ -1891,7 +1891,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
if (IsLateReplay(fullRef, snapshot.SourceTimestampUtc, out var newest))
{
_diag.Record(OpcUaClientDiagnostics.StaleNotificationDropped);
// #676: the OTel counter and the Debug line below are invisible on a default-configured node; the
// the OTel counter and the Debug line below are invisible on a default-configured node; the
// per-recovery Information summary logged at disarm is what makes the guard observable.
lock (_replayGuardLock)
{
@@ -1912,7 +1912,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
}
/// <summary>#670 F2 — remember the last accepted Good upstream source time for <paramref name="fullRef"/>.</summary>
/// <summary>Remember the last accepted Good upstream source time for <paramref name="fullRef"/>.</summary>
private void RecordUpstreamGood(string fullRef, DataValueSnapshot snapshot)
{
if (snapshot.SourceTimestampUtc is not { } src || !StatusCode.IsGood(snapshot.StatusCode)) return;
@@ -1920,7 +1920,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #670 F2 — true when the replay window is open and <paramref name="source"/> is at or below
/// true when the replay window is open and <paramref name="source"/> is at or below
/// <paramref name="fullRef"/>'s high-water mark. Otherwise (inside the window) the notification is accepted and
/// its source time becomes the ref's new mark, so the ref stays guarded for the whole window. A notification
/// with no source time passes without moving the mark. An expired window disarms everything.
@@ -1950,7 +1950,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <summary>
/// Expire the replay guard armed until <paramref name="until"/> — a no-op when it was re-armed or already disarmed
/// since — and log ONE Information summary of what it dropped (#676). The guard's OTel counter and per-drop Debug
/// since — and log ONE Information summary of what it dropped. The guard's OTel counter and per-drop Debug
/// line are invisible on a default-configured node, so before this a recovery's drops left no trace at all.
/// </summary>
/// <param name="until">The expiry the caller observed; only that arming is disarmed.</param>
@@ -1977,7 +1977,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
"notifications across {Refs} refs after recovery.", _driverInstanceId, drops, refs);
/// <summary>
/// #670 F2 — arm the replay guard on a same-session recovery: every ref with a known Good upstream source time,
/// arm the replay guard on a same-session recovery: every ref with a known Good upstream source time,
/// for max(30 s, 2 × the longest tracked subscription keep-alive window).
/// </summary>
/// <returns>The window's expiry in clock ticks.</returns>
@@ -2006,7 +2006,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #676 — disarm the replay guard (and log its summary) when its window ends, even if no notification arrives to
/// disarm the replay guard (and log its summary) when its window ends, even if no notification arrives to
/// disarm it lazily in <see cref="IsLateReplay"/> — a quiet subscription would otherwise never log the summary.
/// </summary>
private async Task DisarmReplayGuardWhenDueAsync(long until, CancellationToken ct)
@@ -2025,13 +2025,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #670 — advance <see cref="DriverHealth.LastSuccessfulRead"/> on upstream traffic (a notification), at most
/// advance <see cref="DriverHealth.LastSuccessfulRead"/> on upstream traffic (a notification), at most
/// once per second. The state is left as it is: a notification is evidence of comms, but the keep-alive
/// is what declares an outage over.
/// </summary>
private void RecordLivenessEvidence()
{
// A dead subscription (M1) must keep the stamp frozen even while OTHER subscriptions still deliver.
// A dead subscription must keep the stamp frozen even while OTHER subscriptions still deliver.
if (Volatile.Read(ref _subscriptionLost) == 1) return;
var now = Clock.GetUtcNow().UtcDateTime;
var last = Interlocked.Read(ref _lastEvidenceStampTicks);
@@ -2041,7 +2041,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// Read-modify-write of <see cref="_health"/> as a CAS loop (#670 review L1): the keep-alive timer, publish
/// Read-modify-write of <see cref="_health"/> as a CAS loop: the keep-alive timer, publish
/// threads and the recovery task all derive the next health from the current one.
/// </summary>
/// <param name="next">Maps the current health to the next one, or null to leave it unchanged.</param>
@@ -2114,7 +2114,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// Pre-resolve the source-node filter set so the per-event notification handler can
// match in O(1) without re-parsing on every event.
// #619: under v3 the host passes RawPaths, never upstream node ids. Translate each to the upstream
// under v3 the host passes RawPaths, never upstream node ids. Translate each to the upstream
// source id its tag authored (TagConfig.nodeId) so the per-event match compares like with like.
// Keys are server-stable (AlarmIndexKey) so a remote namespace reorder cannot orphan them.
var sessionForResolve = Session;
@@ -2165,7 +2165,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
BrowsePath = [], // empty path = the condition node itself
AttributeId = Attributes.NodeId,
});
// #619 review: the host derives Active/Acked solely from AlarmEventArgs.Kind, so the condition state
// the host derives Active/Acked solely from AlarmEventArgs.Kind, so the condition state
// must be selected. TWO-element browse paths — a single "ActiveState/Id" QualifiedName names nothing.
filter.SelectClauses.Add(new SimpleAttributeOperand
{
@@ -2179,7 +2179,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
BrowsePath = [new QualifiedName(BrowseNames.AckedState), new QualifiedName(BrowseNames.Id)],
AttributeId = Attributes.Value,
});
// #619 re-review: BranchId — a non-null one marks a condition BRANCH event (a previous state, with its own
// BranchId — a non-null one marks a condition BRANCH event (a previous state, with its own
// EventId). Only the trunk (null BranchId) is the condition's current state.
filter.SelectClauses.Add(new SimpleAttributeOperand
{
@@ -2188,7 +2188,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
AttributeId = Attributes.Value,
});
// Set by CreateAlarmEventItemAsync so a failure after the handler is attached can detach it (#662).
// Set by CreateAlarmEventItemAsync so a failure after the handler is attached can detach it.
MonitoredItem? eventItem = null;
MonitoredItemNotificationEventHandler? notifHandler = null;
@@ -2207,7 +2207,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
catch
{
// #662: the host retries a failed alarm subscribe from its reconcile, so a half-built subscription
// the host retries a failed alarm subscribe from its reconcile, so a half-built subscription
// left on the session would accumulate one per retry for the length of an outage. Detach the
// handler first — the remove is best-effort and can itself fail against a broken server — and
// bound it, since _gate is held. OnEventNotification also drops anything from an unregistered id.
@@ -2225,7 +2225,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
throw;
}
// #619: a new event item only reports FUTURE transitions — a condition already active upstream would
// a new event item only reports FUTURE transitions — a condition already active upstream would
// stay invisible until it next changed. ConditionRefresh re-delivers every retained condition's
// current state through the normal path (deduplicated against the last-told state).
await TryConditionRefreshAsync(subscription, cancellationToken).ConfigureAwait(false);
@@ -2314,7 +2314,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
var callRequests = new CallMethodRequestCollection();
foreach (var ack in acknowledgements)
{
// #619: the host acks by RawPath; Acknowledge must hit the upstream CONDITION node.
// the host acks by RawPath; Acknowledge must hit the upstream CONDITION node.
// The remembered target pairs the condition node with the EventId of the event that named it,
// so the ack can never mix one condition's node with another's EventId. Nothing seen yet ⇒ the
// tag's authored node (correct when the tag was authored on the condition node), else the id
@@ -2400,7 +2400,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
MonitoredItemNotificationEventArgs args)
{
if (args.NotificationValue is not EventFieldList efl) return;
// #662 review: only a subscription SubscribeAlarmsAsync completed (and nothing has since released) may
// only a subscription SubscribeAlarmsAsync completed (and nothing has since released) may
// deliver. A half-built one whose cleanup failed against a broken server can survive on the session;
// without this it would feed RouteAlarmEvent alongside the real one.
if (!_alarmSubscriptions.ContainsKey(handle.Id)) return;
@@ -2409,10 +2409,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #619 re-review: open (or re-open) the host's alarm subscription over <paramref name="sourceNodeIds"/>.
/// open (or re-open) the host's alarm subscription over <paramref name="sourceNodeIds"/>.
/// A CHANGED set means the host applied an alarm-bearing delta, so every last-told state is forgotten and the
/// post-subscribe ConditionRefresh re-reports as first sight. Since #641 a rebuild KEEPS native condition state,
/// so the host may hold ANY state here — which is why first sight is flagged (#656/#657) rather than assuming
/// post-subscribe ConditionRefresh re-reports as first sight. A rebuild now KEEPS native condition state,
/// so the host may hold ANY state here — which is why first sight is flagged rather than assuming
/// an inactive+acked default. The SAME set (a reinit / reconnect re-subscribe) keeps
/// them, so the refresh copy of an already-reported state emits nothing. Ack targets of refs no longer
/// subscribed are pruned either way.
@@ -2431,7 +2431,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #619 — route one upstream event: drop refresh markers (a RefreshRequired asks for a new refresh), project
/// route one upstream event: drop refresh markers (a RefreshRequired asks for a new refresh), project
/// it, and emit the kinds that move the host from the state last told to the event's. An event that changes
/// nothing the host shows (a ConditionRefresh copy) emits nothing.
/// </summary>
@@ -2477,7 +2477,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
if (prior == told) return;
kinds = [AlarmTransitionKind.Unspecified];
}
// #656: on first sight (a start or deploy respawn) this instance is RE-STATING upstream's current state,
// on first sight (a start or deploy respawn) this instance is RE-STATING upstream's current state,
// not reporting a transition it watched — flagged so the host writes no duplicate history row when its
// condition already shows exactly this. History only; the host still projects the state.
foreach (var kind in kinds)
@@ -2485,7 +2485,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
}
/// <summary>#619 re-review — what the host was last told about one condition: its state plus the message and
/// <summary>What the host was last told about one condition: its state plus the message and
/// exact severity, so a refresh copy is recognised as a duplicate.</summary>
/// <param name="Active">ActiveState/Id last told.</param>
/// <param name="Acked">AckedState/Id last told.</param>
@@ -2517,7 +2517,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|| code == StatusCodes.BadNodeIdUnknown;
/// <summary>
/// #619 — call ConditionRefresh for <paramref name="subscription"/> so conditions already active upstream
/// call ConditionRefresh for <paramref name="subscription"/> so conditions already active upstream
/// are reported. Never throws: an unsupported server is logged once, any other failure warns.
/// </summary>
/// <param name="subscription">The (created) alarm subscription.</param>
@@ -2551,8 +2551,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #619 — ConditionRefresh every alarm subscription on the current session (matched by display name): after
/// a keep-alive outage the session survived (#670) and on a RefreshRequired event. Events missed during the
/// ConditionRefresh every alarm subscription on the current session (matched by display name): after
/// a keep-alive outage the session survived and on a RefreshRequired event. Events missed during the
/// outage reach the host through the normal deduplicated path.
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
@@ -2590,9 +2590,9 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private const string AlarmSubscriptionNamePrefix = "opcua-alarm-sub-";
/// <summary>
/// #619 review — the <see cref="AlarmTransitionKind"/> sequence that moves the host's
/// <c>NativeAlarmProjector</c> (which knows only kinds: Raise ⇒ active+unacked — or, on an already-active condition, a re-statement keeping the ack (#647) — Acknowledge ⇒ acked,
/// ActiveAcknowledged ⇒ active+acked in one step (#656), InactiveUnacknowledged ⇒ inactive+unacked in one step (#657), Clear ⇒ inactive keeping acked) from <paramref name="prior"/> to <paramref name="target"/>. A single
/// the <see cref="AlarmTransitionKind"/> sequence that moves the host's
/// <c>NativeAlarmProjector</c> (which knows only kinds: Raise ⇒ active+unacked — or, on an already-active condition, a re-statement keeping the ack — Acknowledge ⇒ acked,
/// ActiveAcknowledged ⇒ active+acked in one step, InactiveUnacknowledged ⇒ inactive+unacked in one step, Clear ⇒ inactive keeping acked) from <paramref name="prior"/> to <paramref name="target"/>. A single
/// upstream event can need two (an alarm that went active and was acknowledged between two notifications).
/// No state change ⇒ empty (the caller decides whether a message/severity change warrants an Unspecified).
/// </summary>
@@ -2600,8 +2600,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <param name="target">The upstream event's ActiveState/Id + AckedState/Id.</param>
/// <param name="priorKnown">
/// False when this driver instance has told the host nothing about the condition yet (first sight after a
/// start or a deploy respawn), so <paramref name="prior"/> is only the projector's default. Gitea #647 review:
/// the host now treats a Raise on an already-active condition as a re-statement that KEEPS its ack, so an
/// start or a deploy respawn), so <paramref name="prior"/> is only the projector's default. The host now treats a Raise on an already-active condition as a re-statement that KEEPS its ack, so an
/// upstream that says <i>unacknowledged</i> must then be told with <see cref="AlarmTransitionKind.Retrigger"/>
/// — the upstream's ack state is authoritative, and the host may be holding an ack from before the respawn.
/// </param>
@@ -2609,7 +2608,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
internal static IReadOnlyList<AlarmTransitionKind> AlarmTransitions(
(bool Active, bool Acked) prior, (bool Active, bool Acked) target, bool priorKnown = true)
{
// Gitea #657: on first sight the host may hold ANY state (it retains a still-deployed condition across a
// on first sight the host may hold ANY state (it retains a still-deployed condition across a
// respawn), so an inactive target is stated in kinds that land on it from every host state: inactive+unacked
// as ONE InactiveUnacknowledged; inactive+acked as Clear then Acknowledge (flagged by the caller, so a host
// already showing it writes no row, and a host retaining it Active gets a real "Cleared"). Pre-fix an
@@ -2633,7 +2632,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
{
// Active+unacked: a fresh raise, or a re-arm of an active-acked condition.
(true, false) => [prior.Active ? AlarmTransitionKind.Retrigger : AlarmTransitionKind.Raise],
// Active+acked from inactive: ONE atomic ActiveAcknowledged (Gitea #656) — Raise-then-Acknowledge showed
// Active+acked from inactive: ONE atomic ActiveAcknowledged — Raise-then-Acknowledge showed
// clients an Active+UNacked intermediate event before the ack.
(true, true) => prior.Active
? [AlarmTransitionKind.Acknowledge]
@@ -2643,7 +2642,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
? prior.Acked ? [AlarmTransitionKind.Clear] : [AlarmTransitionKind.Clear, AlarmTransitionKind.Acknowledge]
: [AlarmTransitionKind.Acknowledge],
// Inactive+UNacked (went active and cleared unacknowledged — e.g. first seen by a ConditionRefresh): ONE
// atomic InactiveUnacknowledged (Gitea #657) — Raise/Retrigger-then-Clear showed clients the condition
// atomic InactiveUnacknowledged — Raise/Retrigger-then-Clear showed clients the condition
// Active again for an instant. From Active+unacked a plain Clear already lands there.
(false, false) => prior is (true, false)
? [AlarmTransitionKind.Clear]
@@ -2652,7 +2651,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #619 — index an alarm subscription's source refs by UPSTREAM source id. The host (v3) subscribes with
/// index an alarm subscription's source refs by UPSTREAM source id. The host (v3) subscribes with
/// the alarm tags' <b>RawPaths</b>; an upstream event carries its own source NodeId, so the match key is
/// the upstream id the tag authored and the value is the RawPath to report back. A ref
/// <paramref name="resolveUpstream"/> cannot resolve is kept verbatim (direct upstream-id use).
@@ -2670,11 +2669,17 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #619 — project one upstream event into an <see cref="AlarmEventArgs"/>. <c>ConditionId</c> and
/// Project one upstream event into an <see cref="AlarmEventArgs"/>. <c>ConditionId</c> and
/// <c>SourceNodeId</c> are the authored RawPath, because <c>DriverHostActor</c> routes native alarms on
/// (driver, RawPath); the upstream condition node (needed to acknowledge) is handed to
/// <paramref name="rememberCondition"/>. Null when the event's source is not an authored one.
/// </summary>
/// <param name="fields">The event's select-clause field values.</param>
/// <param name="sourceIndex">Upstream source id → authored RawPath.</param>
/// <param name="handle">The alarm subscription handle the event belongs to.</param>
/// <param name="keyOf">Maps an upstream NodeId to its stable string key.</param>
/// <param name="rememberCondition">Callback that records the upstream condition node for later acknowledgement.</param>
/// <returns>The projected event, or null when the event is not for an authored source.</returns>
internal static AlarmEventArgs? ProjectEvent(
IReadOnlyList<Variant> fields,
IReadOnlyDictionary<string, string> sourceIndex,
@@ -2685,6 +2690,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <summary>As the five-argument overload, also returning the event's (ActiveState/Id, AckedState/Id) through
/// <c>state</c> when it is an alarm condition (null otherwise).</summary>
/// <param name="fields">The event's select-clause field values.</param>
/// <param name="sourceIndex">Upstream source id → authored RawPath.</param>
/// <param name="handle">The alarm subscription handle the event belongs to.</param>
/// <param name="keyOf">Maps an upstream NodeId to its stable string key.</param>
/// <param name="rememberCondition">Callback that records the upstream condition node for later acknowledgement.</param>
/// <param name="state">Receives the event's (Active, Acked) state when it is an alarm condition; otherwise null.</param>
/// <returns>The projected event, or null when the event is not for an authored source.</returns>
internal static AlarmEventArgs? ProjectEvent(
IReadOnlyList<Variant> fields,
IReadOnlyDictionary<string, string> sourceIndex,
@@ -2745,17 +2757,17 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
Message: message,
Severity: MapSeverity(severity),
SourceTimestampUtc: time,
// #626: the upstream severity is already the exact Part 9 value — carry it, don't re-bucket.
// the upstream severity is already the exact Part 9 value — carry it, don't re-bucket.
OpcUaSeverity: severity == 0 ? null : severity);
}
/// <summary>#619 — what Acknowledge needs for one RawPath: the upstream condition node (server-stable
/// <summary>What Acknowledge needs for one RawPath: the upstream condition node (server-stable
/// reference) and the EventId of the event that named it.</summary>
/// <param name="ConditionRef">Upstream condition NodeId, rendered by <see cref="AlarmIndexKey"/>.</param>
/// <param name="EventId">EventId of the most recent event seen for that condition.</param>
internal readonly record struct AlarmAckTarget(string ConditionRef, byte[] EventId);
/// <summary>#619 — the key both sides of the alarm index use: server-stable (<c>nsu=</c>) when a map is
/// <summary>The key both sides of the alarm index use: server-stable (<c>nsu=</c>) when a map is
/// available, so a remote namespace-table reorder cannot orphan it.</summary>
/// <param name="map">The current session's namespace map, or null.</param>
/// <param name="nodeId">The NodeId to key.</param>
@@ -2816,7 +2828,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
return [new HostConnectivityStatus(HostName, _hostState, _hostStateChangedUtc)];
}
/// <summary>Hook the SDK's publish-side events into the diagnostics counters (#276).</summary>
/// <summary>Hook the SDK's publish-side events into the diagnostics counters.</summary>
/// <param name="session">The session to observe.</param>
private void AttachDiagnostics(ISession session)
{
@@ -2854,7 +2866,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
};
/// <summary>
/// Session keep-alive handler (Gitea #670). A good keep-alive is liveness evidence: it advances
/// Session keep-alive handler. A good keep-alive is liveness evidence: it advances
/// <see cref="DriverHealth.LastSuccessfulRead"/>, and after a bad one it ends the outage in place (the session
/// survived — e.g. a network blip): health back to Healthy and the outage's Bad refs re-read and re-published
/// Good, because a server whose subscription survived will not resend values that did not change. A bad
@@ -2864,10 +2876,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <remarks>
/// There is deliberately no <c>SessionReconnectHandler</c> any more. In SDK 1.5.378 it retried forever, its
/// session-recreate path cloned subscriptions the driver never re-tracked, and it kept health Healthy while
/// it did so — the #670 symptom. A session that does not come back keeps health Degraded with the read stamp
/// frozen, which is exactly what the host's #527 comms-loss watchdog trips on: ShutdownAsync + InitializeAsync
/// it did so — the symptom. A session that does not come back keeps health Degraded with the read stamp
/// frozen, which is exactly what the host's comms-loss watchdog trips on: ShutdownAsync + InitializeAsync
/// + re-subscribe, whose initial values come back Good. When the keep-alive status proves the session is gone
/// for good (<see cref="IsDefinitiveSessionLoss"/>) the driver also raises <see cref="ConnectionLost"/> (#676),
/// for good (<see cref="IsDefinitiveSessionLoss"/>) the driver also raises <see cref="ConnectionLost"/>,
/// so the host runs that sequence at once instead of after the watchdog's silence window.
/// </remarks>
private void OnKeepAlive(ISession sender, KeepAliveEventArgs e)
@@ -2880,7 +2892,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
{
Interlocked.Exchange(ref _closedChannelFailures, 0);
TransitionTo(HostState.Running);
// M1: the session answers but a subscription is dead — no stamp, no recovery; the watchdog reinit is the fix.
// The session answers but a subscription is dead — no stamp, no recovery; the watchdog reinit is the fix.
if (Volatile.Read(ref _subscriptionLost) == 1)
{
Interlocked.Exchange(ref _sessionLost, 0);
@@ -2920,7 +2932,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
TransitionTo(HostState.Stopped);
_diag.Record(OpcUaClientDiagnostics.KeepAliveMiss);
UpdateHealth(h => new DriverHealth(DriverState.Degraded, h.LastSuccessfulRead, $"keep-alive: {e.Status}"));
// #676: the first bad keep-alive is often ambiguous and a definitive one follows, so this is checked on EVERY
// the first bad keep-alive is often ambiguous and a definitive one follows, so this is checked on EVERY
// bad keep-alive — but only after the outage below has been published, so the Bad reaches subscribers first.
var keepAliveCode = e.Status?.StatusCode ?? StatusCodes.Good;
var definitive = IsDefinitiveSessionLoss(keepAliveCode)
@@ -2940,7 +2952,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #676 live gate A1 — the connection under the session is CLOSED (not merely silent). A real upstream process stop
/// the connection under the session is CLOSED (not merely silent). A real upstream process stop
/// (docker restart, SIGINT, docker kill) never produced a session status on the docker-dev gate: the keep-alives
/// reported <c>BadSecureChannelClosed</c> once, then <c>BadConnectionClosed</c> interleaved with
/// <c>BadNoCommunication</c> for the whole outage. Reproduced in-process (a proxy that resets every connection
@@ -2957,11 +2969,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
status == StatusCodes.BadSecureChannelClosed || status == StatusCodes.BadConnectionClosed;
/// <summary>
/// #676 — keep-alive statuses that prove the session can NEVER recover in place, so waiting out the #527
/// watchdog would only delay the inevitable re-initialise. The server forgot the session
/// keep-alive statuses that prove the session can NEVER recover in place, so waiting out the
/// comms-loss watchdog would only delay the inevitable re-initialise. The server forgot the session
/// (<c>BadSessionIdInvalid</c> — what a re-opened channel to a restarted server answers), closed it
/// (<c>BadSessionClosed</c>) or never activated it (<c>BadSessionNotActivated</c>); or the server HALTED
/// (<c>BadServerHalted</c>) — measured on the #676 restart wire test, the SDK never re-opens a channel the
/// (<c>BadServerHalted</c>) — measured on the restart wire test, the SDK never re-opens a channel the
/// server halted: 15 s after the server was back the same session still failed every request with
/// <c>BadServerHalted</c>, so a halted session is dead for good. A closed connection is definitive too, but only
/// once sustained — see <see cref="IsClosedChannel"/>. Everything else — <c>BadNoCommunication</c>,
@@ -2976,7 +2988,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|| status == StatusCodes.BadSessionNotActivated
|| status == StatusCodes.BadServerHalted;
/// <summary>#676 — raise <see cref="ConnectionLost"/> once for the current session, isolating a faulting subscriber.</summary>
/// <summary>Raise <see cref="ConnectionLost"/> once for the current session, isolating a faulting subscriber.</summary>
/// <param name="reason">Why the connection is definitively gone, for the host's log.</param>
private void RaiseConnectionLost(string reason)
{
@@ -2993,7 +3005,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #670 review M1 — the display name of a tracked subscription that has reported "publishing stopped" for
/// the display name of a tracked subscription that has reported "publishing stopped" for
/// longer than its grace, measured across consecutive good keep-alives; null when none has.
/// </summary>
private string? FindStalledSubscription(DateTime now)
@@ -3020,7 +3032,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #670 review M1 — the server dropped a subscription the driver still tracks. Degraded with the read stamp
/// the server dropped a subscription the driver still tracks. Degraded with the read stamp
/// frozen (sticky until the session is released), and the outage published once, so the host's watchdog
/// re-initialises and re-subscribes.
/// </summary>
@@ -3028,7 +3040,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <param name="now">Detection time.</param>
/// <param name="serverReported">True when the SERVER said the subscription is gone (BadNoSubscription /
/// BadSubscriptionIdInvalid) — definitive, so <see cref="ConnectionLost"/> is raised. False for the publishing-stall
/// heuristic, an inference from silence that stays with the #527 watchdog (review of 3b88056f).</param>
/// heuristic, an inference from silence that stays with the comms-loss watchdog.</param>
private void DeclareSubscriptionLost(string reason, DateTime now, bool serverReported)
{
if (Interlocked.Exchange(ref _subscriptionLost, 1) == 1) return;
@@ -3037,15 +3049,15 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
"OpcUaClientDriver '{DriverInstanceId}': {Reason}; subscribed values are BadNoCommunication until the " +
"host re-initialises the driver and re-subscribes.", _driverInstanceId, reason);
if (Volatile.Read(ref _sessionLost) == 0) PublishCommsLoss(now);
// #676: a subscription the SERVER says is gone never comes back on this session — only the re-subscribe after a
// a subscription the SERVER says is gone never comes back on this session — only the re-subscribe after a
// re-initialise recreates it — so ask the host now rather than after the watchdog's 90 s. The stall heuristic is
// an inference, not a server statement, and keeps going through the watchdog.
if (serverReported) RaiseConnectionLost($"subscription lost: {reason}");
}
/// <summary>
/// Session PublishError: always counted (#276); a BadNoSubscription / BadSubscriptionIdInvalid naming a
/// subscription the driver tracks means the server dropped it while the session lived (#670 review M1).
/// Session PublishError: always counted; a BadNoSubscription / BadSubscriptionIdInvalid naming a
/// subscription the driver tracks means the server dropped it while the session lived.
/// </summary>
private void OnPublishError(object? sender, PublishErrorEventArgs e) =>
HandlePublishError(sender, e.Status?.StatusCode ?? StatusCodes.Good, e.SubscriptionId);
@@ -3068,7 +3080,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #670 — publish the start of an outage: <c>BadNoCommunication</c> once per (subscription, ref) with the last
/// publish the start of an outage: <c>BadNoCommunication</c> once per (subscription, ref) with the last
/// delivered value retained, and a quality-only annotation on every subscribed alarm condition (no state
/// change — an outage says nothing about whether the alarm is active).
/// </summary>
@@ -3097,13 +3109,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #670 — the session survived the outage: re-read the refs still awaiting recovery and publish them (a ref
/// the session survived the outage: re-read the refs still awaiting recovery and publish them (a ref
/// a notification already refreshed is skipped — fresh data beats the read), restore alarm-condition quality
/// and ConditionRefresh so transitions missed during the outage are re-reported (deduplicated). A failed
/// read re-arms the outage so the next good keep-alive tries again.
/// </summary>
/// <param name="session">The session whose keep-alive recovered. Every effect — publishing, re-arming the
/// latch — is conditional on it still being the current session and still out of outage (#670 review M2/L2): a
/// latch — is conditional on it still being the current session and still out of outage: a
/// recovery overtaken by a re-initialise must not leak its outcome onto the NEW session.</param>
private async Task RecoverAfterOutageAsync(ISession session)
{
@@ -3165,7 +3177,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
/// <summary>
/// #676 — the trailing reconcile read after an in-place recovery. Found by the TCP-stall wire test: a value change
/// the trailing reconcile read after an in-place recovery. Found by the TCP-stall wire test: a value change
/// the server published just after a stall ended rode a Publish response that had been in flight across the
/// stall; the SDK timed that request out (<c>BadTimeout</c>), discarded the response, and never republished the
/// message (the following keep-alives advanced the sequence number past it). The node stayed on the value from
@@ -3248,7 +3260,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|| src >= lastSrc;
}
/// <summary>Quality-only annotation (#626 pattern) of every subscribed alarm condition.</summary>
/// <summary>Quality-only annotation of every subscribed alarm condition.</summary>
private void AnnotateAlarmQuality(uint quality, DateTime now)
{
if (_alarmSubscriptions.IsEmpty || OnAlarmEvent is null) return;