diff --git a/docs/requirements/Component-DataConnectionLayer.md b/docs/requirements/Component-DataConnectionLayer.md index 20d61d8d..52d6d0ba 100644 --- a/docs/requirements/Component-DataConnectionLayer.md +++ b/docs/requirements/Component-DataConnectionLayer.md @@ -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. diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/ConditionRefreshCoalescer.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/ConditionRefreshCoalescer.cs new file mode 100644 index 00000000..ccd16335 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/ConditionRefreshCoalescer.cs @@ -0,0 +1,143 @@ +using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters; + +/// +/// Coalesces OPC UA RefreshRequiredEventType notifications into ConditionRefresh calls +/// (Gitea #148, OPC UA Part 9 §5.11.4: on RefreshRequired a client calls ConditionRefresh). +/// +/// +/// +/// 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. therefore only records +/// the alarm handle and returns; a single background loop does the work. +/// +/// +/// 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 : 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 BadRefreshInProgress). +/// +/// +/// 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. +/// +/// +internal sealed class ConditionRefreshCoalescer +{ + private readonly Func, CancellationToken, Task> _execute; + private readonly ILogger _logger; + private readonly ConcurrentDictionary _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; + + /// Initializes the coalescer. + /// Runs one coalesced refresh for the drained set of alarm handles. + /// How long requests accumulate before a refresh is issued. + /// Logger for failures; null uses a null logger. + public ConditionRefreshCoalescer( + Func, CancellationToken, Task> execute, + TimeSpan debounce, + ILogger? logger = null) + { + _execute = execute ?? throw new ArgumentNullException(nameof(execute)); + Debounce = debounce; + _logger = logger ?? NullLogger.Instance; + } + + /// The window over which RefreshRequired notifications coalesce into one refresh. + public TimeSpan Debounce { get; } + + /// Number of refresh batches handed to the executor (diagnostics / tests). + public int ExecutedBatches => Volatile.Read(ref _executedBatches); + private int _executedBatches; + + /// + /// Records that 's item received RefreshRequired. Never blocks + /// and never throws — safe to call from the OPC UA publish thread. + /// + /// The alarm subscription handle whose item received the event. + public void Request(string alarmHandle) + { + _pending[alarmHandle] = 0; + TryStartLoop(); + } + + /// + /// 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. + /// + 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(); + 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(); + } + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs index f49da3b5..e6a302d7 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs @@ -74,6 +74,19 @@ public class RealOpcUaClient : IOpcUaClient private readonly ConcurrentDictionary _alarmSnapshotIds = new(); // Per-handle last (active, acked) by source reference, to derive transition kind. private readonly ConcurrentDictionary> _alarmLastState = new(); + + /// + /// 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. + /// + internal static readonly TimeSpan RefreshRequiredDebounce = TimeSpan.FromMilliseconds(500); + + /// + /// Turns RefreshRequired events into debounced, off-publish-thread ConditionRefresh calls + /// (Gitea #148). Internal-settable so tests can observe or replace the executor. + /// + 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.Instance; + RefreshRequiredCoalescer = new ConditionRefreshCoalescer( + ExecuteRequiredRefreshAsync, RefreshRequiredDebounce, _logger); } /// @@ -544,6 +559,9 @@ public class RealOpcUaClient : IOpcUaClient /// 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() + // 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 }; } + /// + /// 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 ConditionRefresh on the event shard + /// covers them all; otherwise each asking item gets a targeted ConditionRefresh2, 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 + /// turns into a Snapshot epoch and the Native Alarm Actor's + /// snapshot swap uses to clear any condition the refreshed snapshot no longer lists. + /// + /// Alarm handles whose items received RefreshRequired. + /// Cancellation token. + private async Task ExecuteRequiredRefreshAsync(IReadOnlyCollection 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) { diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaClientAlarmFilterTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaClientAlarmFilterTests.cs index 7e7aa309..a33890b7 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaClientAlarmFilterTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaClientAlarmFilterTests.cs @@ -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); } - /// Verifies that a single known condition type produces a single of-type clause with no OR. + /// + /// 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). + /// [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 + } + + /// Verifies that every non-empty WhereClause admits RefreshRequiredEventType (Gitea #148). + [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()) + .Select(o => o.Value.ToString()) + .ToList(); + Assert.Contains(ObjectTypeIds.RefreshRequiredEventType.ToString(), ofTypeOperands); } /// Verifies that condition type matching is case-insensitive. @@ -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)); } /// Verifies that a filter of only unknown types omits the where clause. diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaRefreshRequiredTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaRefreshRequiredTests.cs new file mode 100644 index 00000000..2dde2052 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaRefreshRequiredTests.cs @@ -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; + +/// +/// Gitea #148: OtOpcUa emits RefreshRequiredEventType (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 HandleAlarmEvent and the +/// debounce/coalesce behaviour of . +/// +public class RealOpcUaRefreshRequiredTests +{ + private static readonly MethodInfo Handler = + typeof(RealOpcUaClient).GetMethod("HandleAlarmEvent", BindingFlags.Instance | BindingFlags.NonPublic)!; + + /// OtOpcUa's RefreshRequired shape: SourceNode = Server, SourceName "Server", Message "RefreshRequired". + 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>)field.GetValue(client)!; + map[handle] = new Dictionary(StringComparer.Ordinal); + } + + private static async Task WaitUntilAsync(Func condition, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (!condition()) + { + if (DateTime.UtcNow > deadline) + throw new TimeoutException("condition not reached"); + await Task.Delay(10); + } + } + + /// A RefreshRequired event is never surfaced as a native alarm transition. + [Fact] + public async Task RefreshRequired_IsNotMappedAsAnAlarm_AndRequestsARefresh() + { + var client = new RealOpcUaClient(); + Seed(client, "h1"); + var batches = new ConcurrentQueue>(); + client.RefreshRequiredCoalescer = new ConditionRefreshCoalescer( + (handles, _) => { batches.Enqueue(handles.ToList()); return Task.CompletedTask; }, + TimeSpan.FromMilliseconds(20)); + var sink = new List(); + + Handler.Invoke(client, ["h1", "ns=2;s=Area", RefreshRequiredEvent(), (Action)sink.Add]); + + Assert.Empty(sink); // no phantom condition keyed "Server" + await WaitUntilAsync(() => batches.Count == 1, TimeSpan.FromSeconds(5)); + Assert.Equal(["h1"], batches.Single()); + } + + /// + /// 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. + /// + [Fact] + public async Task RefreshRequired_WithNoSession_IsSwallowed() + { + var client = new RealOpcUaClient(); + Seed(client, "h1"); + var sink = new List(); + + Handler.Invoke(client, ["h1", "", RefreshRequiredEvent(), (Action)sink.Add]); + + await WaitUntilAsync(() => client.RefreshRequiredCoalescer.ExecutedBatches == 1, TimeSpan.FromSeconds(5)); + Assert.Empty(sink); + } + + /// A burst of RefreshRequired across several items costs ONE refresh carrying every handle. + [Fact] + public async Task Burst_CoalescesIntoOneRefresh() + { + var batches = new ConcurrentQueue>(); + 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)); + } + + /// + /// A request arriving WHILE a refresh runs is not lost and does not overlap it: it is served by + /// a second, sequential refresh. + /// + [Fact] + public async Task RequestDuringRefresh_RunsASecondSequentialRefresh() + { + var release = new TaskCompletionSource(); + var concurrent = 0; + var maxConcurrent = 0; + var batches = new ConcurrentQueue>(); + 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]); + } + + /// An executor fault is logged, not thrown, and does not stop later refreshes. + [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)); + } + + /// Clear() (disconnect) drops requests still debouncing — they belong to a dead session. + [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)); + } + + /// + /// RefreshStart/RefreshEnd stay framing sentinels, never alarms, and RefreshRequired arriving + /// between them neither breaks the frame nor emits a condition. + /// + [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(); + 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)sink.Add]); + Handler.Invoke(client, ["h1", "", RefreshRequiredEvent(), (Action)sink.Add]); + Handler.Invoke(client, ["h1", "", Boundary(ObjectTypeIds.RefreshEndEventType), (Action)sink.Add]); + + Assert.Equal(["SnapshotStart", "SnapshotComplete"], sink.Select(t => t.Kind.ToString())); + } +}