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

594 lines
40 KiB
C#

using System.Threading.Channels;
using System.Reflection;
using System.Runtime.CompilerServices;
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;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Two_sdk_cadences_renew_before_expiry_without_reviving_old_notification_evidence()
{
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 published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var identifier = ProjectedDataIds.Identifier("map", origin.Raw.Address);
resolver.TryResolveProjected(DataRealm.Raw, identifier, out var initialProof).ShouldBeTrue();
var initial = initialProof.ShouldNotBeNull();
var initialLease = initial.Lease.ShouldBeOfType<BoundProjectionLease>();
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);
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
var notification = await PublishComposedNotification(client, 1, ct);
notification.Value.StatusCode.ShouldBe(StatusCodes.Good);
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 (connections.MetadataRequests.Reader.TryRead(out _)) { }
while (published.Reader.TryRead(out _)) { }
using var simultaneousSuccessors = new Barrier(2);
access.BeforeSuccessorAdoptionForTests = () =>
{
if (!simultaneousSuccessors.SignalAndWait(TimeSpan.FromSeconds(5)))
throw new TimeoutException("Both cadence successors must prepare before either adopts.");
};
// The 15-second lease must be renewed and a successor baseline accepted
// while its predecessor still has authority. Metadata alone is not data.
origin.Clock.Advance(TimeSpan.FromSeconds(9));
await connections.MetadataRequests.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct);
var freshTask = NextPublished(published.Reader,
x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
for (var i = 0; i < 8 && !freshTask.IsCompleted; i++)
{
origin.Clock.Advance(TimeSpan.FromMilliseconds(500));
await Task.Delay(100, ct);
}
var fresh = await freshTask;
var otherFresh = await NextPublished(published.Reader,
x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
access.BeforeSuccessorAdoptionForTests = null;
otherFresh.SourceProof.ShouldNotBeSameAs(fresh.SourceProof, "each cadence must establish its own successor coverage");
original.SourceProof.IsValid.ShouldBeTrue();
fresh.SourceProof.IsValid.ShouldBeTrue();
otherFresh.SourceProof.IsValid.ShouldBeTrue();
fresh.SourceVersion.ShouldBe(original.SourceVersion, "a fresh baseline may report an unchanged source version");
resolver.TryResolveProjected(DataRealm.Raw, identifier, out var renewedProof).ShouldBeTrue();
var renewed = renewedProof.ShouldNotBeNull();
renewed.ShouldNotBeSameAs(initial);
var renewedLease = renewed.Lease.ShouldBeOfType<BoundProjectionLease>();
renewedLease.Serving.ShouldBe(initialLease.Serving);
initialLease.IsValid.ShouldBeTrue();
var crossExpiry = initialLease.Remaining + TimeSpan.FromMilliseconds(250);
(renewedLease.Remaining - crossExpiry).ShouldBeGreaterThan(renewedLease.UsableDuration / 2,
"the ordinary samples must follow predecessor expiry before the successor is due for renewal");
origin.Clock.Advance(crossExpiry);
initialLease.IsValid.ShouldBeFalse();
original.SourceProof.IsValid.ShouldBeFalse();
fresh.SourceProof.IsValid.ShouldBeTrue();
otherFresh.SourceProof.IsValid.ShouldBeTrue();
var streamBefore = ProjectedStreamDiagnostics.Capture();
var deliveryBefore = ProjectedDeliveryDiagnostics.Capture();
ProjectedValueUpdate? slowUpdate = null, fastUpdate = null;
try
{
slowStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
slowUpdate = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 8), ct);
slowUpdate.SourceProof.IsValid.ShouldBeTrue();
slowUpdate.SourceProof.IsSourceValid.ShouldBeTrue();
var slowValue = await PublishComposedValue(client, 1, ct);
slowValue.StatusCode.ShouldBe(StatusCodes.Good);
slowValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
fastStream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero);
// NextPublished is signaled only after the SDK sink accepts this
// actual sample; it is not merely publisher queue admission.
fastUpdate = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 9), ct);
fastUpdate.SourceProof.IsValid.ShouldBeTrue();
fastUpdate.SourceProof.IsSourceValid.ShouldBeTrue();
var fastValue = await PublishComposedValue(client, 2, ct);
fastValue.StatusCode.ShouldBe(StatusCodes.Good);
fastValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(9);
}
catch (Exception error) when (error is not OutOfMemoryException)
{
throw new InvalidOperationException(DescribeRenewalDelivery(access, sink, anchor, original, fresh, otherFresh,
slowUpdate, fastUpdate, slowStream, fastStream, streamBefore, deliveryBefore), error);
}
// An expired Republish can request another baseline. Check its denial
// after receiving the ordinary samples from both renewed registrations.
var replay = await client.RepublishAsync(new RequestHeader(), slow, notification.Sequence, ct);
StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse();
subscriptions.Opens.ShouldBe(2, "normal metadata renewal retains both physical streams");
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Cache_commit_followed_by_sdk_rejection_retries_with_the_actual_committed_proof()
{
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 published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin);
var rejected = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
origin.Clock.Advance(TimeSpan.FromSeconds(9));
await rejected.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
original.SourceProof.IsValid.ShouldBeTrue("the failed SDK transaction must preserve only the live predecessor");
for (var i = 0; i < 3; i++) { origin.Clock.Advance(TimeSpan.FromSeconds(1)); await Task.Delay(50, ct); }
var successor = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
origin.Clock.Advance(TimeSpan.FromSeconds(4));
original.SourceProof.IsValid.ShouldBeFalse();
successor.SourceProof.IsValid.ShouldBeTrue("the adopted SDK guard must refer to the committed successor lease");
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections,
renewalSinkFactory: inner => new RejectFirstCommittedRenewal(inner, rejected));
}
private sealed class RejectFirstCommittedRenewal(IProjectedNamespacePageSink inner, TaskCompletionSource rejected) : IProjectedNamespacePageSink
{
private int _reject = 1;
public bool TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit) => inner.TryApply(parent, nodes, commit);
public bool TryRemove(NodeId node, ProjectedVariableDefinition expected) => inner.TryRemove(node, expected);
public bool TryApplyRootLeaf(NodeId node, ProjectedVariableDefinition definition, Func<bool> commit) => inner.TryApplyRootLeaf(node, definition, commit);
public bool TryRenewExact(NodeId node, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func<bool> commit)
{
var result = inner.TryRenewExact(node, expected, replacement, () =>
{
if (!commit()) return false;
return Interlocked.Exchange(ref _reject, 0) == 0;
});
if (!result && Volatile.Read(ref _reject) == 0) rejected.TrySetResult();
return result;
}
}
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Unknown_route_provenance_does_not_create_a_proactive_overlap()
{
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 published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin, identified: false);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
while (connections.MetadataRequests.Reader.TryRead(out _)) { }
origin.Clock.Advance(TimeSpan.FromSeconds(9));
stream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
var current = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 8), ct);
current.SourceProof.IsValid.ShouldBeTrue();
original.SourceProof.IsValid.ShouldBeTrue();
connections.MetadataRequests.Reader.TryRead(out _).ShouldBeFalse("an unknown route identity cannot authorize predecessor overlap");
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Missing_successor_snapshot_cannot_be_replaced_by_a_later_ordinary_delta()
{
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 published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin) { SuppressFirstRenewalSnapshot = true };
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, 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 stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, fast, anchor, 2, 50, ct);
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
(await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good);
while (published.Reader.TryRead(out _)) { }
origin.Clock.Advance(TimeSpan.FromSeconds(9));
var healthyTask = NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
for (var i = 0; i < 8 && (!connections.MissingRebindHeld.Task.IsCompleted || !healthyTask.IsCompleted); i++)
{
origin.Clock.Advance(TimeSpan.FromMilliseconds(500));
await Task.Delay(100, ct);
}
await connections.MissingRebindHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
var healthy = await healthyTask;
original.SourceProof.IsValid.ShouldBeTrue("both prerequisites must complete while predecessor authority is still live");
healthy.SourceProof.IsValid.ShouldBeTrue();
connections.ReleaseMissingRebind.TrySetResult();
while (published.Reader.TryRead(out _)) { }
var firstRebind = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var secondRebind = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
(ReferenceEquals(firstRebind, stream) || ReferenceEquals(secondRebind, stream)).ShouldBeTrue();
var before = ProjectedStreamDiagnostics.Capture()["Value"];
stream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
stream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero);
var closed = subscriptions.Closed.Reader.ReadAsync(ct).AsTask();
var processed = Task.Run(() => SpinWait.SpinUntil(() => ProjectedStreamDiagnostics.Capture()["Value"] >= before + 2,
TimeSpan.FromSeconds(5)), ct);
var completed = await Task.WhenAny(closed, processed).WaitAsync(TimeSpan.FromSeconds(7), ct);
if (ReferenceEquals(completed, processed))
{
(await processed).ShouldBeTrue();
using var noPublication = new CancellationTokenSource(TimeSpan.FromSeconds(1));
var available = false;
try { available = await published.Reader.WaitToReadAsync(noPublication.Token); }
catch (OperationCanceledException) when (noPublication.IsCancellationRequested) { }
available.ShouldBeFalse("ordinary deltas cannot establish successor coverage after an empty snapshot");
}
else
healthy.SourceProof.IsValid.ShouldBeTrue("the independent healthy cadence must retain coverage");
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Bad_source_quality_is_preserved_during_complete_metadata_handoff()
{
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 published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin) { BadFirstRenewalSnapshot = true };
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
origin.Clock.Advance(TimeSpan.FromSeconds(9));
var next = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.SourceVersion == 2, ct);
next.SourceProof.IsValid.ShouldBeTrue();
next.Snapshot.StatusCode.ShouldBe(StatusCodes.BadNoCommunication.Code);
var delivered = await PublishComposedValue(client, 1, ct);
delivered.StatusCode.ShouldBe(StatusCodes.BadNoCommunication);
subscriptions.Opens.ShouldBe(1, "an authenticated Bad source value is not a transport failure");
origin.Clock.Advance(TimeSpan.FromSeconds(7));
original.SourceProof.IsValid.ShouldBeFalse();
next.SourceProof.IsValid.ShouldBeTrue();
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Accepted_bad_complete_baselines_do_not_reset_reconnect_backoff()
{
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 published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin) { BadEverySnapshot = true };
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
{
var delays = Channel.CreateUnbounded<TimeSpan>();
access.RetryJitterForTests = delay => { delays.Writer.TryWrite(delay); return TimeSpan.FromMilliseconds(1); };
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
var first = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
(await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct)).Snapshot.StatusCode.ShouldBe(StatusCodes.BadNoCommunication.Code);
await first.DisposeAsync();
(await delays.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBe(TimeSpan.FromMilliseconds(100));
var second = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
(await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct)).Snapshot.StatusCode.ShouldBe(StatusCodes.BadNoCommunication.Code);
await second.DisposeAsync();
(await delays.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBe(TimeSpan.FromMilliseconds(200),
"accepted source-quality Bad must not erase a failure streak");
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Snapshot_request_during_held_renewal_remove_is_coalesced_without_a_second_remove()
{
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 published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin) { HoldFirstRenewalRemoveAck = true };
try
{
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
origin.Clock.Advance(TimeSpan.FromSeconds(9));
await connections.RenewalRemoveAckHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
original.SourceProof.IsValid.ShouldBeTrue();
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
var gate = typeof(ProjectedDataAccess).GetField("_sync", flags)!.GetValue(access)!;
IProjectedDemandLease demand;
lock (gate) demand = ((System.Collections.IEnumerable)typeof(ProjectedDataAccess).GetField("_demands", flags)!
.GetValue(access)!).Cast<object>().OfType<IProjectedDemandLease>().Single();
access.RequestFreshSnapshot(demand).ShouldBeTrue();
// AddEvent follows RefreshEvent through the same cohort reader. Its
// actual upstream Add proves the refresh was processed, not just queued.
await AddComposedItem(client, subscription, anchor, 2, 100, ct);
var added = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
added.ShouldBeSameAs(stream);
stream.RemoveCommands.ShouldBe(1, "the in-flight renewal already provides the requested fresh baseline");
connections.ReleaseRenewalRemoveAck.TrySetResult();
var successor = await NextPublished(published.Reader,
update => update.IsCompleteSnapshot && update.ReceivedTimestamp > original.ReceivedTimestamp, ct);
successor.SourceProof.IsValid.ShouldBeTrue();
var delivered = new HashSet<uint>();
using var deliveryTimeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
deliveryTimeout.CancelAfter(TimeSpan.FromSeconds(10));
while (delivered.Count < 2)
{
var response = await client.PublishAsync(new RequestHeader(), default, deliveryTimeout.Token);
foreach (var notification in ComposedChanges(response.NotificationMessage))
{
if (notification.ClientHandle is not (1 or 2)) continue;
notification.Value.StatusCode.ShouldBe(StatusCodes.Good);
delivered.Add(notification.ClientHandle);
}
}
subscriptions.Opens.ShouldBe(1);
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
finally { connections.ReleaseRenewalRemoveAck.TrySetResult(); }
}
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Acknowledged_renewal_without_snapshot_end_expires_and_releases_its_old_attempt()
{
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 published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin);
FakeSubscriptions.Stream? held = null;
try
{
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
subscriptions.HoldNextSnapshotEnd = true;
origin.Clock.Advance(TimeSpan.FromSeconds(9));
held = await subscriptions.SnapshotEndHeld.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
original.SourceProof.IsValid.ShouldBeTrue();
origin.Clock.Advance(TimeSpan.FromSeconds(7));
original.SourceProof.IsValid.ShouldBeFalse();
await subscriptions.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct);
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
finally { held?.ReleaseSnapshotEnd(); }
}
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Ignored_metadata_cancellation_keeps_physical_quota_until_the_rpc_actually_finishes()
{
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 published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin);
try
{
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscription, anchor, 1, 100, ct);
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
connections.HoldMetadata = true;
origin.Clock.Advance(TimeSpan.FromSeconds(9));
await connections.MetadataHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
var count = typeof(ProjectedDataAccess).GetField("_unaryCount", BindingFlags.NonPublic | BindingFlags.Instance)!;
((int)count.GetValue(access)!).ShouldBe(1);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
await client.DeleteSubscriptionsAsync(new RequestHeader(), [subscription], ct);
((int)count.GetValue(access)!).ShouldBe(1, "timeout and disposed interest do not release an unfinished physical RPC");
connections.ReleaseMetadata.TrySetResult();
SpinWait.SpinUntil(() => (int)count.GetValue(access)! == 0, TimeSpan.FromSeconds(5)).ShouldBeTrue();
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
finally { connections.ReleaseMetadata.TrySetResult(); }
}
private sealed class RenewalConnections(LocalDataFixture fixture, bool identified = true) : IGrpcDataAdapterConnectionSource
{
private readonly object _routeIdentity = new();
internal readonly Channel<bool> MetadataRequests = Channel.CreateUnbounded<bool>();
internal bool HoldMetadata;
internal bool SuppressFirstRenewalSnapshot;
internal bool BadFirstRenewalSnapshot, BadEverySnapshot;
internal bool HoldFirstRenewalRemoveAck;
private int _subscriptions;
internal readonly TaskCompletionSource MissingRebindHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource ReleaseMissingRebind = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource RenewalRemoveAckHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource ReleaseRenewalRemoveAck = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource MetadataHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource ReleaseMetadata = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string id, CancellationToken ct) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(id == "link" ? new Lease(new Connection(fixture.Connection(), this), identified ? _routeIdentity : null) : null);
private sealed class Lease(IDataConnection connection, object? routeIdentity) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
// This opt-in member binds every borrowed connection to this fixture's
// one stable route. It also compiles before the interface gains the seam.
public object? RouteIdentity => routeIdentity;
public ValueTask DisposeAsync() => connection.DisposeAsync();
}
private sealed class Connection(IDataConnection inner, RenewalConnections owner) : IDataConnection
{
public DataTarget Target => inner.Target;
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 async Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken ct)
{
owner.MetadataRequests.Writer.TryWrite(true);
if (owner.HoldMetadata)
{
owner.MetadataHeld.TrySetResult();
await owner.ReleaseMetadata.Task;
}
return await 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 async Task<IDataSubscription> SubscribeAsync(CancellationToken ct)
{
var stream = await inner.SubscribeAsync(ct);
var number = Interlocked.Increment(ref owner._subscriptions);
if (owner.HoldFirstRenewalRemoveAck && number == 1) return new HeldRemovalAckStream(stream, owner);
if (owner.SuppressFirstRenewalSnapshot && number == 1) return new MissingSnapshotStream(stream, owner);
return owner.BadEverySnapshot || owner.BadFirstRenewalSnapshot && number == 1
? new QualitySnapshotStream(stream, owner.BadEverySnapshot) : stream;
}
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
private sealed class HeldRemovalAckStream(IDataSubscription inner, RenewalConnections owner) : IDataSubscription, IDataSubscriptionProvenance
{
private string? _heldCommand;
private int _held;
public ServingIdentity Serving => ((IDataSubscriptionProvenance)inner).Serving;
public Task SendAsync(DataSubscriptionCommand command, CancellationToken ct)
{
if (command is RemoveSubscriptionItems) Interlocked.CompareExchange(ref _heldCommand, command.CommandId, null);
return inner.SendAsync(command, ct);
}
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken ct)
{
await foreach (var frame in inner.ReadAllAsync(ct).WithCancellation(ct))
{
if (frame is DataSubscriptionAck ack && ack.CommandId == Volatile.Read(ref _heldCommand) &&
Interlocked.Exchange(ref _held, 1) == 0)
{
owner.RenewalRemoveAckHeld.TrySetResult();
await owner.ReleaseRenewalRemoveAck.Task.WaitAsync(ct);
}
yield return frame;
}
}
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
private sealed class QualitySnapshotStream(IDataSubscription inner, bool everySnapshot) : IDataSubscription, IDataSubscriptionProvenance
{
private int _renewal;
public ServingIdentity Serving => ((IDataSubscriptionProvenance)inner).Serving;
public Task SendAsync(DataSubscriptionCommand command, CancellationToken ct)
{
if (command is AddSubscriptionItems) Interlocked.Exchange(ref _renewal, 1);
return inner.SendAsync(command, ct);
}
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken ct)
{
await foreach (var frame in inner.ReadAllAsync(ct).WithCancellation(ct))
{
if (frame is DataSubscriptionValues { IsSnapshot: true } values && (everySnapshot || Volatile.Read(ref _renewal) != 0))
{
var converted = values.Items.Select(item =>
{
var sample = item.Sample;
var owned = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(sample.Value.Kind, sample.Value.GetScalar());
return item with { Sample = new DataSample(owned, StatusCodes.BadNoCommunication.Code,
sample.SourceTimestampUtc, sample.ServerTimestampUtc, sample.Serving, sample.Version) };
}).ToArray();
var replacement = new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, true, converted);
values.Dispose();
yield return replacement;
continue;
}
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) Interlocked.Exchange(ref _renewal, 0);
yield return frame;
}
}
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
private sealed class MissingSnapshotStream(IDataSubscription inner, RenewalConnections owner) : IDataSubscription, IDataSubscriptionProvenance
{
private int _suppress;
public ServingIdentity Serving => ((IDataSubscriptionProvenance)inner).Serving;
public async Task SendAsync(DataSubscriptionCommand command, CancellationToken ct)
{
if (command is AddSubscriptionItems)
{
owner.MissingRebindHeld.TrySetResult();
await owner.ReleaseMissingRebind.Task.WaitAsync(ct);
Interlocked.Exchange(ref _suppress, 1);
}
await inner.SendAsync(command, ct);
}
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken ct)
{
await foreach (var frame in inner.ReadAllAsync(ct).WithCancellation(ct))
{
if (frame is DataSubscriptionValues { IsSnapshot: true } && Volatile.Read(ref _suppress) != 0)
{ (frame as IDisposable)?.Dispose(); continue; }
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) Interlocked.Exchange(ref _suppress, 0);
yield return frame;
}
}
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
}
}