432 lines
29 KiB
C#
432 lines
29 KiB
C#
using System.Reflection;
|
|
using System.Threading.Channels;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|
{
|
|
[Theory(Timeout = 90000), Trait("Phase", "P11Renewal")]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task Two_cadences_release_expired_overlap_without_borrowing_witnesses_during_failover(bool sweepExpired)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? first = null, second = null;
|
|
var firstSubscriptions = new FakeSubscriptions(() => first!.Serving);
|
|
var secondSubscriptions = new FakeSubscriptions(() => second!.Serving);
|
|
using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => firstSubscriptions);
|
|
first = originA; firstSubscriptions.SampleClock = originA.Clock;
|
|
using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (_, _) => secondSubscriptions,
|
|
clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2");
|
|
second = originB; secondSubscriptions.SampleClock = originB.Clock;
|
|
secondSubscriptions.SnapshotValue = 8;
|
|
var started = originA.Clock.GetTimestamp();
|
|
var connections = new OverlapFailoverConnections(originA);
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
await WithComposedServer(originA, originA.Raw, async (session, sink, resolver, _, access, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, slow, anchor, 1, 200, ct);
|
|
var slowStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
|
|
var oldNotification = await PublishComposedNotification(client, 1, ct);
|
|
oldNotification.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
originA.Clock.Advance(TimeSpan.FromMilliseconds(125));
|
|
var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, fast, anchor, 2, 50, ct);
|
|
var fastStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
fastStream.Interval.ShouldNotBe(slowStream.Interval);
|
|
(await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
while (published.Reader.TryRead(out _)) { }
|
|
// Stagger P2, then keep the fast cadence on its independently pinned
|
|
// P2 while the slow cadence adopts P3.
|
|
while (originA.Clock.GetElapsedTime(started, originA.Clock.GetTimestamp()) < TimeSpan.FromSeconds(7.5))
|
|
{ originA.Clock.Advance(TimeSpan.FromMilliseconds(125)); await Task.Delay(20, ct); }
|
|
var p2First = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > started, ct);
|
|
originA.Clock.Advance(TimeSpan.FromMilliseconds(125));
|
|
var p2Fast = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2First.ReceivedTimestamp, ct);
|
|
PauseFastRenewalTimer(originA.Clock);
|
|
while (published.Reader.TryRead(out _)) { }
|
|
var remaining = TimeSpan.FromSeconds(15) - originA.Clock.GetElapsedTime(started, originA.Clock.GetTimestamp());
|
|
if (remaining > TimeSpan.Zero) originA.Clock.Advance(remaining);
|
|
p2First.SourceProof.IsValid.ShouldBeTrue();
|
|
var p3Task = NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2Fast.ReceivedTimestamp, ct);
|
|
for (var i = 0; i < 4 && !p3Task.IsCompleted; i++)
|
|
{ originA.Clock.Advance(TimeSpan.FromMilliseconds(250)); await Task.Delay(100, ct); }
|
|
var p3 = await p3Task;
|
|
p3.SourceProof.IsValid.ShouldBeTrue();
|
|
var captured = CapturePredecessorAuthority(access, sink);
|
|
var previous = captured.Previous.ShouldNotBeNull();
|
|
previous.ShouldBeSameAs(captured.FastProof, "the fast demand must independently retain P2");
|
|
captured.Current.ShouldBeSameAs(captured.SlowProof, "the slow demand must independently retain P3");
|
|
captured.FastDemand.IsValid.ShouldBeTrue(); captured.SlowDemand.IsValid.ShouldBeTrue();
|
|
previous.Lease.IsValid.ShouldBeTrue(); captured.Current.Lease.IsValid.ShouldBeTrue();
|
|
fastStream.EmitValue(2, 9, originA.Clock.GetUtcNow(), TimeSpan.Zero);
|
|
var previousSample = await NextPublished(published.Reader, x => !x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 9), ct);
|
|
previousSample.SourceProof.ShouldBeSameAs(p2Fast.SourceProof);
|
|
var previousNotification = await PublishComposedNotification(client, 2, ct);
|
|
previousNotification.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
|
|
access.RetryJitterForTests = _ => TimeSpan.FromMilliseconds(5);
|
|
connections.SetCurrent(null);
|
|
await slowStream.DisposeAsync(); await fastStream.DisposeAsync();
|
|
await connections.BothOfflineEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
originA.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
previous.Lease.IsValid.ShouldBeFalse(); captured.Current.Lease.IsValid.ShouldBeFalse();
|
|
CapturePredecessorAuthority(access, sink).Previous.ShouldBeSameAs(previous,
|
|
"both paused attempts still retain the expired predecessor before recovery");
|
|
var held = CapturePredecessorAuthority(access, sink);
|
|
held.FastProof.ShouldBeSameAs(previous);
|
|
held.SlowProof.ShouldBeSameAs(captured.Current);
|
|
if (sweepExpired)
|
|
{
|
|
const BindingFlags fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
|
var cache = resolver.GetType().GetField("_cache", fields)!.GetValue(resolver)!;
|
|
var cacheGate = cache.GetType().GetField("_sync", fields)!.GetValue(cache)!;
|
|
lock (cacheGate)
|
|
{
|
|
cache.GetType().GetMethod("ReclaimExpired", fields)!.Invoke(cache, null);
|
|
var retired = (System.Collections.IDictionary)cache.GetType().GetField("_retiredPerNode", fields)!.GetValue(cache)!;
|
|
retired.Values.Cast<int>().ShouldHaveSingleItem().ShouldBe(2,
|
|
"both pinned expired proofs must already be retired before recovery");
|
|
}
|
|
}
|
|
// No validity read on SourceState or its sample proofs occurs before
|
|
// releasing the held retry; each demand retains its own old witness.
|
|
connections.SetCurrent(originB);
|
|
var recovered1 = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving, ct)
|
|
.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var recovered2 = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving, ct)
|
|
.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
recovered1.SourceProof.ShouldNotBeSameAs(recovered2.SourceProof);
|
|
recovered1.SourceProof.IsValid.ShouldBeTrue(); recovered2.SourceProof.IsValid.ShouldBeTrue();
|
|
// Publish responses share the session across both subscriptions. Keep
|
|
// both handles instead of discarding whichever arrives first.
|
|
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct))
|
|
{
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
var observed = new HashSet<uint>();
|
|
while (observed.Count < 2)
|
|
{
|
|
var response = await client.PublishAsync(new RequestHeader(), default, timeout.Token);
|
|
foreach (var change in ComposedChanges(response.NotificationMessage))
|
|
{
|
|
if (change.ClientHandle is not (1 or 2)) continue;
|
|
change.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
change.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
|
observed.Add(change.ClientHandle);
|
|
}
|
|
}
|
|
}
|
|
original.SourceProof.IsValid.ShouldBeFalse();
|
|
previousSample.SourceProof.IsValid.ShouldBeFalse();
|
|
p3.SourceProof.IsValid.ShouldBeFalse();
|
|
var replay = await client.RepublishAsync(new RequestHeader(), slow, oldNotification.Sequence, ct);
|
|
StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse();
|
|
var previousReplay = await client.RepublishAsync(new RequestHeader(), fast, previousNotification.Sequence, ct);
|
|
StatusCode.IsGood(ComposedChanges(previousReplay.NotificationMessage).Single(x => x.ClientHandle == 2).Value.StatusCode).ShouldBeFalse();
|
|
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
|
|
public async Task Expired_overlap_after_stream_loss_cannot_block_same_item_new_primary_recovery()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? first = null, second = null;
|
|
var firstSubscriptions = new FakeSubscriptions(() => first!.Serving);
|
|
var secondSubscriptions = new FakeSubscriptions(() => second!.Serving);
|
|
using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => firstSubscriptions);
|
|
first = originA; firstSubscriptions.SampleClock = originA.Clock;
|
|
using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (_, _) => secondSubscriptions,
|
|
clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2");
|
|
second = originB; secondSubscriptions.SampleClock = originB.Clock;
|
|
secondSubscriptions.SnapshotValue = 8;
|
|
var connections = new OverlapFailoverConnections(originA);
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
await WithComposedServer(originA, originA.Raw, async (session, _, _, _, access, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
var oldStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var initial = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
|
|
var firstNotification = await PublishComposedNotification(client, 1, ct);
|
|
firstNotification.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
originA.Clock.Advance(TimeSpan.FromSeconds(9));
|
|
await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > initial.ReceivedTimestamp, ct);
|
|
|
|
const BindingFlags fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
|
var ownerGate = access.GetType().GetField("_sync", fields)!.GetValue(access)!;
|
|
var sources = (System.Collections.IDictionary)access.GetType().GetField("_sources", fields)!.GetValue(access)!;
|
|
object state;
|
|
lock (ownerGate)
|
|
state = sources.Values.Cast<object>().Single(x => x.GetType().GetField("_previousProof", fields)!.GetValue(x) is not null);
|
|
var stateGate = state.GetType().GetField("Gate", fields)!.GetValue(state)!;
|
|
ProjectedNodeProof previous, current;
|
|
lock (stateGate)
|
|
{
|
|
previous = (ProjectedNodeProof)state.GetType().GetField("_previousProof", fields)!.GetValue(state).ShouldNotBeNull();
|
|
current = (ProjectedNodeProof)state.GetType().GetField("_proof", fields)!.GetValue(state).ShouldNotBeNull();
|
|
}
|
|
previous.Lease.IsValid.ShouldBeTrue(); current.Lease.IsValid.ShouldBeTrue();
|
|
// Lose the physical stream while both metadata witnesses are still live.
|
|
// No test or diagnostic reads SourceState.IsValid: that getter currently
|
|
// prunes the predecessor and would mask the retention defect.
|
|
access.RetryJitterForTests = _ => TimeSpan.FromMilliseconds(5);
|
|
connections.SetCurrent(null);
|
|
await oldStream.DisposeAsync();
|
|
var active = state.GetType().GetField("_activeAttempts", fields)!;
|
|
SpinWait.SpinUntil(() => { lock (stateGate) return (int)active.GetValue(state)! == 0; }, TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
|
await connections.OfflineEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
originA.Clock.Advance(TimeSpan.FromSeconds(16));
|
|
previous.Lease.IsValid.ShouldBeFalse(); current.Lease.IsValid.ShouldBeFalse();
|
|
lock (stateGate)
|
|
state.GetType().GetField("_previousProof", fields)!.GetValue(state).ShouldBeSameAs(previous,
|
|
"the paused retry cannot release its predecessor before the controlled recovery boundary");
|
|
|
|
connections.SetCurrent(originB);
|
|
var recovered = await NextPublished(published.Reader,
|
|
x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, 8), ct)
|
|
.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
recovered.SourceProof.IsValid.ShouldBeTrue();
|
|
var value = await PublishComposedValue(client, 1, ct);
|
|
value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
|
var replay = await client.RepublishAsync(new RequestHeader(), sub, firstNotification.Sequence, ct);
|
|
StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse();
|
|
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
|
|
}
|
|
|
|
[Theory(Timeout = 90000), Trait("Phase", "P11Renewal")]
|
|
[InlineData(false, true)]
|
|
[InlineData(true, true)]
|
|
[InlineData(true, false)]
|
|
public async Task New_primary_renews_same_monitored_item_after_a_prior_mapped_read(bool warmByRead, bool subscribeBeforeFailover)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? first = null, second = null;
|
|
var firstSubscriptions = new FakeSubscriptions(() => first!.Serving) { SnapshotVersion = 2 };
|
|
var secondSubscriptions = new FakeSubscriptions(() => second!.Serving) { SnapshotValue = 8 };
|
|
using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => firstSubscriptions);
|
|
first = originA;
|
|
firstSubscriptions.SampleClock = originA.Clock;
|
|
using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (_, _) => secondSubscriptions,
|
|
clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2");
|
|
second = originB;
|
|
secondSubscriptions.SampleClock = originB.Clock;
|
|
originA.Publish(42);
|
|
var connections = new OverlapFailoverConnections(originA);
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
var identifier = ProjectedDataIds.Identifier("map", originA.Raw.Address);
|
|
const BindingFlags fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
|
|
|
await WithComposedServer(originA, originA.Raw, async (session, _, resolver, _, access, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
ProjectedValueUpdate? mappedRead = null;
|
|
if (warmByRead)
|
|
{
|
|
var pending = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
|
|
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct);
|
|
pending.Results[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData);
|
|
mappedRead = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 42), ct);
|
|
mappedRead.Route.Serving.ShouldBe(originA.Serving);
|
|
var cached = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
|
|
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct);
|
|
StatusCode.IsGood(cached.Results[0].StatusCode).ShouldBeTrue();
|
|
cached.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
|
|
|
|
var oldSource = mappedRead.SourceProof.SourceIdentity;
|
|
var gate = oldSource.GetType().GetField("Gate", fields)!.GetValue(oldSource)!;
|
|
lock (gate)
|
|
{
|
|
oldSource.GetType().GetField("ReadOwned", fields)!.GetValue(oldSource).ShouldBe(true);
|
|
oldSource.GetType().GetField("_pin", fields)!.GetValue(oldSource).ShouldNotBeNull();
|
|
}
|
|
}
|
|
|
|
resolver.TryResolveProjected(DataRealm.Raw, identifier, out var oldProof).ShouldBeTrue();
|
|
var oldLease = oldProof.ShouldNotBeNull().Lease.ShouldBeOfType<BoundProjectionLease>();
|
|
oldLease.Serving.ShouldBe(originA.Serving);
|
|
oldLease.IsValid.ShouldBeTrue();
|
|
|
|
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
uint? oldSequence = null;
|
|
access.RetryJitterForTests = _ => TimeSpan.FromMilliseconds(5);
|
|
if (subscribeBeforeFailover)
|
|
{
|
|
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
|
|
var oldStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var oldBaseline = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct);
|
|
oldBaseline.Route.Serving.ShouldBe(originA.Serving);
|
|
if (mappedRead is not null)
|
|
oldBaseline.SourceProof.SourceIdentity.ShouldBeSameAs(mappedRead.SourceProof.SourceIdentity,
|
|
"the old subscription and successful mapped Read must own the same source");
|
|
var oldNotification = await PublishComposedNotification(client, 1, ct);
|
|
oldNotification.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
oldNotification.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7);
|
|
oldSequence = oldNotification.Sequence;
|
|
|
|
connections.SetCurrent(null);
|
|
await oldStream.DisposeAsync();
|
|
await connections.OfflineEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
connections.SetCurrent(originB);
|
|
}
|
|
else
|
|
{
|
|
mappedRead.ShouldNotBeNull();
|
|
firstSubscriptions.Opens.ShouldBe(0, "the old source must have only a unary Read owner");
|
|
SpinWait.SpinUntil(() => !access.HasLiveDemand(DataRealm.Raw, identifier), TimeSpan.FromSeconds(2)).ShouldBeTrue();
|
|
connections.SetCurrent(originB);
|
|
originA.Clock.Advance(oldLease.Remaining + TimeSpan.FromSeconds(1));
|
|
oldLease.IsValid.ShouldBeFalse();
|
|
|
|
var readProof = oldProof.ShouldNotBeNull();
|
|
var cache = (ProjectedCatalogCache)resolver.GetType().GetField("_cache", fields)!.GetValue(resolver)!;
|
|
var beforeBrowse = cache.CaptureRetainedDiagnostics(DataRealm.Raw, identifier);
|
|
beforeBrowse.Retained.ShouldBeTrue();
|
|
beforeBrowse.Retired.ShouldBeFalse("the expired Read-owned proof is still indexed before authenticated Browse");
|
|
beforeBrowse.RemoteLeaseValid.ShouldBe(false);
|
|
beforeBrowse.Generation.ShouldBe(readProof.Generation);
|
|
|
|
// Authenticated Browse installs the new primary's proof before
|
|
// the first item attaches. No old cohort migrates in this case.
|
|
await BrowseAll(client, anchor, 1);
|
|
resolver.TryResolveProjected(DataRealm.Raw, identifier, out var browsedProof).ShouldBeTrue();
|
|
var newPrimaryProof = browsedProof.ShouldNotBeNull();
|
|
newPrimaryProof.ShouldNotBeSameAs(readProof);
|
|
newPrimaryProof.Lease.Serving.ShouldBe(originB.Serving);
|
|
cache.IsCurrentProof(newPrimaryProof).ShouldBeTrue();
|
|
resolver.IsUsableProof(readProof).ShouldBeFalse();
|
|
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
|
|
}
|
|
|
|
var newStream = await secondSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
await NextPublished(published.Reader,
|
|
x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, 8), ct);
|
|
var firstNotification = await PublishComposedNotification(client, 1, ct);
|
|
firstNotification.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
firstNotification.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
|
resolver.TryResolveProjected(DataRealm.Raw, identifier, out var firstProof).ShouldBeTrue();
|
|
var firstLease = firstProof.ShouldNotBeNull().Lease.ShouldBeOfType<BoundProjectionLease>();
|
|
firstLease.Serving.ShouldBe(originB.Serving);
|
|
|
|
secondSubscriptions.SnapshotValue = 9;
|
|
secondSubscriptions.SnapshotVersion = 2;
|
|
originA.Clock.Advance(firstLease.UsableDuration / 2 + TimeSpan.FromSeconds(1));
|
|
await NextPublished(published.Reader,
|
|
x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, 9), ct);
|
|
firstLease.IsValid.ShouldBeTrue("healthy overlap must finish before the new primary's first lease expires");
|
|
resolver.TryResolveProjected(DataRealm.Raw, identifier, out var renewedProof).ShouldBeTrue();
|
|
var successorProof = renewedProof.ShouldNotBeNull();
|
|
successorProof.ShouldNotBeSameAs(firstProof);
|
|
var successorLease = successorProof.Lease.ShouldBeOfType<BoundProjectionLease>();
|
|
(await secondSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct))
|
|
.ShouldBeSameAs(newStream);
|
|
var renewedValue = await PublishComposedValue(client, 1, ct);
|
|
renewedValue.StatusCode.ShouldBe(StatusCodes.Good);
|
|
renewedValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(9);
|
|
|
|
// Cross the first lease without also making its successor due for
|
|
// renewal. The next ordinary samples belong to this accepted cohort.
|
|
originA.Clock.Advance(firstLease.Remaining + TimeSpan.FromMilliseconds(250));
|
|
firstLease.IsValid.ShouldBeFalse();
|
|
successorLease.Remaining.ShouldBeGreaterThan(successorLease.UsableDuration / 2);
|
|
for (var value = 10; value <= 11; value++)
|
|
{
|
|
newStream.EmitValue(value - 7, value, originA.Clock.GetUtcNow(), TimeSpan.Zero);
|
|
var ordinary = await NextPublished(published.Reader,
|
|
x => !x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, value), ct);
|
|
ordinary.SourceVersion.ShouldBe(value - 7L);
|
|
using var deliveryTimeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
deliveryTimeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
var statuses = new List<StatusCode>();
|
|
try
|
|
{
|
|
Opc.Ua.DataValue delivered;
|
|
do
|
|
{
|
|
delivered = await PublishComposedValue(client, 1, deliveryTimeout.Token);
|
|
if (statuses.Count < 8) statuses.Add(delivered.StatusCode);
|
|
}
|
|
while (!StatusCode.IsGood(delivered.StatusCode));
|
|
delivered.StatusCode.ShouldBe(StatusCodes.Good);
|
|
delivered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(value);
|
|
}
|
|
catch (Exception error) when (error is not OutOfMemoryException)
|
|
{
|
|
throw new InvalidOperationException($"Post-expiry SDK value {value} was not delivered. " +
|
|
$"Statuses: {string.Join(", ", statuses)}. Sample proof valid={ordinary.SourceProof.IsValid}, " +
|
|
$"source valid={ordinary.SourceProof.IsSourceValid}, adds={newStream.AddCommands}, removes={newStream.RemoveCommands}.", error);
|
|
}
|
|
}
|
|
|
|
var expiredSequences = new List<uint> { firstNotification.Sequence };
|
|
if (oldSequence is { } previousSequence) expiredSequences.Add(previousSequence);
|
|
foreach (var sequence in expiredSequences)
|
|
{
|
|
var replay = await client.RepublishAsync(new RequestHeader(), subscription, sequence, ct);
|
|
StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode)
|
|
.ShouldBeFalse();
|
|
}
|
|
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
|
|
}
|
|
|
|
private sealed class OverlapFailoverConnections(LocalDataFixture initial) : IGrpcDataAdapterConnectionSource
|
|
{
|
|
private LocalDataFixture? _current = initial;
|
|
private readonly object _routeIdentity = new();
|
|
internal readonly TaskCompletionSource OfflineEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
internal readonly TaskCompletionSource BothOfflineEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
private readonly TaskCompletionSource _online = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
private int _offlineWaiters;
|
|
internal void SetCurrent(LocalDataFixture? fixture)
|
|
{
|
|
Volatile.Write(ref _current, fixture);
|
|
if (fixture is not null) _online.TrySetResult();
|
|
}
|
|
public async ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string id, CancellationToken ct)
|
|
{
|
|
if (id != "link") return null;
|
|
var current = Volatile.Read(ref _current);
|
|
if (current is null)
|
|
{
|
|
OfflineEntered.TrySetResult();
|
|
if (Interlocked.Increment(ref _offlineWaiters) >= 2) BothOfflineEntered.TrySetResult();
|
|
await _online.Task.WaitAsync(ct);
|
|
current = Volatile.Read(ref _current);
|
|
}
|
|
return current is not null ? new Lease(new Connection(current.Connection()), _routeIdentity) : null;
|
|
}
|
|
private sealed class Lease(IDataConnection connection, object identity) : IGrpcDataAdapterConnectionLease
|
|
{
|
|
public IDataConnection Connection => connection;
|
|
public CancellationToken CancellationToken => CancellationToken.None;
|
|
public object RouteIdentity => identity;
|
|
public ValueTask DisposeAsync() => connection.DisposeAsync();
|
|
}
|
|
private sealed class Connection(IDataConnection inner) : IDataConnection
|
|
{
|
|
public DataTarget Target => new(DataTargetMode.Cluster, "cluster", null);
|
|
public TimeProvider Clock => inner.Clock;
|
|
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken ct) => inner.GetCapabilitiesAsync(budget, ct);
|
|
public Task<DataBrowseBranch> BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken ct) => inner.BrowseAsync(request, ct);
|
|
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken ct) => inner.GetMetadataAsync(request, ct);
|
|
public Task<IReadOnlyList<ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult>> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken ct) => inner.ReadAsync(request, ct);
|
|
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken ct) => inner.WriteAsync(request, ct);
|
|
public Task<IDataSubscription> SubscribeAsync(CancellationToken ct) => inner.SubscribeAsync(ct);
|
|
public ValueTask DisposeAsync() => inner.DisposeAsync();
|
|
}
|
|
}
|
|
}
|