6adfc9f449
3.1: seed values are flagged on TagValueReceived; a reconnect/resolution re-seed for a tag that already delivered a live value in the current adapter generation is dropped, an initial-subscribe seed is replaced by the latest live value (a joining instance may have missed earlier live values). 3.8: the connection actor tells subscribers ConnectionQualityChanged(Good) on re-entering Connected; InstanceActor's Good branch only resets the Lever-1 backoff and no longer stamps bound attributes Good.
259 lines
12 KiB
C#
259 lines
12 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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 <c>ConnectionQualityChanged(Good)</c> when it re-enters Connected.
|
|
/// </summary>
|
|
[Collection("DataConnectionManagerActor")]
|
|
public class DataConnectionSeedOrderingTests : TestKit
|
|
{
|
|
private const string Tag = "Mixer.State";
|
|
private const string OtherTag = "Mixer.Speed";
|
|
|
|
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.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<string, string> { ["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);
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
[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<TagValueUpdate>(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<string, object> { [Tag] = "Idle" });
|
|
instance.ExpectMsg<SubscribeTagsResponse>(r => r.Success, TimeSpan.FromSeconds(5));
|
|
var afterSeed = instance.ExpectMsg<TagValueUpdate>(TimeSpan.FromSeconds(5));
|
|
Assert.Equal("Running", afterSeed.Value); // pre-fix: "Idle"
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
[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<string, object> { [Tag] = "Idle" });
|
|
instance.ExpectMsg<SubscribeTagsResponse>(r => r.Success, TimeSpan.FromSeconds(5));
|
|
Assert.Equal("Idle", instance.ExpectMsg<TagValueUpdate>(TimeSpan.FromSeconds(5)).Value);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
[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<SubscribeTagsResponse>(r => r.Success, TimeSpan.FromSeconds(5));
|
|
adapter.ClearCallbacks();
|
|
|
|
var reseedGate = adapter.GateNextRead();
|
|
adapter.RaiseDisconnected();
|
|
var bad = instance.ExpectMsg<ConnectionQualityChanged>(TimeSpan.FromSeconds(5));
|
|
Assert.Equal(QualityCode.Bad, bad.Quality);
|
|
AwaitConnectedCount(name, 2);
|
|
var good = instance.ExpectMsg<ConnectionQualityChanged>(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<TagValueUpdate>(TimeSpan.FromSeconds(5)).Value);
|
|
|
|
reseedGate.Release(new Dictionary<string, object> { [Tag] = "Idle", [OtherTag] = 7 });
|
|
|
|
// OtherTag never re-reported live, so its seed is delivered; Tag's seed must not be.
|
|
var seen = new List<TagValueUpdate>();
|
|
instance.FishForMessage<TagValueUpdate>(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);
|
|
}
|
|
|
|
/// <summary>One held <c>ReadBatchAsync</c> call.</summary>
|
|
internal sealed class ReadGate
|
|
{
|
|
private readonly TaskCompletionSource<Dictionary<string, object>> _tcs =
|
|
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
public Task<Dictionary<string, object>> Values => _tcs.Task;
|
|
|
|
public void Release(Dictionary<string, object> values) => _tcs.SetResult(values);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
internal sealed class SeedGatedAdapter : IDataConnection, IBatchSubscribableConnection
|
|
{
|
|
private readonly ConcurrentDictionary<string, SubscriptionCallback> _callbacks = new();
|
|
private readonly ConcurrentQueue<ReadGate> _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<string, string> connectionDetails, CancellationToken cancellationToken = default)
|
|
{
|
|
Status = ConnectionHealth.Connected;
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task DisconnectAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
|
|
|
|
public Task<IReadOnlyList<TagSubscribeResult>> SubscribeBatchAsync(
|
|
IReadOnlyList<string> tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default)
|
|
{
|
|
var rows = new List<TagSubscribeResult>();
|
|
foreach (var tag in tagPaths)
|
|
{
|
|
_callbacks[tag] = callback;
|
|
rows.Add(new TagSubscribeResult(tag, true, $"h{Interlocked.Increment(ref _handle)}", null));
|
|
}
|
|
return Task.FromResult<IReadOnlyList<TagSubscribeResult>>(rows);
|
|
}
|
|
|
|
public Task UnsubscribeBatchAsync(IReadOnlyList<string> subscriptionIds, CancellationToken cancellationToken = default) =>
|
|
Task.CompletedTask;
|
|
|
|
public Task<string> 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<ReadResult> ReadAsync(string tagPath, CancellationToken cancellationToken = default) =>
|
|
Task.FromResult(new ReadResult(false, null, "no value"));
|
|
|
|
public async Task<IReadOnlyDictionary<string, ReadResult>> ReadBatchAsync(
|
|
IEnumerable<string> tagPaths, CancellationToken cancellationToken = default)
|
|
{
|
|
var values = _readGates.TryDequeue(out var gate)
|
|
? await gate.Values
|
|
: new Dictionary<string, object>();
|
|
return tagPaths
|
|
.Where(values.ContainsKey)
|
|
.ToDictionary(t => t, t => new ReadResult(true,
|
|
new TagValue(values[t], QualityCode.Good, DateTimeOffset.UtcNow), null));
|
|
}
|
|
|
|
public Task<WriteResult> WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default) =>
|
|
Task.FromResult(new WriteResult(true, null));
|
|
|
|
public Task<IReadOnlyDictionary<string, WriteResult>> WriteBatchAsync(
|
|
IDictionary<string, object?> values, CancellationToken cancellationToken = default) =>
|
|
Task.FromResult<IReadOnlyDictionary<string, WriteResult>>(
|
|
values.ToDictionary(kv => kv.Key, _ => new WriteResult(true, null)));
|
|
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|
|
}
|