fix(dcl): handle RefreshRequired by issuing ConditionRefresh (#148)

OtOpcUa now emits RefreshRequiredEventType (SourceNode = Server, no
condition fields) on an incomplete condition snapshot, a removed imported
condition, or a resync that leaves pre-failover EventIds answering
BadEventIdUnknown. RealOpcUaClient had no branch for it: the event fell
through HandleAlarmEvent as a phantom condition keyed "Server" and no
refresh was issued, so the mirror could hold stale / un-ackable state.

- HandleAlarmEvent recognises RefreshRequiredEventType, emits nothing, and
  hands the item's handle to the new ConditionRefreshCoalescer.
- The coalescer runs off the SDK publish thread, debounces 500 ms so a
  burst (one event per affected item) costs one refresh, never overlaps
  refreshes (a request during an in-flight refresh is served by the next),
  logs and swallows failures, and is cleared on disconnect.
- Execution: targeted ConditionRefresh2(eventSubscription, item) per asking
  item; one subscription-wide ConditionRefresh when every live alarm item
  asked, an item has no server id, or ConditionRefresh2 fails. The replay is
  the usual RefreshStart/End frame, so NativeAlarmActor's snapshot swap
  clears conditions the refreshed snapshot no longer lists.
- The server-side OfType WhereClause built from a condition filter now ORs
  in OfType(RefreshRequiredEventType): the server queues RefreshRequired
  through the item's filter, so a bare condition-type clause dropped it.

Tests: RealOpcUaRefreshRequiredTests (branch, no-session tolerance, burst
coalescing, no overlap, failure tolerance, Clear, framing intact);
RealOpcUaClientAlarmFilterTests updated for the added operand.
Component-DataConnectionLayer.md documents the behaviour.
This commit is contained in:
Joseph Doherty
2026-11-28 09:03:02 -05:00
parent 8010fee2d2
commit a117f79ad1
5 changed files with 488 additions and 13 deletions
@@ -0,0 +1,143 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
/// <summary>
/// Coalesces OPC UA <c>RefreshRequiredEventType</c> notifications into ConditionRefresh calls
/// (Gitea #148, OPC UA Part 9 §5.11.4: on RefreshRequired a client calls ConditionRefresh).
/// </summary>
/// <remarks>
/// <para>
/// RefreshRequired arrives on the OPC UA SDK's publish thread inside a monitored-item
/// notification handler, so the refresh itself must never run there: a ConditionRefresh replays
/// its RefreshStart / conditions / RefreshEnd through the SAME publish pipeline, and blocking the
/// handler on the call would stall that pipeline. <see cref="Request"/> therefore only records
/// the alarm handle and returns; a single background loop does the work.
/// </para>
/// <para>
/// A server typically sends RefreshRequired to every event item that may see the affected
/// condition — one origin removal reaches several items at once, and an incomplete re-snapshot
/// can produce a burst. Requests are debounced by <see cref="Debounce"/>: the loop waits, drains
/// every handle requested in that window and hands the whole set to the executor ONCE. A request
/// that arrives while a refresh is running is not lost — it is picked up by the next iteration
/// after another debounce window, so the refreshes never overlap (a server may answer an
/// overlapping one with <c>BadRefreshInProgress</c>).
/// </para>
/// <para>
/// The executor's failures are logged and swallowed: a failed refresh leaves the mirror on its
/// last-known state, exactly as the subscribe-time refresh already does on failure, and the next
/// RefreshRequired (or reconnect) retries it.
/// </para>
/// </remarks>
internal sealed class ConditionRefreshCoalescer
{
private readonly Func<IReadOnlyCollection<string>, CancellationToken, Task> _execute;
private readonly ILogger _logger;
private readonly ConcurrentDictionary<string, byte> _pending = new(StringComparer.Ordinal);
// 0 = no loop running, 1 = a loop owns the work. Only the CAS winner starts a loop.
private int _loopRunning;
// Bumped by Clear(); a loop started under an older generation abandons its drained set.
private int _generation;
/// <summary>Initializes the coalescer.</summary>
/// <param name="execute">Runs one coalesced refresh for the drained set of alarm handles.</param>
/// <param name="debounce">How long requests accumulate before a refresh is issued.</param>
/// <param name="logger">Logger for failures; null uses a null logger.</param>
public ConditionRefreshCoalescer(
Func<IReadOnlyCollection<string>, CancellationToken, Task> execute,
TimeSpan debounce,
ILogger? logger = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
Debounce = debounce;
_logger = logger ?? NullLogger.Instance;
}
/// <summary>The window over which RefreshRequired notifications coalesce into one refresh.</summary>
public TimeSpan Debounce { get; }
/// <summary>Number of refresh batches handed to the executor (diagnostics / tests).</summary>
public int ExecutedBatches => Volatile.Read(ref _executedBatches);
private int _executedBatches;
/// <summary>
/// Records that <paramref name="alarmHandle"/>'s item received RefreshRequired. Never blocks
/// and never throws — safe to call from the OPC UA publish thread.
/// </summary>
/// <param name="alarmHandle">The alarm subscription handle whose item received the event.</param>
public void Request(string alarmHandle)
{
_pending[alarmHandle] = 0;
TryStartLoop();
}
/// <summary>
/// Drops every pending request (the session is going away; a reconnect re-subscribes and
/// refreshes on its own). A loop already sleeping wakes to an empty set and exits.
/// </summary>
public void Clear()
{
Interlocked.Increment(ref _generation);
_pending.Clear();
}
private void TryStartLoop()
{
if (Interlocked.CompareExchange(ref _loopRunning, 1, 0) != 0)
return;
_ = Task.Run(RunLoopAsync);
}
private async Task RunLoopAsync()
{
try
{
while (true)
{
var generation = Volatile.Read(ref _generation);
await Task.Delay(Debounce).ConfigureAwait(false);
var batch = new List<string>();
foreach (var key in _pending.Keys)
{
if (_pending.TryRemove(key, out _))
batch.Add(key);
}
if (batch.Count == 0)
break;
if (generation != Volatile.Read(ref _generation))
continue; // cleared while debouncing — the drained handles belong to a dead session
Interlocked.Increment(ref _executedBatches);
try
{
await _execute(batch, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"ConditionRefresh after RefreshRequired failed for {Count} alarm subscription(s)", batch.Count);
}
}
}
catch (Exception ex)
{
// Defensive: nothing above should throw, but an unobserved fault here would silently
// stop RefreshRequired handling for the life of the client.
_logger.LogWarning(ex, "RefreshRequired coalescing loop faulted");
}
finally
{
Volatile.Write(ref _loopRunning, 0);
// A request that landed after the last drain but before the flag cleared would
// otherwise wait for the next RefreshRequired — restart for it.
if (!_pending.IsEmpty)
TryStartLoop();
}
}
}
@@ -74,6 +74,19 @@ public class RealOpcUaClient : IOpcUaClient
private readonly ConcurrentDictionary<string, Guid> _alarmSnapshotIds = new();
// Per-handle last (active, acked) by source reference, to derive transition kind.
private readonly ConcurrentDictionary<string, Dictionary<string, (bool Active, bool Acked)>> _alarmLastState = new();
/// <summary>
/// How long RefreshRequired notifications coalesce before one ConditionRefresh is issued
/// (Gitea #148). Short enough that a client holding a removed / un-ackable condition is
/// corrected promptly, long enough that a burst (one event per affected item) costs one refresh.
/// </summary>
internal static readonly TimeSpan RefreshRequiredDebounce = TimeSpan.FromMilliseconds(500);
/// <summary>
/// Turns RefreshRequired events into debounced, off-publish-thread ConditionRefresh calls
/// (Gitea #148). Internal-settable so tests can observe or replace the executor.
/// </summary>
internal ConditionRefreshCoalescer RefreshRequiredCoalescer { get; set; }
// Int flag toggled with Interlocked.Exchange so the
// once-only ConnectionLost guard in OnSessionKeepAlive is atomic, not just visible.
// 0 = not fired, 1 = fired.
@@ -102,6 +115,8 @@ public class RealOpcUaClient : IOpcUaClient
{
_globalOptions = globalOptions ?? new OpcUaGlobalOptions();
_logger = logger ?? NullLogger<RealOpcUaClient>.Instance;
RefreshRequiredCoalescer = new ConditionRefreshCoalescer(
ExecuteRequiredRefreshAsync, RefreshRequiredDebounce, _logger);
}
/// <inheritdoc />
@@ -544,6 +559,9 @@ public class RealOpcUaClient : IOpcUaClient
/// <inheritdoc />
public async Task DisconnectAsync(CancellationToken cancellationToken = default)
{
// Pending RefreshRequired work targets this session's subscription ids; a reconnect
// re-subscribes and refreshes on its own (Gitea #148).
RefreshRequiredCoalescer.Clear();
await _applyGate.RunAsync(async () =>
{
foreach (var shard in _dataShards)
@@ -1149,12 +1167,15 @@ public class RealOpcUaClient : IOpcUaClient
if (typeIds.Count == 0)
return;
// Gitea #148: RefreshRequiredEventType is a plain BaseEventType subtype, and a server
// queues it through the item's normal filter path (OtOpcUa's QueueRefreshRequired uses
// MonitoredItem.QueueEvent, which applies the WhereClause). An OfType(<condition types>)
// clause would therefore silently drop it, and the client would never learn it must
// refresh. Always let it through. (RefreshStart/End are left as before: Part 9 has the
// server deliver them for a refresh regardless of the item's filter.)
typeIds.Add(ObjectTypeIds.RefreshRequiredEventType);
var where = filter.WhereClause;
if (typeIds.Count == 1)
{
where.Push(FilterOperator.OfType, typeIds[0]);
return;
}
// OR together each OfType element so an event of ANY listed type passes.
var element = where.Push(FilterOperator.OfType, typeIds[0]);
@@ -1176,6 +1197,82 @@ public class RealOpcUaClient : IOpcUaClient
};
}
/// <summary>
/// Executes one coalesced RefreshRequired batch (Gitea #148), on the coalescer's background
/// loop — never on the publish thread. When every live alarm item asked (or only one
/// subscription-wide call is possible) a single <c>ConditionRefresh</c> on the event shard
/// covers them all; otherwise each asking item gets a targeted <c>ConditionRefresh2</c>, so
/// items the server did not flag keep their mirror untouched. A ConditionRefresh2 failure
/// (e.g. a server without it) falls back to one subscription-wide ConditionRefresh. The replay
/// arrives as the usual RefreshStart → conditions → RefreshEnd frame per item, which
/// <see cref="HandleAlarmEvent"/> turns into a Snapshot epoch and the Native Alarm Actor's
/// snapshot swap uses to clear any condition the refreshed snapshot no longer lists.
/// </summary>
/// <param name="handles">Alarm handles whose items received RefreshRequired.</param>
/// <param name="cancellationToken">Cancellation token.</param>
private async Task ExecuteRequiredRefreshAsync(IReadOnlyCollection<string> handles, CancellationToken cancellationToken)
{
var session = _session;
var eventShard = _eventShard;
if (session == null || eventShard == null)
{
_logger.LogDebug("RefreshRequired for {Count} alarm subscription(s) ignored: no live session", handles.Count);
return;
}
var items = new List<(string Handle, MonitoredItem Item)>();
foreach (var handle in handles)
{
if (_alarmItems.TryGetValue(handle, out var item))
items.Add((handle, item));
}
if (items.Count == 0)
return; // every asking item was removed while the request debounced
_logger.LogInformation(
"OPC UA server sent RefreshRequired for {Count} alarm subscription(s); issuing ConditionRefresh",
items.Count);
if (items.Count >= _alarmItems.Count || items.Any(i => i.Item.ServerId == 0))
{
await CallConditionRefreshAsync(session, eventShard, cancellationToken);
return;
}
foreach (var (handle, item) in items)
{
try
{
await session.CallAsync(
ObjectTypeIds.ConditionType, MethodIds.ConditionType_ConditionRefresh2,
cancellationToken, eventShard.Id, item.ServerId);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"ConditionRefresh2 failed for alarm subscription {Handle}; falling back to ConditionRefresh on the event subscription",
handle);
await CallConditionRefreshAsync(session, eventShard, cancellationToken);
return; // the subscription-wide refresh covers the remaining items
}
}
}
private async Task CallConditionRefreshAsync(ISession session, Subscription eventShard, CancellationToken cancellationToken)
{
try
{
await session.CallAsync(
ObjectTypeIds.ConditionType, MethodIds.ConditionType_ConditionRefresh,
cancellationToken, eventShard.Id);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "ConditionRefresh after RefreshRequired failed for event subscription {SubscriptionId}",
eventShard.Id);
}
}
private async Task TriggerConditionRefreshAsync(
string handle, Subscription eventShard, CancellationToken cancellationToken)
{
@@ -1208,6 +1305,18 @@ public class RealOpcUaClient : IOpcUaClient
NodeId? eventType = fields[0] is NodeId et ? et : null;
// Gitea #148 / OPC UA Part 9 §5.11.4: RefreshRequired is NOT a condition (it carries
// SourceNode = Server and no condition fields). It tells the client its view is no longer
// trustworthy — an incomplete re-snapshot, a removed condition, or EventIds invalidated
// by a resync — and that it must call ConditionRefresh. Never map it as an alarm (it used
// to fall through and mirror a phantom condition keyed "Server"); hand it to the
// coalescer, which issues the refresh off this publish thread.
if (eventType == ObjectTypeIds.RefreshRequiredEventType)
{
RefreshRequiredCoalescer.Request(handle);
return;
}
// RefreshStart/End bracket the snapshot replay.
if (eventType == ObjectTypeIds.RefreshStartEventType)
{