From d52aff1bee0dcaa716bd0ce9decf3ceb5bf4f065 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:57:13 -0500 Subject: [PATCH] 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) --- .../Component-DataConnectionLayer.md | 2 +- .../Actors/DataConnectionActor.cs | 33 +++- .../Adapters/MxGatewayDataConnection.cs | 5 +- .../Adapters/OpcUaDataConnection.cs | 5 +- .../Adapters/RealMxGatewayClient.cs | 46 ++++- .../DataConnectionResubscribeLoopTests.cs | 182 ++++++++++++++++++ .../RealMxGatewaySharedAdviseTests.cs | 58 ++++++ 7 files changed, 317 insertions(+), 14 deletions(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionResubscribeLoopTests.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealMxGatewaySharedAdviseTests.cs diff --git a/docs/requirements/Component-DataConnectionLayer.md b/docs/requirements/Component-DataConnectionLayer.md index 59744bf9..de95df27 100644 --- a/docs/requirements/Component-DataConnectionLayer.md +++ b/docs/requirements/Component-DataConnectionLayer.md @@ -300,7 +300,7 @@ Three subscribe paths, deliberately paced differently: | **Reconnect re-subscribe** (`ReSubscribeAll`) | **Sequential** chunks of `SubscribeBatchSize` with `SubscribeBatchDelay` between them, all inside ONE background task; each chunk reports its per-tag results back to the actor as its own message. Replaces a tight loop that fired one fire-and-forget task per tag. | | **Tag-resolution probe** | The whole not-in-flight unresolved set, chunked at `SubscribeBatchSize`, as one probe round per timer tick. | -Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed is additionally bound to its session: entering Reconnecting, an adapter swap or actor stop cancels it, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21). **A connection-level failure row in a reconnect re-subscribe or probe batch (DCL-8)** now puts the tag into the resolution retry set (previously it was only logged, and with `_subscriptionIds`/`_unresolvedTags` already cleared by `ReSubscribeAll` the tag sat in no retry set until an unrelated reconnect when the session stayed up). **A seed never overwrites a newer live value (2026-12-02 review DCL-1).** The subscription is live before the seed read starts, and a seed is held until its whole seed operation finishes, so a live change inside that window used to be regressed to the older seed value (Good quality, indefinitely for a rarely-changing tag). Seed values now travel as `TagValueReceived` marked with their origin, and the actor keeps the latest live value per tag for the current adapter generation (cleared when the generation advances on reconnect/swap, dropped when the tag loses its last subscriber). A reconnect or tag-resolution re-seed for a tag that has already delivered a live value in that generation is **dropped**; an initial-subscribe seed for such a tag is **replaced by the latest live value** (the joining instance may have registered after the tag's earlier live values were fanned out, and a static tag would otherwise never give it a value). The rule is generation-based, not a timestamp comparison, which would depend on device/server clocks and the configured timestamp mode. **On re-entering Connected after a reconnect the actor tells every subscriber `ConnectionQualityChanged(Good)`** (SRT-6) — a restore signal the Instance Actor uses only to reset its tag-subscribe backoff; per-tag quality is restored by the re-subscribe and re-seed. +Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed **and the reconnect re-subscribe loop** are additionally bound to their session (one shared token, created before either starts): entering Reconnecting, an adapter swap or actor stop cancels them, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21), and a re-subscribe loop whose chunk wedged across a reconnect stops at that chunk instead of issuing its remaining chunks against the same adapter's new client (2026-12-02 review DCL-4 — previously duplicate OPC UA monitored items / MxGateway subscribes whose stale-generation results were dropped unreleased). The adapters dereference their session client once per batch call. **The MxGateway per-handle supervisory advise is shared by concurrent callers and runs under the client's lifetime (bounded at 60 s), not the token of the caller that created it** (DCL-9) — each caller applies its own deadline to its wait only, so a write timing out no longer cancels the advise a concurrent subscribe awaits; a faulted/timed-out shared advise is evicted and retried by the next caller. **A connection-level failure row in a reconnect re-subscribe or probe batch (DCL-8)** now puts the tag into the resolution retry set (previously it was only logged, and with `_subscriptionIds`/`_unresolvedTags` already cleared by `ReSubscribeAll` the tag sat in no retry set until an unrelated reconnect when the session stayed up). **A seed never overwrites a newer live value (2026-12-02 review DCL-1).** The subscription is live before the seed read starts, and a seed is held until its whole seed operation finishes, so a live change inside that window used to be regressed to the older seed value (Good quality, indefinitely for a rarely-changing tag). Seed values now travel as `TagValueReceived` marked with their origin, and the actor keeps the latest live value per tag for the current adapter generation (cleared when the generation advances on reconnect/swap, dropped when the tag loses its last subscriber). A reconnect or tag-resolution re-seed for a tag that has already delivered a live value in that generation is **dropped**; an initial-subscribe seed for such a tag is **replaced by the latest live value** (the joining instance may have registered after the tag's earlier live values were fanned out, and a static tag would otherwise never give it a value). The rule is generation-based, not a timestamp comparison, which would depend on device/server clocks and the configured timestamp mode. **On re-entering Connected after a reconnect the actor tells every subscriber `ConnectionQualityChanged(Good)`** (SRT-6) — a restore signal the Instance Actor uses only to reset its tag-subscribe backoff; per-tag quality is restored by the re-subscribe and re-seed. **OPC UA subscription sharding.** `RealOpcUaClient` places monitored items on the first subscription shard with free capacity (`MaxMonitoredItemsPerSubscription`), creating a shard when all are full and deleting one once it empties. A batch is N × `AddItem` plus **one** `ApplyChanges` per touched shard. Alarms & Conditions event items are pinned to a **dedicated event shard**, so `ConditionRefresh` has a single subscription id to target and `QueueSize:1000` event items never consume data-shard capacity. Every structural mutation (AddItem / RemoveItem / ApplyChanges / Create / Delete) and every shard-list mutation serializes behind ONE per-client gate — the SDK `Subscription` is not safe under concurrent structural mutation, and the subscribe task, resolution probe and alarm subscribe are otherwise unordered. diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs index 5e689b51..61a4923f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs @@ -2977,6 +2977,17 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers var batchSize = Math.Max(1, _options.SubscribeBatchSize); var chunkDelay = _options.SubscribeBatchDelay; + // Session-bound background work (the re-subscribe loop below AND the re-seed further + // down) shares ONE token, created BEFORE either starts. CancelSessionWork — entering + // Reconnecting, an adapter swap, actor stop — cancels it. DCL-4: the loop used to have + // no token, so a loop left over from a dead session (a chunk wedged across a reconnect) + // carried on issuing its remaining chunks against the SAME adapter object's NEW client: + // duplicate OPC UA monitored items / MxGateway subscribes whose stale-generation results + // were then dropped without release. + CancelSessionWork(); + _sessionWorkCts = new CancellationTokenSource(); + var sessionToken = _sessionWorkCts.Token; + // Bounded, sequential chunks in ONE background task — replacing the previous // "one fire-and-forget task per tag" storm (37,500 concurrent subscribes at the // sizing target). Sequential because subscription creation on one session is @@ -2987,8 +2998,22 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers { for (var offset = 0; offset < allTags.Count; offset += batchSize) { - if (offset > 0 && chunkDelay > TimeSpan.Zero) - await Task.Delay(chunkDelay); + try + { + if (offset > 0 && chunkDelay > TimeSpan.Zero) + await Task.Delay(chunkDelay, sessionToken); + } + catch (OperationCanceledException) + { + // Fall through to the cancellation check below. + } + + if (sessionToken.IsCancellationRequested) + { + _log.Debug("[{0}] Reconnect re-subscribe abandoned at tag {1}/{2} — its session has ended", + _connectionName, offset, allTags.Count); + return; + } var chunk = allTags.GetRange(offset, Math.Min(batchSize, allTags.Count - offset)); try @@ -3022,9 +3047,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers // repopulated for the new adapter generation. Seeds delivered after registration is // already established, so the ordering hazard does not apply here. var reseedAdapter = _adapter; - CancelSessionWork(); - _sessionWorkCts = new CancellationTokenSource(); - var reseedToken = _sessionWorkCts.Token; + var reseedToken = sessionToken; Task.Run(async () => { try diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/MxGatewayDataConnection.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/MxGatewayDataConnection.cs index 063f0e7a..84dcd39e 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/MxGatewayDataConnection.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/MxGatewayDataConnection.cs @@ -370,7 +370,10 @@ public class MxGatewayDataConnection // ONE gateway round trip per batch (SubscribeBulk = AddItem + Advise per tag in a // single worker pass) instead of the historical 2 RPCs per tag. var session = Volatile.Read(ref _session); - var outcomes = await _client!.SubscribeBulkAsync(tagPaths, cancellationToken); + // Dereference the session's client ONCE (DCL-4); results from a session that ended + // mid-call are not registered (the `current` check below). + var client = _client!; + var outcomes = await client.SubscribeBulkAsync(tagPaths, cancellationToken); var current = session == Volatile.Read(ref _session); var results = new List(outcomes.Count); foreach (var outcome in outcomes) diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaDataConnection.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaDataConnection.cs index 279e8caf..7b035328 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaDataConnection.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaDataConnection.cs @@ -215,10 +215,13 @@ public class OpcUaDataConnection IReadOnlyList tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default) { EnsureConnected(); + // Dereference the session's client ONCE (DCL-4): a reconnect swaps _client, and a call + // must run entirely against the client it started on. + var client = _client!; // ONE shared callback for the whole batch — the client hands back the node id // (== tag path for OPC UA), so no per-tag closure is needed. - var outcomes = await _client!.CreateSubscriptionsAsync( + var outcomes = await client.CreateSubscriptionsAsync( tagPaths, (nodeId, value, timestamp, statusCode) => { diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs index 7e0f0261..c96e74e7 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs @@ -47,6 +47,20 @@ public sealed class RealMxGatewayClient : IMxGatewayClient // completed. A faulted advise is evicted so the next write retries. private readonly ConcurrentDictionary> _supervisoryAdvised = new(); + /// + /// Cancelled on . The SHARED supervisory-advise task runs under + /// this (plus ), never under the token of + /// whichever caller happened to create it (DCL-9). + /// + private readonly CancellationTokenSource _lifetime = new(); + + /// + /// Upper bound on one shared supervisory advise. The gateway session has no command + /// deadline of its own yet, so without a bound a hung advise would wedge every later + /// caller for that handle; a timed-out advise is evicted and the next caller retries. + /// + internal static readonly TimeSpan SharedSupervisoryAdviseTimeout = TimeSpan.FromSeconds(60); + // With no configured MXAccess write-user this connection behaves as a // supervisory client: every advise defaults to AdviseSupervisory so writes are // accepted. A configured write-user keeps the prior plain-advise behaviour. @@ -517,6 +531,7 @@ public sealed class RealMxGatewayClient : IMxGatewayClient /// A task that represents the asynchronous operation. public async ValueTask DisposeAsync() { + _lifetime.Cancel(); if (_session is not null) await _session.DisposeAsync().ConfigureAwait(false); if (_client is not null) await _client.DisposeAsync().ConfigureAwait(false); if (_galaxy is not null) await _galaxy.DisposeAsync().ConfigureAwait(false); @@ -633,27 +648,46 @@ public sealed class RealMxGatewayClient : IMxGatewayClient /// builds every other command). The result is remembered per handle; a failure is /// not cached so the next attempt retries rather than wedging the item permanently. /// - private async Task EnsureSupervisoryAdvisedAsync(int handle, CancellationToken ct) + internal async Task EnsureSupervisoryAdvisedAsync(int handle, CancellationToken ct) { // GetOrAdd + Lazy runs the advise at most once per handle; concurrent // callers await the same Task and so never reach WriteBulk before it // completes (default Lazy is thread-safe, factory runs once). + // + // DCL-9: the shared task must NOT capture the creating caller's token — a write's 30 s + // deadline firing would cancel the advise a concurrent, deadline-free subscribe is also + // awaiting, failing that subscribe as a tag-resolution error. The shared advise runs under + // the client lifetime (bounded by SharedSupervisoryAdviseTimeout); each caller applies its + // OWN token to its wait only. var advise = _supervisoryAdvised.GetOrAdd( handle, - h => new Lazy(() => AdviseSupervisoryCoreAsync(h, ct))); + h => new Lazy(() => RunSharedSupervisoryAdviseAsync(h))); try { - await advise.Value.ConfigureAwait(false); + await advise.Value.WaitAsync(ct).ConfigureAwait(false); } catch { - // Evict the faulted entry (only if it's still the one we awaited) so the - // next write retries rather than caching a transient advise failure. - _supervisoryAdvised.TryRemove(new KeyValuePair>(handle, advise)); + // Evict a faulted/cancelled SHARED entry (only if it's still the one we awaited) so + // the next call retries rather than caching a transient advise failure. A caller that + // merely stopped waiting on its own token leaves the shared advise running for the + // others. + if (advise.Value.IsFaulted || advise.Value.IsCanceled) + _supervisoryAdvised.TryRemove(new KeyValuePair>(handle, advise)); throw; } } + private async Task RunSharedSupervisoryAdviseAsync(int handle) + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); + cts.CancelAfter(SharedSupervisoryAdviseTimeout); + await (AdviseCoreOverride ?? AdviseSupervisoryCoreAsync)(handle, cts.Token).ConfigureAwait(false); + } + + /// Test seam: replaces the gateway round trip of one supervisory advise. + internal Func? AdviseCoreOverride { get; set; } + private async Task AdviseSupervisoryCoreAsync(int handle, CancellationToken ct) { var reply = await _session!.InvokeAsync( diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionResubscribeLoopTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionResubscribeLoopTests.cs new file mode 100644 index 00000000..cad06189 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionResubscribeLoopTests.cs @@ -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; + +/// +/// 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; + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealMxGatewaySharedAdviseTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealMxGatewaySharedAdviseTests.cs new file mode 100644 index 00000000..91d1221b --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealMxGatewaySharedAdviseTests.cs @@ -0,0 +1,58 @@ +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters; + +/// +/// 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. +/// +public class RealMxGatewaySharedAdviseTests +{ + /// The first caller's cancellation fails only that caller; the shared advise completes for the second. + [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(() => 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 + } + + /// A faulted shared advise is evicted so the next caller retries it. + [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(() => client.EnsureSupervisoryAdvisedAsync(7, CancellationToken.None)); + await client.EnsureSupervisoryAdvisedAsync(7, CancellationToken.None); + Assert.Equal(2, coreCalls); + } +}