Merge #926: OpcUaClient RefreshEnd signals initial alarm state only for a lossless bracket; post-signal loss withdraws known; deferred alarm/mark replay in arrival order; 2 review rounds
This commit is contained in:
@@ -26,6 +26,10 @@ internal sealed class OpcUaClientDiagnostics
|
||||
public const string KeepAliveRecovered = "keepalive_recovered";
|
||||
/// <summary>A late replayed notification (source time at or below the ref's high-water mark) was dropped inside the post-recovery replay window.</summary>
|
||||
public const string StaleNotificationDropped = "stale_notification_dropped";
|
||||
/// <summary>#926: the upstream reported an <c>EventQueueOverflowEventType</c> on an alarm event item (events lost).</summary>
|
||||
public const string AlarmEventQueueOverflow = "alarm_event_queue_overflow";
|
||||
/// <summary>#926: a RefreshEnd was NOT taken as "initial alarm state delivered" because its replay was lossy.</summary>
|
||||
public const string AlarmRefreshLossy = "alarm_refresh_lossy";
|
||||
|
||||
private readonly string _driverInstanceId;
|
||||
|
||||
|
||||
@@ -268,6 +268,15 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
ReportRefreshUnsignalable(ras.Subscription);
|
||||
}
|
||||
|
||||
/// <summary>Test-only seam (#926): a ConditionRefresh call of <paramref name="handle"/>'s subscription failed, as the
|
||||
/// refresh catch reports it.</summary>
|
||||
/// <param name="handle">The alarm subscription handle.</param>
|
||||
internal void ReportRefreshFailedForTest(IAlarmSubscriptionHandle handle)
|
||||
{
|
||||
if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras))
|
||||
NoteConditionRefreshFailed(ras.Subscription);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test-only seam to install the <see cref="NamespaceMap"/> that connect builds at
|
||||
/// runtime, so the v3 RawPath → upstream node id resolution can be exercised without a live
|
||||
@@ -1365,7 +1374,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
|
||||
foreach (var key in _alarmSubscriptions.Keys)
|
||||
{
|
||||
if (!_alarmSubscriptions.TryRemove(key, out var ras)) continue;
|
||||
RemoteAlarmSubscription? ras;
|
||||
// #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it.
|
||||
lock (_alarmStateLock)
|
||||
if (!_alarmSubscriptions.TryRemove(key, out ras)) continue;
|
||||
try { ras.EventItem.Notification -= ras.Handler; }
|
||||
catch { /* best-effort */ }
|
||||
if (sessionAlive) deletes.Add(DeleteSubscriptionBestEffortAsync(ras.Subscription, budget.Token));
|
||||
@@ -2434,6 +2446,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
private const int AlarmFieldAckedState = 8;
|
||||
private const int AlarmFieldBranchId = 9;
|
||||
|
||||
/// <summary>#926: the requested queue size of the alarm event item (was 1000). See its use.</summary>
|
||||
internal const uint AlarmEventQueueSize = 10_000;
|
||||
|
||||
/// <summary>#926 test seam (the live overflow gate shrinks it): the queue size the alarm event item requests.</summary>
|
||||
internal uint AlarmEventItemQueueSize { get; set; } = AlarmEventQueueSize;
|
||||
|
||||
/// <summary>#926 test seam (the live gate flips it to make a lossy replay KEEP its RefreshEnd): the alarm event
|
||||
/// item's DiscardOldest. Production: false (the newest events are dropped on overflow).</summary>
|
||||
internal bool AlarmEventItemDiscardOldest { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(
|
||||
IReadOnlyList<string> sourceNodeIds, CancellationToken cancellationToken)
|
||||
@@ -2574,8 +2596,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
StartNodeId = ObjectIds.Server,
|
||||
AttributeId = Attributes.EventNotifier,
|
||||
MonitoringMode = MonitoringMode.Reporting,
|
||||
QueueSize = 1000, // deep queue — a server can fire many alarms in bursts
|
||||
DiscardOldest = false,
|
||||
// #926: deep queue — a ConditionRefresh replays EVERY retained upstream condition in one burst, and a
|
||||
// server can fire many alarms at once. An overflow is still detected (EventQueueOverflowEventType ⇒ the
|
||||
// refresh's RefreshEnd does not signal and it is re-run); the depth only makes it rarer. The server
|
||||
// may revise it down (logged with the retry budget's exhaustion).
|
||||
QueueSize = AlarmEventItemQueueSize,
|
||||
DiscardOldest = AlarmEventItemDiscardOldest,
|
||||
Filter = filter,
|
||||
})
|
||||
{
|
||||
@@ -2623,7 +2649,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
public async Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken)
|
||||
{
|
||||
if (handle is not OpcUaAlarmSubscriptionHandle h) return;
|
||||
if (!_alarmSubscriptions.TryRemove(h.Id, out var rs)) return;
|
||||
RemoteAlarmSubscription? rs;
|
||||
// #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it.
|
||||
lock (_alarmStateLock)
|
||||
if (!_alarmSubscriptions.TryRemove(h.Id, out rs)) return;
|
||||
var emptied = NoteSubscriptionDeleted();
|
||||
|
||||
await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
@@ -2790,6 +2819,21 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
// without this it would feed RouteAlarmEvent alongside the real one.
|
||||
if (!_alarmSubscriptions.ContainsKey(handle.Id)) return;
|
||||
RecordLivenessEvidence();
|
||||
RouteAlarmEventFieldList(efl, sourceFilter, handle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Route one delivered event: first #926's publish-sequence check (a gap inside a refresh bracket makes it
|
||||
/// lossy — checked BEFORE the event, so a RefreshEnd in the first message after the gap is already suppressed),
|
||||
/// then <see cref="RouteAlarmEvent"/>.
|
||||
/// </summary>
|
||||
/// <param name="efl">The delivered event (the SDK sets <c>Message</c> to its notification message).</param>
|
||||
/// <param name="sourceFilter">The subscription's upstream-key → RawPath index.</param>
|
||||
/// <param name="handle">The subscription handle.</param>
|
||||
internal void RouteAlarmEventFieldList(
|
||||
EventFieldList efl, IReadOnlyDictionary<string, string> sourceFilter, IAlarmSubscriptionHandle handle)
|
||||
{
|
||||
NoteAlarmMessageSequence(handle, efl.Message?.SequenceNumber ?? 0);
|
||||
RouteAlarmEvent(efl.EventFields.ToList(), sourceFilter, handle);
|
||||
}
|
||||
|
||||
@@ -2826,25 +2870,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
internal void RouteAlarmEvent(
|
||||
IReadOnlyList<Variant> fields, IReadOnlyDictionary<string, string> sourceFilter, IAlarmSubscriptionHandle handle)
|
||||
{
|
||||
if (IsRefreshRequired(fields))
|
||||
if (fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId markerType
|
||||
&& IsBracketEventType(markerType))
|
||||
{
|
||||
// Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh.
|
||||
// r2 R2-1: bound to the session's work token, which a shutdown cancels first thing.
|
||||
var sessionWork = _sessionWorkCts.Token;
|
||||
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork));
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsRefreshEnd(fields))
|
||||
{
|
||||
// grpc-data A1 (F1): the refresh replay this subscription requested is complete and every refreshed event
|
||||
// before it was routed (sequential publishing, G2). Under the emission lock, so the signal is ordered
|
||||
// behind every emission. Covers the subscription's alarm RawPaths.
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras))
|
||||
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false);
|
||||
}
|
||||
RouteBracketEvent(markerType, handle);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2893,6 +2922,346 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
/// <param name="Severity">Exact severity last told (null before any event).</param>
|
||||
private readonly record struct AlarmToldState(bool Active, bool Acked, string? Message, int? Severity);
|
||||
|
||||
/// <summary>#926: the event types that drive the refresh bracket (never alarms): the three ConditionRefresh
|
||||
/// markers and the server's <c>EventQueueOverflowEventType</c>.</summary>
|
||||
/// <param name="t">The event's EventType.</param>
|
||||
/// <returns>Whether it is a bracket event.</returns>
|
||||
private static bool IsBracketEventType(NodeId t) =>
|
||||
t == ObjectTypeIds.RefreshStartEventType || t == ObjectTypeIds.RefreshEndEventType
|
||||
|| t == ObjectTypeIds.RefreshRequiredEventType || t == ObjectTypeIds.EventQueueOverflowEventType;
|
||||
|
||||
/// <summary>
|
||||
/// #926 — route one bracket event. Matched by EventType BEFORE any source filtering: an
|
||||
/// <c>EventQueueOverflowEventType</c> (Part 4) and the refresh markers come from the Server object, never
|
||||
/// from an authored condition source, so the projector's source filter would drop them.
|
||||
/// <list type="bullet">
|
||||
/// <item>RefreshStart opens a bracket and clears the loss record — unless a bracket is still open (its
|
||||
/// RefreshEnd never arrived): an overlapping start is itself a loss, kept.</item>
|
||||
/// <item>EventQueueOverflow is a definite loss: the bracket's RefreshEnd will not signal, and a bounded driver
|
||||
/// re-refresh is requested (also outside a bracket — a lost live transition is repaired by a replay).</item>
|
||||
/// <item>RefreshRequired is a loss too; it keeps its existing (coalesced) sweep, which IS the re-refresh.</item>
|
||||
/// <item>RefreshEnd signals (grpc-data A1) only for a bracket that was opened and saw no loss; otherwise it
|
||||
/// stays silent — the conditions stay unknown (Uncertain), the safe invariant — and requests the
|
||||
/// re-refresh if none was yet.</item>
|
||||
/// </list>
|
||||
/// Any loss after the subscription signalled also WITHDRAWS "known" from its conditions (see
|
||||
/// <see cref="NoteBracketLoss"/>).
|
||||
/// </summary>
|
||||
/// <param name="type">The bracket event's EventType.</param>
|
||||
/// <param name="handle">The subscription the event arrived on.</param>
|
||||
private void RouteBracketEvent(NodeId type, IAlarmSubscriptionHandle handle)
|
||||
{
|
||||
RemoteAlarmSubscription? ras = null;
|
||||
if (handle is OpcUaAlarmSubscriptionHandle h) _alarmSubscriptions.TryGetValue(h.Id, out ras);
|
||||
|
||||
if (type == ObjectTypeIds.RefreshRequiredEventType)
|
||||
{
|
||||
if (ras is not null)
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
// The sweep below re-refreshes this subscription, so no driver retry is requested for it.
|
||||
NoteBracketLoss(ras, "RefreshRequired", requestRetry: false);
|
||||
ras.Bracket.RetryRequestedSinceStart = true;
|
||||
}
|
||||
RequestRefreshRequiredSweep();
|
||||
return;
|
||||
}
|
||||
|
||||
if (ras is null) return; // a released / stray subscription: no bracket, no signal (G5)
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
var b = ras.Bracket;
|
||||
if (type == ObjectTypeIds.RefreshStartEventType)
|
||||
{
|
||||
if (b.Open)
|
||||
{
|
||||
// The previous bracket's RefreshEnd never arrived (or brackets overlap): that is a loss, and it must
|
||||
// not be erased by this start.
|
||||
NoteBracketLoss(ras, "overlapping RefreshStart (the previous RefreshEnd never arrived)", requestRetry: false);
|
||||
}
|
||||
else
|
||||
{
|
||||
b.LossSinceStart = null;
|
||||
b.RetryRequestedSinceStart = false;
|
||||
}
|
||||
b.Open = true;
|
||||
}
|
||||
else if (type == ObjectTypeIds.EventQueueOverflowEventType)
|
||||
{
|
||||
_diag.Record(OpcUaClientDiagnostics.AlarmEventQueueOverflow);
|
||||
NoteBracketLoss(ras, "EventQueueOverflow (the upstream discarded events of this subscription)",
|
||||
requestRetry: true);
|
||||
}
|
||||
else if (type == ObjectTypeIds.RefreshEndEventType)
|
||||
{
|
||||
var opened = b.Open;
|
||||
b.Open = false;
|
||||
if (opened && b.LossSinceStart is null)
|
||||
{
|
||||
// #926 review r2: re-checked UNDER the lock (the lookup above ran outside it, and an unsubscribe
|
||||
// removes the record under this lock): a released subscription never signals.
|
||||
if (!IsRegisteredLocked(ras)) return;
|
||||
// grpc-data A1 (F1): the refresh replay this subscription requested is complete, lossless, and every
|
||||
// refreshed event before it was routed (sequential publishing, G2). Under the emission lock, so the
|
||||
// signal is ordered behind every emission. Covers the subscription's alarm RawPaths. Ends the
|
||||
// lossy episode: the next loss gets a fresh budget.
|
||||
b.Retries = 0;
|
||||
b.ExhaustedLogged = false;
|
||||
b.Signalled = true;
|
||||
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false);
|
||||
return;
|
||||
}
|
||||
|
||||
var reason = b.LossSinceStart ?? "RefreshEnd without its RefreshStart (the bracket start was lost)";
|
||||
_diag.Record(OpcUaClientDiagnostics.AlarmRefreshLossy);
|
||||
_logger.LogWarning(
|
||||
"OpcUaClientDriver '{DriverInstanceId}': RefreshEnd on alarm subscription {SubscriptionId} NOT taken " +
|
||||
"as 'initial alarm state delivered' — {Reason}; its conditions stay unknown until a lossless refresh.",
|
||||
_driverInstanceId, ras.Handle.DiagnosticId, reason);
|
||||
WithdrawKnownLocked(ras, reason);
|
||||
if (!b.RetryRequestedSinceStart)
|
||||
b.RetryRequestedSinceStart = ScheduleAlarmRefreshRetryLocked(ras, reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #926: record a loss against <paramref name="ras"/>'s bracket, withdraw "known" if the subscription had
|
||||
/// signalled (an event lost AFTER the conditions were declared known — a live Raise in an overflowed queue or a
|
||||
/// skipped publish message — would otherwise leave a consumer holding a known-inactive condition that is active
|
||||
/// upstream), and (once per bracket) request a bounded re-refresh. Caller holds <c>_alarmStateLock</c>.
|
||||
/// </summary>
|
||||
/// <param name="ras">The alarm subscription.</param>
|
||||
/// <param name="reason">What was lost (logged).</param>
|
||||
/// <param name="requestRetry">Whether the driver itself should re-run ConditionRefresh.</param>
|
||||
private void NoteBracketLoss(RemoteAlarmSubscription ras, string reason, bool requestRetry)
|
||||
{
|
||||
var b = ras.Bracket;
|
||||
b.LossSinceStart ??= reason;
|
||||
WithdrawKnownLocked(ras, reason);
|
||||
if (!requestRetry || b.RetryRequestedSinceStart) return;
|
||||
// Only a retry actually scheduled (or already pending) covers this bracket's loss; a spent budget leaves the
|
||||
// request open, so a loss after the cool-down can still start one.
|
||||
b.RetryRequestedSinceStart = ScheduleAlarmRefreshRetryLocked(ras, reason);
|
||||
}
|
||||
|
||||
/// <summary>#926: if <paramref name="ras"/> signalled since its last loss, tell the host its conditions are no longer
|
||||
/// known (<see cref="AlarmInitialStateEventArgs.Withdrawn"/>) — ordered after every alarm event already raised, as the
|
||||
/// signal is. A later clean RefreshEnd signals them known again. Caller holds <c>_alarmStateLock</c>.</summary>
|
||||
/// <param name="ras">The alarm subscription.</param>
|
||||
/// <param name="reason">Why (logged).</param>
|
||||
private void WithdrawKnownLocked(RemoteAlarmSubscription ras, string reason)
|
||||
{
|
||||
if (!ras.Bracket.Signalled) return;
|
||||
ras.Bracket.Signalled = false;
|
||||
// #926 review r2: a stale record (unsubscribed after the caller's lookup, still Signalled) must not withdraw
|
||||
// refs that may now belong to a NEW subscription. Checked under the lock the unsubscribe removes it under.
|
||||
if (!IsRegisteredLocked(ras)) return;
|
||||
_logger.LogWarning(
|
||||
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost events after its conditions " +
|
||||
"were declared known ({Reason}); withdrawing 'known' until a lossless ConditionRefresh.",
|
||||
_driverInstanceId, ras.Handle.DiagnosticId, reason);
|
||||
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false, withdrawn: true);
|
||||
}
|
||||
|
||||
/// <summary>#926 review r2: <paramref name="ras"/> is still the registered subscription for its handle. Caller holds
|
||||
/// <c>_alarmStateLock</c>; removals take it too, so the answer holds for the rest of the critical section.</summary>
|
||||
/// <param name="ras">The alarm subscription record.</param>
|
||||
/// <returns>Whether it is the live registration.</returns>
|
||||
private bool IsRegisteredLocked(RemoteAlarmSubscription ras) =>
|
||||
_alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) && ReferenceEquals(current, ras);
|
||||
|
||||
/// <summary>
|
||||
/// #926: the publish-sequence check of alarm subscription <paramref name="handle"/>. The alarm subscription holds
|
||||
/// exactly one (event) monitored item, so every data-bearing notification message it receives carries its
|
||||
/// events and consumes one sequence number (keep-alives consume none). With <c>SequentialPublishing</c> the SDK
|
||||
/// delivers messages in order and waits for a missing one (republish); if the republish fails it SKIPS the gap
|
||||
/// and delivers the next message. That skip is reported to nothing the driver can observe — SDK 2.0.1 raises its
|
||||
/// <c>PublishStateChangedMask.Republish</c> only in a message-worker pass that also delivers a message, which a
|
||||
/// gap holding every later message prevents (pinned by the real-SDK test). So the driver compares sequence
|
||||
/// numbers itself: a newer message that is not the successor of the previous one means messages were lost —
|
||||
/// inside a bracket the replay is lossy, outside it a live transition may be lost; either way it is a loss
|
||||
/// (withdraw if signalled + bounded re-refresh). An OLDER (or repeated) number is ignored and not recorded, so a
|
||||
/// stray late message cannot make the next in-order one read as a second gap. A StatusChange-only message
|
||||
/// (transfer / timeout) also consumes a number and reads as a gap: a bounded extra refresh, never a wrong signal.
|
||||
/// </summary>
|
||||
/// <param name="handle">The alarm subscription handle.</param>
|
||||
/// <param name="sequenceNumber">The delivered message's sequence number (0 = unknown, ignored).</param>
|
||||
internal void NoteAlarmMessageSequence(IAlarmSubscriptionHandle handle, uint sequenceNumber)
|
||||
{
|
||||
if (sequenceNumber == 0) return;
|
||||
if (handle is not OpcUaAlarmSubscriptionHandle h || !_alarmSubscriptions.TryGetValue(h.Id, out var ras)) return;
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
var b = ras.Bracket;
|
||||
var last = b.LastSequenceNumber;
|
||||
if (last == 0) { b.LastSequenceNumber = sequenceNumber; return; }
|
||||
// Wrap-aware "newer" (RFC 1982-style, as the SDK compares): forward distance in (0, 2^31). Sequence numbers
|
||||
// skip 0 on the wrap (… uint.MaxValue, 1 …), so the successor of uint.MaxValue is 1.
|
||||
var forward = unchecked(sequenceNumber - last);
|
||||
if (forward == 0 || forward >= 0x8000_0000u) return; // repeat or older: ignore, do not record
|
||||
b.LastSequenceNumber = sequenceNumber;
|
||||
var next = last == uint.MaxValue ? 1u : last + 1;
|
||||
if (sequenceNumber == next) return;
|
||||
NoteBracketLoss(ras,
|
||||
$"publish message(s) lost (sequence {last} → {sequenceNumber}){(b.Open ? " during a refresh replay" : "")}",
|
||||
requestRetry: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>#926: the bounded number of driver-initiated re-refreshes per lossy episode (an episode ends with a clean
|
||||
/// RefreshEnd). When spent, the conditions stay unknown (Uncertain) and the host's
|
||||
/// <c>ConditionKnownSignalTimeout</c> diagnostic reports them — never known-inactive. After
|
||||
/// <see cref="AlarmRefreshRetryCooldown"/> without a retry, a further loss starts a new budget, so a structurally
|
||||
/// lossy upstream is retried at most <see cref="MaxAlarmRefreshRetries"/> times per cool-down — no storm, and no
|
||||
/// permanent give-up either.</summary>
|
||||
internal const int MaxAlarmRefreshRetries = 3;
|
||||
|
||||
/// <summary>#926: the first re-refresh delay; each further retry doubles it (2 s, 4 s, 8 s), giving the
|
||||
/// upstream time to drain whatever overflowed. Test seam.</summary>
|
||||
internal TimeSpan AlarmRefreshRetryBaseDelay { get; set; } = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>#926: after the budget is spent, how long since the last retry before a new loss gets a new budget.
|
||||
/// Test seam.</summary>
|
||||
internal TimeSpan AlarmRefreshRetryCooldown { get; set; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>#926 test seam: replaces the ConditionRefresh call of a driver re-refresh.</summary>
|
||||
internal Func<Subscription, CancellationToken, Task>? AlarmRefreshRetryInvokerForTest { get; set; }
|
||||
|
||||
/// <summary>#926: schedule one bounded re-refresh of <paramref name="ras"/> (coalesced while one is pending).
|
||||
/// Caller holds <c>_alarmStateLock</c>.</summary>
|
||||
/// <param name="ras">The alarm subscription.</param>
|
||||
/// <param name="reason">Why (logged).</param>
|
||||
/// <returns>Whether a retry is now pending (scheduled here or already) — false when the budget is spent.</returns>
|
||||
private bool ScheduleAlarmRefreshRetryLocked(RemoteAlarmSubscription ras, string reason)
|
||||
{
|
||||
var b = ras.Bracket;
|
||||
if (b.RetryPending) return true;
|
||||
var now = Clock.GetUtcNow().UtcDateTime;
|
||||
if (b.Retries >= MaxAlarmRefreshRetries && b.LastRetryUtc is { } lastRetry && now - lastRetry >= AlarmRefreshRetryCooldown)
|
||||
{
|
||||
b.Retries = 0; // a new episode after the cool-down
|
||||
b.ExhaustedLogged = false;
|
||||
}
|
||||
if (b.Retries >= MaxAlarmRefreshRetries)
|
||||
{
|
||||
if (!b.ExhaustedLogged)
|
||||
{
|
||||
b.ExhaustedLogged = true;
|
||||
_logger.LogWarning(
|
||||
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost refresh events " +
|
||||
"{Retries} time(s) in a row ({Reason}); no further re-refresh for {Cooldown}. Its conditions stay " +
|
||||
"unknown (Uncertain) until a lossless ConditionRefresh (RefreshRequired, reconnect, resubscribe, or a " +
|
||||
"loss after the cool-down). The event item's revised queue size is {QueueSize}.",
|
||||
_driverInstanceId, ras.Handle.DiagnosticId, b.Retries, reason, AlarmRefreshRetryCooldown,
|
||||
ras.EventItem.Status?.QueueSize);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
b.Retries++;
|
||||
b.RetryPending = true;
|
||||
b.LastRetryUtc = now;
|
||||
var generation = ++b.RetryGeneration;
|
||||
var delay = AlarmRefreshRetryBaseDelay * (1 << (b.Retries - 1));
|
||||
_logger.LogWarning(
|
||||
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId}: {Reason}; re-running " +
|
||||
"ConditionRefresh in {Delay} (attempt {Attempt}/{Max}).",
|
||||
_driverInstanceId, ras.Handle.DiagnosticId, reason, delay, b.Retries, MaxAlarmRefreshRetries);
|
||||
var sessionWork = _sessionWorkCts.Token;
|
||||
_ = Task.Run(() => RetryAlarmRefreshAsync(ras, generation, delay, sessionWork));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>#926: after <paramref name="delay"/>, re-run ConditionRefresh on <paramref name="ras"/> — only while it
|
||||
/// is still the registered subscription for its handle (an unsubscribe / re-init releases it).</summary>
|
||||
/// <param name="ras">The alarm subscription.</param>
|
||||
/// <param name="generation">This retry's generation: only it may clear <c>RetryPending</c>.</param>
|
||||
/// <param name="delay">The back-off.</param>
|
||||
/// <param name="cancellationToken">The session's work token (cancelled by shutdown / re-init).</param>
|
||||
/// <returns>A task completing when the refresh call returned (or was skipped).</returns>
|
||||
private async Task RetryAlarmRefreshAsync(
|
||||
RemoteAlarmSubscription ras, long generation, TimeSpan delay, CancellationToken cancellationToken)
|
||||
{
|
||||
var gateHeld = false;
|
||||
try
|
||||
{
|
||||
if (delay > TimeSpan.Zero) await Task.Delay(delay, Clock, cancellationToken).ConfigureAwait(false);
|
||||
await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
gateHeld = true;
|
||||
if (!_alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) || !ReferenceEquals(current, ras)) return;
|
||||
// From here a further loss may request the next retry: it belongs to THIS refresh's replay. That matters
|
||||
// when the replay's own RefreshStart is lost too (queue still full) — without the reset, no bracket opens
|
||||
// and nothing could request again. A lossy RefreshEnd of the PREVIOUS replay still in flight can then
|
||||
// request one extra refresh; that is inside the bound.
|
||||
ReleaseRetryPending(ras, generation, resetRequested: true);
|
||||
if (AlarmRefreshRetryInvokerForTest is { } invoke)
|
||||
await invoke(ras.Subscription, cancellationToken).ConfigureAwait(false);
|
||||
else if (ras.Subscription.Session is not null && ras.Subscription.Created)
|
||||
await TryConditionRefreshAsync(ras.Subscription, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) { /* shutdown / re-init: the subscription is being released */ }
|
||||
catch (ObjectDisposedException) { /* driver disposed */ }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "OpcUaClientDriver '{DriverInstanceId}': alarm re-refresh of {SubscriptionId} failed; " +
|
||||
"its conditions stay unknown until a later lossless ConditionRefresh.",
|
||||
_driverInstanceId, ras.Handle.DiagnosticId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Only THIS retry's pending flag: a retry scheduled while the refresh call ran (a new generation) stands.
|
||||
ReleaseRetryPending(ras, generation, resetRequested: false);
|
||||
if (gateHeld)
|
||||
{
|
||||
try { _subscriptionGate.Release(); } catch (ObjectDisposedException) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>#926: clear <c>RetryPending</c> if it still belongs to retry <paramref name="generation"/>.</summary>
|
||||
/// <param name="ras">The alarm subscription.</param>
|
||||
/// <param name="generation">The retry's generation.</param>
|
||||
/// <param name="resetRequested">Also re-allow a retry request for the current bracket.</param>
|
||||
private void ReleaseRetryPending(RemoteAlarmSubscription ras, long generation, bool resetRequested)
|
||||
{
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
if (ras.Bracket.RetryGeneration != generation) return;
|
||||
ras.Bracket.RetryPending = false;
|
||||
if (resetRequested) ras.Bracket.RetryRequestedSinceStart = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>#926: a ConditionRefresh call on <paramref name="subscription"/> failed (not "unsupported"): no
|
||||
/// RefreshEnd will come for it, so request a bounded re-refresh instead of waiting for the next external trigger.</summary>
|
||||
/// <param name="subscription">The SDK alarm subscription.</param>
|
||||
private void NoteConditionRefreshFailed(Subscription subscription)
|
||||
{
|
||||
foreach (var ras in _alarmSubscriptions.Values)
|
||||
{
|
||||
if (!ReferenceEquals(ras.Subscription, subscription)) continue;
|
||||
lock (_alarmStateLock) _ = ScheduleAlarmRefreshRetryLocked(ras, "ConditionRefresh call failed");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>1 while a RefreshRequired-triggered sweep is queued and has not started (coalescing).</summary>
|
||||
private int _refreshRequiredSweepQueued;
|
||||
|
||||
/// <summary>
|
||||
/// #926 (review r1 #7): a RefreshRequired asks for a refresh of every alarm subscription. Coalesced: while one
|
||||
/// sweep is queued and not yet started, further RefreshRequired events add nothing (that sweep covers them). A
|
||||
/// RefreshRequired arriving once the sweep has started queues the next one — it may report a later loss.
|
||||
/// </summary>
|
||||
private void RequestRefreshRequiredSweep()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _refreshRequiredSweepQueued, 1, 0) != 0) return;
|
||||
// Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh.
|
||||
// r2 R2-1: bound to the session's work token, which a shutdown cancels first thing.
|
||||
var sessionWork = _sessionWorkCts.Token;
|
||||
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork,
|
||||
onStart: () => Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0)));
|
||||
}
|
||||
|
||||
/// <summary>True for a <c>RefreshRequiredEventType</c> event (the server asks the client to ConditionRefresh).</summary>
|
||||
/// <param name="fields">The event's fields.</param>
|
||||
/// <returns>Whether the event is a RefreshRequired marker.</returns>
|
||||
@@ -2907,12 +3276,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId t
|
||||
&& t == ObjectTypeIds.RefreshEndEventType;
|
||||
|
||||
private void RaiseInitialAlarmState(IReadOnlyList<string> refs, bool unsignalable)
|
||||
private void RaiseInitialAlarmState(IReadOnlyList<string> refs, bool unsignalable, bool withdrawn = false)
|
||||
{
|
||||
if (refs.Count == 0) return;
|
||||
try
|
||||
{
|
||||
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs, unsignalable));
|
||||
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs, unsignalable, withdrawn));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -2967,6 +3336,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
"OpcUaClientDriver '{DriverInstanceId}': ConditionRefresh on alarm subscription {SubscriptionId} failed; " +
|
||||
"conditions already active upstream may not be reported until their next transition.",
|
||||
_driverInstanceId, subscription.Id);
|
||||
// #926 (review r1 #4): no RefreshEnd will come for this call — retry it, bounded.
|
||||
NoteConditionRefreshFailed(subscription);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
@@ -2992,9 +3363,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
/// outage reach the host through the normal deduplicated path.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <param name="onStart">Invoked first thing (the RefreshRequired coalescing flag's release).</param>
|
||||
/// <returns>A task completing when every refresh call has returned.</returns>
|
||||
private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken)
|
||||
private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken, Action? onStart = null)
|
||||
{
|
||||
onStart?.Invoke();
|
||||
if (_alarmSubscriptions.IsEmpty) return;
|
||||
try
|
||||
{
|
||||
@@ -3146,6 +3519,9 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
if (fields.Count <= AlarmFieldConditionId) return null;
|
||||
// ConditionRefresh brackets its re-delivery with RefreshStart/RefreshEnd — markers, never alarms.
|
||||
if (IsRefreshMarker(UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]))) return null;
|
||||
// #926: the server's queue-overflow notice is not an alarm either (pass-through would otherwise project it).
|
||||
if (UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId et && et == ObjectTypeIds.EventQueueOverflowEventType)
|
||||
return null;
|
||||
// A condition BRANCH event reports a previous state with its own EventId: projecting it would flip the
|
||||
// trunk's state, remembering it would make Acknowledge ack the branch.
|
||||
if (fields.Count > AlarmFieldBranchId && UpstreamValueMapping.ToClr(fields[AlarmFieldBranchId]) is NodeId branch && !branch.IsNull)
|
||||
@@ -3238,7 +3614,54 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
OpcUaAlarmSubscriptionHandle Handle,
|
||||
MonitoredItem EventItem,
|
||||
MonitoredItemNotificationEventHandler Handler,
|
||||
IReadOnlyList<string> AlarmRefs);
|
||||
IReadOnlyList<string> AlarmRefs)
|
||||
{
|
||||
/// <summary>#926: this subscription's ConditionRefresh bracket + bounded re-refresh state. Mutated only
|
||||
/// under <c>_alarmStateLock</c>.</summary>
|
||||
public AlarmRefreshBracket Bracket { get; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #926 — the RefreshStart…RefreshEnd bracket of one alarm subscription. A RefreshEnd declares the conditions it
|
||||
/// covers state-known (grpc-data A1), so it may only signal when the replay it closes is provably complete: its
|
||||
/// RefreshStart was seen and no loss (EventQueueOverflow, RefreshRequired, a publish-sequence gap) was
|
||||
/// observed since. Every field is read and written under <c>_alarmStateLock</c>.
|
||||
/// </summary>
|
||||
internal sealed class AlarmRefreshBracket
|
||||
{
|
||||
/// <summary>A RefreshStart was routed and its RefreshEnd not yet.</summary>
|
||||
public bool Open;
|
||||
|
||||
/// <summary>The first loss observed since the last RefreshStart (null = none). A RefreshEnd with a loss
|
||||
/// does not signal.</summary>
|
||||
public string? LossSinceStart;
|
||||
|
||||
/// <summary>A re-refresh was already requested for the loss since the last RefreshStart or the last re-refresh's
|
||||
/// start (so the lossy RefreshEnd that follows does not request a second one).</summary>
|
||||
public bool RetryRequestedSinceStart;
|
||||
|
||||
/// <summary>A driver re-refresh is scheduled and has not started its ConditionRefresh call yet.</summary>
|
||||
public bool RetryPending;
|
||||
|
||||
/// <summary>Driver re-refreshes spent since the last clean (signalled) RefreshEnd.</summary>
|
||||
public int Retries;
|
||||
|
||||
/// <summary>The retry budget is spent and that was logged (once per episode).</summary>
|
||||
public bool ExhaustedLogged;
|
||||
|
||||
/// <summary>Sequence number of the last delivered notification message (0 = none yet).</summary>
|
||||
public uint LastSequenceNumber;
|
||||
|
||||
/// <summary>This subscription's conditions were declared known (a clean RefreshEnd) and no loss since: a loss
|
||||
/// now must withdraw "known".</summary>
|
||||
public bool Signalled;
|
||||
|
||||
/// <summary>When the last driver re-refresh was scheduled (cool-down of a spent budget).</summary>
|
||||
public DateTime? LastRetryUtc;
|
||||
|
||||
/// <summary>Generation of the last scheduled re-refresh; only that retry may clear <see cref="RetryPending"/>.</summary>
|
||||
public long RetryGeneration;
|
||||
}
|
||||
|
||||
private sealed record OpcUaAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user