Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs
T

141 lines
9.1 KiB
C#

using System.Collections;
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.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Live_predecessor_cadence_publishes_ordinary_delta_after_peer_adopts_next_authority()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var started = origin.Clock.GetTimestamp();
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, 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 subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
origin.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 subscriptions.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 timer phases so each cadence establishes P2 independently.
while (origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp()) < TimeSpan.FromSeconds(7.5))
{ origin.Clock.Advance(TimeSpan.FromMilliseconds(125)); await Task.Delay(20, ct); }
var p2First = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > started, ct);
origin.Clock.Advance(TimeSpan.FromMilliseconds(125));
var p2Fast = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2First.ReceivedTimestamp, ct);
p2Fast.SourceProof.IsValid.ShouldBeTrue();
// Hold only the fast cadence's next renewal tick. Its transport, demand,
// original P2 lease and value stream continue to run independently.
PauseFastRenewalTimer(origin.Clock);
while (published.Reader.TryRead(out _)) { }
var remaining = TimeSpan.FromSeconds(15) - origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp());
if (remaining > TimeSpan.Zero) origin.Clock.Advance(remaining);
p2First.SourceProof.IsValid.ShouldBeTrue(); // Also releases the expired P1 cache pin.
var p3Task = NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2Fast.ReceivedTimestamp, ct);
for (var i = 0; i < 4 && !p3Task.IsCompleted; i++)
{ origin.Clock.Advance(TimeSpan.FromMilliseconds(250)); await Task.Delay(100, ct); }
var p3 = await p3Task;
p3.SourceProof.IsValid.ShouldBeTrue();
var state = CapturePredecessorAuthority(access, sink);
state.SlowDemand.IsValid.ShouldBeTrue();
state.FastDemand.IsValid.ShouldBeTrue();
state.Current.ShouldBeSameAs(state.SlowProof);
state.Previous.ShouldBeSameAs(state.FastProof);
state.FastProof.Lease.IsValid.ShouldBeTrue();
state.Current.Lease.IsValid.ShouldBeTrue();
p2Fast.SourceProof.IsValid.ShouldBeTrue();
p2Fast.SourceProof.IsSourceValid.ShouldBeTrue();
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
var before = ProjectedStreamDiagnostics.Capture()["FreshAge"];
fastStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
SpinWait.SpinUntil(() => ProjectedStreamDiagnostics.Capture()["FreshAge"] > before, TimeSpan.FromSeconds(5)).ShouldBeTrue(
"the fast cadence's ordinary frame must reach Runtime admission");
var delta = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 8), ct);
delta.IsCompleteSnapshot.ShouldBeFalse();
delta.SourceProof.ShouldBeSameAs(p2Fast.SourceProof);
delta.SourceProof.IsValid.ShouldBeTrue();
delta.SourceVersion.ShouldBe(2);
subscriptions.Opens.ShouldBe(2);
var originalP2Lease = state.FastProof.Lease;
var originalP3Lease = state.Current.Lease;
var untilP2Expired = TimeSpan.FromSeconds(23) - origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp());
if (untilP2Expired > TimeSpan.Zero) origin.Clock.Advance(untilP2Expired);
delta.OriginAgeBounds.Advance(origin.Clock.GetElapsedTime(delta.ReceivedTimestamp, origin.Clock.GetTimestamp()))
.IsFresh(TimeSpan.FromSeconds(30)).ShouldBeTrue("the sample must still be fresh when its original authority expires");
originalP2Lease.IsValid.ShouldBeFalse();
delta.SourceProof.IsValid.ShouldBeFalse("P2 evidence cannot borrow P3's longer authority lifetime");
originalP3Lease.IsValid.ShouldBeTrue();
p3.SourceProof.IsValid.ShouldBeTrue();
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
private static void PauseFastRenewalTimer(ManualTimeProvider clock)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
var sync = typeof(ManualTimeProvider).GetField("_lock", flags)!.GetValue(clock)!;
lock (sync)
{
var timers = (IEnumerable)typeof(ManualTimeProvider).GetField("_timers", flags)!.GetValue(clock)!;
var fastDue = clock.GetUtcNow().AddMilliseconds(250);
var matches = timers.Cast<object>().Where(timer =>
Equals(timer.GetType().GetField("Period", flags)!.GetValue(timer), TimeSpan.FromMilliseconds(250)) &&
Equals(timer.GetType().GetField("Due", flags)!.GetValue(timer), fastDue)).ToArray();
matches.Length.ShouldBe(1, "the staggered fast renewal timer must be uniquely identifiable");
((ITimer)matches[0]).Dispose();
}
}
private static (ProjectedNodeProof Current, ProjectedNodeProof? Previous, ProjectedNodeProof SlowProof,
ProjectedNodeProof FastProof, IProjectedDemandLease SlowDemand, IProjectedDemandLease FastDemand)
CapturePredecessorAuthority(ProjectedDataAccess access, SdkAddressSpaceSink sink)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
var keys = (IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
var items = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Where(item => item.ClientHandle is 1 or 2).ToArray();
IProjectedDemandLease Demand(uint handle) => (IProjectedDemandLease)items.Single(item => item.ClientHandle == handle)
.GetType().GetField("_demand", flags)!.GetValue(items.Single(item => item.ClientHandle == handle))!;
ProjectedNodeProof Proof(IProjectedDemandLease demand) => (ProjectedNodeProof)demand.GetType().GetProperty("Proof", flags)!.GetValue(demand)!;
var slow = Demand(1); var fast = Demand(2);
var sync = typeof(ProjectedDataAccess).GetField("_sync", flags)!.GetValue(access)!;
object source;
lock (sync) source = ((IDictionary)typeof(ProjectedDataAccess).GetField("_sources", flags)!.GetValue(access)!).Values.Cast<object>().Single();
var sourceGate = source.GetType().GetField("Gate", flags)!.GetValue(source)!;
lock (sourceGate)
{
var current = (ProjectedNodeProof)source.GetType().GetField("_proof", flags)!.GetValue(source)!;
var previous = (ProjectedNodeProof?)source.GetType().GetField("_previousProof", flags)!.GetValue(source);
return (current, previous, Proof(slow), Proof(fast), slow, fast);
}
}
}