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

144 lines
9.2 KiB
C#

using System.Threading.Channels;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task Deployed_framed_grpc_challenge_delivers_finite_age_to_sdk_monitored_item()
{
var ct = TestContext.Current.CancellationToken;
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
LocalDataFixture? peer = null;
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) =>
new LocalSubscriptionService(peer!.Services, context, target, demand, new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity));
peer = origin; origin.Publish(42);
await using var deployment = NewFreshnessDeployment(origin);
var deployed = new DeployedGrpcDataConnectionSource(deployment);
await WaitForDeployedFreshness(deployed, ct);
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var source = new DeployedFreshnessSplitSource(origin, deployed);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, 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 update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct).WaitAsync(TimeSpan.FromSeconds(8), ct);
update.OriginAgeBounds.Upper.ShouldNotBeNull();
Opc.Ua.DataValue notification;
do { notification = await PublishComposedValue(client, 1, ct); }
while (!StatusCode.IsGood(notification.StatusCode));
notification.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
}, onPublished: x => published.Writer.TryWrite(x), connectionSource: source);
}
[Fact(Timeout = 30000), Trait("Phase", "P11Wire")]
public async Task Deployed_framed_grpc_challenge_respects_batch_limit_and_scope_revocation()
{
var ct = TestContext.Current.CancellationToken;
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
LocalDataFixture? peer = null;
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) =>
new LocalSubscriptionService(peer!.Services, context, target, demand, new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity));
peer = origin; origin.Publish(42);
await using var deployment = NewFreshnessDeployment(origin);
var source = new DeployedGrpcDataConnectionSource(deployment);
await WaitForDeployedFreshness(source, ct);
await using var lease = (await source.AcquireAsync("link", ct)).ShouldNotBeNull();
await using var stream = await lease.Connection.SubscribeAsync(ct);
var support = stream.ShouldBeAssignableTo<IDataSubscriptionFreshnessSupport>();
support.SupportsFreshnessChallenges.ShouldBeTrue();
support.FreshnessMaxItems.ShouldBe(2);
var handle = new DataItemHandle("s", 1, 1, 1);
await Should.ThrowAsync<ArgumentOutOfRangeException>(() => stream.SendAsync(
new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [handle, handle, handle]), ct));
deployment.BeginAttempt("new-artifact");
await Should.ThrowAsync<OperationCanceledException>(() => stream.SendAsync(
new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [handle]), ct));
}
[Fact(Timeout = 30000), Trait("Phase", "P11Wire")]
public async Task Deployed_scope_does_not_advertise_challenges_for_unsupported_stream()
{
var ct = TestContext.Current.CancellationToken;
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
LocalDataFixture? peer = null;
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) =>
new LocalSubscriptionService(peer!.Services, context, target, demand, new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity));
peer = origin;
await using var inner = origin.Connection();
await using var lease = new DataConnectionDeploymentLease(inner, CancellationToken.None, DataOperations.Subscribe,
TimeSpan.FromSeconds(5), 2, 2, 1_000_000, 2, 8, 1_000_000, () => true, () => { });
await using var stream = await lease.SubscribeAsync(ct);
var support = stream.ShouldBeAssignableTo<IDataSubscriptionFreshnessSupport>();
support.SupportsFreshnessChallenges.ShouldBeFalse();
support.FreshnessMaxItems.ShouldBe(0);
await Should.ThrowAsync<InvalidOperationException>(() => stream.SendAsync(
new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [new DataItemHandle("s", 1, 1, 1)]), ct));
}
private static DataConnectionDeploymentRuntime NewFreshnessDeployment(LocalDataFixture origin)
{
var runtime = new DataConnectionDeploymentRuntime("consumer", "owner", new FreshnessSecurity(origin), new ImmediateFreshnessScope(), 4, origin.Clock);
runtime.Apply(new DataConnectionDeploymentSnapshot(1, "freshness-artifact", [new DataConnection
{
DataConnectionId = "link", ClusterId = "owner", Revision = 1, Enabled = true, ConsumerNodeIds = ["consumer"],
TargetMode = DataTargetMode.Node, ExpectedClusterId = "cluster", ExpectedNodeId = "node-a", Endpoints = ["https://fixture.test"],
SecretReference = "secret", SecretScopeClusterId = "owner", AllowedOperations = DataOperations.Subscribe,
MaxMessageBytes = 1_000_000, MaxBatchItems = 2, MaxPageItems = 2, MaxStreams = 2,
MaxMonitoredItems = 8, MaxPendingBytes = 1_000_000, TimeoutMilliseconds = 5000
}]));
return runtime;
}
private static async Task WaitForDeployedFreshness(DeployedGrpcDataConnectionSource source, CancellationToken ct)
{
for (var i = 0; i < 250; i++)
{
var lease = await source.AcquireAsync("link", ct);
if (lease is not null) { await lease.DisposeAsync(); return; }
await Task.Delay(20, ct);
}
throw new TimeoutException("Deployed route did not become ready.");
}
private sealed class ImmediateFreshnessScope : IDataConnectionScopeActivator
{
public Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken) => Task.CompletedTask;
}
private sealed class DeployedFreshnessSplitSource(LocalDataFixture origin, DeployedGrpcDataConnectionSource deployed) : IGrpcDataAdapterConnectionSource
{
public async ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string id, CancellationToken ct)
{
var lease = await deployed.AcquireAsync(id, ct);
return lease is null ? null : new SplitLease(origin.Connection(), lease);
}
private sealed class SplitLease(IDataConnection local, IGrpcDataAdapterConnectionLease deployedLease) : IGrpcDataAdapterConnectionLease, IDataConnection
{
public IDataConnection Connection => this;
public CancellationToken CancellationToken => deployedLease.CancellationToken;
public DataTarget Target => deployedLease.Connection.Target;
public TimeProvider Clock => deployedLease.Connection.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget b, CancellationToken ct) => local.GetCapabilitiesAsync(b, ct);
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest r, CancellationToken ct) => local.BrowseAsync(r, ct);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest r, CancellationToken ct) => local.GetMetadataAsync(r, ct);
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest r, CancellationToken ct) => local.ReadAsync(r, ct);
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch r, CancellationToken ct) => local.WriteAsync(r, ct);
public Task<IDataSubscription> SubscribeAsync(CancellationToken ct) => deployedLease.Connection.SubscribeAsync(ct);
public async ValueTask DisposeAsync() { await local.DisposeAsync(); await deployedLease.DisposeAsync(); }
}
}
}