Merge #1106: deploy-seal timeouts were a lost dispatch — harness declared the cluster formed before DistributedPubSub registries converged; harness now waits for deployments/deployment-acks registries, timeouts dump lost-vs-slow diagnostics, deterministic slow-gossip regression test
v2-ci / unit-tests (push) Has started running

This commit is contained in:
Joseph Doherty
2026-12-04 20:49:42 -05:00
3 changed files with 306 additions and 30 deletions
@@ -40,7 +40,7 @@ public sealed class DeployHappyPathTests
await using var db = await CreateDbAsync(harness); await using var db = await CreateDbAsync(harness);
var d = await db.Deployments.AsNoTracking().FirstOrDefaultAsync(d => d.DeploymentId == deploymentId, Ct); var d = await db.Deployments.AsNoTracking().FirstOrDefaultAsync(d => d.DeploymentId == deploymentId, Ct);
return d?.Status == DeploymentStatus.Sealed; return d?.Status == DeploymentStatus.Sealed;
}, TwoNodeClusterHarness.DeploySealTimeout); }, TwoNodeClusterHarness.DeploySealTimeout, () => harness.DescribeDeploymentAsync(deploymentId));
await using var db = await CreateDbAsync(harness); await using var db = await CreateDbAsync(harness);
var deployment = await db.Deployments.AsNoTracking() var deployment = await db.Deployments.AsNoTracking()
@@ -55,6 +55,38 @@ public sealed class DeployHappyPathTests
nodeStates.ShouldAllBe(s => s.Status == NodeDeploymentStatus.Applied); nodeStates.ShouldAllBe(s => s.Status == NodeDeploymentStatus.Applied);
} }
/// <summary>
/// lmxopcua#1106 regression: a deploy started the moment the harness reports the cluster formed must reach BOTH
/// nodes. With DistributedPubSub's registry gossip slowed to 10 s, node A's mediator does not learn node B's
/// <c>deployments</c> subscription for ~10 s after B is Up; before the harness waited for the deploy topics to
/// gossip (<see cref="TwoNodeClusterHarness.WaitForDeployTopicsAsync"/>) the dispatch went to node A only and the
/// deployment sat AwaitingApplyAcks until the 120 s apply deadline — deterministically here, and 1 in ~10–20 runs
/// under heavy load at the default 1 s interval (the #843/#1106 seal-timeout flake).
/// </summary>
[Fact]
public async Task Deploy_right_after_formation_reaches_both_nodes_even_with_slow_pubsub_gossip()
{
await using var harness = await TwoNodeClusterHarness.StartAsync(
formationTimeout: TimeSpan.FromSeconds(45),
extraHocon: "akka.cluster.pub-sub.gossip-interval = 10s");
await harness.SeedDefaultClusterAsync();
await using var scope = harness.NodeA.Services.CreateAsyncScope();
var client = scope.ServiceProvider.GetRequiredService<IAdminOperationsClient>();
var result = await client.StartDeploymentAsync(createdBy: "alice@test", Ct);
result.Outcome.ShouldBe(StartDeploymentOutcome.Accepted);
var deploymentId = result.DeploymentId!.Value.Value;
// Both nodes apply in milliseconds once dispatched; a lost dispatch never seals before the 120 s apply deadline,
// so the ordinary seal wait separates the two outcomes. Diagnose without the late-seal grace.
await WaitForAsync(async () =>
{
await using var db = await CreateDbAsync(harness);
var d = await db.Deployments.AsNoTracking().FirstOrDefaultAsync(d => d.DeploymentId == deploymentId, Ct);
return d?.Status == DeploymentStatus.Sealed;
}, TwoNodeClusterHarness.DeploySealTimeout, () => harness.DescribeDeploymentAsync(deploymentId, TimeSpan.Zero));
}
/// <summary>Verifies that replaying dispatch to same revision is idempotent and a no-op.</summary> /// <summary>Verifies that replaying dispatch to same revision is idempotent and a no-op.</summary>
[Fact] [Fact]
public async Task Replaying_dispatch_to_same_revision_is_idempotent_no_op() public async Task Replaying_dispatch_to_same_revision_is_idempotent_no_op()
@@ -74,7 +106,7 @@ public sealed class DeployHappyPathTests
var d = await db.Deployments.AsNoTracking() var d = await db.Deployments.AsNoTracking()
.FirstOrDefaultAsync(d => d.DeploymentId == first.DeploymentId!.Value.Value, Ct); .FirstOrDefaultAsync(d => d.DeploymentId == first.DeploymentId!.Value.Value, Ct);
return d?.Status == DeploymentStatus.Sealed; return d?.Status == DeploymentStatus.Sealed;
}, TwoNodeClusterHarness.DeploySealTimeout); }, TwoNodeClusterHarness.DeploySealTimeout, () => harness.DescribeDeploymentAsync(first.DeploymentId!.Value.Value));
// Same DB state → same revision hash → AdminOperations short-circuits with NoChanges, // Same DB state → same revision hash → AdminOperations short-circuits with NoChanges,
// OR (if it accepts) the second dispatch is idempotent (DriverHostActor recognises // OR (if it accepts) the second dispatch is idempotent (DriverHostActor recognises
@@ -90,7 +122,7 @@ public sealed class DeployHappyPathTests
var d = await db.Deployments.AsNoTracking() var d = await db.Deployments.AsNoTracking()
.FirstOrDefaultAsync(d => d.DeploymentId == second.DeploymentId!.Value.Value, Ct); .FirstOrDefaultAsync(d => d.DeploymentId == second.DeploymentId!.Value.Value, Ct);
return d?.Status == DeploymentStatus.Sealed; return d?.Status == DeploymentStatus.Sealed;
}, TwoNodeClusterHarness.DeploySealTimeout); }, TwoNodeClusterHarness.DeploySealTimeout, () => harness.DescribeDeploymentAsync(second.DeploymentId!.Value.Value));
second.RevisionHash!.Value.Value.ShouldBe(first.RevisionHash!.Value.Value); second.RevisionHash!.Value.Value.ShouldBe(first.RevisionHash!.Value.Value);
} }
@@ -106,7 +138,7 @@ public sealed class DeployHappyPathTests
return await factory.CreateDbContextAsync(); return await factory.CreateDbContextAsync();
} }
private static async Task WaitForAsync(Func<Task<bool>> condition, TimeSpan timeout) private static async Task WaitForAsync(Func<Task<bool>> condition, TimeSpan timeout, Func<Task<string>> diagnose)
{ {
var deadline = DateTime.UtcNow + timeout; var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline) while (DateTime.UtcNow < deadline)
@@ -114,6 +146,7 @@ public sealed class DeployHappyPathTests
if (await condition()) return; if (await condition()) return;
await Task.Delay(200); await Task.Delay(200);
} }
throw new TimeoutException($"Condition not met within {timeout}"); // lmxopcua#1106: say where the deploy stood (rows, cluster views, DPS subscriber counts), not just that it timed out.
throw new TimeoutException($"Condition not met within {timeout}; state at timeout: {await diagnose()}");
} }
} }
@@ -85,7 +85,7 @@ public sealed class EquipmentNamespaceMaterializationTests
return true; return true;
} }
return false; return false;
}, TwoNodeClusterHarness.DeploySealTimeout, () => DescribeDeploymentAsync(harness, deploymentId)); }, TwoNodeClusterHarness.DeploySealTimeout, () => harness.DescribeDeploymentAsync(deploymentId));
var composition = DeploymentArtifact.ParseComposition(artifact); var composition = DeploymentArtifact.ParseComposition(artifact);
@@ -182,7 +182,7 @@ public sealed class EquipmentNamespaceMaterializationTests
return true; return true;
} }
return false; return false;
}, TwoNodeClusterHarness.DeploySealTimeout, () => DescribeDeploymentAsync(harness, deploymentId)); }, TwoNodeClusterHarness.DeploySealTimeout, () => harness.DescribeDeploymentAsync(deploymentId));
await using (var db = await CreateDbAsync(harness)) await using (var db = await CreateDbAsync(harness))
{ {
@@ -273,26 +273,4 @@ public sealed class EquipmentNamespaceMaterializationTests
throw new TimeoutException($"Condition not met within {timeout}" throw new TimeoutException($"Condition not met within {timeout}"
+ (diagnose is null ? "" : $"; state at timeout: {await diagnose()}")); + (diagnose is null ? "" : $"; state at timeout: {await diagnose()}"));
} }
/// <summary>
/// lmxopcua#843: the seal wait used to time out with a bare "Condition not met within 45s" (seen once at load
/// average 140–280, 48 s against a normal 3 s). Report where the deploy stood — the deployment row, each node's
/// per-node state, and both nodes' cluster views — so the next failure says whether it was a slow apply, a node
/// that never received the dispatch (no ack, still Applying), or a failed apply.
/// </summary>
private static async Task<string> DescribeDeploymentAsync(TwoNodeClusterHarness harness, Guid deploymentId)
{
await using var db = await CreateDbAsync(harness);
var d = await db.Deployments.AsNoTracking().FirstOrDefaultAsync(x => x.DeploymentId == deploymentId);
var nodes = await db.NodeDeploymentStates.AsNoTracking()
.Where(s => s.DeploymentId == deploymentId).ToListAsync();
static string View(Akka.Actor.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 $"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 {harness.NodeANodeId}, {harness.NodeBNodeId}); "
+ $"A view=[{View(harness.NodeASystem)}] B view=[{View(harness.NodeBSystem)}]";
}
} }
@@ -192,14 +192,24 @@ public sealed class TwoNodeClusterHarness : IAsyncDisposable
/// drivers reach <c>Connected</c>/Healthy in-process. Null (default) leaves the production /// 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> /// <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="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>
/// <remarks>
/// lmxopcua#1106: "formed" includes the deploy topics' DistributedPubSub registries having gossiped to both
/// nodes (<see cref="WaitForDeployTopicsAsync"/>) — 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( public static async Task<TwoNodeClusterHarness> StartAsync(
TimeSpan? formationTimeout = null, TimeSpan? formationTimeout = null,
IDriverFactory? driverFactory = null, IDriverFactory? driverFactory = null,
IDriverProbe? driverProbe = null) IDriverProbe? driverProbe = null,
string? extraHocon = null)
{ {
var harness = new TwoNodeClusterHarness(); var harness = new TwoNodeClusterHarness();
harness._driverFactory = driverFactory; harness._driverFactory = driverFactory;
harness._driverProbe = driverProbe; harness._driverProbe = driverProbe;
harness._extraHocon = extraHocon;
harness.NodeAAkkaPort = AllocateFreePort(); harness.NodeAAkkaPort = AllocateFreePort();
harness.NodeBAkkaPort = AllocateFreePort(); harness.NodeBAkkaPort = AllocateFreePort();
@@ -225,16 +235,68 @@ public sealed class TwoNodeClusterHarness : IAsyncDisposable
// Node A boots first as the seed. // Node A boots first as the seed.
harness.NodeA = await BuildNodeAsync(harness, NodeRole.Seed); harness.NodeA = await BuildNodeAsync(harness, NodeRole.Seed);
harness._eventLogA = NodeEventLog.Attach(harness.NodeASystem);
harness.NodeB = await BuildNodeAsync(harness, NodeRole.Joiner); harness.NodeB = await BuildNodeAsync(harness, NodeRole.Joiner);
harness._eventLogB = NodeEventLog.Attach(harness.NodeBSystem);
await WaitForClusterFormationAsync( await WaitForClusterFormationAsync(
harness.NodeASystem, harness.NodeASystem,
harness.NodeBSystem, harness.NodeBSystem,
formationTimeout ?? TimeSpan.FromSeconds(20)); formationTimeout ?? TimeSpan.FromSeconds(20));
await harness.WaitForDeployTopicsAsync(formationTimeout ?? TimeSpan.FromSeconds(20));
return harness; return harness;
} }
private string? _extraHocon;
/// <summary>
/// lmxopcua#1106: waits until each node's DistributedPubSub registry carries BOTH nodes' <c>deployments</c>
/// subscriptions (the dispatch reaches every driver host, whichever node hosts the coordinator) and the same,
/// non-empty <c>deployment-acks</c> subscriber set (every node's ack reaches the coordinator).
/// </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>
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<string> Keys)> view)
{
var deployments = Owners(view, "deployments");
return deployments.Contains(a) && deployments.Contains(b) && Owners(view, "deployment-acks").Count > 0;
}
}
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> /// <summary>
/// Gracefully shuts node B down, so CoordinatedShutdown runs and the node performs a /// 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. /// Cluster.Leave; node A sees the member transition to Removed within a couple of seconds.
@@ -263,11 +325,13 @@ public sealed class TwoNodeClusterHarness : IAsyncDisposable
public async Task RestartNodeBAsync(TimeSpan? formationTimeout = null) public async Task RestartNodeBAsync(TimeSpan? formationTimeout = null)
{ {
NodeB = await BuildNodeAsync(this, NodeRole.Joiner); NodeB = await BuildNodeAsync(this, NodeRole.Joiner);
_eventLogB = NodeEventLog.Attach(NodeBSystem);
await WaitForClusterFormationAsync( await WaitForClusterFormationAsync(
NodeASystem, NodeASystem,
NodeBSystem, NodeBSystem,
formationTimeout ?? TimeSpan.FromSeconds(20)); formationTimeout ?? TimeSpan.FromSeconds(20));
await WaitForDeployTopicsAsync(formationTimeout ?? TimeSpan.FromSeconds(20));
} }
/// <summary> /// <summary>
@@ -360,6 +424,204 @@ public sealed class TwoNodeClusterHarness : IAsyncDisposable
$"Cluster did not converge to {expectedUpMembers} Up members within {timeout}. Actual={actual}"); $"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 the two deploy topics (<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, "deployments", "deployment-acks")}] "
+ $"B dps=[{DescribeDpsRegistry(NodeBSystem, "deployments", "deployment-acks")}]";
}
/// <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. Akka exposes no public per-topic, cluster-wide view (<c>CountSubscribers</c> counts only this
/// node's LOCAL subscribers), so this reads the mediator's private <c>_registry</c> by reflection: test-only, a
/// best-effort snapshot taken off the mediator's thread, and it reports a failure instead of throwing.
/// </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)
{
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 enum NodeRole { Seed, Joiner }
private static async Task<WebApplication> BuildNodeAsync(TwoNodeClusterHarness harness, NodeRole role) private static async Task<WebApplication> BuildNodeAsync(TwoNodeClusterHarness harness, NodeRole role)
@@ -452,6 +714,9 @@ public sealed class TwoNodeClusterHarness : IAsyncDisposable
// harness's whole value is that it is wired the way a real node is. // harness's whole value is that it is wired the way a real node is.
ab.WithOtOpcUaClusterRedundancySingleton( ab.WithOtOpcUaClusterRedundancySingleton(
sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<AkkaClusterOptions>>().Value); 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); builder.Services.AddOtOpcUaAuth(builder.Configuration);