From 2e8bede3b2d3657d403adad7e06295c5b7822f71 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:53:44 -0500 Subject: [PATCH] fix(dcl): retry failed alarm re-subscribes, check alarm item create status, retry connection-level re-subscribe rows (DCL-2, DCL-3, DCL-8, WP3 task 3.2) --- .../Component-DataConnectionLayer.md | 4 +- .../Actors/DataConnectionActor.cs | 128 ++++++++++++++-- .../Adapters/RealOpcUaClient.cs | 62 +++++++- .../Actors/DataConnectionRetryGapTests.cs | 138 ++++++++++++++++++ .../Adapters/RealOpcUaAlarmItemStatusTests.cs | 45 ++++++ 5 files changed, 355 insertions(+), 22 deletions(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionRetryGapTests.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaAlarmItemStatusTests.cs diff --git a/docs/requirements/Component-DataConnectionLayer.md b/docs/requirements/Component-DataConnectionLayer.md index 9407dbd6..59744bf9 100644 --- a/docs/requirements/Component-DataConnectionLayer.md +++ b/docs/requirements/Component-DataConnectionLayer.md @@ -300,7 +300,7 @@ Three subscribe paths, deliberately paced differently: | **Reconnect re-subscribe** (`ReSubscribeAll`) | **Sequential** chunks of `SubscribeBatchSize` with `SubscribeBatchDelay` between them, all inside ONE background task; each chunk reports its per-tag results back to the actor as its own message. Replaces a tight loop that fired one fire-and-forget task per tag. | | **Tag-resolution probe** | The whole not-in-flight unresolved set, chunked at `SubscribeBatchSize`, as one probe round per timer tick. | -Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed is additionally bound to its session: entering Reconnecting, an adapter swap or actor stop cancels it, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21). **A seed never overwrites a newer live value (2026-12-02 review DCL-1).** The subscription is live before the seed read starts, and a seed is held until its whole seed operation finishes, so a live change inside that window used to be regressed to the older seed value (Good quality, indefinitely for a rarely-changing tag). Seed values now travel as `TagValueReceived` marked with their origin, and the actor keeps the latest live value per tag for the current adapter generation (cleared when the generation advances on reconnect/swap, dropped when the tag loses its last subscriber). A reconnect or tag-resolution re-seed for a tag that has already delivered a live value in that generation is **dropped**; an initial-subscribe seed for such a tag is **replaced by the latest live value** (the joining instance may have registered after the tag's earlier live values were fanned out, and a static tag would otherwise never give it a value). The rule is generation-based, not a timestamp comparison, which would depend on device/server clocks and the configured timestamp mode. **On re-entering Connected after a reconnect the actor tells every subscriber `ConnectionQualityChanged(Good)`** (SRT-6) — a restore signal the Instance Actor uses only to reset its tag-subscribe backoff; per-tag quality is restored by the re-subscribe and re-seed. +Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed is additionally bound to its session: entering Reconnecting, an adapter swap or actor stop cancels it, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21). **A connection-level failure row in a reconnect re-subscribe or probe batch (DCL-8)** now puts the tag into the resolution retry set (previously it was only logged, and with `_subscriptionIds`/`_unresolvedTags` already cleared by `ReSubscribeAll` the tag sat in no retry set until an unrelated reconnect when the session stayed up). **A seed never overwrites a newer live value (2026-12-02 review DCL-1).** The subscription is live before the seed read starts, and a seed is held until its whole seed operation finishes, so a live change inside that window used to be regressed to the older seed value (Good quality, indefinitely for a rarely-changing tag). Seed values now travel as `TagValueReceived` marked with their origin, and the actor keeps the latest live value per tag for the current adapter generation (cleared when the generation advances on reconnect/swap, dropped when the tag loses its last subscriber). A reconnect or tag-resolution re-seed for a tag that has already delivered a live value in that generation is **dropped**; an initial-subscribe seed for such a tag is **replaced by the latest live value** (the joining instance may have registered after the tag's earlier live values were fanned out, and a static tag would otherwise never give it a value). The rule is generation-based, not a timestamp comparison, which would depend on device/server clocks and the configured timestamp mode. **On re-entering Connected after a reconnect the actor tells every subscriber `ConnectionQualityChanged(Good)`** (SRT-6) — a restore signal the Instance Actor uses only to reset its tag-subscribe backoff; per-tag quality is restored by the re-subscribe and re-seed. **OPC UA subscription sharding.** `RealOpcUaClient` places monitored items on the first subscription shard with free capacity (`MaxMonitoredItemsPerSubscription`), creating a shard when all are full and deleting one once it empties. A batch is N × `AddItem` plus **one** `ApplyChanges` per touched shard. Alarms & Conditions event items are pinned to a **dedicated event shard**, so `ConditionRefresh` has a single subscription id to target and `QueueSize:1000` event items never consume data-shard capacity. Every structural mutation (AddItem / RemoveItem / ApplyChanges / Create / Delete) and every shard-list mutation serializes behind ONE per-client gate — the SDK `Subscription` is not safe under concurrent structural mutation, and the subscribe task, resolution probe and alarm subscribe are otherwise unordered. @@ -391,7 +391,7 @@ The registered `SourceReference` is a **NodeId** for OPC UA (the picker, CSV and - **State gating**: `SubscribeAlarmsRequest` is handled only in the **Connected** state; requests arriving while **Connecting**/**Reconnecting** are coalesced to the latest request per subscriber actor/source and processed on entering Connected. Unsubscribes and subscriber termination are handled in every state. - **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. +- **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. **A re-subscribe that fails is retried by the DCL itself (2026-12-02 review DCL-2):** the reconnect re-subscribe has no requester (the `NativeAlarmActor` already counts its feed as established and does not re-subscribe on `NativeAlarmSourceUnavailable`), so a failed one — e.g. an `nsu=` namespace the restarted server has not loaded yet — is re-issued on a per-source backed-off timer (`TagResolutionRetryInterval` doubling to `TagResolutionRetryMaxInterval`) while the source still has subscribers; a later reconnect or the last unsubscribe cancels it. **The OPC UA alarm subscribe checks the event monitored item's create status (DCL-3)**, as the data path does: `ApplyChanges` does not throw for a per-item rejection (unknown node, not an event notifier, rejected filter), so the item is removed from the event shard, its per-handle bookkeeping dropped, and the subscribe fails instead of reporting a live feed that never delivers. - **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. diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs index aea38159..5e689b51 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs @@ -492,6 +492,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers // No session yet — a probe would fail for every tag. ReSubscribeAll's chunk // completions re-arm the timer once the link is up. break; + case RetryAlarmResubscribe: + // No session — ReSubscribeAllAlarms re-issues every feed once the link is up. + break; case ServiceLevelPollTick or ServiceLevelSampled or ServiceLevelProbed: // ScadaBridge#138: belongs to a session that is over; BecomeConnected restarts it. break; @@ -621,6 +624,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers case RetryTagResolution: HandleRetryTagResolution(); break; + case RetryAlarmResubscribe retryAlarm: + HandleRetryAlarmResubscribe(retryAlarm); + break; case BrowseNodeCommand browse: HandleBrowse(browse); break; @@ -985,6 +991,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers // Ignore — the adapter has no live session; ReSubscribeAll's chunk // completions re-arm the retry timer after reconnect. break; + case RetryAlarmResubscribe: + // Ignore — ReSubscribeAllAlarms re-issues every feed after reconnect. + break; case ServiceLevelProbed { AfterDisconnect: true } lostLinkProbe: // ScadaBridge#141: the other endpoint's verdict for a link lost after a Degraded level. HandleDisconnectProbed(lostLinkProbe); @@ -2781,10 +2790,17 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers } else if (row.ConnectionLevelFailure) { - // Connection-level fault: not a tag-resolution problem. The reconnect - // cycle re-issues everything from _subscriptionsByInstance. + // Connection-level fault on a re-subscribe / probe row. If the adapter also + // raises Disconnected, the reconnect cycle re-issues everything from + // _subscriptionsByInstance — but nothing here starts that cycle, and + // ReSubscribeAll already cleared _subscriptionIds/_unresolvedTags, so a + // chunk that failed while the session stayed healthy used to leave its tags + // in NO retry set: Bad until some unrelated reconnect (DCL-8). Put them in + // the resolution retry set; a reconnect clears it and re-issues them anyway. _log.Warning("[{0}] Batch subscribe for {1} failed at connection level: {2}", _connectionName, row.TagPath, row.Error); + if (_instancesByTag.ContainsKey(row.TagPath) && !_subscriptionIds.ContainsKey(row.TagPath)) + _unresolvedTags.Add(row.TagPath); } else { @@ -3425,8 +3441,19 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers { _log.Warning("[{0}] Alarm subscribe failed for source {1}: {2}", _connectionName, msg.SourceReference, msg.Error); + + // DCL-2: a reconnect re-subscribe (ReplyTo == null) has no requester to retry it — + // the NativeAlarmActor already counts the feed as established and its + // NativeAlarmSourceUnavailable handler deliberately does not re-subscribe — so the + // DCL retries it itself on a backed-off timer while the source still has + // subscribers. An interactive subscribe's failure is retried by its requester. + if (msg.ReplyTo is null) + ScheduleAlarmResubscribeRetry(msg.SourceReference); } + if (msg.Success) + CancelAlarmResubscribeRetry(msg.SourceReference); + // ReplyTo is null for reconnect re-subscribes (no original requester to answer). msg.ReplyTo?.Tell(new SubscribeAlarmsResponse( msg.CorrelationId ?? string.Empty, msg.InstanceUniqueName ?? string.Empty, @@ -3595,6 +3622,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers UnindexAlarmSource(sourceReference); _alarmSourceFilter.Remove(sourceReference); _alarmSourceFilterPredicate.Remove(sourceReference); + CancelAlarmResubscribeRetry(sourceReference); // Clear the in-flight marker so that if an adapter // subscribe is still in flight for this source, the late AlarmSubscribeCompleted // is recognized as orphaned (its guard checks _alarmSourceSubscribers, now empty) @@ -3616,24 +3644,89 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers _alarmSubscriptionIds.Clear(); _alarmReplay.Clear(); _alarmSubscribesInFlight.Clear(); - var self = Self; - var generation = _adapterGeneration; + // A fresh session re-issues every feed: retries armed against the previous one are moot + // and their backoff starts over. + foreach (var sourceRef in _alarmResubscribeInterval.Keys.ToList()) + CancelAlarmResubscribeRetry(sourceRef); foreach (var sourceRef in _alarmSourceSubscribers.Keys.ToList()) + IssueAlarmResubscribe(alarmable, sourceRef); + } + + /// + /// Issues one requester-less (ReplyTo == null) alarm-feed subscribe for + /// against — the reconnect + /// re-subscribe and its DCL-2 retry. + /// + private void IssueAlarmResubscribe(IAlarmSubscribableConnection alarmable, string sourceRef) + { + var self = Self; + var generation = _adapterGeneration; + var sr = sourceRef; + var filter = _alarmSourceFilter.GetValueOrDefault(sourceRef); + _alarmSubscribesInFlight.Add(sr); + alarmable.SubscribeAlarmsAsync(sr, filter, + t => self.Tell(new AlarmTransitionReceived(t, generation))) + .ContinueWith(task => task.IsCompletedSuccessfully + ? new AlarmSubscribeCompleted( + sr, true, task.Result, null, null, null, null, generation, alarmable) as object + : new AlarmSubscribeCompleted(sr, false, null, + task.Exception?.GetBaseException().Message ?? "Unknown error", + null, null, null, generation, alarmable)) + .PipeTo(self); + } + + // ── DCL-2: alarm re-subscribe retry ── + + /// + /// Next retry delay per alarm source whose requester-less re-subscribe failed. Same floor, + /// doubling and ceiling as the tag-resolution probe + /// ( → + /// ). + /// + private readonly Dictionary _alarmResubscribeInterval = new(); + + private static string AlarmResubscribeTimerKey(string sourceRef) => "alarm-resubscribe:" + sourceRef; + + private void ScheduleAlarmResubscribeRetry(string sourceRef) + { + if (!_alarmSourceSubscribers.ContainsKey(sourceRef)) + return; + + var delay = _alarmResubscribeInterval.TryGetValue(sourceRef, out var current) + ? current + : _options.TagResolutionRetryInterval; + _alarmResubscribeInterval[sourceRef] = NextTagResolutionInterval( + delay, _options.TagResolutionRetryInterval, _options.TagResolutionRetryMaxInterval); + Timers.StartSingleTimer(AlarmResubscribeTimerKey(sourceRef), + new RetryAlarmResubscribe(sourceRef, _adapterGeneration), delay); + _log.Info("[{0}] Alarm feed for source {1} will be re-subscribed in {2}", + _connectionName, sourceRef, delay); + } + + private void CancelAlarmResubscribeRetry(string sourceRef) + { + _alarmResubscribeInterval.Remove(sourceRef); + Timers.Cancel(AlarmResubscribeTimerKey(sourceRef)); + } + + private void HandleRetryAlarmResubscribe(RetryAlarmResubscribe msg) + { + // A retry armed against an earlier session is moot: the reconnect re-issued every feed. + if (msg.AdapterGeneration != _adapterGeneration) + return; + if (!_alarmSourceSubscribers.ContainsKey(msg.SourceReference)) { - var sr = sourceRef; - var filter = _alarmSourceFilter.GetValueOrDefault(sourceRef); - _alarmSubscribesInFlight.Add(sr); - alarmable.SubscribeAlarmsAsync(sr, filter, - t => self.Tell(new AlarmTransitionReceived(t, generation))) - .ContinueWith(task => task.IsCompletedSuccessfully - ? new AlarmSubscribeCompleted( - sr, true, task.Result, null, null, null, null, generation, alarmable) as object - : new AlarmSubscribeCompleted(sr, false, null, - task.Exception?.GetBaseException().Message ?? "Unknown error", - null, null, null, generation, alarmable)) - .PipeTo(self); + CancelAlarmResubscribeRetry(msg.SourceReference); + return; } + if (_alarmSubscriptionIds.ContainsKey(msg.SourceReference) + || _alarmSubscribesInFlight.Contains(msg.SourceReference) + || _adapter is not IAlarmSubscribableConnection alarmable) + return; + + _log.Info("[{0}] Retrying alarm feed subscribe for source {1}", _connectionName, msg.SourceReference); + IssueAlarmResubscribe(alarmable, msg.SourceReference); } /// Notifies alarm subscribers that the source feed is unavailable (connection lost). @@ -3693,6 +3786,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers } internal record RetryTagResolution; + /// DCL-2: backed-off retry of a failed requester-less alarm-feed re-subscribe. + internal record RetryAlarmResubscribe(string SourceReference, int AdapterGeneration); + /// Coalescing-timer tick for the tag-quality counter push. internal record QualityFlushTick; diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs index 4de0230d..e4293564 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs @@ -962,11 +962,29 @@ public class RealOpcUaClient : IOpcUaClient HandleAlarmEvent(handle, sourceNodeId, efl, onTransition); }; - await _applyGate.RunAsync(async () => + try { - eventShard.AddItem(item); - await eventShard.ApplyChangesAsync(cancellationToken); - }, cancellationToken); + await _applyGate.RunAsync(async () => + { + eventShard.AddItem(item); + await eventShard.ApplyChangesAsync(cancellationToken); + }, cancellationToken); + } + catch + { + await DiscardFailedAlarmItemAsync(handle, eventShard, item); + throw; + } + + // DCL-3: ApplyChangesAsync does NOT throw for a per-item create failure — the server's + // verdict is on the item's status, exactly as on the data path. An unknown node, a node + // that is not an event notifier or a rejected event filter used to be recorded as a live + // feed (SubscribeAlarmsResponse Success) that never delivers anything. + if (AlarmItemCreateError(item) is { } createError) + { + await DiscardFailedAlarmItemAsync(handle, eventShard, item); + throw new ServiceResultException(createError); + } _alarmItems[handle] = item; // Replay currently-active conditions as a Snapshot…SnapshotComplete sequence. @@ -974,6 +992,42 @@ public class RealOpcUaClient : IOpcUaClient return handle; } + /// + /// The server's per-item verdict on an alarm event monitored item after + /// ApplyChangesAsync: the bad when the create was rejected, + /// else null (DCL-3). + /// + internal static ServiceResult? AlarmItemCreateError(MonitoredItem item) + { + var error = item.Status?.Error; + return error != null && ServiceResult.IsBad(error) ? error : null; + } + + /// + /// Unwinds a half-created alarm feed: removes the item from the event shard (best effort — + /// a dead session must not mask the original failure) and drops the per-handle bookkeeping + /// created up front. + /// + private async Task DiscardFailedAlarmItemAsync(string handle, Subscription eventShard, MonitoredItem item) + { + try + { + await _applyGate.RunAsync(async () => + { + eventShard.RemoveItem(item); + await eventShard.ApplyChangesAsync(CancellationToken.None); + }, CancellationToken.None); + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Removing a failed alarm event item from the event shard failed (ignored)."); + } + + _alarmInRefresh.TryRemove(handle, out _); + _alarmSnapshotIds.TryRemove(handle, out _); + _alarmLastState.TryRemove(handle, out _); + } + /// public async Task RemoveAlarmSubscriptionAsync(string subscriptionHandle, CancellationToken cancellationToken = default) { diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionRetryGapTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionRetryGapTests.cs new file mode 100644 index 00000000..21850772 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionRetryGapTests.cs @@ -0,0 +1,138 @@ +using Akka.Actor; +using Akka.TestKit.Xunit2; +using NSubstitute; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors; +using ZB.MOM.WW.ScadaBridge.HealthMonitoring; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors; + +/// +/// WP3 task 3.2 (2026-12-02 review): failures on the reconnect paths that used to leave a feed or +/// a tag in NO retry set. +/// +/// DCL-2 — a requester-less alarm re-subscribe that fails after a reconnect is retried on +/// a backed-off timer. +/// DCL-8 — a connection-level failure row in a re-subscribe batch puts the tag into the +/// resolution retry set instead of only logging it. +/// +/// +[Collection("DataConnectionManagerActor")] +public class DataConnectionRetryGapTests : TestKit +{ + private readonly ISiteHealthCollector _health = Substitute.For(); + private readonly IDataConnectionFactory _factory = Substitute.For(); + + private readonly DataConnectionOptions _options = new() + { + ReconnectInterval = TimeSpan.FromMilliseconds(100), + TagResolutionRetryInterval = TimeSpan.FromMilliseconds(200), + TagResolutionRetryMaxInterval = TimeSpan.FromSeconds(1), + WriteTimeout = TimeSpan.FromSeconds(5), + SeedReadMaxAttempts = 1, + SeedReadRetryDelay = TimeSpan.FromMilliseconds(10), + SubscribeBatchDelay = TimeSpan.Zero + }; + + private void AwaitConnectedCount(string name, int count) => + AwaitCondition(() => _health.ReceivedCalls().Count(c => + c.GetMethodInfo().Name == nameof(ISiteHealthCollector.UpdateConnectionHealth) && + c.GetArguments() is [string n, ConnectionHealth reported, ..] && + n == name && reported == ConnectionHealth.Connected) >= count, + TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10)); + + private static NativeAlarmTransition AlarmRaise(string source) => + new(source + ".Hi", source, "AnalogLimit.Hi", AlarmTransitionKind.Raise, + new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 500), + "Process", "hi", "hi", "", "", null, DateTimeOffset.UtcNow, "92", "90"); + + /// + /// DCL-2: after a reconnect the DCL re-issues the alarm feed itself (no requester). That + /// re-subscribe fails once (e.g. an nsu= namespace the restarted server has not loaded + /// yet); the DCL must retry it, and transitions from the retried feed must reach the instance. + /// Pre-fix the failure was only logged and the source stayed silent until the next reconnect. + /// + [Fact] + public void FailedAlarmResubscribeAfterReconnect_IsRetried() + { + const string name = "alarm-resub-retry"; + var adapter = Substitute.For(); + adapter.ConnectAsync(Arg.Any>(), Arg.Any()) + .Returns(Task.CompletedTask); + var calls = 0; + AlarmTransitionCallback? latest = null; + ((IAlarmSubscribableConnection)adapter) + .SubscribeAlarmsAsync(Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any()) + .Returns(ci => + { + var n = Interlocked.Increment(ref calls); + if (n == 2) + return Task.FromException(new InvalidOperationException("namespace not loaded yet")); + latest = (AlarmTransitionCallback)ci[2]; + return Task.FromResult($"alarm-sub-{n}"); + }); + + var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor( + name, adapter, _options, _health, _factory, "OpcUa")), name); + AwaitConnectedCount(name, 1); + + var instance = CreateTestProbe(); + instance.Send(actor, new SubscribeAlarmsRequest("c", "inst", name, "Tank01", null, DateTimeOffset.UtcNow)); + instance.ExpectMsg(m => m.Success, TimeSpan.FromSeconds(5)); + + adapter.Disconnected += Raise.Event(); + AwaitConnectedCount(name, 2); + + // Call 2 (the reconnect re-subscribe) failed; the retry is call 3. + AwaitCondition(() => Volatile.Read(ref calls) >= 3, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(20)); + + // The retried feed is live: a transition reaches the instance. + AwaitCondition(() => latest != null, TimeSpan.FromSeconds(5)); + AwaitAssert(() => + { + latest!(AlarmRaise("Tank01")); + instance.FishForMessage( + u => u.Transition.SourceObjectReference == "Tank01", TimeSpan.FromMilliseconds(500)); + }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100)); + } + + /// + /// DCL-8: a reconnect re-subscribe chunk fails with a connection-level exception while the + /// session stays up (no Disconnected). The tag must land in the resolution retry set and + /// be re-subscribed by the probe; pre-fix it sat in no retry set — Bad until an unrelated + /// reconnect. + /// + [Fact] + public void ConnectionLevelFailureRowInResubscribe_IsRetriedByTheResolutionProbe() + { + const string name = "resub-connlevel"; + const string tag = "sensor/temp"; + var adapter = new DataConnectionSameAdapterReconnectTests.GatedAdapter(); + var config = new Dictionary { ["Endpoint"] = "opc.tcp://plc:4840" }; + var actor = Sys.ActorOf(Props.Create(() => + new DataConnectionActor(name, adapter, _options, _health, _factory, "OpcUa", config, null, 3)), name); + AwaitConnectedCount(name, 1); + + var instance = CreateTestProbe(); + instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [tag], DateTimeOffset.UtcNow)); + adapter.AwaitCall(0).Complete(tag, "h0"); + instance.FishForMessage(m => m.Success, TimeSpan.FromSeconds(5)); + + adapter.RaiseDisconnected(); + AwaitConnectedCount(name, 2); + + // The re-subscribe chunk fails at connection level; the session itself stays healthy. + adapter.AwaitCall(1).Fail(new InvalidOperationException("transient transport fault")); + + // The resolution probe re-issues the tag (pre-fix: never). + adapter.AwaitCall(2).Complete(tag, "h2"); + AwaitCondition(() => actor.Ask( + new DataConnectionActor.GetHealthReport(), TimeSpan.FromSeconds(1)).Result.ResolvedTags == 1, + TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(20)); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaAlarmItemStatusTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaAlarmItemStatusTests.cs new file mode 100644 index 00000000..3dbc2b20 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaAlarmItemStatusTests.cs @@ -0,0 +1,45 @@ +using System.Reflection; +using Opc.Ua; +using Opc.Ua.Client; +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters; + +/// +/// DCL-3 (2026-12-02 review, WP3 task 3.2): ApplyChangesAsync does not throw for a +/// per-item create failure, so the alarm path must read the event item's status — as the data +/// path already does — instead of recording a rejected item as a live feed. +/// +public class RealOpcUaAlarmItemStatusTests +{ +#pragma warning disable CS0618 // the parameterless MonitoredItem ctor is fine for a status-only probe + private static MonitoredItem NewItem() => new(); +#pragma warning restore CS0618 + + // MonitoredItemStatus.SetError is not public; the SDK calls it when the server rejects a create. + private static void SetError(MonitoredItem item, ServiceResult error) => + typeof(MonitoredItemStatus) + .GetMethod("SetError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)! + .Invoke(item.Status, [error]); + + /// A rejected create (e.g. BadNodeIdUnknown) is reported as the item's error. + [Fact] + public void RejectedItem_ReportsTheBadStatus() + { + var item = NewItem(); + SetError(item, new ServiceResult(StatusCodes.BadNodeIdUnknown)); + + var error = RealOpcUaClient.AlarmItemCreateError(item); + + Assert.NotNull(error); + Assert.Equal(StatusCodes.BadNodeIdUnknown, error!.StatusCode.Code); + } + + /// An item with no error (created) is not reported. + [Fact] + public void CreatedItem_ReportsNoError() + { + var item = NewItem(); + Assert.Null(RealOpcUaClient.AlarmItemCreateError(item)); + } +}