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

325 lines
22 KiB
C#

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
{
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task Existing_sdk_item_rebinds_to_verified_new_primary_without_reusing_old_evidence()
{
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; secondSubscriptions.SnapshotVersion = 1;
var connections = new SwitchableConnections(originA);
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
await WithComposedServer(originA, originA.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct);
var oldStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var old = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct);
var initial = await PublishComposedNotification(client, 1, ct);
initial.Value.StatusCode.ShouldBe(StatusCodes.Good);
connections.SetCurrent(originB);
await oldStream.DisposeAsync();
var next = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
next.Route.Serving.ShouldBe(originB.Serving);
next.SourceProof.IsValid.ShouldBeTrue();
old.SourceProof.IsValid.ShouldBeFalse();
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(), subscriptionId, initial.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 SwitchableConnections(LocalDataFixture initial) : IGrpcDataAdapterConnectionSource
{
private LocalDataFixture _current = initial;
internal void SetCurrent(LocalDataFixture current) => Volatile.Write(ref _current, current);
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string id, CancellationToken ct) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(id == "link" ? new Lease(new ClusterConnection(Volatile.Read(ref _current).Connection())) : null);
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => connection.DisposeAsync();
}
private sealed class ClusterConnection(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();
}
}
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task Subscribe_only_sdk_caller_renews_exact_node_without_browse_read_or_extra_subscription()
{
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>();
await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) =>
{
// Deployment-owned discovery materializes the node before the restricted session
// subscribes; it is fully disposed before the caller's monitored item is created.
var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access,
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
var configured = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, origin.Raw.Address), ct);
configured.ShouldNotBeNull();
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
await configured.DisposeAsync();
await subscriptions.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
while (published.Reader.TryRead(out _)) { }
var client = (SessionClient)session;
var deniedBrowse = await client.BrowseAsync(new RequestHeader(), null, 10, [new BrowseDescription
{
NodeId = anchor, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
}], ct);
StatusCode.IsGood(deniedBrowse.Results[0].StatusCode).ShouldBeFalse();
var deniedRead = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Neither,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct);
deniedRead.Results[0].StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct);
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
subscriptions.Opens.ShouldBe(2);
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
update.SourceProof.IsValid.ShouldBeTrue();
subscriptions.Opens.ShouldBe(3, "exact metadata renewal must not create another physical subscription");
(await PublishComposedValue(client, 1, ct)).WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
}, onPublished: update => published.Writer.TryWrite(update), localPermissions: 4);
}
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task Quiet_live_stream_renews_expired_metadata_without_client_browse_or_forced_close()
{
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>();
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct);
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var old = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
origin.Clock.Advance(TimeSpan.FromSeconds(16));
old.SourceProof.IsValid.ShouldBeFalse();
// The peer stream is still open: the owned maintenance timer must initiate renewal.
await subscriptions.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var renewed = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
renewed.SourceProof.IsValid.ShouldBeTrue();
var value = await PublishComposedValue(client, 1, ct);
value.StatusCode.ShouldBe(StatusCodes.Good);
value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
}, onPublished: update => published.Writer.TryWrite(update));
}
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task Existing_sdk_item_stays_denied_during_deployment_and_recovers_after_compatible_authority_returns()
{
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>();
LocalCatalogCoordinator? coordinator = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, placements, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscriptionId, 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 && Equals(x.Snapshot.Value, 7), ct);
var initial = await PublishComposedNotification(client, 1, ct);
initial.Value.StatusCode.ShouldBe(StatusCodes.Good);
var replacement = Prepare(coordinator!); // Suspends authority before completing the compatible deployment.
original.SourceProof.IsValid.ShouldBeFalse();
try
{
var replay = await client.RepublishAsync(new RequestHeader(), subscriptionId, initial.Sequence, ct);
StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse();
}
catch (ServiceResultException error) { StatusCode.IsBad(error.StatusCode).ShouldBeTrue(); }
var mapping = Mapping(origin.Raw);
mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata;
placements.Stage(replacement, [mapping], [Connection()]);
coordinator!.Complete(replacement, true).ShouldBeTrue();
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
origin.Clock.Advance(TimeSpan.FromSeconds(5));
var recovered = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
recovered.SourceProof.IsValid.ShouldBeTrue();
original.SourceProof.IsValid.ShouldBeFalse("the previous authority evidence must not revive");
var value = await PublishComposedValue(client, 1, ct);
value.StatusCode.ShouldBe(StatusCodes.Good);
value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
}, onPublished: update => published.Writer.TryWrite(update), onCoordinator: value => coordinator = value);
}
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task Metadata_retry_recovers_after_cache_commit_loses_the_sdk_guard_race()
{
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 forced = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct);
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
await stream.DisposeAsync();
await forced.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
var update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
update.SourceProof.IsValid.ShouldBeTrue();
var value = await PublishComposedValue(client, 1, ct);
value.StatusCode.ShouldBe(StatusCodes.Good);
value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
}, onPublished: update => published.Writer.TryWrite(update),
renewalSinkFactory: inner => new ExpiringCommitSink(inner, () =>
{
origin.Clock.Advance(TimeSpan.FromSeconds(16));
forced.TrySetResult();
}));
}
private sealed class ExpiringCommitSink(IProjectedNamespacePageSink inner, Action afterCommit) : IProjectedNamespacePageSink
{
private int _forced;
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) =>
inner.TryRenewExact(node, expected, replacement, () =>
{
var accepted = commit();
if (accepted && Interlocked.Exchange(ref _forced, 1) == 0) afterCommit();
return accepted;
});
}
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task Existing_sdk_monitored_item_renews_expired_metadata_without_another_client_browse()
{
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>();
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1); // Initial discovery only; no browse after expiry.
var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct);
var firstStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
origin.Clock.Advance(TimeSpan.FromSeconds(16)); // The configured metadata lease lasts at most 15 seconds.
original.SourceProof.IsValid.ShouldBeFalse();
subscriptions.SnapshotVersion = 2;
subscriptions.SnapshotValue = 8;
await firstStream.DisposeAsync();
var renewed = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
renewed.SourceProof.IsValid.ShouldBeTrue();
access.HasLiveDemand(DataRealm.Raw, renewed.Route.LocalIdentifier).ShouldBeTrue();
var notification = await PublishComposedValue(client, 1, ct);
notification.StatusCode.ShouldBe(StatusCodes.Good);
notification.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
}, onPublished: update => published.Writer.TryWrite(update));
}
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task Existing_sdk_monitored_item_recovers_after_upstream_stream_ends()
{
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>();
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
((IProjectedNodeLookup)sink).TryResolve(anchor, out var definition).ShouldBeTrue();
var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct);
var firstStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct);
var first = await PublishComposedNotification(client, 1, ct);
first.Value.StatusCode.ShouldBe(StatusCodes.Good);
first.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7);
subscriptions.SnapshotVersion = 2;
subscriptions.SnapshotValue = 8;
await firstStream.DisposeAsync(); // Model an upstream session lifetime ending while the SDK item stays alive.
var next = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
next.ShouldNotBeSameAs(firstStream);
var recovered = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
recovered.SourceProof.IsValid.ShouldBeTrue();
access.HasLiveDemand(DataRealm.Raw, definition!.LocalIdentifier).ShouldBeTrue();
subscriptions.Opens.ShouldBe(2);
var second = await PublishComposedValue(client, 1, ct);
second.StatusCode.ShouldBe(StatusCodes.Good);
second.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
var oldReplay = await client.RepublishAsync(new RequestHeader(), subscriptionId, first.Sequence, ct);
StatusCode.IsGood(ComposedChanges(oldReplay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode)
.ShouldBeFalse("a new attempt must not revive a notification from the old source era");
}, onPublished: update => published.Writer.TryWrite(update));
}
}