fix(dcl): bind the reconnect re-subscribe loop to its session; shared supervisory advise ignores the first caller's token (DCL-4, DCL-9, WP3 task 3.3)
This commit is contained in:
+182
@@ -0,0 +1,182 @@
|
||||
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-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).
|
||||
/// </summary>
|
||||
[Collection("DataConnectionManagerActor")]
|
||||
public class DataConnectionResubscribeLoopTests : 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.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));
|
||||
|
||||
/// <summary>The wedged loop from the dead session issues no further chunks once its session ends.</summary>
|
||||
[Fact]
|
||||
public void ResubscribeLoopFromAnEndedSession_StopsAtItsWedgedChunk()
|
||||
{
|
||||
const string name = "resub-loop-cancel";
|
||||
var adapter = new HangableAdapter();
|
||||
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, ["A", "B", "C"], DateTimeOffset.UtcNow));
|
||||
instance.FishForMessage<SubscribeTagsResponse>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A held subscribe call.</summary>
|
||||
internal sealed class HeldCall
|
||||
{
|
||||
private readonly TaskCompletionSource<IReadOnlyList<TagSubscribeResult>> _tcs =
|
||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public volatile bool Started;
|
||||
|
||||
public IReadOnlyList<string> Tags { get; set; } = [];
|
||||
|
||||
public Task<IReadOnlyList<TagSubscribeResult>> Task => _tcs.Task;
|
||||
|
||||
public void Fail(Exception ex) => _tcs.SetException(ex);
|
||||
}
|
||||
|
||||
/// <summary>Batch adapter that succeeds at once, except for one call the test chooses to hold.</summary>
|
||||
internal sealed class HangableAdapter : IDataConnection, IBatchSubscribableConnection
|
||||
{
|
||||
private readonly ConcurrentQueue<string> _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<string, string> 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<IReadOnlyList<TagSubscribeResult>> SubscribeBatchAsync(
|
||||
IReadOnlyList<string> 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<IReadOnlyList<TagSubscribeResult>>(tagPaths
|
||||
.Select(t => new TagSubscribeResult(t, true, $"h{Interlocked.Increment(ref _handle)}", null))
|
||||
.ToList());
|
||||
}
|
||||
|
||||
public Task UnsubscribeBatchAsync(IReadOnlyList<string> subscriptionIds, CancellationToken cancellationToken = default) =>
|
||||
System.Threading.Tasks.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) =>
|
||||
System.Threading.Tasks.Task.CompletedTask;
|
||||
|
||||
public Task<ReadResult> ReadAsync(string tagPath, CancellationToken cancellationToken = default) =>
|
||||
System.Threading.Tasks.Task.FromResult(new ReadResult(false, null, "no value"));
|
||||
|
||||
public Task<IReadOnlyDictionary<string, ReadResult>> ReadBatchAsync(
|
||||
IEnumerable<string> tagPaths, CancellationToken cancellationToken = default) =>
|
||||
System.Threading.Tasks.Task.FromResult<IReadOnlyDictionary<string, ReadResult>>(
|
||||
new Dictionary<string, ReadResult>());
|
||||
|
||||
public Task<WriteResult> WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default) =>
|
||||
System.Threading.Tasks.Task.FromResult(new WriteResult(true, null));
|
||||
|
||||
public Task<IReadOnlyDictionary<string, WriteResult>> WriteBatchAsync(
|
||||
IDictionary<string, object?> values, CancellationToken cancellationToken = default) =>
|
||||
System.Threading.Tasks.Task.FromResult<IReadOnlyDictionary<string, WriteResult>>(
|
||||
values.ToDictionary(kv => kv.Key, _ => new WriteResult(true, null)));
|
||||
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// DCL-9 (2026-12-02 review, WP3 task 3.3): the per-handle supervisory advise is shared by every
|
||||
/// concurrent caller, so it must not run under the token of whichever caller created it. A write
|
||||
/// whose deadline fires must not cancel the advise a concurrent, deadline-free subscribe awaits.
|
||||
/// </summary>
|
||||
public class RealMxGatewaySharedAdviseTests
|
||||
{
|
||||
/// <summary>The first caller's cancellation fails only that caller; the shared advise completes for the second.</summary>
|
||||
[Fact]
|
||||
public async Task FirstCallersCancellation_DoesNotCancelTheSharedAdvise()
|
||||
{
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var coreCalls = 0;
|
||||
CancellationToken coreToken = default;
|
||||
var client = new RealMxGatewayClient(null)
|
||||
{
|
||||
AdviseCoreOverride = async (_, ct) =>
|
||||
{
|
||||
Interlocked.Increment(ref coreCalls);
|
||||
coreToken = ct;
|
||||
await release.Task.WaitAsync(ct);
|
||||
},
|
||||
};
|
||||
|
||||
using var writeDeadline = new CancellationTokenSource();
|
||||
var write = client.EnsureSupervisoryAdvisedAsync(42, writeDeadline.Token);
|
||||
var subscribe = client.EnsureSupervisoryAdvisedAsync(42, CancellationToken.None);
|
||||
|
||||
writeDeadline.Cancel();
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => write);
|
||||
Assert.False(coreToken.IsCancellationRequested); // pre-fix: the shared advise was cancelled
|
||||
|
||||
release.SetResult();
|
||||
await subscribe.WaitAsync(TimeSpan.FromSeconds(5)); // pre-fix: OperationCanceledException
|
||||
Assert.Equal(1, coreCalls); // advise-once still holds
|
||||
}
|
||||
|
||||
/// <summary>A faulted shared advise is evicted so the next caller retries it.</summary>
|
||||
[Fact]
|
||||
public async Task FaultedSharedAdvise_IsRetriedByTheNextCaller()
|
||||
{
|
||||
var coreCalls = 0;
|
||||
var client = new RealMxGatewayClient(null)
|
||||
{
|
||||
AdviseCoreOverride = (_, _) => Interlocked.Increment(ref coreCalls) == 1
|
||||
? Task.FromException(new InvalidOperationException("gateway busy"))
|
||||
: Task.CompletedTask,
|
||||
};
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => client.EnsureSupervisoryAdvisedAsync(7, CancellationToken.None));
|
||||
await client.EnsureSupervisoryAdvisedAsync(7, CancellationToken.None);
|
||||
Assert.Equal(2, coreCalls);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user