Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorOffThreadAckTests.cs
T
Joseph Doherty ea976ffa81 fix(perf): #996 Wave 4 — blob-free health probes, narrow data-connections load, off-thread coordinator acks + AdminOps audit, events page cap, capped reservations page
C-6: DeploymentQueries projects Deployment without ArtifactBlob (DbHealthProbe, readiness, ClusterOverview, DriverHost boot).
C-11/A-5: DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync + one-parse-per-artifact LoadAppliedAsync + capped pickers.
H-6: ConfigPublishCoordinator persists acks off the actor thread (AckPersisted); deadline backlog kicked in parallel.
H-3: Restart/Reconnect reply = dispatch; ConfigEdit audit written off-mailbox, failure logged not surfaced.
U-6: ServerHistorian:MaxEventsPerRead (default 10000) pages HistoryReadEvents; advertised as MaxReturnEventValues.
A-8: /reservations active-only by default, projected, capped at 200.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 10:58:50 -05:00

108 lines
5.1 KiB
C#

using System.Diagnostics;
using Akka.Actor;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
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.Coordinators;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
/// <summary>
/// lmxopcua#996 (review H-6): the per-node ack write used to be a blocking <c>SaveChanges</c> on the coordinator's
/// thread, so with a slow or unreachable ConfigDb N acks cost N x the connect timeout of unresponsive mailbox. The
/// write now runs on a pool thread and reports back as a message.
/// </summary>
public sealed class ConfigPublishCoordinatorOffThreadAckTests : ControlPlaneActorTestBase
{
private static readonly RevisionHash Revision = RevisionHash.Parse(new string('e', 64));
private static readonly TimeSpan NoTimeout = TimeSpan.FromMinutes(5);
private static readonly TimeSpan PerCall = TimeSpan.FromMilliseconds(500);
private const int NodeCount = 6;
/// <summary>
/// Six acks arrive while every ConfigDb call takes 500 ms (a slow link or a connect timeout). The mailbox stays live
/// (an Identify round-trip answers in well under the 3 s the serialised writes would take), and every ack still lands
/// and seals the deployment (positive control: the writes DID happen, off-thread).
/// </summary>
[Fact]
public async Task Slow_ConfigDb_acks_do_not_block_the_coordinator_mailbox_and_still_seal()
{
var ct = TestContext.Current.CancellationToken;
var dbName = Guid.NewGuid().ToString("N");
var direct = NewInMemoryDbFactory(dbName);
var slow = new SlowDbFactory(NewInMemoryDbFactory(dbName));
var nodes = Enumerable.Range(1, NodeCount).Select(i => $"site-a-{i}:4053").ToArray();
Seed(direct, nodes, out var deploymentId);
var coordinator = Sys.ActorOf(ConfigPublishCoordinator.Props(
slow, NoTimeout, loadRetryMin: TimeSpan.FromMilliseconds(50), loadRetryMax: TimeSpan.FromMilliseconds(200)));
coordinator.Tell(new DispatchDeployment(deploymentId, Revision, CorrelationId.NewId()));
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(DeploymentStatus.AwaitingApplyAcks);
}, duration: PresenceBudget, cancellationToken: ct);
slow.Delay = PerCall;
foreach (var node in nodes)
coordinator.Tell(new ApplyAck(deploymentId, NodeId.Parse(node), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
var sw = Stopwatch.StartNew();
var identity = await coordinator.Ask<ActorIdentity>(new Identify("probe"), TimeSpan.FromSeconds(10), ct);
sw.Stop();
identity.Subject.ShouldBe(coordinator);
// Serialised on the actor thread this is >= 6 x 500 ms = 3 s; off-thread it is one scheduling hop.
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromMilliseconds(1500),
"the coordinator mailbox must not wait on the ConfigDb writes of the acks");
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(DeploymentStatus.Sealed);
db.NodeDeploymentStates.Count(s => s.Status == NodeDeploymentStatus.Applied).ShouldBe(NodeCount);
}, duration: PresenceBudget, cancellationToken: ct);
}
private static void Seed(IDbContextFactory<OtOpcUaConfigDbContext> factory, string[] nodeIds, out DeploymentId id)
{
id = DeploymentId.NewId();
using var db = factory.CreateDbContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = "SITE-A", Name = "Site A", Enterprise = "zb", Site = "site-a",
NodeCount = (byte)nodeIds.Length, RedundancyMode = RedundancyMode.None, CreatedBy = "test",
});
foreach (var nodeId in nodeIds)
db.ClusterNodes.Add(new ClusterNode
{
NodeId = nodeId, ClusterId = "SITE-A", Host = nodeId.Split(':')[0],
ApplicationUri = $"urn:OtOpcUa:{nodeId}", Enabled = true, CreatedBy = "test",
});
db.Deployments.Add(new Deployment
{
DeploymentId = id.Value, RevisionHash = Revision.Value, Status = DeploymentStatus.Dispatching, CreatedBy = "test",
});
db.SaveChanges();
}
/// <summary>A factory whose synchronous context creation takes <see cref="Delay"/> (a slow connect).</summary>
private sealed class SlowDbFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
public TimeSpan Delay { get => _delay; set => _delay = value; }
private TimeSpan _delay;
public OtOpcUaConfigDbContext CreateDbContext()
{
var delay = Delay;
if (delay > TimeSpan.Zero) Thread.Sleep(delay);
return inner.CreateDbContext();
}
}
}