320 lines
20 KiB
C#
320 lines
20 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();
|
|
await using var provider = RegisteredOriginServices(registry).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); }
|
|
}
|
|
|
|
[Theory(Timeout = 30000), Trait("Phase", "P11")]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task Healthy_origin_catalog_stays_ready_while_another_thread_holds_the_dispatch_fence(bool warm)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var system = ActorSystem.Create("grpc-role-snapshot-" + Guid.NewGuid().ToString("N"));
|
|
try
|
|
{
|
|
var registry = new ActorRegistry();
|
|
registry.Register<DriverHostActorKey>(system.ActorOf(Props.Create(() => new LocalActor())));
|
|
await using var provider = RegisteredOriginServices(registry, warm).BuildServiceProvider();
|
|
var catalog = provider.GetRequiredService<LocalCatalogCoordinator>();
|
|
var role = provider.GetRequiredService<RedundancyRoleView>();
|
|
var warmRole = provider.GetRequiredService<DataConnectionWarmRoleView>();
|
|
var warmOwner = warm ? warmRole.RegisterOwner() : 0;
|
|
if (warm) warmRole.Publish(warmOwner, WarmRole.Active).ShouldBeTrue();
|
|
role.PublishDataServingRole(RedundancyRole.Primary, true);
|
|
|
|
var key = new ApiKey { ApiKeyId = "key", Name = "key", Principal = "peer", SecretHash = "hash", Enabled = true };
|
|
var attempt = catalog.BeginAttempt("revision");
|
|
catalog.InstallAuthority(attempt, new DataPlaneAuthorityProjection("cluster", [key], [],
|
|
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>())).ShouldBeTrue();
|
|
const string nodeId = "node-a:4840";
|
|
var draft = new DraftSnapshot { GenerationId = 0, ClusterId = "cluster",
|
|
ClusterNodes = [new ClusterNode { ClusterId = "cluster", NodeId = nodeId, Host = "node-a",
|
|
ApplicationUri = "urn:node-a", CreatedBy = "test" }] };
|
|
catalog.Stage(attempt, draft, nodeId).ShouldBeTrue();
|
|
catalog.Complete(attempt, true).ShouldBeTrue();
|
|
var deployment = provider.GetRequiredService<DataConnectionDeploymentRuntime>();
|
|
deployment.Apply(new DataConnectionDeploymentSnapshot(1, "revision", []));
|
|
using var scopeDeadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
scopeDeadline.CancelAfter(TimeSpan.FromSeconds(5));
|
|
while (!deployment.CurrentScopeReady) await Task.Delay(10, scopeDeadline.Token);
|
|
|
|
var activeCatalog = catalog.Current.ShouldNotBeNull();
|
|
var serving = activeCatalog.Serving;
|
|
serving.Role.ShouldBe("Primary");
|
|
serving.ServingGeneration.ShouldBeGreaterThan(0);
|
|
var context = new DataAuthenticatedContext("peer", "key", DataCallerIdentity.CredentialVersionFor(key),
|
|
null, serving.AuthorityEpoch);
|
|
var factory = provider.GetRequiredService<IDataConnectionFactory>();
|
|
await using var connection = factory.Create(context, new(DataTargetMode.Node, "cluster", nodeId));
|
|
var budget = new DataBudget(TimeSpan.FromSeconds(5), 100, 1_000_000);
|
|
(await connection.GetCapabilitiesAsync(budget, ct)).Readiness.ShouldBe(DataReadiness.Ready);
|
|
|
|
using var withdraw = new ManualResetEventSlim();
|
|
using var release = new ManualResetEventSlim();
|
|
var fenceHeld = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var verdictWithdrawn = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var fence = provider.GetRequiredService<DataWriteDispatchFence>();
|
|
var owner = Task.Run(() =>
|
|
{
|
|
using var lease = fence.Enter();
|
|
fenceHeld.SetResult();
|
|
if (!withdraw.Wait(TimeSpan.FromSeconds(8), ct) || release.IsSet) return;
|
|
if (warm) warmRole.Publish(warmOwner, WarmRole.Standby).ShouldBeTrue();
|
|
else role.PublishDataServingRole(null, false);
|
|
verdictWithdrawn.SetResult();
|
|
release.Wait(TimeSpan.FromSeconds(8), ct).ShouldBeTrue();
|
|
}, ct);
|
|
try
|
|
{
|
|
await fenceHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
// Establish real contention without relying on a sleep or changing the
|
|
// underlying verdict. The fence remains exclusive for dispatch.
|
|
var exclusiveEntry = fence.TryEnter(out var unexpectedLease);
|
|
unexpectedLease?.Dispose();
|
|
exclusiveEntry.ShouldBeFalse();
|
|
catalog.Current.ShouldBeSameAs(activeCatalog);
|
|
catalog.Serving.ShouldBe(serving);
|
|
var contended = await connection.GetCapabilitiesAsync(budget, ct);
|
|
contended.Readiness.ShouldBe(DataReadiness.Ready);
|
|
contended.Serving.ShouldBe(serving);
|
|
|
|
withdraw.Set();
|
|
await verdictWithdrawn.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
var withdrawn = await connection.GetCapabilitiesAsync(budget, ct);
|
|
withdrawn.Readiness.ShouldBe(DataReadiness.Unavailable);
|
|
withdrawn.Operations.ShouldBe(DataOperations.None);
|
|
withdrawn.Serving.ShouldNotBe(serving);
|
|
}
|
|
finally
|
|
{
|
|
release.Set();
|
|
withdraw.Set();
|
|
await owner.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
}
|
|
|
|
var afterRelease = await connection.GetCapabilitiesAsync(budget, ct);
|
|
afterRelease.Readiness.ShouldBe(DataReadiness.Unavailable);
|
|
afterRelease.Serving.ServingGeneration.ShouldBeGreaterThan(serving.ServingGeneration);
|
|
}
|
|
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();
|
|
try
|
|
{
|
|
await lease.GetCapabilitiesAsync(new DataBudget(TimeSpan.FromSeconds(1), 1, 1024), ct);
|
|
throw new Xunit.Sdk.XunitException("A withdrawn route must not reach the network.");
|
|
}
|
|
catch (OperationCanceledException) when (lease.CancellationToken.IsCancellationRequested) { }
|
|
catch (InvalidOperationException ex) when (ex.Message == "Connection is no longer ready in the current scope.") { }
|
|
lease.Dispose();
|
|
}
|
|
|
|
private static ServiceCollection RegisteredOriginServices(ActorRegistry registry, bool warm = false)
|
|
{
|
|
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());
|
|
if (warm) services.AddSingleton(new WarmRedundancySettings(OpcUaRedundancyMode.Warm));
|
|
services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true);
|
|
return services;
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|