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:
@@ -34,6 +34,15 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
/// once with <see cref="AlarmInitialStateEventArgs.Unsignalable"/> set: the host then applies its
|
||||
/// per-driver-type backstop timer to those conditions instead. No other shipped source should use it.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Withdrawing (#926).</b> A source that signalled and then LOSES events for those conditions (an OPC UA
|
||||
/// event-queue overflow, a publish gap) raises the event with <see cref="AlarmInitialStateEventArgs.Withdrawn"/>
|
||||
/// set: the host takes "known" back from them (Uncertain on a consumer) until the source signals again or a
|
||||
/// transition re-establishes one. Same ordering rule: after every alarm event raised before it. Only a source
|
||||
/// that SIGNALLED withdraws: conditions that became known through the <see cref="AlarmInitialStateEventArgs.Unsignalable"/>
|
||||
/// backstop are not withdrawn by a later loss (the OPC UA client has no refresh bracket there, and its loss
|
||||
/// detection never re-arms the backstop) — that residual is the backstop's own.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public interface IAlarmInitialStateSignal
|
||||
{
|
||||
@@ -50,11 +59,18 @@ public sealed class AlarmInitialStateEventArgs : EventArgs
|
||||
/// <see langword="true"/> when the source can never signal for these conditions (no refresh upstream);
|
||||
/// the host's backstop timer applies instead of an immediate mark.
|
||||
/// </param>
|
||||
public AlarmInitialStateEventArgs(IReadOnlyList<string> conditionIds, bool unsignalable = false)
|
||||
/// <param name="withdrawn">
|
||||
/// <see langword="true"/> (#926) when the source can no longer vouch for these conditions' state (it lost events
|
||||
/// after establishing them): the host withdraws "known". Exclusive with <paramref name="unsignalable"/>.
|
||||
/// </param>
|
||||
public AlarmInitialStateEventArgs(IReadOnlyList<string> conditionIds, bool unsignalable = false, bool withdrawn = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(conditionIds);
|
||||
if (unsignalable && withdrawn)
|
||||
throw new ArgumentException("A signal is either unsignalable or a withdrawal, not both.", nameof(withdrawn));
|
||||
ConditionIds = conditionIds;
|
||||
Unsignalable = unsignalable;
|
||||
Withdrawn = withdrawn;
|
||||
}
|
||||
|
||||
/// <summary>The driver condition ids (= RawPaths) the completed read covers. Never "everything".</summary>
|
||||
@@ -65,4 +81,10 @@ public sealed class AlarmInitialStateEventArgs : EventArgs
|
||||
/// so the per-driver-type backstop timer (OpcUaClient only) decides when they become known.
|
||||
/// </summary>
|
||||
public bool Unsignalable { get; }
|
||||
|
||||
/// <summary>
|
||||
/// #926: the source lost events for these conditions after establishing them, so their state is no longer
|
||||
/// known. The host withdraws "known" (never starting a backstop) until the next real signal.
|
||||
/// </summary>
|
||||
public bool Withdrawn { get; }
|
||||
}
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -213,6 +213,31 @@ public sealed partial class DriverHostActor
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.Args.Withdrawn)
|
||||
{
|
||||
// #926: the source lost events after establishing these conditions. Take "known" back (same chain as its
|
||||
// projections, so it lands after them), keep them out of the backstop (which would re-mark them known by
|
||||
// timer), and put them back in the F5 window so a source that never re-signals is diagnosed.
|
||||
t.Unsignalable.ExceptWith(msg.Args.ConditionIds);
|
||||
var withdrawn = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds, known: false);
|
||||
if (t.GoodSinceUtc is not null && _alarmRefsByDriver.TryGetValue(msg.DriverInstanceId, out var owned))
|
||||
{
|
||||
var ownedPaths = owned.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal);
|
||||
var before = t.Pending.Count;
|
||||
t.Pending.UnionWith(msg.Args.ConditionIds.Where(ownedPaths.Contains));
|
||||
// An F5 window already running covers them; otherwise start one now. A diagnostic already raised for
|
||||
// that window must count them too (#926 review r2).
|
||||
if (t.Pending.Count != before)
|
||||
{
|
||||
if (t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t);
|
||||
else if (t.DiagnosticRaised) _conditionSignals.Hub?.UpdateUnsignalled(msg.DriverInstanceId, t.Pending.Count);
|
||||
}
|
||||
}
|
||||
_log.Info("DriverHost {Node}: driver {Driver} withdrew {Count} condition(s) ({Routed} routed) — state no longer known (events lost)",
|
||||
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, withdrawn);
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.Args.Unsignalable)
|
||||
{
|
||||
// InitialStateUnsignalable: no real signal will come. Only a driver type with a backstop (OpcUaClient) marks
|
||||
@@ -327,7 +352,7 @@ public sealed partial class DriverHostActor
|
||||
}
|
||||
|
||||
/// <summary>Route driver condition ids (RawPaths) to their condition nodes and send one mark per realm.</summary>
|
||||
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds)
|
||||
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds, bool known = true)
|
||||
{
|
||||
if (_opcUaPublishActor is null || conditionIds.Count == 0) return 0;
|
||||
var byRealm = new Dictionary<AddressSpaceRealm, List<string>>();
|
||||
@@ -344,7 +369,7 @@ public sealed partial class DriverHostActor
|
||||
var count = 0;
|
||||
foreach (var (realm, ids) in byRealm)
|
||||
{
|
||||
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm));
|
||||
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm, Known: known));
|
||||
count += ids.Count;
|
||||
}
|
||||
|
||||
|
||||
@@ -238,7 +238,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <see cref="AttributeAlarmPublished"/>, so it reaches <see cref="DriverHostActor"/> after every alarm event the
|
||||
/// driver raised before it.</summary>
|
||||
/// <remarks>A1 review S2: <paramref name="ConnectionEpoch"/> is the connection (Connected entry) the driver raised
|
||||
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge.</remarks>
|
||||
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge. #926: keep this message
|
||||
/// IN-PROCESS (child → parent only) — it carries <see cref="AlarmInitialStateEventArgs"/> by reference, and a
|
||||
/// serialized copy that dropped <c>Withdrawn</c> would default it to false and turn a withdrawal into a "known" mark.</remarks>
|
||||
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args,
|
||||
long? ConnectionEpoch = null);
|
||||
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch);
|
||||
|
||||
@@ -1165,47 +1165,89 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying {Count} deferred status writes threw", statuses.Count); }
|
||||
}
|
||||
|
||||
// G3 pre-pass: a deferred projection outside the applied scope is skipped — its source's KNOWN marks are discarded
|
||||
// wherever they sit in the arrival order (the conservative reading of "never known over a projection that did
|
||||
// not land").
|
||||
foreach (var (alarm, _) in _deferred.Alarms)
|
||||
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) _deferred.NoteAlarmLoss(alarm.Source);
|
||||
|
||||
// #926 review r2: alarm states, alarm qualities and condition-known marks replay as ONE list in ARRIVAL order.
|
||||
// Marks used to replay after every alarm, which was right for a "known" mark (it summarises the projections
|
||||
// before it) but wrong for a withdrawal followed by a live transition: replayed transition-then-withdrawal,
|
||||
// the condition ended unknown although the transition had re-established it — and the host, which saw the
|
||||
// transition last, no longer counted it in F5. Arrival order is exactly what the live path applies.
|
||||
var items = new List<(long Seq, int Kind, int Index)>();
|
||||
var alarmList = _deferred.Alarms.ToList();
|
||||
var qualityList = _deferred.AlarmQualities.ToList();
|
||||
var markList = _deferred.Marks.ToList();
|
||||
for (var i = 0; i < alarmList.Count; i++) items.Add((alarmList[i].Seq, 0, i));
|
||||
for (var i = 0; i < qualityList.Count; i++) items.Add((qualityList[i].Seq, 1, i));
|
||||
for (var i = 0; i < markList.Count; i++) items.Add((markList[i].Seq, 2, i));
|
||||
items.Sort((x, y) => x.Seq.CompareTo(y.Seq));
|
||||
|
||||
var alarms = 0;
|
||||
foreach (var alarm in _deferred.Alarms)
|
||||
{
|
||||
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId)))
|
||||
{
|
||||
_deferred.NoteAlarmLoss(alarm.Source); // G3: a skipped projection — the source's marks go too
|
||||
continue;
|
||||
}
|
||||
|
||||
alarms++;
|
||||
try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
|
||||
}
|
||||
|
||||
var qualities = 0;
|
||||
foreach (var quality in _deferred.AlarmQualities)
|
||||
{
|
||||
if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
|
||||
qualities++;
|
||||
try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
|
||||
}
|
||||
|
||||
// A1 F2/G3: the deferred "known" marks replay LAST, after every deferred alarm — and only for a source none of
|
||||
// whose deferred projections was dropped or skipped. A discarded mark leaves its conditions unknown (Uncertain)
|
||||
// until the source's next signal.
|
||||
var marks = 0;
|
||||
var discarded = 0;
|
||||
foreach (var (mark, sender) in _deferred.Marks)
|
||||
var discardedBySender = new Dictionary<(string Source, AddressSpaceRealm Realm), (IActorRef? Sender, List<string> Ids)>();
|
||||
// Consecutive marks of one (source, realm, known) are applied as one sink call.
|
||||
string? runSource = null;
|
||||
AddressSpaceRealm runRealm = default;
|
||||
var runKnown = false;
|
||||
var runIds = new List<string>();
|
||||
void FlushRun()
|
||||
{
|
||||
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
|
||||
if (mark.Known && _deferred.SourceLost(mark.Source))
|
||||
if (runIds.Count == 0) return;
|
||||
marks++;
|
||||
ApplyMark(new MarkConditionsKnown(runSource!, runIds.ToList(), runRealm, runKnown));
|
||||
runIds.Clear();
|
||||
}
|
||||
|
||||
foreach (var (_, kind, index) in items)
|
||||
{
|
||||
if (kind == 2)
|
||||
{
|
||||
discarded++;
|
||||
TellDiscarded(sender, new ConditionMarksDiscarded(mark.Source, mark.ConditionIds, mark.Realm));
|
||||
var m = markList[index];
|
||||
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
|
||||
if (m.Known && _deferred.SourceLost(m.Source))
|
||||
{
|
||||
discarded++;
|
||||
if (!discardedBySender.TryGetValue((m.Source, m.Realm), out var d))
|
||||
discardedBySender[(m.Source, m.Realm)] = d = (m.Sender, new List<string>());
|
||||
d.Ids.Add(m.ConditionId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runIds.Count > 0 && (runSource != m.Source || runRealm != m.Realm || runKnown != m.Known)) FlushRun();
|
||||
runSource = m.Source;
|
||||
runRealm = m.Realm;
|
||||
runKnown = m.Known;
|
||||
runIds.Add(m.ConditionId);
|
||||
continue;
|
||||
}
|
||||
|
||||
marks++;
|
||||
ApplyMark(mark);
|
||||
FlushRun();
|
||||
if (kind == 0)
|
||||
{
|
||||
var alarm = alarmList[index].Msg;
|
||||
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) continue; // counted in the pre-pass
|
||||
alarms++;
|
||||
try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
|
||||
}
|
||||
else
|
||||
{
|
||||
var quality = qualityList[index].Msg;
|
||||
if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
|
||||
qualities++;
|
||||
try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
|
||||
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
|
||||
}
|
||||
}
|
||||
FlushRun();
|
||||
|
||||
foreach (var ((source, realm), (sender, ids)) in discardedBySender)
|
||||
TellDiscarded(sender, new ConditionMarksDiscarded(source, ids, realm));
|
||||
|
||||
// N1: a KNOWN mark that did not fit the deferral was dropped (staying unknown is safe) — its sender hears it.
|
||||
foreach (var (source, sender) in _deferred.OverflowedMarkSources)
|
||||
@@ -1233,6 +1275,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// the two live writes leave on the node). Bounded by <see cref="Capacity"/> distinct keys across all kinds;
|
||||
/// beyond it a NEW key is not held (an existing key still updates), counted in <see cref="Dropped"/>.
|
||||
/// </summary>
|
||||
/// <summary>One deferred condition-known mark (#926 review r2: per condition, with its arrival sequence).</summary>
|
||||
private sealed record DeferredMark(
|
||||
string Source, string ConditionId, AddressSpaceRealm Realm, bool Known, IActorRef? Sender, long Seq);
|
||||
|
||||
private sealed class DeferredWrites(int capacity)
|
||||
{
|
||||
private struct VariableEntry
|
||||
@@ -1246,11 +1292,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new();
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), AlarmStateUpdate> _alarms = new();
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), AlarmQualityUpdate> _qualities = new();
|
||||
// A1: condition-known marks in arrival order (bounded by Capacity — a dropped mark only keeps conditions
|
||||
// unknown, which is always safe), and the sources that lost a deferred alarm projection (G3).
|
||||
private readonly List<(MarkConditionsKnown Msg, IActorRef? Sender)> _marks = new();
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), (AlarmStateUpdate Msg, long Seq)> _alarms = new();
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), (AlarmQualityUpdate Msg, long Seq)> _qualities = new();
|
||||
// A1 / #926 review r2: the LATEST condition-known mark per (realm, condition id), with its arrival sequence, and
|
||||
// the sources that lost a deferred alarm projection (G3). Per-condition, so a withdrawal-heavy plan window holds
|
||||
// at most one entry per condition (bounded by the address space), and replay can interleave marks with alarm
|
||||
// states in arrival order.
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), DeferredMark> _marks = new();
|
||||
private long _seq;
|
||||
private readonly Dictionary<string, IActorRef?> _overflowedMarkSources = new(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _lossySources = new(StringComparer.Ordinal);
|
||||
private bool _unattributedLoss;
|
||||
@@ -1259,20 +1308,31 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
public long Dropped { get; private set; }
|
||||
public int Count => _variables.Count + _alarms.Count + _qualities.Count;
|
||||
public bool IsEmpty => Count == 0 && _marks.Count == 0;
|
||||
public IEnumerable<AlarmStateUpdate> Alarms => _alarms.Values;
|
||||
public IEnumerable<AlarmQualityUpdate> AlarmQualities => _qualities.Values;
|
||||
public IReadOnlyList<(MarkConditionsKnown Msg, IActorRef? Sender)> Marks => _marks;
|
||||
public IEnumerable<(AlarmStateUpdate Msg, long Seq)> Alarms => _alarms.Values;
|
||||
public IEnumerable<(AlarmQualityUpdate Msg, long Seq)> AlarmQualities => _qualities.Values;
|
||||
public IEnumerable<DeferredMark> Marks => _marks.Values;
|
||||
|
||||
/// <summary>
|
||||
/// Defer a mark. A withdrawal (<c>Known: false</c>) is never dropped — review round 2 N1: staying KNOWN over a
|
||||
/// lost withdrawal is the unsafe direction, and withdrawals are bounded by connectivity edges. A known mark
|
||||
/// beyond <see cref="Capacity"/> is dropped (unknown is safe) and its source is remembered so the sender hears
|
||||
/// of it at replay (N2).
|
||||
/// Defer a mark, per condition: a later mark of the same condition replaces the earlier (the later one is what
|
||||
/// the live path leaves). A withdrawal (<c>Known: false</c>) is never dropped — review round 2 N1: staying KNOWN
|
||||
/// over a lost withdrawal is the unsafe direction. It is bounded anyway: one entry per condition, so at most
|
||||
/// the number of conditions in the address space (#926 made withdrawals routine, so the old "bounded by
|
||||
/// connectivity edges" no longer held). A known mark for a NEW condition beyond <see cref="Capacity"/> marks is
|
||||
/// dropped (unknown is safe) and its source is remembered so the sender hears of it at replay (N2).
|
||||
/// </summary>
|
||||
public void Mark(MarkConditionsKnown msg, IActorRef? sender)
|
||||
{
|
||||
if (!msg.Known || _marks.Count < Capacity) _marks.Add((msg, sender));
|
||||
else _overflowedMarkSources[msg.Source] = sender;
|
||||
foreach (var id in msg.ConditionIds)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id)) continue;
|
||||
var key = (msg.Realm, id);
|
||||
if (msg.Known && !_marks.ContainsKey(key) && _marks.Count >= Capacity)
|
||||
{
|
||||
_overflowedMarkSources[msg.Source] = sender;
|
||||
continue;
|
||||
}
|
||||
_marks[key] = new DeferredMark(msg.Source, id, msg.Realm, msg.Known, sender, ++_seq);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<(string Source, IActorRef? Sender)> OverflowedMarkSources =>
|
||||
@@ -1325,12 +1385,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
public bool Alarm(AlarmStateUpdate msg)
|
||||
{
|
||||
var key = (msg.Realm, msg.AlarmNodeId);
|
||||
if (!Put(_alarms, key, msg)) return false;
|
||||
if (!Put(_alarms, key, (msg, _seq + 1))) return false;
|
||||
_seq++;
|
||||
_qualities.Remove(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool AlarmQuality(AlarmQualityUpdate msg) => Put(_qualities, (msg.Realm, msg.AlarmNodeId), msg);
|
||||
public bool AlarmQuality(AlarmQualityUpdate msg)
|
||||
{
|
||||
if (!Put(_qualities, (msg.Realm, msg.AlarmNodeId), (msg, _seq + 1))) return false;
|
||||
_seq++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public (List<ValueWrite> Values, List<StatusWrite> Statuses) VariableWrites(Func<(AddressSpaceRealm, string), bool> include)
|
||||
{
|
||||
@@ -1357,6 +1423,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
_lossySources.Clear();
|
||||
_unattributedLoss = false;
|
||||
Dropped = 0;
|
||||
_seq = 0;
|
||||
}
|
||||
|
||||
private bool Put<T>(Dictionary<(AddressSpaceRealm, string), T> map, (AddressSpaceRealm, string) key, T value)
|
||||
|
||||
Reference in New Issue
Block a user