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
@@ -371,7 +371,7 @@ The `AlarmTransitionCallback` delivers a protocol-neutral `NativeAlarmTransition
### Protocol Adapters
- **OPC UA** (`OpcUaDataConnection` + `RealOpcUaClient`): one **event MonitoredItem per source binding** (`AttributeId = EventNotifier`), sharing an event subscription (the empty binding selects the Server object), with an `EventFilter` selecting `EventType` / `SourceNode` / `Severity` plus the `ConditionType` / `AcknowledgeableConditionType` / `AlarmConditionType` state fields. `ConditionRefresh` is invoked on subscribe to replay active conditions as the snapshot. The OPC UA field → `NativeAlarmTransition` mapping is isolated in the pure helper `OpcUaAlarmMapper`, unit-testable without a live server.
- **OPC UA** (`OpcUaDataConnection` + `RealOpcUaClient`): one **event MonitoredItem per source binding** (`AttributeId = EventNotifier`), sharing an event subscription (the empty binding selects the Server object), with an `EventFilter` selecting `EventType` / `SourceNode` / `Severity` plus the `ConditionType` / `AcknowledgeableConditionType` / `AlarmConditionType` state fields. `ConditionRefresh` is invoked on subscribe to replay active conditions as the snapshot, and again (coalesced) whenever the server sends `RefreshRequiredEventType` (#148, below). The OPC UA field → `NativeAlarmTransition` mapping is isolated in the pure helper `OpcUaAlarmMapper`, unit-testable without a live server.
- **MxGateway** (`MxGatewayDataConnection` + `RealMxGatewayClient`): mirrors over the gateway package's `StreamAlarmsAsync` — a resumable background stream whose reconnect re-sends a snapshot. The field mapping lives in `MxGatewayAlarmMapper`.
Other/custom protocols do not implement the capability; a subscribe request against such a connection is replied to with a failure (`SubscribeAlarmsResponse.Success = false`).
@@ -386,6 +386,7 @@ The registered `SourceReference` is a **NodeId** for OPC UA (the picker, CSV and
- **Capability check**: if `_adapter is not IAlarmSubscribableConnection`, the actor replies `SubscribeAlarmsResponse(Success = false, ...)`.
- **Reconnect handling**: on entering **Reconnecting**, the actor pushes a `NativeAlarmSourceUnavailable` to every alarm subscriber (consumers mark mirrored alarms uncertain rather than clearing them). On successful reconnection it re-subscribes the feed; the adapter re-emits a snapshot, reconciling state.
- **Server-initiated refresh**: a RefreshStart/RefreshEnd pair the server sends on its own on an existing feed (OtOpcUa's promotion refresh under Warm redundancy, #138) takes the same snapshot path — forwarded in order under its own epoch, and it replaces the cached state for the source.
- **RefreshRequired (Gitea #148)**: an OPC UA server sends `RefreshRequiredEventType` (`SourceNode = Server`, no condition fields) when the client's view can no longer be trusted — OtOpcUa sends it on an incomplete condition snapshot, a removed imported condition, and a resync that left pre-failover EventIds un-ackable (`BadEventIdUnknown`). Part 9 says the client must call ConditionRefresh. `RealOpcUaClient.HandleAlarmEvent` therefore never maps it as an alarm (it used to fall through as a phantom condition keyed `Server`); it hands the item's handle to `ConditionRefreshCoalescer`, which runs off the SDK publish thread, debounces 500 ms so a burst (the server sends one event per item that may see the condition) costs one refresh, and never overlaps refreshes (a request during an in-flight refresh is served by the next one). The refresh is a targeted `ConditionRefresh2(eventSubscription, item)` per asking item, or one subscription-wide `ConditionRefresh` when every live alarm item asked, an item has no server id yet, or `ConditionRefresh2` fails. Failures are logged, never thrown, and leave the mirror on its last-known state until the next RefreshRequired or reconnect; a disconnect drops pending requests. The replay is the ordinary RefreshStart → conditions → RefreshEnd frame, so the Native Alarm Actor's snapshot swap clears every condition the refreshed snapshot no longer lists (a removed condition gets its return-to-normal). Because the server queues RefreshRequired through the item's WhereClause, the server-side `OfType` clause built from a condition filter always ORs in `OfType(RefreshRequiredEventType)`. Covered by `RealOpcUaRefreshRequiredTests` and `RealOpcUaClientAlarmFilterTests`.
- **Shared condition filter (last-subscriber-wins)**: because the feed is opened once per source, it carries a single condition filter. A second subscriber that registers a *different* filter for the same source overwrites it (last writer wins) and the actor logs a warning — co-subscribers to one source are expected to agree on the filter.
- **Routing index**: subscribed sources are bucketed by the **first path segment** of their reference (everything before the first `.`), and a transition is matched only against the bucket for its own first segment, plus a residue list of sources that carry no separator at all (a prefix shorter than one segment, which can match other buckets). This is sound because a source reference containing a separator can only prefix a reference sharing its entire first segment. The per-source `StartsWith` test and the condition-type gate inside the bucket are unchanged, so routing decisions are identical to the previous linear scan over every subscribed source; snapshot boundaries bypass the condition filter, but OPC UA boundaries are sent only to the exact source binding. Connection-wide Mx boundaries broadcast to all subscribers while preserving their refresh epoch.
- **Gateway union filter (MxGateway)**: `StreamAlarms` carries a single `alarm_filter_prefix`, so the adapter opens the stream on the **longest common prefix** of the currently subscribed source references and restarts it for each new source, including one covered by the existing prefix, so every newly bound source receives standing state. Restarts are **coalesced** (review 2026-10-21): subscribes arriving within `MxAlarmStreamReopenDebounce` (200 ms) of the first share ONE restart on the union prefix, so a staggered deploy batch of N alarm-bound instances costs one close/reopen and one connection-wide snapshot replay instead of N (each of which was broadcast to every already-subscribed source — O(N·M) boundary messages). A reconnect, teardown or last unsubscribe invalidates a pending restart. Each transport refresh has connection-wide start/end markers and a distinct epoch. An unsubscribe never restarts the stream — the prefix it leaves behind is at worst too broad, which may increase bandwidth. Correctness also depends on the epoch-scoped snapshot cache merging concurrent live updates and rejecting stale snapshot ends (DC-5); a broad filter alone provides no such guarantee. The prefix is a bandwidth optimisation only; the actor's per-source + condition-type gate remains authoritative, mirroring the OPC UA server-side WhereClause stance.
@@ -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)
{
@@ -29,21 +29,44 @@ public class RealOpcUaClientAlarmFilterTests
var filter = RealOpcUaClient.BuildAlarmEventFilter(parsed);
Assert.NotEmpty(filter.WhereClause.Elements.ToList());
// Two known types → two OfType operands (OR'd when more than one).
// Two known types + the always-admitted RefreshRequiredEventType (Gitea #148) →
// three OfType operands, OR'd together.
var ofTypeCount = filter.WhereClause.Elements.ToList().Count(e => e.FilterOperator == FilterOperator.OfType);
Assert.Equal(2, ofTypeCount);
Assert.Equal(3, ofTypeCount);
Assert.Contains(filter.WhereClause.Elements.ToList(), e => e.FilterOperator == FilterOperator.Or);
}
/// <summary>Verifies that a single known condition type produces a single of-type clause with no OR.</summary>
/// <summary>
/// Verifies that a single known condition type produces its OfType OR'd with
/// OfType(RefreshRequiredEventType) — the server queues RefreshRequired through the item's
/// WhereClause, so a bare OfType(condition type) would drop it (Gitea #148).
/// </summary>
[Fact]
public void BuildAlarmEventFilter_SingleKnownType_BuildsSingleOfType_NoOr()
public void BuildAlarmEventFilter_SingleKnownType_IsOrdWithRefreshRequired()
{
var parsed = AlarmConditionFilter.Parse("AlarmConditionType");
var filter = RealOpcUaClient.BuildAlarmEventFilter(parsed);
Assert.Single(filter.WhereClause.Elements.ToList());
Assert.Equal(FilterOperator.OfType, filter.WhereClause.Elements.ToList()[0].FilterOperator);
var elements = filter.WhereClause.Elements.ToList();
Assert.Equal(2, elements.Count(e => e.FilterOperator == FilterOperator.OfType));
Assert.Single(elements, e => e.FilterOperator == FilterOperator.Or);
Assert.Equal(FilterOperator.Or, elements[0].FilterOperator); // the root element is the OR
}
/// <summary>Verifies that every non-empty WhereClause admits RefreshRequiredEventType (Gitea #148).</summary>
[Theory]
[InlineData("AlarmConditionType")]
[InlineData("LimitAlarmType,DiscreteAlarmType")]
public void BuildAlarmEventFilter_WhereClause_AlwaysAdmitsRefreshRequired(string types)
{
var filter = RealOpcUaClient.BuildAlarmEventFilter(AlarmConditionFilter.Parse(types));
var ofTypeOperands = filter.WhereClause.Elements.ToList()
.Where(e => e.FilterOperator == FilterOperator.OfType)
.SelectMany(e => e.GetOperands().OfType<LiteralOperand>())
.Select(o => o.Value.ToString())
.ToList();
Assert.Contains(ObjectTypeIds.RefreshRequiredEventType.ToString(), ofTypeOperands);
}
/// <summary>Verifies that condition type matching is case-insensitive.</summary>
@@ -52,7 +75,8 @@ public class RealOpcUaClientAlarmFilterTests
{
var parsed = AlarmConditionFilter.Parse("limitalarmtype");
var filter = RealOpcUaClient.BuildAlarmEventFilter(parsed);
Assert.Single(filter.WhereClause.Elements.ToList(), e => e.FilterOperator == FilterOperator.OfType);
// LimitAlarmType + the always-admitted RefreshRequiredEventType.
Assert.Equal(2, filter.WhereClause.Elements.ToList().Count(e => e.FilterOperator == FilterOperator.OfType));
}
/// <summary>Verifies that a filter of only unknown types omits the where clause.</summary>
@@ -0,0 +1,198 @@
using System.Collections.Concurrent;
using System.Reflection;
using Opc.Ua;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters;
/// <summary>
/// Gitea #148: OtOpcUa emits <c>RefreshRequiredEventType</c> (SourceNode = Server, no condition
/// fields) on an incomplete condition snapshot, a removed imported condition, or a resync that
/// invalidates EventIds. Per OPC UA Part 9 the client must call ConditionRefresh and must NOT treat
/// the event as an alarm. These tests pin the event branch in <c>HandleAlarmEvent</c> and the
/// debounce/coalesce behaviour of <see cref="ConditionRefreshCoalescer"/>.
/// </summary>
public class RealOpcUaRefreshRequiredTests
{
private static readonly MethodInfo Handler =
typeof(RealOpcUaClient).GetMethod("HandleAlarmEvent", BindingFlags.Instance | BindingFlags.NonPublic)!;
/// <summary>OtOpcUa's RefreshRequired shape: SourceNode = Server, SourceName "Server", Message "RefreshRequired".</summary>
private static EventFieldList RefreshRequiredEvent() => new()
{
EventFields = new Variant[]
{
Variant.From(ObjectTypeIds.RefreshRequiredEventType), // 0 EventType
Variant.From(ObjectIds.Server), // 1 SourceNode
Variant.From("Server"), // 2 SourceName
Variant.From(DateTime.UtcNow), // 3 Time
Variant.From(new LocalizedText("RefreshRequired")), // 4 Message
Variant.From((ushort)100), // 5 Severity
Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null,
}
};
private static void Seed(RealOpcUaClient client, string handle)
{
var field = typeof(RealOpcUaClient).GetField("_alarmLastState", BindingFlags.Instance | BindingFlags.NonPublic)!;
var map = (ConcurrentDictionary<string, Dictionary<string, (bool Active, bool Acked)>>)field.GetValue(client)!;
map[handle] = new Dictionary<string, (bool Active, bool Acked)>(StringComparer.Ordinal);
}
private static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (!condition())
{
if (DateTime.UtcNow > deadline)
throw new TimeoutException("condition not reached");
await Task.Delay(10);
}
}
/// <summary>A RefreshRequired event is never surfaced as a native alarm transition.</summary>
[Fact]
public async Task RefreshRequired_IsNotMappedAsAnAlarm_AndRequestsARefresh()
{
var client = new RealOpcUaClient();
Seed(client, "h1");
var batches = new ConcurrentQueue<IReadOnlyCollection<string>>();
client.RefreshRequiredCoalescer = new ConditionRefreshCoalescer(
(handles, _) => { batches.Enqueue(handles.ToList()); return Task.CompletedTask; },
TimeSpan.FromMilliseconds(20));
var sink = new List<NativeAlarmTransition>();
Handler.Invoke(client, ["h1", "ns=2;s=Area", RefreshRequiredEvent(), (Action<NativeAlarmTransition>)sink.Add]);
Assert.Empty(sink); // no phantom condition keyed "Server"
await WaitUntilAsync(() => batches.Count == 1, TimeSpan.FromSeconds(5));
Assert.Equal(["h1"], batches.Single());
}
/// <summary>
/// The production executor tolerates a client with no live session: a RefreshRequired that
/// lands after a disconnect is logged and dropped, never thrown on the publish thread.
/// </summary>
[Fact]
public async Task RefreshRequired_WithNoSession_IsSwallowed()
{
var client = new RealOpcUaClient();
Seed(client, "h1");
var sink = new List<NativeAlarmTransition>();
Handler.Invoke(client, ["h1", "", RefreshRequiredEvent(), (Action<NativeAlarmTransition>)sink.Add]);
await WaitUntilAsync(() => client.RefreshRequiredCoalescer.ExecutedBatches == 1, TimeSpan.FromSeconds(5));
Assert.Empty(sink);
}
/// <summary>A burst of RefreshRequired across several items costs ONE refresh carrying every handle.</summary>
[Fact]
public async Task Burst_CoalescesIntoOneRefresh()
{
var batches = new ConcurrentQueue<IReadOnlyCollection<string>>();
var coalescer = new ConditionRefreshCoalescer(
(handles, _) => { batches.Enqueue(handles.ToList()); return Task.CompletedTask; },
TimeSpan.FromMilliseconds(100));
for (var i = 0; i < 50; i++)
coalescer.Request(i % 2 == 0 ? "a" : "b");
await WaitUntilAsync(() => batches.Count >= 1, TimeSpan.FromSeconds(5));
await Task.Delay(300); // no trailing second refresh
Assert.Single(batches);
Assert.Equal(["a", "b"], batches.Single().OrderBy(h => h));
}
/// <summary>
/// A request arriving WHILE a refresh runs is not lost and does not overlap it: it is served by
/// a second, sequential refresh.
/// </summary>
[Fact]
public async Task RequestDuringRefresh_RunsASecondSequentialRefresh()
{
var release = new TaskCompletionSource();
var concurrent = 0;
var maxConcurrent = 0;
var batches = new ConcurrentQueue<IReadOnlyCollection<string>>();
var coalescer = new ConditionRefreshCoalescer(async (handles, _) =>
{
var now = Interlocked.Increment(ref concurrent);
maxConcurrent = Math.Max(maxConcurrent, now);
batches.Enqueue(handles.ToList());
if (batches.Count == 1)
await release.Task;
Interlocked.Decrement(ref concurrent);
}, TimeSpan.FromMilliseconds(20));
coalescer.Request("a");
await WaitUntilAsync(() => batches.Count == 1, TimeSpan.FromSeconds(5));
coalescer.Request("b"); // while the first refresh is still in flight
await Task.Delay(100);
Assert.Single(batches);
release.SetResult();
await WaitUntilAsync(() => batches.Count == 2, TimeSpan.FromSeconds(5));
Assert.Equal(1, maxConcurrent);
Assert.Equal(["b"], batches.ToArray()[1]);
}
/// <summary>An executor fault is logged, not thrown, and does not stop later refreshes.</summary>
[Fact]
public async Task ExecutorFailure_IsSwallowed_AndLaterRequestsStillRefresh()
{
var calls = 0;
var coalescer = new ConditionRefreshCoalescer((_, _) =>
{
if (Interlocked.Increment(ref calls) == 1)
throw new ServiceResultException(StatusCodes.BadRefreshInProgress);
return Task.CompletedTask;
}, TimeSpan.FromMilliseconds(20));
coalescer.Request("a");
await WaitUntilAsync(() => Volatile.Read(ref calls) == 1, TimeSpan.FromSeconds(5));
await Task.Delay(50);
coalescer.Request("a");
await WaitUntilAsync(() => Volatile.Read(ref calls) == 2, TimeSpan.FromSeconds(5));
}
/// <summary>Clear() (disconnect) drops requests still debouncing — they belong to a dead session.</summary>
[Fact]
public async Task Clear_DropsPendingRequests()
{
var calls = 0;
var coalescer = new ConditionRefreshCoalescer(
(_, _) => { Interlocked.Increment(ref calls); return Task.CompletedTask; },
TimeSpan.FromMilliseconds(100));
coalescer.Request("a");
coalescer.Clear();
await Task.Delay(300);
Assert.Equal(0, Volatile.Read(ref calls));
}
/// <summary>
/// RefreshStart/RefreshEnd stay framing sentinels, never alarms, and RefreshRequired arriving
/// between them neither breaks the frame nor emits a condition.
/// </summary>
[Fact]
public void RefreshRequiredInsideARefreshFrame_LeavesTheFrameIntact()
{
var client = new RealOpcUaClient();
Seed(client, "h1");
client.RefreshRequiredCoalescer = new ConditionRefreshCoalescer(
(_, _) => Task.CompletedTask, TimeSpan.FromMilliseconds(10));
var sink = new List<NativeAlarmTransition>();
EventFieldList Boundary(NodeId type) => new()
{
EventFields = new Variant[] { Variant.From(type), Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null }
};
Handler.Invoke(client, ["h1", "", Boundary(ObjectTypeIds.RefreshStartEventType), (Action<NativeAlarmTransition>)sink.Add]);
Handler.Invoke(client, ["h1", "", RefreshRequiredEvent(), (Action<NativeAlarmTransition>)sink.Add]);
Handler.Invoke(client, ["h1", "", Boundary(ObjectTypeIds.RefreshEndEventType), (Action<NativeAlarmTransition>)sink.Add]);
Assert.Equal(["SnapshotStart", "SnapshotComplete"], sink.Select(t => t.Kind.ToString()));
}
}