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));
}
}