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)
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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,11 +3644,24 @@ 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Issues one requester-less (<c>ReplyTo == null</c>) alarm-feed subscribe for
|
||||
/// <paramref name="sourceRef"/> against <paramref name="alarmable"/> — the reconnect
|
||||
/// re-subscribe and its DCL-2 retry.
|
||||
/// </summary>
|
||||
private void IssueAlarmResubscribe(IAlarmSubscribableConnection alarmable, string sourceRef)
|
||||
{
|
||||
var self = Self;
|
||||
var generation = _adapterGeneration;
|
||||
var sr = sourceRef;
|
||||
var filter = _alarmSourceFilter.GetValueOrDefault(sourceRef);
|
||||
_alarmSubscribesInFlight.Add(sr);
|
||||
@@ -3634,6 +3675,58 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
null, null, null, generation, alarmable))
|
||||
.PipeTo(self);
|
||||
}
|
||||
|
||||
// ── DCL-2: alarm re-subscribe retry ──
|
||||
|
||||
/// <summary>
|
||||
/// Next retry delay per alarm source whose requester-less re-subscribe failed. Same floor,
|
||||
/// doubling and ceiling as the tag-resolution probe
|
||||
/// (<see cref="DataConnectionOptions.TagResolutionRetryInterval"/> →
|
||||
/// <see cref="DataConnectionOptions.TagResolutionRetryMaxInterval"/>).
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, TimeSpan> _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))
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Notifies alarm subscribers that the source feed is unavailable (connection lost).</summary>
|
||||
@@ -3693,6 +3786,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
}
|
||||
internal record RetryTagResolution;
|
||||
|
||||
/// <summary>DCL-2: backed-off retry of a failed requester-less alarm-feed re-subscribe.</summary>
|
||||
internal record RetryAlarmResubscribe(string SourceReference, int AdapterGeneration);
|
||||
|
||||
/// <summary>Coalescing-timer tick for the tag-quality counter push.</summary>
|
||||
internal record QualityFlushTick;
|
||||
|
||||
|
||||
@@ -962,11 +962,29 @@ public class RealOpcUaClient : IOpcUaClient
|
||||
HandleAlarmEvent(handle, sourceNodeId, efl, onTransition);
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server's per-item verdict on an alarm event monitored item after
|
||||
/// <c>ApplyChangesAsync</c>: the bad <see cref="ServiceResult"/> when the create was rejected,
|
||||
/// else <c>null</c> (DCL-3).
|
||||
/// </summary>
|
||||
internal static ServiceResult? AlarmItemCreateError(MonitoredItem item)
|
||||
{
|
||||
var error = item.Status?.Error;
|
||||
return error != null && ServiceResult.IsBad(error) ? error : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="CreateAlarmSubscriptionAsync"/> created up front.
|
||||
/// </summary>
|
||||
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 _);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task RemoveAlarmSubscriptionAsync(string subscriptionHandle, CancellationToken cancellationToken = default)
|
||||
{
|
||||
|
||||
+138
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// <list type="bullet">
|
||||
/// <item>DCL-2 — a requester-less alarm re-subscribe that fails after a reconnect is retried on
|
||||
/// a backed-off timer.</item>
|
||||
/// <item>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.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
[Collection("DataConnectionManagerActor")]
|
||||
public class DataConnectionRetryGapTests : TestKit
|
||||
{
|
||||
private readonly ISiteHealthCollector _health = Substitute.For<ISiteHealthCollector>();
|
||||
private readonly IDataConnectionFactory _factory = Substitute.For<IDataConnectionFactory>();
|
||||
|
||||
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");
|
||||
|
||||
/// <summary>
|
||||
/// DCL-2: after a reconnect the DCL re-issues the alarm feed itself (no requester). That
|
||||
/// re-subscribe fails once (e.g. an <c>nsu=</c> 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.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void FailedAlarmResubscribeAfterReconnect_IsRetried()
|
||||
{
|
||||
const string name = "alarm-resub-retry";
|
||||
var adapter = Substitute.For<IDataConnection, IAlarmSubscribableConnection>();
|
||||
adapter.ConnectAsync(Arg.Any<IDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
var calls = 0;
|
||||
AlarmTransitionCallback? latest = null;
|
||||
((IAlarmSubscribableConnection)adapter)
|
||||
.SubscribeAlarmsAsync(Arg.Any<string>(), Arg.Any<string?>(),
|
||||
Arg.Any<AlarmTransitionCallback>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ci =>
|
||||
{
|
||||
var n = Interlocked.Increment(ref calls);
|
||||
if (n == 2)
|
||||
return Task.FromException<string>(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<SubscribeAlarmsResponse>(m => m.Success, TimeSpan.FromSeconds(5));
|
||||
|
||||
adapter.Disconnected += Raise.Event<Action>();
|
||||
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<NativeAlarmTransitionUpdate>(
|
||||
u => u.Transition.SourceObjectReference == "Tank01", TimeSpan.FromMilliseconds(500));
|
||||
}, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DCL-8: a reconnect re-subscribe chunk fails with a connection-level exception while the
|
||||
/// session stays up (no <c>Disconnected</c>). 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.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ConnectionLevelFailureRowInResubscribe_IsRetriedByTheResolutionProbe()
|
||||
{
|
||||
const string name = "resub-connlevel";
|
||||
const string tag = "sensor/temp";
|
||||
var adapter = new DataConnectionSameAdapterReconnectTests.GatedAdapter();
|
||||
var config = new Dictionary<string, string> { ["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<SubscribeTagsResponse>(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<DataConnectionHealthReport>(
|
||||
new DataConnectionActor.GetHealthReport(), TimeSpan.FromSeconds(1)).Result.ResolvedTags == 1,
|
||||
TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(20));
|
||||
}
|
||||
}
|
||||
+45
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// DCL-3 (2026-12-02 review, WP3 task 3.2): <c>ApplyChangesAsync</c> 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.
|
||||
/// </summary>
|
||||
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]);
|
||||
|
||||
/// <summary>A rejected create (e.g. BadNodeIdUnknown) is reported as the item's error.</summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>An item with no error (created) is not reported.</summary>
|
||||
[Fact]
|
||||
public void CreatedItem_ReportsNoError()
|
||||
{
|
||||
var item = NewItem();
|
||||
Assert.Null(RealOpcUaClient.AlarmItemCreateError(item));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user