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;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
///
/// #968: a metadata renewal replaces the node's committed definition. TryResolve read the committed map twice
/// and answered "no such node" when the definition was replaced between the reads, so every subscription demand
/// check racing a renewal (its freshness check, the source lookup of a frame, a rebind) saw a live node as gone for
/// an instant and tore its physical stream down. Two cadences renewing the same node made it likely: the second,
/// redundant renewal replaces the definition again while the first cadence is mid-rebind.
///
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task A_definition_replaced_by_a_renewal_never_resolves_as_missing()
{
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;
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
{
await BrowseAll((SessionClient)session, anchor, 1);
var lookup = (IProjectedNodeLookup)sink;
var pages = (IProjectedNamespacePageSink)sink;
lookup.TryResolve(anchor, out var initial).ShouldBeTrue();
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(2));
long replacements = 0, resolutions = 0, missing = 0;
// Replace the committed definition with an identical one as fast as possible: exactly what a renewal
// commits, minus the metadata round trip.
var renewer = Task.Run(() =>
{
while (!stop.IsCancellationRequested)
{
if (!lookup.TryResolve(anchor, out var current) || current is null) continue;
if (pages.TryRenewExact(anchor, current, current with { }, () => true)) replacements++;
}
}, CancellationToken.None);
var readers = Enumerable.Range(0, 2).Select(_ => Task.Run(() =>
{
while (!stop.IsCancellationRequested)
{
Interlocked.Increment(ref resolutions);
if (!lookup.TryResolve(anchor, out var resolved) || resolved is null) Interlocked.Increment(ref missing);
}
}, CancellationToken.None)).ToArray();
await Task.WhenAll([renewer, .. readers]).WaitAsync(TimeSpan.FromSeconds(30), ct);
replacements.ShouldBeGreaterThan(100, "the renewer must actually replace the definition");
resolutions.ShouldBeGreaterThan(1000);
missing.ShouldBe(0, $"a live node resolved as missing {missing} times in {resolutions} lookups racing {replacements} renewals");
lookup.TryResolve(anchor, out var final).ShouldBeTrue();
final.ShouldNotBeSameAs(initial);
});
}
///
/// #968: both cadences reach the renewal window on the same tick and each renews the same predecessor. The second
/// commit adopts the successor the first already committed (and replaces the node's definition once more) after the
/// first cadence has rebound; neither physical stream may be torn down.
///
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Concurrent_cadence_renewals_committing_the_same_successor_keep_both_streams()
{
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();
var connections = new RenewalConnections(origin);
var gate = new HoldSecondRenewalCommit();
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, 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(SetupWait, ct);
var original = await NextPublishedRenewal(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);
var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct);
(await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good);
while (connections.MetadataRequests.Reader.TryRead(out _)) { }
while (published.Reader.TryRead(out _)) { }
// Hold the origin until BOTH renewals are in flight, let one commit and its cadence rebind, then let the
// other (identical) renewal commit.
connections.HoldMetadata = true;
await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(9), ct, oneStep: true);
await connections.MetadataRequests.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct);
await connections.MetadataRequests.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct);
connections.ReleaseMetadata.TrySetResult();
await gate.SecondHeld.Task.WaitAsync(SetupWait, ct);
var first = await NextPublishedRenewal(published.Reader,
x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
gate.ReleaseSecond.TrySetResult();
(await gate.SecondCommitted.Task.WaitAsync(SetupWait, ct)).ShouldBeTrue("the second renewal adopts the committed successor");
var second = await NextPublishedRenewal(published.Reader,
x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
first.SourceProof.IsValid.ShouldBeTrue();
second.SourceProof.IsValid.ShouldBeTrue();
slowStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
(await NextPublishedRenewal(published.Reader, x => Equals(x.Snapshot.Value, 8), ct)).SourceProof.IsValid.ShouldBeTrue();
fastStream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero);
(await NextPublishedRenewal(published.Reader, x => Equals(x.Snapshot.Value, 9), ct)).SourceProof.IsValid.ShouldBeTrue();
subscriptions.Opens.ShouldBe(2, "a renewal another cadence already committed must not tear down a physical stream");
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections,
renewalSinkFactory: gate.Wrap);
}
private sealed class HoldSecondRenewalCommit
{
private int _calls;
public readonly TaskCompletionSource SecondHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
public readonly TaskCompletionSource ReleaseSecond = new(TaskCreationOptions.RunContinuationsAsynchronously);
public readonly TaskCompletionSource SecondCommitted = new(TaskCreationOptions.RunContinuationsAsynchronously);
public IProjectedNamespacePageSink Wrap(IProjectedNamespacePageSink inner) => new Sink(inner, this);
private sealed class Sink(IProjectedNamespacePageSink inner, HoldSecondRenewalCommit owner) : IProjectedNamespacePageSink
{
public bool TryApply(NodeId parent, IReadOnlyList nodes, Func 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 commit) => inner.TryApplyRootLeaf(node, definition, commit);
public bool TryRenewExact(NodeId node, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func commit)
{
if (Interlocked.Increment(ref owner._calls) != 2) return inner.TryRenewExact(node, expected, replacement, commit);
owner.SecondHeld.TrySetResult();
owner.ReleaseSecond.Task.Wait(TimeSpan.FromSeconds(30));
var result = inner.TryRenewExact(node, expected, replacement, commit);
owner.SecondCommitted.TrySetResult(result);
return result;
}
}
}
}