using System.Net.Sockets; using Akka.Actor; using Akka.Cluster; using Akka.Hosting; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using ZB.MOM.WW.OtOpcUa.AdminUI; using ZB.MOM.WW.OtOpcUa.AdminUI.Api; using ZB.MOM.WW.OtOpcUa.AdminUI.Clients; using ZB.MOM.WW.OtOpcUa.AdminUI.Hubs; using ZB.MOM.WW.OtOpcUa.Cluster; using ZB.MOM.WW.OtOpcUa.Configuration; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.ControlPlane; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Host.Health; using ZB.MOM.WW.OtOpcUa.Runtime; using ZB.MOM.WW.OtOpcUa.Security; using ZB.MOM.WW.OtOpcUa.Security.Endpoints; using ZB.MOM.WW.OtOpcUa.Security.Ldap; namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests; /// /// Spins up two in-process OtOpcUa.Host-equivalent instances /// that share an and form a 2-member Akka cluster. Both /// nodes carry the admin + driver roles, matching design §8's failover-test 2-node /// profile. /// /// Default mode uses EF InMemoryDatabase + . Optional /// real-infra modes (env-var driven, see ): /// /// OTOPCUA_HARNESS_USE_SQL=1 → swap the in-memory DB for SQL Server on /// localhost:14331 (see docker-compose.yml). Each harness gets a unique /// database name (OtOpcUa_Harness_{guid}) created via EnsureCreated /// and dropped via EnsureDeleted on dispose. Override the SQL / LDAP host with /// OTOPCUA_HARNESS_SQL_HOST / OTOPCUA_HARNESS_LDAP_HOST to point at native /// fixtures on the shared Docker host (avoids the arm64-Mac emulated-mssql slowdown). /// OTOPCUA_HARNESS_USE_LDAP=1 → drop the stub and point LdapAuthService /// at the GLAuth container on localhost:3894 (see Docker/glauth/config.toml). /// /// /// Why not WebApplicationFactory<Program>? Program.cs reads OTOPCUA_ROLES /// from process env (shared across in-process WAF instances) and writes both Serilog file sinks /// + Akka cluster TCP listener to the host process — neither survives two parallel WAFs cleanly. /// This harness instead replays the Program.cs DI graph from a clean /// per node with per-node config overrides. /// public sealed class TwoNodeClusterHarness : IAsyncDisposable { public const string TestRoles = "admin,driver"; /// The deploy-API key both harness nodes are configured with (Security:DeployApiKey). public const string HarnessDeployApiKey = "test-deploy-key"; /// Gets the shared database name for both cluster nodes. public string SharedDbName { get; } = $"two-node-cluster-{Guid.NewGuid():N}"; /// Resolves node A's bound HTTP base address (Kestrel binds an ephemeral port), for /// driving the REST surface over real HTTP in tests. public string NodeABaseAddress => ResolveBaseAddress(NodeA); private static string ResolveBaseAddress(WebApplication app) { var feature = app.Services.GetRequiredService() .Features.Get(); return feature?.Addresses.FirstOrDefault() ?? throw new InvalidOperationException("Node A has no bound HTTP address."); } /// Gets the harness mode configuration from environment variables. public HarnessMode Mode { get; } = HarnessMode.FromEnvironment(); private string? _sqlDbName; private string? _sqlConnString; /// Optional opt-in both nodes register so deployed drivers can /// reach Connected/Healthy in-process. Null (default) leaves the production /// from AddOtOpcUaRuntime() in place — unchanged behaviour for /// existing tests. private IDriverFactory? _driverFactory; private IDriverProbe? _driverProbe; /// Gets the first web application node. public WebApplication NodeA { get; private set; } = null!; /// Gets the second web application node. public WebApplication NodeB { get; private set; } = null!; /// Gets the Akka port allocated for node A. public int NodeAAkkaPort { get; private set; } /// Gets the Akka port allocated for node B. public int NodeBAkkaPort { get; private set; } // Both nodes bind to 127.0.0.1 — ClusterRoleInfo + ConfigPublishCoordinator encode // host:port into NodeId so the cluster membership stays distinct on different ports. public const string LoopbackHost = "127.0.0.1"; /// /// How long a deploy-seal assertion waits. Generous on purpose: since per-cluster mesh /// Phase 1 the coordinator waits for a real ApplyAck from every configured node before /// sealing, so this measures an end-to-end two-node deploy rather than — as it did when the /// expected-ack set came up empty — an immediate seal. The old 15s had enormous margin /// against "instant" and thin margin against the real thing, which showed up as deploy /// tests failing only under full-suite CPU contention. /// public static readonly TimeSpan DeploySealTimeout = TimeSpan.FromSeconds(45); /// Gets the Akka ActorSystem for node A. public ActorSystem NodeASystem => NodeA.Services.GetRequiredService(); /// Gets the Akka ActorSystem for node B. public ActorSystem NodeBSystem => NodeB.Services.GetRequiredService(); /// /// The host:port identity each node's DriverHostActor / NodeDeploymentState /// row uses, derived the same way ClusterRoleInfo derives LocalNode from /// Cluster:PublicHostname + Cluster:Port. Seed a ClusterNode.NodeId with this /// value to bind a node to a logical ClusterId for multi-cluster scoping tests. /// public string NodeANodeId => $"{LoopbackHost}:{NodeAAkkaPort}"; /// public string NodeBNodeId => $"{LoopbackHost}:{NodeBAkkaPort}"; /// Opens a new over the shared ConfigDb (the same /// store both nodes read) so a test can seed clusters/nodes/drivers before triggering a deploy. /// A new DbContext the caller is responsible for disposing. public Task CreateConfigDbContextAsync() => NodeA.Services.GetRequiredService>().CreateDbContextAsync(); /// /// Seeds a default plus a row for BOTH /// harness nodes ( / ) so the real-SQL FK /// constraint FK_NodeDeploymentState_ClusterNode_NodeId is satisfied when a deployment /// records per-node state. Against SQL Server each node's NodeDeploymentState INSERT /// fails without its parent row and the deployment never seals. /// Call once, before StartDeploymentAsync, in tests that don't already seed their own /// cluster + both nodes. /// /// /// This used to no-op in in-memory mode ("the in-memory provider ignores FK /// constraints, so deploy E2E tests pass without it"). That stopped being true in per-cluster /// mesh Phase 1: ConfigPublishCoordinator now derives its expected-ack set from these /// rows rather than from cluster membership, so with none seeded it seals immediately /// with an empty set. "Wait for Sealed" then no longer implies "every node has applied", and /// since DriverHostActor.UpsertNodeDeploymentState writes each node's row on its own /// schedule, any test counting those rows after a seal became a race — reproducibly green /// alone and red under suite load. Seeding in both modes restores the invariant the tests /// were written against, and is closer to production either way: a real fleet always has /// these rows, because the FK requires them. /// /// Cluster id for the seeded rows. Defaults to MAIN. public async Task SeedDefaultClusterAsync(string clusterId = "MAIN") { await using var db = await CreateConfigDbContextAsync(); db.ServerClusters.Add(new ServerCluster { ClusterId = clusterId, Name = "Harness Default Cluster", Enterprise = "zb", Site = "central", // 2-node cluster → Warm/Hot per CK_ServerCluster_RedundancyMode_NodeCount // (NodeCount=1↔None, NodeCount=2↔Warm|Hot). The harness runs two nodes. NodeCount = 2, RedundancyMode = RedundancyMode.Warm, CreatedBy = "harness", }); db.ClusterNodes.AddRange( new ClusterNode { NodeId = NodeANodeId, ClusterId = clusterId, Host = LoopbackHost, ApplicationUri = "urn:zb:harness:node-a", CreatedBy = "harness", }, new ClusterNode { NodeId = NodeBNodeId, ClusterId = clusterId, Host = LoopbackHost, ApplicationUri = "urn:zb:harness:node-b", CreatedBy = "harness", }); await db.SaveChangesAsync(); } /// Boots both nodes and waits up to for cluster convergence. /// Maximum time to wait for cluster formation; defaults to 20 seconds if not provided. /// Optional opt-in both nodes register so deployed /// drivers reach Connected/Healthy in-process. Null (default) leaves the production /// default in place — unchanged behaviour for existing tests. /// Optional probe that both nodes expose to the admin operations singleton. /// Optional HOCON prepended to both nodes' Akka config (tests that need a non-default /// Akka setting, e.g. a slow DistributedPubSub gossip interval). /// /// lmxopcua#1106: "formed" includes the deploy topics' DistributedPubSub registries having gossiped to both /// nodes () — not just both members being Up. A deploy published in the /// window between the two was silently delivered to node A only (DPS publishes to the buckets it knows), so the /// deployment could never seal: the seal-timeout flake behind #843/#1106. /// public static async Task StartAsync( TimeSpan? formationTimeout = null, IDriverFactory? driverFactory = null, IDriverProbe? driverProbe = null, string? extraHocon = null) { var harness = new TwoNodeClusterHarness(); harness._driverFactory = driverFactory; harness._driverProbe = driverProbe; harness._extraHocon = extraHocon; harness.NodeAAkkaPort = AllocateFreePort(); harness.NodeBAkkaPort = AllocateFreePort(); if (harness.Mode.UseSqlServer) { harness._sqlDbName = $"OtOpcUa_Harness_{Guid.NewGuid():N}"; // SQL host is overridable so the heavy 2-node E2E tests can target NATIVE-amd64 SQL on the // shared Docker host instead of the arm64 Mac's emulated mssql:2022 (no arm64 image → ~5-10× // slower → the deploy/failover E2E tests time out). Set OTOPCUA_HARNESS_SQL_HOST=10.100.0.35,14331 // with the harness sql container brought up there. Defaults to localhost,14331. var sqlHost = Environment.GetEnvironmentVariable("OTOPCUA_HARNESS_SQL_HOST") ?? "localhost,14331"; var sqlPassword = Environment.GetEnvironmentVariable("OTOPCUA_HARNESS_SQL_PASSWORD") ?? "OtOpcUa!Harness123"; harness._sqlConnString = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder { DataSource = sqlHost, InitialCatalog = harness._sqlDbName, UserID = "sa", Password = sqlPassword, TrustServerCertificate = true, }.ConnectionString; await EnsureSqlSchemaCreatedAsync(harness._sqlConnString); } // Node A boots first as the seed. harness.NodeA = await BuildNodeAsync(harness, NodeRole.Seed); harness._eventLogA = NodeEventLog.Attach(harness.NodeASystem); harness.NodeB = await BuildNodeAsync(harness, NodeRole.Joiner); harness._eventLogB = NodeEventLog.Attach(harness.NodeBSystem); await WaitForClusterFormationAsync( harness.NodeASystem, harness.NodeBSystem, formationTimeout ?? TimeSpan.FromSeconds(20)); await harness.WaitForDeployTopicsAsync(formationTimeout ?? TimeSpan.FromSeconds(20)); return harness; } private string? _extraHocon; /// /// lmxopcua#1106: waits until each node's DistributedPubSub registry carries BOTH nodes' deployments /// subscriptions (the dispatch reaches every driver host, whichever node hosts the coordinator) and the same, /// non-empty deployment-acks subscriber set (every node's ack reaches the coordinator). /// /// /// Cluster membership and the DPS registry converge independently: a member is Up as soon as cluster gossip says /// so, but the mediators exchange their subscription buckets on their own gossip tick (1 s by default) and a /// Publish reaches only the buckets its mediator already holds. Under heavy load (#1106 reproduced it at /// load average 250–430, 1 in ~10–20 runs) the test's deploy landed in that window — 13 ms after node B came Up — /// node B never received the dispatch, and the deployment sat AwaitingApplyAcks until the 120 s apply deadline. /// In production this is the documented fire-and-forget dispatch (no re-dispatch; the apply deadline is the /// backstop) — on the DPS transport only, which split-topology nodes no longer use. /// /// The time allowed; the gossip interval plus slack is plenty. public async Task WaitForDeployTopicsAsync(TimeSpan timeout) { var a = NodeAAkkaPort.ToString(); var b = NodeBAkkaPort.ToString(); var deadline = DateTime.UtcNow + timeout; while (true) { var viewA = ReadDpsRegistry(NodeASystem); var viewB = ReadDpsRegistry(NodeBSystem); if (Converged(viewA) && Converged(viewB) && Owners(viewA, "deployment-acks").SetEquals(Owners(viewB, "deployment-acks"))) return; if (DateTime.UtcNow >= deadline) throw new TimeoutException( $"The deploy topics did not gossip to both nodes within {timeout}: " + $"A=[{DescribeDpsRegistry(NodeASystem, "deployments", "deployment-acks")}] " + $"B=[{DescribeDpsRegistry(NodeBSystem, "deployments", "deployment-acks")}] (expected deployments@{{{a},{b}}})"); await Task.Delay(50); } bool Converged(IReadOnlyList<(string Owner, List Keys)> view) { var deployments = Owners(view, "deployments"); return deployments.Contains(a) && deployments.Contains(b) && Owners(view, "deployment-acks").Count > 0; } } private static HashSet Owners(IReadOnlyList<(string Owner, List Keys)> view, string topic) => view.Where(x => x.Keys.Any(k => k.EndsWith("/" + topic, StringComparison.Ordinal))) .Select(x => x.Owner) .ToHashSet(StringComparer.Ordinal); /// /// Gracefully shuts node B down, so CoordinatedShutdown runs and the node performs a /// Cluster.Leave; node A sees the member transition to Removed within a couple of seconds. /// Use this for failover scenarios; call to bring it back on /// the same Akka port. /// /// /// This used to call DisposeAsync alone, on the stated belief that disposal "runs /// CoordinatedShutdown". It does not — see . A disposed-but-never- /// stopped node never leaves the cluster gracefully; node A only notices once the failure /// detector times it out, which is a slower and materially different path from the graceful /// leave these failover tests mean to exercise. /// public async Task StopNodeBAsync() { if (NodeB is null) return; await ShutDownAsync(NodeB); NodeB = null!; } /// /// Rebuilds node B on the same Akka port + same ConfigDb and waits for the cluster /// to re-converge to 2 Up members. Use after to test rejoin. /// /// The maximum time to wait for cluster formation; defaults to 20 seconds. public async Task RestartNodeBAsync(TimeSpan? formationTimeout = null) { NodeB = await BuildNodeAsync(this, NodeRole.Joiner); _eventLogB = NodeEventLog.Attach(NodeBSystem); await WaitForClusterFormationAsync( NodeASystem, NodeBSystem, formationTimeout ?? TimeSpan.FromSeconds(20)); await WaitForDeployTopicsAsync(formationTimeout ?? TimeSpan.FromSeconds(20)); } /// /// Abruptly crashes node A (the seed / oldest member) by shutting down its remoting transport — the /// canonical in-process crash simulation. All associations drop and heartbeats/gossip stop instantly /// with NO graceful Cluster.Leave (the transport is dead, so A cannot gossip anything). Node B's /// failure detector therefore marks A Unreachable (not Removed), which is the only state the /// split-brain resolver acts on: with an active resolver (keep-oldest + down-if-alone, active here via /// both the akka.conf block and Akka.Cluster.Hosting's default downing provider) B downs the alone /// oldest node and takes over; with downing disabled (explicit NoDowning) B keeps A Unreachable forever /// and never fails over. This is the crash the graceful path (a real /// Cluster.Leave, which removes a member with no downing decision) can NOT simulate. /// The ActorSystem itself stays alive with a dead transport until harness teardown disposes it. /// public async Task HardKillNodeAAsync() { if (NodeA is null) return; var provider = (Akka.Remote.IRemoteActorRefProvider)((ExtendedActorSystem)NodeASystem).Provider; await provider.Transport.Shutdown(); } /// /// Waits until node B's own cluster view has the crashed node A removed (B is the sole Up member) AND /// B has become the driver-role leader — i.e. the split-brain resolver downed the alone oldest /// node and B took over. Queries (node A is dead after a hard kill, so its /// view can't be read). Returns the elapsed time to takeover; throws if /// B never becomes the sole driver-leader within (the failure signature of /// an INACTIVE resolver — A stays Unreachable and B never fails over). /// /// Upper bound; must exceed acceptable-heartbeat-pause (10s) + stable-after (15s). public async Task WaitForNodeBSoleDriverLeaderAsync(TimeSpan timeout) { var start = DateTime.UtcNow; var deadline = start + timeout; // Require the outcome to hold across several consecutive polls so a transient during A's // Up -> Down convergence (the members list can briefly flap while gossip settles) can't be // mistaken for a settled takeover. const int requiredStableStreak = 4; var streak = 0; while (DateTime.UtcNow < deadline) { var clusterB = Akka.Cluster.Cluster.Get(NodeBSystem); var state = clusterB.State; var upCount = state.Members.Count(m => m.Status == MemberStatus.Up); var driverLeader = state.RoleLeader("driver"); // SBR proof: the crashed oldest node has been DOWNED (no longer Up, so B is the sole Up // member) and B has become the driver-role leader. With the resolver INACTIVE (NoDowning) A // would instead stay Up-but-Unreachable — B would still see 2 Up members and never gain a // stable role leader. (A lingers as a Down member in the Unreachable set until reaped; that // reaping is not part of the failover contract, so it is NOT required here.) if (upCount == 1 && driverLeader == clusterB.SelfAddress) { if (++streak >= requiredStableStreak) return DateTime.UtcNow - start; } else { streak = 0; } await Task.Delay(250); } var finalState = Akka.Cluster.Cluster.Get(NodeBSystem).State; throw new TimeoutException( $"Node B did not become the sole driver-role leader within {timeout} after node A was hard-killed. " + $"Up={finalState.Members.Count(m => m.Status == MemberStatus.Up)}, " + $"Unreachable={finalState.Unreachable.Count}, " + $"driverLeader={finalState.RoleLeader("driver")}, selfB={Akka.Cluster.Cluster.Get(NodeBSystem).SelfAddress}. " + "A stuck-Unreachable A with no takeover is the signature of an INACTIVE split-brain resolver."); } /// /// Waits for node A's cluster view to reach members in /// . Used for asserting shrink-after-stop or grow-after-restart. /// /// The expected number of Up members in the cluster. /// The maximum time to wait for the expected cluster size. public async Task WaitForClusterSizeAsync(int expectedUpMembers, TimeSpan timeout) { var deadline = DateTime.UtcNow + timeout; while (DateTime.UtcNow < deadline) { var count = Akka.Cluster.Cluster.Get(NodeASystem).State.Members .Count(m => m.Status == MemberStatus.Up); if (count == expectedUpMembers) return; await Task.Delay(200); } var actual = Akka.Cluster.Cluster.Get(NodeASystem).State.Members .Count(m => m.Status == MemberStatus.Up); throw new TimeoutException( $"Cluster did not converge to {expectedUpMembers} Up members within {timeout}. Actual={actual}"); } /// /// lmxopcua#843 / #1106: where a deploy stood when a seal wait gave up — the deployment row, each node's /// per-node state, both nodes' cluster views, which members each node's DistributedPubSub registry holds a /// subscriber on for the two deploy topics (), and both nodes' recent Akka log /// events. A node whose driver host never logged "reading artifact" for the deployment never received the /// dispatch; one that applied (its own Applied row — on a fused node DriverHostActor writes that itself, so /// it does NOT prove the coordinator counted the ack) while the coordinator never sealed lost the ack. /// /// After the snapshot it keeps watching the row for (default /// ) and says whether the deployment sealed LATE (and how late) or stayed /// unsealed — the one observation that separates a starved-but-progressing deploy (CPU contention: widen /// nothing, the machine was overloaded) from a lost dispatch/ack (a real race: it never seals before the /// coordinator's apply deadline closes it TimedOut). /// /// /// The deployment that did not seal. /// How long to keep watching for a late seal; = . /// A one-line description for the timeout message. public async Task DescribeDeploymentAsync(Guid deploymentId, TimeSpan? lateGrace = null) { var snapshot = await SnapshotDeploymentAsync(deploymentId); var grace = lateGrace ?? LateSealGrace; var watch = System.Diagnostics.Stopwatch.StartNew(); string late = $"still not terminal {grace.TotalSeconds:0}s after the wait gave up (lost, not slow)"; while (watch.Elapsed < grace) { try { await using var db = await CreateConfigDbContextAsync(); var status = await db.Deployments.AsNoTracking() .Where(x => x.DeploymentId == deploymentId).Select(x => (DeploymentStatus?)x.Status).FirstOrDefaultAsync(); if (status is DeploymentStatus.Sealed or DeploymentStatus.PartiallyFailed or DeploymentStatus.TimedOut) { late = $"became {status} {watch.Elapsed.TotalSeconds:0.0}s after the wait gave up (slow, not lost)"; break; } } catch { // Best effort: the snapshot above already carries the failure, if the DB itself is the problem. } await Task.Delay(250); } return $"{snapshot}; late: {late}; A events=[{_eventLogA?.Dump()}]; B events=[{_eventLogB?.Dump()}]"; } private NodeEventLog? _eventLogA; private NodeEventLog? _eventLogB; /// /// lmxopcua#1106: a bounded ring of one node's Akka log events (the ActorSystem's configured level and up) and /// dead letters, captured from boot, so a seal timeout can show what the coordinator / driver hosts / publish /// actor said. The harness hosts route Akka logging into the Microsoft logger, which no test output captures. /// private sealed class NodeEventLog { private const int Capacity = 400; private readonly System.Collections.Concurrent.ConcurrentQueue _lines = new(); public static NodeEventLog Attach(ActorSystem system) { var log = new NodeEventLog(); var listener = system.ActorOf(Props.Create(() => new Listener(log)), $"harness-event-log-{Guid.NewGuid():N}"); system.EventStream.Subscribe(listener, typeof(Akka.Event.LogEvent)); system.EventStream.Subscribe(listener, typeof(Akka.Event.AllDeadLetters)); return log; } private void Add(string line) { _lines.Enqueue($"{DateTime.UtcNow:HH:mm:ss.fff} {line}"); while (_lines.Count > Capacity && _lines.TryDequeue(out _)) { } } /// The deploy-relevant lines (or the last few of everything when none match), newest last. public string Dump() { var all = _lines.ToArray(); string[] needles = ["Deploy", "deploy", "Dispatch", "ApplyAck", "DriverHost", "OpcUaPublish", "Rebuild", "apply"]; var relevant = all.Where(l => needles.Any(n => l.Contains(n, StringComparison.Ordinal))).TakeLast(40).ToArray(); return string.Join(" | ", relevant.Length > 0 ? relevant : all.TakeLast(15)); } private sealed class Listener : ReceiveActor { public Listener(NodeEventLog log) { Receive(e => log.Add($"{e.LogLevel()} [{e.LogSource}] {e.Message}")); Receive(d => log.Add( $"DEADLETTER {d.Message.GetType().Name} {d.Message} from {d.Sender} to {d.Recipient}")); } } } /// How long keeps watching for a late seal (lmxopcua#1106). public static readonly TimeSpan LateSealGrace = TimeSpan.FromSeconds(60); private async Task SnapshotDeploymentAsync(Guid deploymentId) { string dbPart; try { await using var db = await CreateConfigDbContextAsync(); var d = await db.Deployments.AsNoTracking().FirstOrDefaultAsync(x => x.DeploymentId == deploymentId); var nodes = await db.NodeDeploymentStates.AsNoTracking() .Where(s => s.DeploymentId == deploymentId).ToListAsync(); dbPart = $"deployment={d?.Status.ToString() ?? ""} artifact={d?.ArtifactBlob.Length ?? 0}B " + $"failure='{d?.FailureReason}' created={d?.CreatedAtUtc:O} now={DateTime.UtcNow:O}; " + $"nodes=[{string.Join("; ", nodes.Select(n => $"{n.NodeId} {n.Status} started={n.StartedAtUtc:O} applied={n.AppliedAtUtc:O} failure='{n.FailureReason}'"))}] " + $"(expected {NodeANodeId}, {NodeBNodeId})"; } catch (Exception ex) { dbPart = $""; } static string View(ActorSystem s) => string.Join(",", Akka.Cluster.Cluster.Get(s).State.Members.Select(m => $"{m.Address.Port}:{m.Status}")) + $" unreachable={Akka.Cluster.Cluster.Get(s).State.Unreachable.Count}"; return $"{dbPart}; A view=[{View(NodeASystem)}] B view=[{View(NodeBSystem)}]; " + $"A dps=[{DescribeDpsRegistry(NodeASystem, "deployments", "deployment-acks")}] " + $"B dps=[{DescribeDpsRegistry(NodeBSystem, "deployments", "deployment-acks")}]"; } /// /// lmxopcua#1106: which cluster members THIS node's DistributedPubSub mediator currently knows a subscriber on, per /// topic — i.e. where a Publish from this node would be delivered right now. A publish only reaches the /// members whose registry bucket has gossiped here, so a message published before the peer's bucket arrived is /// silently lost. Akka exposes no public per-topic, cluster-wide view (CountSubscribers counts only this /// node's LOCAL subscribers), so this reads the mediator's private _registry by reflection: test-only, a /// best-effort snapshot taken off the mediator's thread, and it reports a failure instead of throwing. /// /// The node whose mediator to read. /// The topics to report. /// e.g. deployments@{4053,4054} deployment-acks@{4053} (member ports). public static string DescribeDpsRegistry(ActorSystem system, params string[] topics) { try { var view = ReadDpsRegistry(system); return string.Join(" ", topics.Select(topic => $"{topic}@{{{string.Join(",", Owners(view, topic).Order(StringComparer.Ordinal))}}}")); } catch (Exception ex) { return $""; } } /// /// Reads one node's DistributedPubSub registry (see ): per bucket owner (member /// port), every key with a live subscriber. The mediator mutates its dictionary on its own thread, so a read that /// races a mutation is retried; a missing member (Akka internals changed) throws . /// /// The node whose mediator to read. /// (owner port, keys) per registry bucket. private static IReadOnlyList<(string Owner, List Keys)> ReadDpsRegistry(ActorSystem system) { const System.Reflection.BindingFlags Any = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic; var mediator = Akka.Cluster.Tools.PublishSubscribe.DistributedPubSub.Get(system).Mediator; var cell = (mediator as ActorRefWithCell)?.Underlying as ActorCell ?? throw new NotSupportedException("the DPS mediator is not a local actor cell"); for (var attempt = 1; ; attempt++) { try { var actor = typeof(ActorCell).GetProperty("Actor", Any)?.GetValue(cell) ?? throw new NotSupportedException("no ActorCell.Actor (Akka internals changed)"); var registry = actor.GetType().GetField("_registry", Any)?.GetValue(actor) as System.Collections.IDictionary ?? throw new NotSupportedException("no DistributedPubSubMediator._registry (Akka internals changed)"); var snapshot = new List<(string Owner, List Keys)>(); foreach (System.Collections.DictionaryEntry e in registry) { var bucket = e.Value!; var content = bucket.GetType().GetProperty("Content", Any)?.GetValue(bucket) as System.Collections.IEnumerable ?? throw new NotSupportedException("no Bucket.Content (Akka internals changed)"); var keys = new List(); foreach (var kv in content) { var key = (string)kv.GetType().GetProperty("Key")!.GetValue(kv)!; var holder = kv.GetType().GetProperty("Value")!.GetValue(kv)!; var actorRef = holder.GetType().GetProperty("Ref", Any)?.GetValue(holder) as IActorRef; if (actorRef is not null && !actorRef.IsNobody()) keys.Add(key); } var owner = (Address)e.Key; snapshot.Add((owner.Port?.ToString() ?? owner.ToString(), keys)); } return snapshot; } catch (InvalidOperationException) when (attempt < 10) { // "Collection was modified": the mediator changed its registry mid-read. Read again. } } } private enum NodeRole { Seed, Joiner } private static async Task BuildNodeAsync(TwoNodeClusterHarness harness, NodeRole role) { var akkaPort = role == NodeRole.Seed ? harness.NodeAAkkaPort : harness.NodeBAkkaPort; var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = [] }); builder.WebHost.UseKestrel(o => o.Listen(System.Net.IPAddress.Parse(LoopbackHost), 0)); var configOverrides = new Dictionary { ["ConnectionStrings:ConfigDb"] = harness._sqlConnString ?? "Server=test;Database=test;Trusted_Connection=True;TrustServerCertificate=True;", ["Cluster:Hostname"] = LoopbackHost, ["Cluster:Port"] = akkaPort.ToString(), ["Cluster:PublicHostname"] = LoopbackHost, ["Cluster:SeedNodes:0"] = $"akka.tcp://otopcua@{LoopbackHost}:{harness.NodeAAkkaPort}", ["Cluster:Roles:0"] = "admin", ["Cluster:Roles:1"] = "driver", ["Security:Jwt:SigningKey"] = "two-node-harness-test-signing-key-with-enough-bytes-for-hs256", ["Security:Jwt:Issuer"] = "otopcua-test", ["Security:DeployApiKey"] = HarnessDeployApiKey, ["Security:Jwt:Audience"] = "otopcua-test", }; if (harness.Mode.UseRealLdap) { // Bound section is Security:Ldap (see LdapOptions.SectionName); Transport replaces the // old UseTls bool and AllowInsecure replaces AllowInsecureLdap (Task 1.4). configOverrides["Security:Ldap:Enabled"] = "true"; // Overridable alongside the SQL host so the GLAuth container can live on the Docker host too. configOverrides["Security:Ldap:Server"] = Environment.GetEnvironmentVariable("OTOPCUA_HARNESS_LDAP_HOST") ?? "localhost"; configOverrides["Security:Ldap:Port"] = Environment.GetEnvironmentVariable("OTOPCUA_HARNESS_LDAP_PORT") ?? "3894"; configOverrides["Security:Ldap:Transport"] = "None"; configOverrides["Security:Ldap:AllowInsecure"] = "true"; configOverrides["Security:Ldap:SearchBase"] = "dc=zb,dc=local"; // GLAuth's search-capable bind account (see Docker/glauth/config.toml) — matches the // shared GLAuth the data-plane binds against. Replaced the retired OpenLDAP cn=admin. configOverrides["Security:Ldap:ServiceAccountDn"] = "cn=serviceaccount,dc=zb,dc=local"; configOverrides["Security:Ldap:ServiceAccountPassword"] = "serviceaccount123"; } builder.Configuration.AddInMemoryCollection(configOverrides); // Provider swap: same DbContext type wired to either InMemory or SqlServer at startup. if (harness.Mode.UseSqlServer) { builder.Services.AddDbContextFactory(opt => opt.UseSqlServer(harness._sqlConnString)); builder.Services.AddDbContext(opt => opt.UseSqlServer(harness._sqlConnString)); } else { builder.Services.AddDbContextFactory(opt => opt.UseInMemoryDatabase(harness.SharedDbName)); builder.Services.AddDbContext(opt => opt.UseInMemoryDatabase(harness.SharedDbName)); } // Production fidelity: Program.cs calls AddOtOpcUaRuntime() (DI registration) AND // WithOtOpcUaRuntimeActors() (Akka spawn). The harness historically called only the latter, // so IDriverHealthPublisher fell back to NullDriverHealthPublisher (no health on the // driver-health DPS topic) and IDriverFactory to NullDriverFactory (deployed drivers never // reached Connected). Register the opt-in fake factory FIRST so its registration wins over the // TryAddSingleton(NullDriverFactory) seeded inside AddOtOpcUaRuntime; when no // factory was passed, the Null default stays — unchanged behaviour for existing tests. Must run // BEFORE AddAkka (see the AddOtOpcUaRuntime XML doc). if (harness._driverFactory is not null) builder.Services.AddSingleton(harness._driverFactory); if (harness._driverProbe is not null) builder.Services.AddSingleton(harness._driverProbe); builder.Services.AddOtOpcUaRuntime(); builder.Services.AddOtOpcUaCluster(builder.Configuration); builder.Services.AddAkka("otopcua", (ab, sp) => { ab.WithOtOpcUaClusterBootstrap(sp); ab.WithOtOpcUaControlPlaneSingletons(); ab.WithOtOpcUaRuntimeActors(); // Production fidelity, per-cluster mesh Phase 6 (`a2c5d57f`). RedundancyStateActor moved OUT // of WithOtOpcUaControlPlaneSingletons and into its own cluster-role-scoped registration, // which Program.cs makes from its DRIVER branch — a driver-only site pair has no admin node // to elect its Primary. The harness models a fused admin,driver node but was never updated, // so from that commit until now NO node here spawned the singleton: nothing published // `redundancy-state`, every node sat at "role unknown" forever, and PrimaryGateFailoverTests // polled for 45s and timed out. // // This is the second time this exact shape has bitten the harness — see the AddOtOpcUaRuntime // note above, where calling only the Akka-spawn half left IDriverHealthPublisher on its Null // default. When Program.cs grows an actor registration, this list has to grow with it; the // harness's whole value is that it is wired the way a real node is. ab.WithOtOpcUaClusterRedundancySingleton( sp.GetRequiredService>().Value); if (harness._extraHocon is { Length: > 0 } hocon) ab.AddHocon(hocon, HoconAddMode.Prepend); }); builder.Services.AddOtOpcUaAuth(builder.Configuration); if (!harness.Mode.UseRealLdap) builder.Services.AddSingleton(); builder.Services.AddAdminUI(); builder.Services.AddSignalR(); builder.Services.AddOtOpcUaAdminClients(); builder.Services.AddOtOpcUaHealth(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapOtOpcUaAuth(); app.MapOtOpcUaHubs(); app.MapOtOpcUaHealth(); app.MapOtOpcUaDeployApi(app.Configuration); await app.StartAsync(); return app; } private static async Task EnsureSqlSchemaCreatedAsync(string connString) { var opts = new DbContextOptionsBuilder() .UseSqlServer(connString) .Options; await using var db = new OtOpcUaConfigDbContext(opts); // EnsureCreated bypasses migrations but builds the model in one shot — fine for tests. // Production deployments use Migrate-To-V2.ps1 to apply EF migrations. await db.Database.EnsureCreatedAsync(); } private static async Task DropSqlDatabaseAsync(string connString) { var opts = new DbContextOptionsBuilder() .UseSqlServer(connString) .Options; await using var db = new OtOpcUaConfigDbContext(opts); await db.Database.EnsureDeletedAsync(); } private static async Task WaitForClusterFormationAsync(ActorSystem a, ActorSystem b, TimeSpan timeout) { var deadline = DateTime.UtcNow + timeout; while (DateTime.UtcNow < deadline) { var aMembers = Akka.Cluster.Cluster.Get(a).State.Members .Where(m => m.Status == MemberStatus.Up).ToArray(); var bMembers = Akka.Cluster.Cluster.Get(b).State.Members .Where(m => m.Status == MemberStatus.Up).ToArray(); if (aMembers.Length >= 2 && bMembers.Length >= 2) return; await Task.Delay(200); } throw new TimeoutException( $"Cluster did not form within {timeout}. " + $"A up={Akka.Cluster.Cluster.Get(a).State.Members.Count(m => m.Status == MemberStatus.Up)}, " + $"B up={Akka.Cluster.Cluster.Get(b).State.Members.Count(m => m.Status == MemberStatus.Up)}"); } /// /// Stops a node's hosted services, then disposes it. /// /// /// /// is not optional, and disposal is not a substitute for /// it. Host.DisposeAsync only disposes the service provider; it never invokes /// . Akka.Hosting terminates the /// from that callback, so a disposed-but-never-stopped node /// leaves a live ActorSystem — remoting transport, dispatcher thread pools and all — /// rooted for the lifetime of the test process. /// /// /// Every test here starts two of them, so the cost compounded across the suite: a single /// test host was measured at ~30 GB RSS, which starved timeout-based assertions /// into false failures that looked exactly like real regressions. /// /// /// The node to stop and dispose. private static async Task ShutDownAsync(WebApplication node) { // Best-effort: a node already stopped (or mid-CoordinatedShutdown from a failover test) // throws here, and a failure to stop must never mask the test's own assertion failure. try { await node.StopAsync(TimeSpan.FromSeconds(10)); } catch { // fall through to disposal } await node.DisposeAsync(); } private static int AllocateFreePort() { using var listener = new TcpListener(System.Net.IPAddress.Parse(LoopbackHost), 0); listener.Start(); var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } /// Asynchronously disposes both nodes and cleans up the SQL database if used. public async ValueTask DisposeAsync() { if (NodeB is not null) await ShutDownAsync(NodeB); if (NodeA is not null) await ShutDownAsync(NodeA); if (_sqlConnString is not null) { try { await DropSqlDatabaseAsync(_sqlConnString); } catch { /* best-effort cleanup */ } } } /// Captures the env-var driven harness mode at construction time. public sealed record HarnessMode(bool UseSqlServer, bool UseRealLdap) { /// Creates a HarnessMode from environment variable settings. /// A HarnessMode configured from OTOPCUA_HARNESS_USE_SQL and OTOPCUA_HARNESS_USE_LDAP environment variables. public static HarnessMode FromEnvironment() => new( UseSqlServer: Environment.GetEnvironmentVariable("OTOPCUA_HARNESS_USE_SQL") == "1", UseRealLdap: Environment.GetEnvironmentVariable("OTOPCUA_HARNESS_USE_LDAP") == "1"); } private sealed class StubLdapAuthService : ILdapAuthService { /// Asynchronously authenticates a user with the stub LDAP service. /// The username to authenticate. /// The password to authenticate against. /// The cancellation token. /// A task that returns the LDAP authentication result. public Task AuthenticateAsync(string username, string password, CancellationToken ct = default) => Task.FromResult(new LdapAuthResult( Success: password == "valid-password", DisplayName: username, Username: username, Groups: ["Administrator"], Roles: ["Administrator"], Error: null)); } }