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-1 (2026-12-02 review, WP3 task 3.1): a seed read is held until its whole seed operation /// completes, while the subscription is already live, so a seed can arrive AFTER a newer live value. /// Decided rule: a seed for a tag that has already delivered a live value in the current subscribe /// generation never overwrites it. Also covers SRT-6 / task 3.8 — the connection actor tells its /// subscribers ConnectionQualityChanged(Good) when it re-enters Connected. /// [Collection("DataConnectionManagerActor")] public class DataConnectionSeedOrderingTests : TestKit { private const string Tag = "Mixer.State"; private const string OtherTag = "Mixer.Speed"; 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), SubscribeBatchDelay = TimeSpan.Zero }; private IActorRef CreateConnectionActor(string name, SeedGatedAdapter adapter) { var config = new Dictionary { ["Endpoint"] = "opc.tcp://plc:4840" }; return Sys.ActorOf(Props.Create(() => new DataConnectionActor( name, adapter, _options, _health, _factory, "OpcUa", config, null, 3)), name); } 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 TagValue Good(object value) => new(value, QualityCode.Good, DateTimeOffset.UtcNow); /// /// Initial subscribe: the live "Running" arrives while the seed read is still out; the seed /// then returns the older "Idle". The instance must end on "Running" — the stale seed is /// replaced by the latest live value (pre-fix it regressed the attribute to "Idle", Good). /// [Fact] public void InitialSubscribe_SeedArrivingAfterLiveValue_DoesNotRegressIt() { const string name = "seed-initial"; var adapter = new SeedGatedAdapter(); var actor = CreateConnectionActor(name, adapter); AwaitConnectedCount(name, 1); var seedGate = adapter.GateNextRead(); var instance = CreateTestProbe(); instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag], DateTimeOffset.UtcNow)); // The subscription is live before the seed read returns. adapter.AwaitCallback(Tag)(Tag, Good("Running")); var live = instance.ExpectMsg(TimeSpan.FromSeconds(5)); Assert.Equal("Running", live.Value); // The seed read (taken before the change) now completes with the older value. seedGate.Release(new Dictionary { [Tag] = "Idle" }); instance.ExpectMsg(r => r.Success, TimeSpan.FromSeconds(5)); var afterSeed = instance.ExpectMsg(TimeSpan.FromSeconds(5)); Assert.Equal("Running", afterSeed.Value); // pre-fix: "Idle" } /// /// A seed for a tag that has delivered NO live value is still delivered — the seed is the /// only value a static tag will ever produce. /// [Fact] public void InitialSubscribe_SeedForTagWithNoLiveValue_IsDelivered() { const string name = "seed-static"; var adapter = new SeedGatedAdapter(); var actor = CreateConnectionActor(name, adapter); AwaitConnectedCount(name, 1); var seedGate = adapter.GateNextRead(); var instance = CreateTestProbe(); instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag], DateTimeOffset.UtcNow)); adapter.AwaitCallback(Tag); seedGate.Release(new Dictionary { [Tag] = "Idle" }); instance.ExpectMsg(r => r.Success, TimeSpan.FromSeconds(5)); Assert.Equal("Idle", instance.ExpectMsg(TimeSpan.FromSeconds(5)).Value); } /// /// Reconnect: the re-subscribe goes live and delivers "Running" while the re-seed is still out; /// the re-seed then returns "Idle" for that tag (dropped) and a value for a tag that has not /// re-reported (delivered). The connection also signals Good on re-entering Connected (3.8). /// [Fact] public void Reconnect_ReseedArrivingAfterLiveValue_IsDropped_AndGoodIsSignalled() { const string name = "seed-reconnect"; var adapter = new SeedGatedAdapter(); var actor = CreateConnectionActor(name, adapter); AwaitConnectedCount(name, 1); var instance = CreateTestProbe(); instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag, OtherTag], DateTimeOffset.UtcNow)); instance.ExpectMsg(r => r.Success, TimeSpan.FromSeconds(5)); adapter.ClearCallbacks(); var reseedGate = adapter.GateNextRead(); adapter.RaiseDisconnected(); var bad = instance.ExpectMsg(TimeSpan.FromSeconds(5)); Assert.Equal(QualityCode.Bad, bad.Quality); AwaitConnectedCount(name, 2); var good = instance.ExpectMsg(TimeSpan.FromSeconds(5)); Assert.Equal(QualityCode.Good, good.Quality); // pre-fix: Good was never sent // The new subscription delivers a live change before the re-seed returns. adapter.AwaitCallback(Tag)(Tag, Good("Running")); Assert.Equal("Running", instance.ExpectMsg(TimeSpan.FromSeconds(5)).Value); reseedGate.Release(new Dictionary { [Tag] = "Idle", [OtherTag] = 7 }); // OtherTag never re-reported live, so its seed is delivered; Tag's seed must not be. var seen = new List(); instance.FishForMessage(u => { seen.Add(u); return u.TagPath == OtherTag; }, TimeSpan.FromSeconds(5)); instance.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); Assert.DoesNotContain(seen, u => u.TagPath == Tag); // pre-fix: Tag = "Idle" Assert.Equal(7, seen.Single(u => u.TagPath == OtherTag).Value); } /// One held ReadBatchAsync call. internal sealed class ReadGate { private readonly TaskCompletionSource> _tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); public Task> Values => _tcs.Task; public void Release(Dictionary values) => _tcs.SetResult(values); } /// /// Batch-capable adapter whose subscribes succeed at once (capturing each tag's live /// callback) and whose seed reads can be held until the test releases them. /// internal sealed class SeedGatedAdapter : IDataConnection, IBatchSubscribableConnection { private readonly ConcurrentDictionary _callbacks = new(); private readonly ConcurrentQueue _readGates = new(); private int _handle; public ConnectionHealth Status { get; private set; } = ConnectionHealth.Disconnected; public event Action? Disconnected; public ReadGate GateNextRead() { var gate = new ReadGate(); _readGates.Enqueue(gate); return gate; } public void ClearCallbacks() => _callbacks.Clear(); public SubscriptionCallback AwaitCallback(string tag) { var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); while (DateTime.UtcNow < deadline) { if (_callbacks.TryGetValue(tag, out var cb)) return cb; Thread.Sleep(10); } throw new TimeoutException($"No subscription for {tag}."); } public void RaiseDisconnected() { Status = ConnectionHealth.Disconnected; Disconnected?.Invoke(); } public Task ConnectAsync(IDictionary connectionDetails, CancellationToken cancellationToken = default) { Status = ConnectionHealth.Connected; return Task.CompletedTask; } public Task DisconnectAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; public Task> SubscribeBatchAsync( IReadOnlyList tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default) { var rows = new List(); foreach (var tag in tagPaths) { _callbacks[tag] = callback; rows.Add(new TagSubscribeResult(tag, true, $"h{Interlocked.Increment(ref _handle)}", null)); } return Task.FromResult>(rows); } public Task UnsubscribeBatchAsync(IReadOnlyList subscriptionIds, CancellationToken cancellationToken = default) => 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) => Task.CompletedTask; public Task ReadAsync(string tagPath, CancellationToken cancellationToken = default) => Task.FromResult(new ReadResult(false, null, "no value")); public async Task> ReadBatchAsync( IEnumerable tagPaths, CancellationToken cancellationToken = default) { var values = _readGates.TryDequeue(out var gate) ? await gate.Values : new Dictionary(); return tagPaths .Where(values.ContainsKey) .ToDictionary(t => t, t => new ReadResult(true, new TagValue(values[t], QualityCode.Good, DateTimeOffset.UtcNow), null)); } public Task WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default) => Task.FromResult(new WriteResult(true, null)); public Task> WriteBatchAsync( IDictionary values, CancellationToken cancellationToken = default) => Task.FromResult>( values.ToDictionary(kv => kv.Key, _ => new WriteResult(true, null))); public ValueTask DisposeAsync() => ValueTask.CompletedTask; } }