Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/TwoNodeClusterHarness.cs
T

948 lines
53 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
/// <summary>
/// Spins up two in-process <c>OtOpcUa.Host</c>-equivalent <see cref="WebApplication"/> instances
/// that share an <see cref="OtOpcUaConfigDbContext"/> and form a 2-member Akka cluster. Both
/// nodes carry the <c>admin</c> + <c>driver</c> roles, matching design §8's failover-test 2-node
/// profile.
///
/// <para>Default mode uses EF InMemoryDatabase + <see cref="StubLdapAuthService"/>. Optional
/// real-infra modes (env-var driven, see <see cref="HarnessMode.FromEnvironment"/>):</para>
/// <list type="bullet">
/// <item><c>OTOPCUA_HARNESS_USE_SQL=1</c> → swap the in-memory DB for SQL Server on
/// <c>localhost:14331</c> (see <c>docker-compose.yml</c>). Each harness gets a unique
/// database name (<c>OtOpcUa_Harness_{guid}</c>) created via <c>EnsureCreated</c>
/// and dropped via <c>EnsureDeleted</c> on dispose. Override the SQL / LDAP host with
/// <c>OTOPCUA_HARNESS_SQL_HOST</c> / <c>OTOPCUA_HARNESS_LDAP_HOST</c> to point at native
/// fixtures on the shared Docker host (avoids the arm64-Mac emulated-mssql slowdown).</item>
/// <item><c>OTOPCUA_HARNESS_USE_LDAP=1</c> → drop the stub and point <c>LdapAuthService</c>
/// at the GLAuth container on <c>localhost:3894</c> (see Docker/glauth/config.toml).</item>
/// </list>
///
/// <para>Why not <c>WebApplicationFactory&lt;Program&gt;</c>? Program.cs reads <c>OTOPCUA_ROLES</c>
/// 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
/// <see cref="WebApplicationBuilder"/> per node with per-node config overrides.</para>
/// </summary>
public sealed class TwoNodeClusterHarness : IAsyncDisposable
{
public const string TestRoles = "admin,driver";
/// <summary>The deploy-API key both harness nodes are configured with (Security:DeployApiKey).</summary>
public const string HarnessDeployApiKey = "test-deploy-key";
/// <summary>Gets the shared database name for both cluster nodes.</summary>
public string SharedDbName { get; } = $"two-node-cluster-{Guid.NewGuid():N}";
/// <summary>Resolves node A's bound HTTP base address (Kestrel binds an ephemeral port), for
/// driving the REST surface over real HTTP in tests.</summary>
public string NodeABaseAddress => ResolveBaseAddress(NodeA);
private static string ResolveBaseAddress(WebApplication app)
{
var feature = app.Services.GetRequiredService<Microsoft.AspNetCore.Hosting.Server.IServer>()
.Features.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>();
return feature?.Addresses.FirstOrDefault()
?? throw new InvalidOperationException("Node A has no bound HTTP address.");
}
/// <summary>Gets the harness mode configuration from environment variables.</summary>
public HarnessMode Mode { get; } = HarnessMode.FromEnvironment();
private string? _sqlDbName;
private string? _sqlConnString;
/// <summary>Optional opt-in <see cref="IDriverFactory"/> both nodes register so deployed drivers can
/// reach <c>Connected</c>/Healthy in-process. Null (default) leaves the production
/// <see cref="NullDriverFactory"/> from <c>AddOtOpcUaRuntime()</c> in place — unchanged behaviour for
/// existing tests.</summary>
private IDriverFactory? _driverFactory;
private IDriverProbe? _driverProbe;
/// <summary>Gets the first web application node.</summary>
public WebApplication NodeA { get; private set; } = null!;
/// <summary>Gets the second web application node.</summary>
public WebApplication NodeB { get; private set; } = null!;
/// <summary>Gets the Akka port allocated for node A.</summary>
public int NodeAAkkaPort { get; private set; }
/// <summary>Gets the Akka port allocated for node B.</summary>
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";
/// <summary>
/// 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.
/// </summary>
public static readonly TimeSpan DeploySealTimeout = TimeSpan.FromSeconds(45);
/// <summary>Gets the Akka ActorSystem for node A.</summary>
public ActorSystem NodeASystem => NodeA.Services.GetRequiredService<ActorSystem>();
/// <summary>Gets the Akka ActorSystem for node B.</summary>
public ActorSystem NodeBSystem => NodeB.Services.GetRequiredService<ActorSystem>();
/// <summary>
/// The <c>host:port</c> identity each node's <c>DriverHostActor</c> / <c>NodeDeploymentState</c>
/// row uses, derived the same way <c>ClusterRoleInfo</c> derives <c>LocalNode</c> from
/// <c>Cluster:PublicHostname</c> + <c>Cluster:Port</c>. Seed a <c>ClusterNode.NodeId</c> with this
/// value to bind a node to a logical ClusterId for multi-cluster scoping tests.
/// </summary>
public string NodeANodeId => $"{LoopbackHost}:{NodeAAkkaPort}";
/// <inheritdoc cref="NodeANodeId"/>
public string NodeBNodeId => $"{LoopbackHost}:{NodeBAkkaPort}";
/// <summary>Opens a new <see cref="OtOpcUaConfigDbContext"/> over the shared ConfigDb (the same
/// store both nodes read) so a test can seed clusters/nodes/drivers before triggering a deploy.</summary>
/// <returns>A new DbContext the caller is responsible for disposing.</returns>
public Task<OtOpcUaConfigDbContext> CreateConfigDbContextAsync()
=> NodeA.Services.GetRequiredService<IDbContextFactory<OtOpcUaConfigDbContext>>().CreateDbContextAsync();
/// <summary>
/// Seeds a default <see cref="ServerCluster"/> plus a <see cref="ClusterNode"/> row for BOTH
/// harness nodes (<see cref="NodeANodeId"/> / <see cref="NodeBNodeId"/>) so the real-SQL FK
/// constraint <c>FK_NodeDeploymentState_ClusterNode_NodeId</c> is satisfied when a deployment
/// records per-node state. Against SQL Server each node's <c>NodeDeploymentState</c> INSERT
/// fails without its parent <see cref="ClusterNode"/> row and the deployment never seals.
/// Call once, before <c>StartDeploymentAsync</c>, in tests that don't already seed their own
/// cluster + both nodes.
/// </summary>
/// <remarks>
/// <b>This used to no-op in in-memory mode</b> ("the in-memory provider ignores FK
/// constraints, so deploy E2E tests pass without it"). That stopped being true in per-cluster
/// mesh Phase 1: <c>ConfigPublishCoordinator</c> now derives its expected-ack set from these
/// rows rather than from cluster membership, so with none seeded it seals <i>immediately</i>
/// with an empty set. "Wait for Sealed" then no longer implies "every node has applied", and
/// since <c>DriverHostActor.UpsertNodeDeploymentState</c> 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.
/// </remarks>
/// <param name="clusterId">Cluster id for the seeded rows. Defaults to <c>MAIN</c>.</param>
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();
}
/// <summary>Boots both nodes and waits up to <paramref name="formationTimeout"/> for cluster convergence.</summary>
/// <param name="formationTimeout">Maximum time to wait for cluster formation; defaults to 20 seconds if not provided.</param>
/// <param name="driverFactory">Optional opt-in <see cref="IDriverFactory"/> both nodes register so deployed
/// drivers reach <c>Connected</c>/Healthy in-process. Null (default) leaves the production
/// <see cref="NullDriverFactory"/> default in place — unchanged behaviour for existing tests.</param>
/// <param name="driverProbe">Optional probe that both nodes expose to the admin operations singleton.</param>
/// <param name="extraHocon">Optional HOCON prepended to both nodes' Akka config (tests that need a non-default
/// Akka setting, e.g. a slow DistributedPubSub gossip interval).</param>
/// <param name="requiredTopics">The pub/sub topics whose registry gossip to wait for before reporting the cluster
/// formed (lmxopcua#1108); null (default) waits for every topic the host nodes subscribe to at boot
/// (<see cref="BootTopics"/>). A test that publishes on a topic outside the set is exposed to the #1106 window.</param>
/// <remarks>
/// lmxopcua#1106 / #1108: "formed" includes the host topics' DistributedPubSub registries having gossiped to both
/// nodes (<see cref="WaitForPubSubConvergedAsync"/>) — 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.
/// </remarks>
public static async Task<TwoNodeClusterHarness> StartAsync(
TimeSpan? formationTimeout = null,
IDriverFactory? driverFactory = null,
IDriverProbe? driverProbe = null,
string? extraHocon = null,
IReadOnlyList<PubSubTopic>? requiredTopics = null)
{
var harness = new TwoNodeClusterHarness();
harness._requiredTopics = requiredTopics ?? BootTopics;
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.WaitForPubSubConvergedAsync(formationTimeout ?? TimeSpan.FromSeconds(20), harness._requiredTopics);
return harness;
}
private string? _extraHocon;
/// <summary>
/// A DistributedPubSub topic a host node subscribes to, and how many of the two nodes must hold a subscriber for it
/// before the harness reports the cluster formed (lmxopcua#1108).
/// </summary>
/// <param name="Name">The topic name.</param>
/// <param name="MinNodes">1 when the subscriber is a cluster singleton (it lives on one node), 2 for a per-node subscriber.</param>
/// <param name="AtBoot">True when the subscriber exists as soon as the harness has booted (the default wait set);
/// false when it is only created later (a deploy spawns it, or a test/host adds the bridge), so waiting for it in
/// <c>StartAsync</c> would time out - such a test calls <see cref="WaitForPubSubConvergedAsync"/> itself once the
/// subscriber exists.</param>
public readonly record struct PubSubTopic(string Name, int MinNodes, bool AtBoot = true);
/// <summary>
/// lmxopcua#1108: every topic the host nodes subscribe to (the <c>Subscribe(...)</c> call sites under
/// <c>src/</c>). <see cref="StartAsync"/> waits for the <see cref="PubSubTopic.AtBoot"/> subset by default
/// (measured against the harness hosts: the others have no subscriber until something creates one). A new
/// subscribed topic must be added here or a test publishing on it has the #1106 lost-publish window
/// (<c>PubSubTopicCoverageGuardTests</c> fails when one is missing).
/// <para>
/// The <c>AtBoot: false</c> topics (alarm-commands, opcua-endpoint-state, driver-health,
/// driver-resilience-status, script-logs) have no subscriber until something creates one. A test that spawns
/// such a subscriber and then publishes from the OTHER node must call
/// <see cref="WaitForPubSubConvergedAsync"/> with that topic first. (#1111: no current test does - they
/// publish from the subscriber's own node, which is delivered locally without gossip.)
/// </para>
/// </summary>
public static readonly IReadOnlyList<PubSubTopic> AllHostTopics =
[
new(ZB.MOM.WW.OtOpcUa.Runtime.Drivers.DriverHostActor.DeploymentsTopic, 2),
new(ZB.MOM.WW.OtOpcUa.Runtime.Drivers.DriverHostActor.DeploymentAcksTopic, 1),
new(ZB.MOM.WW.OtOpcUa.Runtime.Drivers.DriverHostActor.DriverControlTopic, 2),
new(ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RedundancyStateTopic, 2),
new(ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmHostActor.AlarmCommandsTopic, 2, AtBoot: false),
new(ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmHostActor.AlertsTopic, 2),
new(ZB.MOM.WW.OtOpcUa.Runtime.Redundancy.OpcUaEndpointStepDownActor.Topic, 2, AtBoot: false),
new(ZB.MOM.WW.OtOpcUa.Commons.Messages.Drivers.DriverHealthChanged.TopicName, 2, AtBoot: false),
new(ZB.MOM.WW.OtOpcUa.Commons.Messages.Drivers.DriverResilienceStatusChanged.TopicName, 2, AtBoot: false),
new(ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.VirtualTagActor.ScriptLogsTopic, 2, AtBoot: false),
];
private IReadOnlyList<PubSubTopic> _requiredTopics = BootTopics;
/// <summary>The topics <see cref="StartAsync"/> waits for by default: those subscribed as soon as the hosts boot.</summary>
public static IReadOnlyList<PubSubTopic> BootTopics { get; } = AllHostTopics.Where(t => t.AtBoot).ToList();
/// <summary>
/// lmxopcua#1106 / #1108: waits until each node's DistributedPubSub registry carries a subscriber from at least
/// <see cref="PubSubTopic.MinNodes"/> nodes for every topic in <paramref name="topics"/> (default
/// <see cref="BootTopics"/>), and both nodes see the same owner set - so a publish from either node reaches
/// every subscriber.
/// </summary>
/// <remarks>
/// 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
/// <c>Publish</c> 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.
/// </remarks>
/// <param name="timeout">The time allowed; the gossip interval plus slack is plenty.</param>
/// <param name="topics">The topics to wait for; null waits for <see cref="BootTopics"/>.</param>
public async Task WaitForPubSubConvergedAsync(TimeSpan timeout, IReadOnlyList<PubSubTopic>? topics = null)
{
topics ??= BootTopics;
var deadline = DateTime.UtcNow + timeout;
while (true)
{
var viewA = ReadDpsRegistry(NodeASystem);
var viewB = ReadDpsRegistry(NodeBSystem);
var pending = topics.Where(t => !Converged(t, viewA, viewB)).ToList();
if (pending.Count == 0) return;
if (DateTime.UtcNow >= deadline)
{
var names = pending.Select(t => $"{t.Name}(>={t.MinNodes} node(s))").ToArray();
throw new TimeoutException(
$"These pub/sub topics did not gossip to both nodes within {timeout}: {string.Join(", ", names)}. "
+ $"A=[{DescribeDpsRegistry(NodeASystem, pending.Select(t => t.Name).ToArray())}] "
+ $"B=[{DescribeDpsRegistry(NodeBSystem, pending.Select(t => t.Name).ToArray())}]");
}
await Task.Delay(50);
}
static bool Converged(
PubSubTopic t,
IReadOnlyList<(string Owner, List<string> Keys)> a,
IReadOnlyList<(string Owner, List<string> Keys)> b)
{
var oa = Owners(a, t.Name);
return oa.Count >= t.MinNodes && oa.SetEquals(Owners(b, t.Name));
}
}
/// <summary>lmxopcua#1106 name kept for callers; equivalent to <see cref="WaitForPubSubConvergedAsync"/> over the required topics.</summary>
/// <param name="timeout">The time allowed.</param>
public Task WaitForDeployTopicsAsync(TimeSpan timeout) => WaitForPubSubConvergedAsync(timeout, _requiredTopics);
private static HashSet<string> Owners(IReadOnlyList<(string Owner, List<string> Keys)> view, string topic) =>
view.Where(x => x.Keys.Any(k => k.EndsWith("/" + topic, StringComparison.Ordinal)))
.Select(x => x.Owner)
.ToHashSet(StringComparer.Ordinal);
/// <summary>
/// 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 <see cref="RestartNodeBAsync"/> to bring it back on
/// the same Akka port.
/// </summary>
/// <remarks>
/// This used to call <c>DisposeAsync</c> alone, on the stated belief that disposal "runs
/// CoordinatedShutdown". It does not — see <see cref="ShutDownAsync"/>. 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.
/// </remarks>
public async Task StopNodeBAsync()
{
if (NodeB is null) return;
await ShutDownAsync(NodeB);
NodeB = null!;
}
/// <summary>
/// Rebuilds node B on the same Akka port + same ConfigDb and waits for the cluster
/// to re-converge to 2 Up members. Use after <see cref="StopNodeBAsync"/> to test rejoin.
/// </summary>
/// <param name="formationTimeout">The maximum time to wait for cluster formation; defaults to 20 seconds.</param>
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 WaitForPubSubConvergedAsync(formationTimeout ?? TimeSpan.FromSeconds(20), _requiredTopics);
}
/// <summary>
/// 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 <c>Cluster.Leave</c> (the transport is dead, so A cannot gossip anything). Node B's
/// failure detector therefore marks A <b>Unreachable</b> (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 <see cref="StopNodeBAsync"/> path (a real
/// <c>Cluster.Leave</c>, 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.
/// </summary>
public async Task HardKillNodeAAsync()
{
if (NodeA is null) return;
var provider = (Akka.Remote.IRemoteActorRefProvider)((ExtendedActorSystem)NodeASystem).Provider;
await provider.Transport.Shutdown();
}
/// <summary>
/// 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 <c>driver</c>-role leader — i.e. the split-brain resolver downed the alone oldest
/// node and B took over. Queries <see cref="NodeBSystem"/> (node A is dead after a hard kill, so its
/// view can't be read). Returns the elapsed time to takeover; throws <see cref="TimeoutException"/> if
/// B never becomes the sole driver-leader within <paramref name="timeout"/> (the failure signature of
/// an INACTIVE resolver — A stays Unreachable and B never fails over).
/// </summary>
/// <param name="timeout">Upper bound; must exceed acceptable-heartbeat-pause (10s) + stable-after (15s).</param>
public async Task<TimeSpan> 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.");
}
/// <summary>
/// Waits for node A's cluster view to reach <paramref name="expectedUpMembers"/> members in
/// <see cref="MemberStatus.Up"/>. Used for asserting shrink-after-stop or grow-after-restart.
/// </summary>
/// <param name="expectedUpMembers">The expected number of Up members in the cluster.</param>
/// <param name="timeout">The maximum time to wait for the expected cluster size.</param>
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}");
}
/// <summary>
/// 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 each host topic (<see cref="DescribeDpsRegistry"/>), 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 <c>DriverHostActor</c> writes that itself, so
/// it does NOT prove the coordinator counted the ack) while the coordinator never sealed lost the ack.
/// <para>
/// After the snapshot it keeps watching the row for <paramref name="lateGrace"/> (default
/// <see cref="LateSealGrace"/>) 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).
/// </para>
/// </summary>
/// <param name="deploymentId">The deployment that did not seal.</param>
/// <param name="lateGrace">How long to keep watching for a late seal; <see langword="null"/> = <see cref="LateSealGrace"/>.</param>
/// <returns>A one-line description for the timeout message.</returns>
public async Task<string> 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;
/// <summary>
/// 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.
/// </summary>
private sealed class NodeEventLog
{
private const int Capacity = 400;
private readonly System.Collections.Concurrent.ConcurrentQueue<string> _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 _)) { }
}
/// <summary>The deploy-relevant lines (or the last few of everything when none match), newest last.</summary>
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<Akka.Event.LogEvent>(e => log.Add($"{e.LogLevel()} [{e.LogSource}] {e.Message}"));
Receive<Akka.Event.AllDeadLetters>(d => log.Add(
$"DEADLETTER {d.Message.GetType().Name} {d.Message} from {d.Sender} to {d.Recipient}"));
}
}
}
/// <summary>How long <see cref="DescribeDeploymentAsync"/> keeps watching for a late seal (lmxopcua#1106).</summary>
public static readonly TimeSpan LateSealGrace = TimeSpan.FromSeconds(60);
private async Task<string> 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() ?? "<missing>"} 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 = $"<db read failed: {ex.GetType().Name}: {ex.Message}>";
}
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, AllHostTopics.Select(t => t.Name).ToArray())}] "
+ $"B dps=[{DescribeDpsRegistry(NodeBSystem, AllHostTopics.Select(t => t.Name).ToArray())}]";
}
/// <summary>
/// lmxopcua#1106: which cluster members THIS node's DistributedPubSub mediator currently knows a subscriber on, per
/// topic — i.e. where a <c>Publish</c> 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.
/// <para>
/// lmxopcua#1108 - why reflection: Akka.Cluster.Tools 1.5.62's public mediator queries cannot answer "which
/// member's bucket do I hold". <c>GetTopics</c>/<c>CurrentTopics</c> returns the union of every bucket's keys with
/// no owner (a topic subscribed on one node looks identical whichever node's bucket supplied it);
/// <c>CountSubscribers</c>/<c>Count</c> are <c>internal</c> and local-only. A public publish-probe can prove a
/// bucket arrived, but only for the probe's own topic, not that the real subscriptions are in it. So this reads
/// the mediator's private <c>_registry</c>: test-only, a best-effort snapshot taken off the mediator's thread.
/// On an Akka upgrade that renames those members <see cref="ReadDpsRegistry"/> throws a
/// <see cref="NotSupportedException"/> naming the Akka version; this method reports it inline.
/// </para>
/// </summary>
/// <param name="system">The node whose mediator to read.</param>
/// <param name="topics">The topics to report.</param>
/// <returns>e.g. <c>deployments@{4053,4054} deployment-acks@{4053}</c> (member ports).</returns>
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 $"<dps registry unreadable: {ex.GetType().Name}: {ex.Message}>";
}
}
/// <summary>
/// Reads one node's DistributedPubSub registry (see <see cref="DescribeDpsRegistry"/>): 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 <see cref="NotSupportedException"/>.
/// </summary>
/// <param name="system">The node whose mediator to read.</param>
/// <returns>(owner port, keys) per registry bucket.</returns>
private static IReadOnlyList<(string Owner, List<string> Keys)> ReadDpsRegistry(ActorSystem system)
{
try
{
return ReadDpsRegistryCore(system);
}
catch (NotSupportedException ex)
{
var version = typeof(Akka.Cluster.Tools.PublishSubscribe.DistributedPubSub).Assembly.GetName().Version;
throw new NotSupportedException(
$"TwoNodeClusterHarness reads DistributedPubSubMediator's private registry by reflection (lmxopcua#1108), "
+ $"which no longer matches Akka.Cluster.Tools {version} (Directory.Packages.props pins 1.5.62): {ex.Message}. "
+ "Update ReadDpsRegistryCore for the new internals, or replace it with a public API if the new Akka "
+ "version offers a per-owner registry query.", ex);
}
}
private static IReadOnlyList<(string Owner, List<string> Keys)> ReadDpsRegistryCore(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<string> 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<string>();
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<WebApplication> 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<string, string?>
{
["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<OtOpcUaConfigDbContext>(opt => opt.UseSqlServer(harness._sqlConnString));
builder.Services.AddDbContext<OtOpcUaConfigDbContext>(opt => opt.UseSqlServer(harness._sqlConnString));
}
else
{
builder.Services.AddDbContextFactory<OtOpcUaConfigDbContext>(opt => opt.UseInMemoryDatabase(harness.SharedDbName));
builder.Services.AddDbContext<OtOpcUaConfigDbContext>(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<IDriverFactory>(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<Microsoft.Extensions.Options.IOptions<AkkaClusterOptions>>().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<ILdapAuthService, StubLdapAuthService>();
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<OtOpcUaConfigDbContext>()
.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<OtOpcUaConfigDbContext>()
.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)}");
}
/// <summary>
/// Stops a node's hosted services, then disposes it.
/// </summary>
/// <remarks>
/// <para>
/// <b><see cref="IHost.StopAsync"/> is not optional, and disposal is not a substitute for
/// it.</b> <c>Host.DisposeAsync</c> only disposes the service provider; it never invokes
/// <see cref="IHostedService.StopAsync"/>. Akka.Hosting terminates the
/// <see cref="ActorSystem"/> 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.
/// </para>
/// <para>
/// Every test here starts two of them, so the cost compounded across the suite: a single
/// test host was measured at <b>~30 GB RSS</b>, which starved timeout-based assertions
/// into false failures that looked exactly like real regressions.
/// </para>
/// </remarks>
/// <param name="node">The node to stop and dispose.</param>
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;
}
/// <summary>Asynchronously disposes both nodes and cleans up the SQL database if used.</summary>
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 */ }
}
}
/// <summary>Captures the env-var driven harness mode at construction time.</summary>
public sealed record HarnessMode(bool UseSqlServer, bool UseRealLdap)
{
/// <summary>Creates a HarnessMode from environment variable settings.</summary>
/// <returns>A HarnessMode configured from OTOPCUA_HARNESS_USE_SQL and OTOPCUA_HARNESS_USE_LDAP environment variables.</returns>
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
{
/// <summary>Asynchronously authenticates a user with the stub LDAP service.</summary>
/// <param name="username">The username to authenticate.</param>
/// <param name="password">The password to authenticate against.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>A task that returns the LDAP authentication result.</returns>
public Task<LdapAuthResult> 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));
}
}