eb78875c24
- ReadviseSubscriptionAsync: a reconnect completing between two subscriptions of a pass (dropped-event resync loop had no per-iteration check) sent the next SubscribeBulk to the NEW gateway session under the OLD session number; TryRebind refused it (SessionChanged) and the live new-session advises were never bound or released, then duplicated by the replay. The pass now refuses to dial once its session moved. Releasing afterwards was rejected: once the session moved, which session issued the reply's handles is ambiguous and old numbers are reused (#861); not dialling is the unambiguous fix. - Dropped-event resync passes are at least 5 s apart (DropResyncMinInterval); drops reported meanwhile coalesce into the next pass, so repeated overflow bursts no longer churn re-advises into the overflowing channel. - Test seams: ResyncDroppedHandlesForTestsAsync, NotifyEventsDroppedForTests, DropResyncMinIntervalForTests; AdvisingSubscriber gained after-subscribe/unsubscribe hooks.
301 lines
15 KiB
C#
301 lines
15 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Threading.Channels;
|
|
using Google.Protobuf.WellKnownTypes;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
|
|
|
/// <summary>
|
|
/// #991 G-4 / G-6 — the two re-advise paths of the event stream.
|
|
/// <list type="bullet">
|
|
/// <item><b>G-4</b>: MXAccess sends a value only when it changes, so a data-change event the full bounded
|
|
/// <see cref="EventPump"/> channel drops (newest-dropped) left its tag at the previous value, Good, until the
|
|
/// attribute happened to change again. The pump now records the dropped item handles and, once the channel
|
|
/// has drained, the driver re-advises exactly those tags — MXAccess answers an advise with the current
|
|
/// value — and releases the superseded handles.</item>
|
|
/// <item><b>G-6</b>: the replay-gap re-snapshot re-advised every tag on the SAME gateway session without
|
|
/// releasing the previous handles, doubling the gateway's advise count per gap. It now releases them (only
|
|
/// same-session handles — a dead session's numbers are reused by the next one and must never be sent).</item>
|
|
/// </list>
|
|
/// </summary>
|
|
public sealed class DroppedEventResyncTests
|
|
{
|
|
private static GalaxyDriverOptions Opts(int capacity) => new(
|
|
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
|
|
new GalaxyMxAccessOptions("OtOpcUa-A", EventPumpChannelCapacity: capacity),
|
|
new GalaxyRepositoryOptions(WatchDeployEvents: false),
|
|
new GalaxyReconnectOptions());
|
|
|
|
private static GalaxyDriver NewDriver(AdvisingSubscriber subscriber, int capacity = 64) =>
|
|
new("g", Opts(capacity), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber);
|
|
|
|
/// <summary>
|
|
/// Capacity-1 pump, handler wedged: the last two changes of a burst are dropped. Before the fix the tag ended
|
|
/// at the last value that made it through the channel (2.0) — Good, and wrong — indefinitely. Now it ends at
|
|
/// the real current value (4.0), and the handle the drop affected is released once its replacement is bound.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_value_dropped_by_a_full_event_channel_is_resynced_once_the_channel_drains()
|
|
{
|
|
var subscriber = new AdvisingSubscriber();
|
|
subscriber.Current["Tank.SP"] = 0.0;
|
|
using var driver = NewDriver(subscriber, capacity: 1);
|
|
|
|
var values = new ConcurrentQueue<double>();
|
|
using var gate = new ManualResetEventSlim(true);
|
|
using var blocked = new SemaphoreSlim(0);
|
|
driver.OnDataChange += (_, e) =>
|
|
{
|
|
if (e.Snapshot.Value is double d) values.Enqueue(d);
|
|
if (!gate.IsSet)
|
|
{
|
|
blocked.Release();
|
|
gate.Wait(TimeSpan.FromSeconds(20));
|
|
}
|
|
};
|
|
|
|
await driver.SubscribeAsync(["Tank.SP"], TimeSpan.Zero, TestContext.Current.CancellationToken);
|
|
await TestWait.UntilAsync(() => values.Contains(0.0), "the initial value must be published");
|
|
var firstHandle = subscriber.LiveHandlesFor("Tank.SP").ShouldHaveSingleItem();
|
|
|
|
gate.Reset();
|
|
subscriber.Set("Tank.SP", 1.0);
|
|
(await blocked.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken))
|
|
.ShouldBeTrue("the dispatch thread must be wedged in the handler on 1.0");
|
|
|
|
subscriber.Set("Tank.SP", 2.0);
|
|
subscriber.Set("Tank.SP", 3.0);
|
|
subscriber.Set("Tank.SP", 4.0);
|
|
var pump = (EventPump)driver.EventPumpInstanceForTests.ShouldNotBeNull();
|
|
await TestWait.UntilAsync(() => pump.DroppedCountForTests >= 2,
|
|
"with one slot and the dispatcher wedged, the burst's tail must be dropped");
|
|
|
|
gate.Set();
|
|
|
|
await TestWait.UntilAsync(() => values.LastOrDefault() == 4.0,
|
|
"a dropped change must be resynced — the tag must not stay at the last value that fit in the channel",
|
|
() => $"published=[{string.Join(", ", values)}] subscribes={subscriber.SubscribeCalls}");
|
|
await TestWait.UntilAsync(() => subscriber.Unsubscribed.Contains(firstHandle),
|
|
"the handle superseded by the re-advise must be released, not leaked on the gateway");
|
|
subscriber.LiveHandlesFor("Tank.SP").ShouldHaveSingleItem().ShouldNotBe(firstHandle);
|
|
|
|
// Positive control: the re-advised tag keeps receiving live changes on its new handle.
|
|
subscriber.Set("Tank.SP", 5.0);
|
|
await TestWait.UntilAsync(() => values.LastOrDefault() == 5.0, "live data must keep flowing after the resync");
|
|
}
|
|
|
|
/// <summary>
|
|
/// No drop, no re-advise: an unwedged pump delivers every change and the subscriber sees exactly one
|
|
/// SubscribeBulk. Guards the resync against firing on ordinary traffic.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Without_a_drop_nothing_is_re_advised()
|
|
{
|
|
var subscriber = new AdvisingSubscriber();
|
|
subscriber.Current["Tank.SP"] = 0.0;
|
|
using var driver = NewDriver(subscriber);
|
|
var values = new ConcurrentQueue<double>();
|
|
driver.OnDataChange += (_, e) => { if (e.Snapshot.Value is double d) values.Enqueue(d); };
|
|
|
|
await driver.SubscribeAsync(["Tank.SP"], TimeSpan.Zero, TestContext.Current.CancellationToken);
|
|
for (var i = 1; i <= 20; i++) subscriber.Set("Tank.SP", i);
|
|
await TestWait.UntilAsync(() => values.LastOrDefault() == 20.0, "every change must be delivered");
|
|
|
|
subscriber.SubscribeCalls.ShouldBe(1);
|
|
subscriber.Unsubscribed.ShouldBeEmpty();
|
|
}
|
|
|
|
/// <summary>
|
|
/// G-6: a replay gap re-advises every tag on the same session; the pre-gap handles are released once the
|
|
/// fresh ones are bound, and data keeps flowing on the fresh handles (positive control).
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_replay_gap_resnapshot_releases_the_pre_gap_handles()
|
|
{
|
|
var subscriber = new AdvisingSubscriber();
|
|
subscriber.Current["Tank.A"] = 1.0;
|
|
subscriber.Current["Tank.B"] = 2.0;
|
|
using var driver = NewDriver(subscriber);
|
|
var values = new ConcurrentQueue<(string Ref, double Value)>();
|
|
driver.OnDataChange += (_, e) => { if (e.Snapshot.Value is double d) values.Enqueue((e.FullReference, d)); };
|
|
|
|
await driver.SubscribeAsync(["Tank.A", "Tank.B"], TimeSpan.Zero, TestContext.Current.CancellationToken);
|
|
var preGap = subscriber.LiveHandles.ToArray();
|
|
preGap.Length.ShouldBe(2);
|
|
|
|
subscriber.EmitGap();
|
|
|
|
await TestWait.UntilAsync(() => subscriber.SubscribeCalls >= 2, "the replay gap must trigger a re-snapshot");
|
|
await TestWait.UntilAsync(() => preGap.All(subscriber.Unsubscribed.Contains),
|
|
"the re-snapshot must release the pre-gap handles — the session is the same, so they are still advised",
|
|
() => $"unsubscribed=[{string.Join(", ", subscriber.Unsubscribed)}] preGap=[{string.Join(", ", preGap)}]");
|
|
subscriber.LiveHandles.Count.ShouldBe(2, "exactly one advise per tag after the gap");
|
|
|
|
subscriber.Set("Tank.B", 9.0);
|
|
await TestWait.UntilAsync(() => values.Contains(("Tank.B", 9.0)), "data must flow on the post-gap handles");
|
|
}
|
|
|
|
/// <summary>
|
|
/// #991 review: a reconnect that completes in the MIDDLE of a multi-subscription re-advise pass (here: between
|
|
/// the dropped-event resync's first and second subscription) made the pass dial its next SubscribeBulk on the
|
|
/// NEW gateway session with the OLD session number — the rebind then refused it (SessionChanged) and the fresh,
|
|
/// live new-session advises were never bound nor released: a leak on the gateway, doubled by the replay that
|
|
/// re-advises the same tags. A pass whose session is gone must not dial at all.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_session_swap_mid_resync_leaves_no_unbound_new_session_advises()
|
|
{
|
|
var subscriber = new AdvisingSubscriber();
|
|
subscriber.Current["Tank.A"] = 1.0;
|
|
subscriber.Current["Tank.B"] = 2.0;
|
|
using var driver = NewDriver(subscriber);
|
|
await driver.SubscribeAsync(["Tank.A"], TimeSpan.Zero, TestContext.Current.CancellationToken);
|
|
await driver.SubscribeAsync(["Tank.B"], TimeSpan.Zero, TestContext.Current.CancellationToken);
|
|
var hA = subscriber.LiveHandlesFor("Tank.A").ShouldHaveSingleItem();
|
|
var hB = subscriber.LiveHandlesFor("Tank.B").ShouldHaveSingleItem();
|
|
var session = driver.SubscriptionsForTests.CurrentSession;
|
|
|
|
var swapped = 0;
|
|
var createdAfterSwap = new ConcurrentQueue<int>();
|
|
subscriber.AfterSubscribe = handles =>
|
|
{
|
|
if (Volatile.Read(ref swapped) == 1) foreach (var h in handles) createdAfterSwap.Enqueue(h);
|
|
};
|
|
// Tank.A's re-advise ends by releasing hA: the reconnect completes right there, before Tank.B's re-advise.
|
|
subscriber.AfterUnsubscribe = handles =>
|
|
{
|
|
if (handles.Contains(hA) && Interlocked.Exchange(ref swapped, 1) == 0) driver.SubscriptionsForTests.StartNewSession();
|
|
};
|
|
|
|
await driver.ResyncDroppedHandlesForTestsAsync([hA, hB], session);
|
|
|
|
Volatile.Read(ref swapped).ShouldBe(1, "the swap must have happened mid-pass");
|
|
createdAfterSwap.Where(h => !subscriber.Unsubscribed.Contains(h))
|
|
.ShouldBeEmpty("no advise issued after the swap may be left unbound and unreleased");
|
|
}
|
|
|
|
/// <summary>
|
|
/// #991 review: repeated overflow bursts each started a resync pass as soon as the previous one finished —
|
|
/// re-advising (and pushing initial values into) the very channel that was overflowing. Passes are now at least
|
|
/// <c>DropResyncMinInterval</c> apart, and the drops reported meanwhile coalesce into the next pass.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Repeated_drop_bursts_are_rate_limited_and_coalesced()
|
|
{
|
|
var subscriber = new AdvisingSubscriber();
|
|
subscriber.Current["Tank.A"] = 1.0;
|
|
using var driver = NewDriver(subscriber);
|
|
driver.DropResyncMinIntervalForTests = TimeSpan.FromSeconds(1.5);
|
|
await driver.SubscribeAsync(["Tank.A"], TimeSpan.Zero, TestContext.Current.CancellationToken);
|
|
var baseline = subscriber.SubscribeCalls;
|
|
|
|
driver.NotifyEventsDroppedForTests([subscriber.LiveHandlesFor("Tank.A").Single()]);
|
|
await TestWait.UntilAsync(() => subscriber.SubscribeCalls == baseline + 1, "the first burst resyncs at once");
|
|
await TestWait.UntilAsync(() => subscriber.LiveHandlesFor("Tank.A").Length == 1, "superseded handle released");
|
|
|
|
// Five more bursts in quick succession, each against the tag's current handle.
|
|
for (var i = 0; i < 5; i++)
|
|
{
|
|
driver.NotifyEventsDroppedForTests([subscriber.LiveHandlesFor("Tank.A").Single()]);
|
|
await Task.Delay(50, TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
await Task.Delay(500, TestContext.Current.CancellationToken);
|
|
subscriber.SubscribeCalls.ShouldBe(baseline + 1, "no second pass inside the minimum interval");
|
|
|
|
await TestWait.UntilAsync(() => subscriber.SubscribeCalls == baseline + 2, "the coalesced bursts resync once the interval passes");
|
|
await Task.Delay(500, TestContext.Current.CancellationToken);
|
|
subscriber.SubscribeCalls.ShouldBe(baseline + 2, "five bursts cost one pass, not five");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Behaves like the gateway + MXAccess for the parts these tests need: every SubscribeBulk issues fresh item
|
|
/// handles and pushes each one's current value (an advise's initial value), a change is pushed on every live
|
|
/// handle advising that reference, and UnsubscribeBulk retires handles.
|
|
/// </summary>
|
|
private sealed class AdvisingSubscriber : IGalaxySubscriber
|
|
{
|
|
private readonly Channel<MxEvent> _events = Channel.CreateUnbounded<MxEvent>();
|
|
private readonly ConcurrentDictionary<int, string> _live = new();
|
|
private int _nextHandle = 100;
|
|
private int _subscribeCalls;
|
|
|
|
public ConcurrentDictionary<string, double> Current { get; } = new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
public ConcurrentQueue<int> Unsubscribed { get; } = new();
|
|
|
|
public int SubscribeCalls => Volatile.Read(ref _subscribeCalls);
|
|
|
|
public ICollection<int> LiveHandles => _live.Keys;
|
|
|
|
public int[] LiveHandlesFor(string fullRef) =>
|
|
[.. _live.Where(kv => string.Equals(kv.Value, fullRef, StringComparison.OrdinalIgnoreCase)).Select(kv => kv.Key)];
|
|
|
|
public void Set(string fullRef, double value)
|
|
{
|
|
Current[fullRef] = value;
|
|
foreach (var handle in LiveHandlesFor(fullRef)) Emit(handle, value);
|
|
}
|
|
|
|
public void EmitGap() => _events.Writer.TryWrite(new MxEvent
|
|
{
|
|
Family = MxEventFamily.Unspecified,
|
|
ReplayGap = new ReplayGap { RequestedAfterSequence = 1, OldestAvailableSequence = 2 },
|
|
}).ShouldBeTrue();
|
|
|
|
private void Emit(int handle, double value) => _events.Writer.TryWrite(new MxEvent
|
|
{
|
|
Family = MxEventFamily.OnDataChange,
|
|
ItemHandle = handle,
|
|
Value = new MxValue { DoubleValue = value },
|
|
Quality = 192,
|
|
SourceTimestamp = Timestamp.FromDateTime(DateTime.UtcNow),
|
|
}).ShouldBeTrue();
|
|
|
|
/// <summary>Called with the handles each SubscribeBulk issued, after issuing them.</summary>
|
|
public Action<IReadOnlyList<int>>? AfterSubscribe { get; set; }
|
|
|
|
/// <summary>Called with the handles each UnsubscribeBulk retired, after retiring them.</summary>
|
|
public Action<IReadOnlyList<int>>? AfterUnsubscribe { get; set; }
|
|
|
|
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
|
|
IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
|
|
{
|
|
Interlocked.Increment(ref _subscribeCalls);
|
|
var results = new List<SubscribeResult>(fullReferences.Count);
|
|
foreach (var r in fullReferences)
|
|
{
|
|
var handle = Interlocked.Increment(ref _nextHandle);
|
|
_live[handle] = r;
|
|
results.Add(new SubscribeResult { TagAddress = r, ItemHandle = handle, WasSuccessful = true });
|
|
if (Current.TryGetValue(r, out var v)) Emit(handle, v); // the advise's initial value
|
|
}
|
|
AfterSubscribe?.Invoke([.. results.Select(x => x.ItemHandle)]);
|
|
return Task.FromResult<IReadOnlyList<SubscribeResult>>(results);
|
|
}
|
|
|
|
public Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken)
|
|
{
|
|
foreach (var h in itemHandles)
|
|
{
|
|
Unsubscribed.Enqueue(h);
|
|
_live.TryRemove(h, out _);
|
|
}
|
|
AfterUnsubscribe?.Invoke(itemHandles);
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public async IAsyncEnumerable<MxEvent> StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
|
{
|
|
await foreach (var ev in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
|
yield return ev;
|
|
}
|
|
}
|
|
}
|