Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs
T

212 lines
14 KiB
C#

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using Akka.Actor;
using Akka.Hosting;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
using ZB.MOM.WW.Secrets.Abstractions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
public sealed class GrpcDataRuntimeRegistrationTests
{
[Fact, Trait("Phase", "P08")]
public async Task Projection_services_share_the_live_deployed_connection_and_catalog_graph()
{
var services = new ServiceCollection();
services.AddSingleton<IClusterRoleInfo>(new LocalRole());
services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService<DataWriteDispatchFence>()));
services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService<DataWriteDispatchFence>()));
services.AddSingleton<IPermissionEvaluator>(sp => new TriePermissionEvaluator(sp.GetRequiredService<DataPlaneAuthorityState>().Tries));
services.AddSingleton<ISecretStore>(new GrpcDataSecretProvisioningTests.MemoryStore());
services.AddSingleton<ISecretCipher>(new GrpcDataSecretProvisioningTests.TestCipher());
services.AddSingleton<ISecretCacheInvalidator>(new GrpcDataSecretProvisioningTests.NoopInvalidator());
services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true);
await using var provider = services.BuildServiceProvider();
var resolver = provider.GetRequiredService<RemoteNamespaceResolver>();
provider.GetRequiredService<IFederatedProjectionCatalog>().ShouldBeSameAs(resolver);
provider.GetRequiredService<IGrpcDataAdapterConnectionSource>()
.ShouldBeSameAs(provider.GetRequiredService<DeployedGrpcDataConnectionSource>());
provider.GetRequiredService<ProjectedMappingDeploymentRuntime>().Active.ShouldBeEmpty();
provider.GetRequiredService<IProjectedValuePublisher>()
.ShouldBeSameAs(provider.GetRequiredService<ActorProjectedValuePublisher>());
provider.GetRequiredService<IProjectedDataAccess>().ShouldNotBeNull();
provider.GetRequiredService<IConfiguredProjectionDiscovery>().ShouldNotBeNull();
provider.GetRequiredService<IProjectedDependencyInterestSink>()
.ShouldBeSameAs(provider.GetRequiredService<ConfiguredProjectedInterestOwner>());
}
[Fact]
public void Disabled_registration_requires_no_driver_or_secret_store_and_exposes_no_facade()
{
var services = new ServiceCollection();
var options = services.AddOtOpcUaDataConnections(new ConfigurationBuilder().Build(), new Environment(), hasDriver: false);
options.Enabled.ShouldBeFalse();
using var provider = services.BuildServiceProvider();
provider.GetService<IDataConnectionFactory>().ShouldBeNull();
}
[Fact]
public void Enabled_surface_requires_the_actual_driver_role()
{
var services = new ServiceCollection();
Should.Throw<InvalidOperationException>(() => services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: false));
}
[Fact]
public void Startup_facade_is_available_without_constructing_a_disconnected_actor_graph()
{
var services = new ServiceCollection();
services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true);
using var provider = services.BuildServiceProvider();
var factory = provider.GetRequiredService<IDataConnectionFactory>();
Should.Throw<InvalidOperationException>(() => factory.Create(new("peer", "key", "version", null, 1),
new(DataTargetMode.Node, "cluster", "node")));
}
[Fact]
public async Task Real_registered_graph_activates_scope_and_catalog_for_deferred_factory()
{
var ct = TestContext.Current.CancellationToken;
var system = ActorSystem.Create("grpc-di-" + Guid.NewGuid().ToString("N"));
try
{
var registry = new ActorRegistry();
var services = new ServiceCollection();
services.AddSingleton(registry);
services.AddSingleton<IClusterRoleInfo>(new LocalRole());
services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService<DataWriteDispatchFence>()));
services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService<DataWriteDispatchFence>()));
services.AddSingleton<IPermissionEvaluator>(sp => new TriePermissionEvaluator(sp.GetRequiredService<DataPlaneAuthorityState>().Tries));
services.AddSingleton<ISecretStore>(new GrpcDataSecretProvisioningTests.MemoryStore());
services.AddSingleton<ISecretCipher>(new GrpcDataSecretProvisioningTests.TestCipher());
services.AddSingleton<ISecretCacheInvalidator>(new GrpcDataSecretProvisioningTests.NoopInvalidator());
services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true);
await using var provider = services.BuildServiceProvider();
var factory = provider.GetRequiredService<IDataConnectionFactory>();
var target = new DataTarget(DataTargetMode.Node, "cluster", "node-a:4840");
var key = new ApiKey { ApiKeyId = "key", Name = "key", Principal = "peer", SecretHash = "hash", Enabled = true };
var catalog = provider.GetRequiredService<LocalCatalogCoordinator>();
var role = provider.GetRequiredService<RedundancyRoleView>();
role.PublishDataServingRole(RedundancyRole.Primary, true);
var attempt = catalog.BeginAttempt("revision");
catalog.InstallAuthority(attempt, new DataPlaneAuthorityProjection("cluster", [key], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>())).ShouldBeTrue();
var context = new DataAuthenticatedContext("peer", "key", DataCallerIdentity.CredentialVersionFor(key), null,
provider.GetRequiredService<DataPlaneAuthorityState>().Current.GenerationId);
Should.Throw<InvalidOperationException>(() => factory.Create(context, target)); // no registered host
var actor = system.ActorOf(Props.Create(() => new LocalActor()));
registry.Register<DriverHostActorKey>(actor);
await using var connection = factory.Create(context, target);
var budget = new DataBudget(TimeSpan.FromSeconds(5), 100, 1_000_000);
(await connection.GetCapabilitiesAsync(budget, ct)).Readiness.ShouldBe(DataReadiness.Unavailable);
var snapshot = new DraftSnapshot { GenerationId = 0, ClusterId = "cluster",
ClusterNodes = [new ClusterNode { ClusterId = "cluster", NodeId = "node-a:4840", Host = "node-a", ApplicationUri = "urn:node-a", CreatedBy = "test" }] };
catalog.Stage(attempt, snapshot, "node-a:4840").ShouldBeTrue();
catalog.Complete(attempt, true).ShouldBeTrue();
(await connection.GetCapabilitiesAsync(budget, ct)).Readiness.ShouldBe(DataReadiness.Unavailable); // scope not yet durable
var deployment = provider.GetRequiredService<DataConnectionDeploymentRuntime>();
deployment.Apply(new DataConnectionDeploymentSnapshot(1, "revision", []));
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
deadline.CancelAfter(TimeSpan.FromSeconds(5));
while (!deployment.CurrentScopeReady) await Task.Delay(10, deadline.Token);
var ready = await connection.GetCapabilitiesAsync(budget, ct);
ready.Readiness.ShouldBe(DataReadiness.Ready);
ready.Serving.NodeId.ShouldBe("node-a:4840");
ready.Serving.Incarnation.ShouldBe(catalog.Serving.Incarnation);
var composition = provider.GetRequiredService<LocalDataRuntimeComposition>();
composition.AcquisitionCapacity.ShouldBeSameAs(provider.GetRequiredService<SubscriptionAcquisitionCapacity>());
composition.Services.Clock.ShouldBeSameAs(provider.GetRequiredService<TimeProvider>());
}
finally { await system.Terminate().WaitAsync(ct); }
}
[Fact]
public async Task Local_warm_standby_overrides_hot_artifact_and_withdraws_ready_import()
{
var ct = TestContext.Current.CancellationToken; var services = new ServiceCollection();
services.AddSingleton<IClusterRoleInfo>(new LocalRole());
services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService<DataWriteDispatchFence>()));
services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService<DataWriteDispatchFence>()));
services.AddSingleton(new WarmRedundancySettings(OpcUaRedundancyMode.Warm));
services.AddSingleton<ISecretStore>(new GrpcDataSecretProvisioningTests.MemoryStore());
services.AddSingleton<ISecretCipher>(new GrpcDataSecretProvisioningTests.TestCipher());
services.AddSingleton<ISecretCacheInvalidator>(new GrpcDataSecretProvisioningTests.NoopInvalidator());
services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true);
await using var provider = services.BuildServiceProvider();
var role = provider.GetRequiredService<RedundancyRoleView>();
var warm = provider.GetRequiredService<DataConnectionWarmRoleView>();
var owner = warm.RegisterOwner(); warm.Publish(owner, WarmRole.Active);
role.PublishDataServingRole(RedundancyRole.Primary, true);
var runtime = provider.GetRequiredService<DataConnectionDeploymentRuntime>();
var connection = new DataConnection { DataConnectionId = "link", ClusterId = "cluster", Revision = 1, Enabled = true,
ConsumerNodeIds = ["node-a:4840"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "remote", ExpectedNodeId = "remote:4840",
Endpoints = ["https://remote.example:8443"], SecretReference = "secret:data/key", SecretScopeClusterId = "cluster", AllowedOperations = DataOperations.Read };
runtime.Apply(new DataConnectionDeploymentSnapshot(1, "revision", [connection], RedundancyMode.Hot));
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); deadline.CancelAfter(TimeSpan.FromSeconds(5));
while (!runtime.CurrentScopeReady) await Task.Delay(10, deadline.Token);
await provider.GetRequiredService<DataConnectionSecretProvisioner>().ApplyAsync(new("cluster", "node-a:4840", 1,
[new("link", "secret:data/key", "bearer", false)], 1), ct);
using var key = RSA.Create(2048);
var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
using var ca = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
await provider.GetRequiredService<DataConnectionTrustPolicyStore>().SetAsync("link", 1, [ca], 1, ct);
DataConnectionDeploymentLease? lease = null;
while (!runtime.TryAcquire("link", out lease)) await Task.Delay(10, deadline.Token);
lease.ShouldNotBeNull();
role.PublishDataServingRole(RedundancyRole.Secondary, false);
warm.Publish(owner, WarmRole.Standby);
runtime.TryAcquire("link", out _).ShouldBeFalse();
Should.Throw<InvalidOperationException>(() => lease.GetCapabilitiesAsync(new DataBudget(TimeSpan.FromSeconds(1), 1, 1024), ct));
lease.Dispose();
}
private sealed class LocalActor : ReceiveActor { }
private sealed class LocalRole : IClusterRoleInfo
{
public NodeId LocalNode => NodeId.Parse("node-a:4840");
public IReadOnlySet<string> LocalRoles => new HashSet<string> { "driver", "cluster-cluster" };
public string? ClusterRole => "cluster-cluster";
public string? ClusterId => "cluster";
public bool HasRole(string role) => LocalRoles.Contains(role);
public IReadOnlyList<NodeId> MembersWithRole(string role) => [];
public NodeId? RoleLeader(string role) => null;
public event EventHandler<RoleLeaderChangedEventArgs>? RoleLeaderChanged { add { } remove { } }
}
private static IConfiguration Configuration() => new ConfigurationBuilder().AddInMemoryCollection(
new Dictionary<string, string?>
{
["DataConnections:Enabled"] = "true", ["DataConnections:ListenPort"] = "9443",
["DataConnections:AllowedHosts:0"] = "source.local", ["DataConnections:CertificatePath"] = "server.pem"
}).Build();
private sealed class Environment : IHostEnvironment
{
public string EnvironmentName { get; set; } = Environments.Production;
public string ApplicationName { get; set; } = "GrpcDataTests";
public string ContentRootPath { get; set; } = "/";
public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider();
}
}