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(new LocalRole()); services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService())); services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService())); services.AddSingleton(sp => new TriePermissionEvaluator(sp.GetRequiredService().Tries)); services.AddSingleton(new GrpcDataSecretProvisioningTests.MemoryStore()); services.AddSingleton(new GrpcDataSecretProvisioningTests.TestCipher()); services.AddSingleton(new GrpcDataSecretProvisioningTests.NoopInvalidator()); services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true); await using var provider = services.BuildServiceProvider(); var resolver = provider.GetRequiredService(); provider.GetRequiredService().ShouldBeSameAs(resolver); provider.GetRequiredService() .ShouldBeSameAs(provider.GetRequiredService()); provider.GetRequiredService().Active.ShouldBeEmpty(); provider.GetRequiredService() .ShouldBeSameAs(provider.GetRequiredService()); provider.GetRequiredService().ShouldNotBeNull(); provider.GetRequiredService().ShouldNotBeNull(); provider.GetRequiredService() .ShouldBeSameAs(provider.GetRequiredService()); } [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().ShouldBeNull(); } [Fact] public void Enabled_surface_requires_the_actual_driver_role() { var services = new ServiceCollection(); Should.Throw(() => 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(); Should.Throw(() => 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(); 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(); var role = provider.GetRequiredService(); role.PublishDataServingRole(RedundancyRole.Primary, true); var attempt = catalog.BeginAttempt("revision"); catalog.InstallAuthority(attempt, new DataPlaneAuthorityProjection("cluster", [key], [], new Dictionary>())).ShouldBeTrue(); var context = new DataAuthenticatedContext("peer", "key", DataCallerIdentity.CredentialVersionFor(key), null, provider.GetRequiredService().Current.GenerationId); Should.Throw(() => factory.Create(context, target)); // no registered host var actor = system.ActorOf(Props.Create(() => new LocalActor())); registry.Register(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(); 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(); composition.AcquisitionCapacity.ShouldBeSameAs(provider.GetRequiredService()); composition.Services.Clock.ShouldBeSameAs(provider.GetRequiredService()); } 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(system.ActorOf(Props.Create(() => new LocalActor()))); await using var provider = RegisteredOriginServices(registry, warm).BuildServiceProvider(); var catalog = provider.GetRequiredService(); var role = provider.GetRequiredService(); var warmRole = provider.GetRequiredService(); 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>())).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(); 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(); 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(); 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(new LocalRole()); services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService())); services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService())); services.AddSingleton(new WarmRedundancySettings(OpcUaRedundancyMode.Warm)); services.AddSingleton(new GrpcDataSecretProvisioningTests.MemoryStore()); services.AddSingleton(new GrpcDataSecretProvisioningTests.TestCipher()); services.AddSingleton(new GrpcDataSecretProvisioningTests.NoopInvalidator()); services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true); await using var provider = services.BuildServiceProvider(); var role = provider.GetRequiredService(); var warm = provider.GetRequiredService(); var owner = warm.RegisterOwner(); warm.Publish(owner, WarmRole.Active); role.PublishDataServingRole(RedundancyRole.Primary, true); var runtime = provider.GetRequiredService(); 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().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().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(new LocalRole()); services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService())); services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService())); services.AddSingleton(sp => new TriePermissionEvaluator(sp.GetRequiredService().Tries)); services.AddSingleton(new GrpcDataSecretProvisioningTests.MemoryStore()); services.AddSingleton(new GrpcDataSecretProvisioningTests.TestCipher()); services.AddSingleton(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 LocalRoles => new HashSet { "driver", "cluster-cluster" }; public string? ClusterRole => "cluster-cluster"; public string? ClusterId => "cluster"; public bool HasRole(string role) => LocalRoles.Contains(role); public IReadOnlyList MembersWithRole(string role) => []; public NodeId? RoleLeader(string role) => null; public event EventHandler? RoleLeaderChanged { add { } remove { } } } private static IConfiguration Configuration() => new ConfigurationBuilder().AddInMemoryCollection( new Dictionary { ["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(); } }