using System.Collections.Concurrent; 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.Enums; using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors; using ZB.MOM.WW.ScadaBridge.HealthMonitoring; namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors; /// /// DCL-4 (2026-12-02 review, WP3 task 3.3): the reconnect re-subscribe loop is bound to its /// session. A loop whose chunk wedged across a reconnect must stop when that session ends instead /// of carrying on with its remaining chunks against the SAME adapter's NEW client (duplicate /// monitored items / gateway subscribes whose stale-generation results were dropped unreleased). /// [Collection("DataConnectionManagerActor")] public class DataConnectionResubscribeLoopTests : TestKit { private readonly ISiteHealthCollector _health = Substitute.For(); private readonly IDataConnectionFactory _factory = Substitute.For(); private readonly DataConnectionOptions _options = new() { ReconnectInterval = TimeSpan.FromMilliseconds(100), TagResolutionRetryInterval = TimeSpan.FromSeconds(30), WriteTimeout = TimeSpan.FromSeconds(5), SeedReadMaxAttempts = 1, SeedReadRetryDelay = TimeSpan.FromMilliseconds(10), SubscribeBatchSize = 1, 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)); /// The wedged loop from the dead session issues no further chunks once its session ends. [Fact] public void ResubscribeLoopFromAnEndedSession_StopsAtItsWedgedChunk() { const string name = "resub-loop-cancel"; var adapter = new HangableAdapter(); 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, ["A", "B", "C"], DateTimeOffset.UtcNow)); instance.FishForMessage(m => m.Success, TimeSpan.FromSeconds(5)); // Session 2: the re-subscribe loop's FIRST chunk wedges. var wedged = adapter.HangNextCall(); adapter.RaiseDisconnected(); AwaitConnectedCount(name, 2); AwaitCondition(() => wedged.Started, TimeSpan.FromSeconds(5)); // The tags the wedged session-2 loop had NOT reached yet. var notReached = new[] { "A", "B", "C" }.Except(wedged.Tags).ToList(); Assert.Equal(2, notReached.Count); // Session 3: a fresh loop re-subscribes every tag. adapter.RaiseDisconnected(); AwaitConnectedCount(name, 3); AwaitCondition(() => notReached.All(t => adapter.CallsFor(t) == 2), TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10)); // The wedged chunk finally returns (the old client's operation timeout). wedged.Fail(new TimeoutException("old session's operation timed out")); // Pre-fix the session-2 loop carried on: its remaining chunks were issued a THIRD time. var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(500); while (DateTime.UtcNow < deadline) { foreach (var tag in notReached) Assert.Equal(2, adapter.CallsFor(tag)); Thread.Sleep(20); } } /// A held subscribe call. internal sealed class HeldCall { private readonly TaskCompletionSource> _tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); public volatile bool Started; public IReadOnlyList Tags { get; set; } = []; public Task> Task => _tcs.Task; public void Fail(Exception ex) => _tcs.SetException(ex); } /// Batch adapter that succeeds at once, except for one call the test chooses to hold. internal sealed class HangableAdapter : IDataConnection, IBatchSubscribableConnection { private readonly ConcurrentQueue _subscribedTags = new(); private HeldCall? _holdNext; private int _handle; public ConnectionHealth Status { get; private set; } = ConnectionHealth.Disconnected; public event Action? Disconnected; public int CallsFor(string tag) => _subscribedTags.Count(t => t == tag); public HeldCall HangNextCall() { var held = new HeldCall(); Volatile.Write(ref _holdNext, held); return held; } public void RaiseDisconnected() { Status = ConnectionHealth.Disconnected; Disconnected?.Invoke(); } public Task ConnectAsync(IDictionary connectionDetails, CancellationToken cancellationToken = default) { Status = ConnectionHealth.Connected; return System.Threading.Tasks.Task.CompletedTask; } public Task DisconnectAsync(CancellationToken cancellationToken = default) => System.Threading.Tasks.Task.CompletedTask; public Task> SubscribeBatchAsync( IReadOnlyList tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default) { foreach (var tag in tagPaths) _subscribedTags.Enqueue(tag); if (Interlocked.Exchange(ref _holdNext, null) is { } held) { held.Tags = tagPaths.ToList(); held.Started = true; return held.Task; } return System.Threading.Tasks.Task.FromResult>(tagPaths .Select(t => new TagSubscribeResult(t, true, $"h{Interlocked.Increment(ref _handle)}", null)) .ToList()); } public Task UnsubscribeBatchAsync(IReadOnlyList subscriptionIds, CancellationToken cancellationToken = default) => System.Threading.Tasks.Task.CompletedTask; public Task SubscribeAsync(string tagPath, SubscriptionCallback callback, CancellationToken cancellationToken = default) => throw new NotSupportedException("batch-capable adapter"); public Task UnsubscribeAsync(string subscriptionId, CancellationToken cancellationToken = default) => System.Threading.Tasks.Task.CompletedTask; public Task ReadAsync(string tagPath, CancellationToken cancellationToken = default) => System.Threading.Tasks.Task.FromResult(new ReadResult(false, null, "no value")); public Task> ReadBatchAsync( IEnumerable tagPaths, CancellationToken cancellationToken = default) => System.Threading.Tasks.Task.FromResult>( new Dictionary()); public Task WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default) => System.Threading.Tasks.Task.FromResult(new WriteResult(true, null)); public Task> WriteBatchAsync( IDictionary values, CancellationToken cancellationToken = default) => System.Threading.Tasks.Task.FromResult>( values.ToDictionary(kv => kv.Key, _ => new WriteResult(true, null))); public ValueTask DisposeAsync() => ValueTask.CompletedTask; } }