Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorDriverOperationTests.cs
T
Joseph Doherty 69f475392c fix(controlplane): #1051 coordinator dispatch seed + terminal writes off the actor thread; driver-operation audit write retried
H-6 remainder: ConfigPublishCoordinator runs the dispatch guard/seed (incl. the #977 superseded close) and the
Sealed/PartiallyFailed/TimedOut writes through RunDbWork - a pool-thread task whose outcome is applied on the actor
thread while a Busy behaviour stashes everything else. A failed write is rethrown when it reports back (same
restart-and-recover contract as before); recovery runs the same work inline (failure = failed load).
H-3 remainder: a transient Restart/Reconnect ConfigEdit audit failure is retried (1 s doubling, 30 s cap, 6 attempts);
a ConfigDb rejection (poison allowlist) is not.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 15:07:25 -05:00

189 lines
9.6 KiB
C#

using Akka.Actor;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
/// <summary>
/// lmxopcua#996 (review H-3): Restart/Reconnect report the DISPATCH. A ConfigDb failure while writing the audit row
/// must not turn an already-dispatched command into a "failed" reply (the operator retries ⇒ a second restart), and the
/// audit write must not suspend the admin mailbox.
/// </summary>
public sealed class AdminOperationsActorDriverOperationTests : ControlPlaneActorTestBase
{
private static readonly TimeSpan AckBudget = TimeSpan.FromSeconds(1);
private static readonly TimeSpan FastRetry = TimeSpan.FromMilliseconds(30);
private (IActorRef Actor, Akka.TestKit.TestProbe Router) Create(IDbContextFactory<OtOpcUaConfigDbContext> factory)
{
var router = CreateTestProbe("router");
var coordinator = CreateTestProbe("coord");
var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(), meshRouter: router.Ref,
driverAuditRetryDelay: FastRetry));
return (actor, router);
}
/// <summary>
/// lmxopcua#1051 (H-3 remainder): a TRANSIENT audit-write failure (ConfigDb briefly unreachable) is retried on a
/// backoff, so the ConfigEdit row is still recorded once the database answers — it used to be logged and lost.
/// </summary>
[Fact]
public void Transient_audit_failure_is_retried_until_the_row_is_recorded()
{
var inner = NewInMemoryDbFactory();
var flaky = new FlakyAsyncFactory(inner, failures: 3, () => new InvalidOperationException("ConfigDb unreachable (simulated)"));
var (actor, _) = Create(flaky);
actor.Tell(new RestartDriver("MAIN", "drv-9", "joe", Guid.NewGuid()));
ExpectMsg<RestartDriverResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
AwaitAssert(() =>
{
flaky.Calls.ShouldBe(4);
using var db = inner.CreateDbContext();
db.ConfigEdits.Single().EditedBy.ShouldBe("joe");
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>The retry is bounded: a ConfigDb that never answers costs <see cref="AdminOperationsActor.MaxDriverAuditAttempts"/> attempts, then the record is logged and dropped.</summary>
[Fact]
public void Audit_retry_gives_up_after_the_attempt_cap()
{
var inner = NewInMemoryDbFactory();
var flaky = new FlakyAsyncFactory(inner, failures: int.MaxValue, () => new InvalidOperationException("ConfigDb unreachable (simulated)"));
var (actor, _) = Create(flaky);
actor.Tell(new ReconnectDriver("MAIN", "drv-9", "joe", Guid.NewGuid()));
ExpectMsg<ReconnectDriverResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
AwaitAssert(() => flaky.Calls.ShouldBe(AdminOperationsActor.MaxDriverAuditAttempts),
duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
// Absence after the cap, with a positive control: well past several backoff periods, still exactly the cap.
ExpectNoMsg(TimeSpan.FromMilliseconds(30 * 64), TestContext.Current.CancellationToken);
flaky.Calls.ShouldBe(AdminOperationsActor.MaxDriverAuditAttempts);
}
/// <summary>A write the database REJECTS (a constraint / truncation) fails identically every time: not retried.</summary>
[Fact]
public void Rejected_audit_write_is_not_retried()
{
var inner = NewInMemoryDbFactory();
var flaky = new FlakyAsyncFactory(inner, failures: int.MaxValue,
() => new DbUpdateException("rejected", SqlExceptionFactory.Create(8152, "String or binary data would be truncated.")));
var (actor, _) = Create(flaky);
actor.Tell(new RestartDriver("MAIN", "drv-9", "joe", Guid.NewGuid()));
ExpectMsg<RestartDriverResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
AwaitAssert(() => flaky.Calls.ShouldBe(1), duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
ExpectNoMsg(TimeSpan.FromMilliseconds(30 * 16), TestContext.Current.CancellationToken);
flaky.Calls.ShouldBe(1);
}
private sealed class FlakyAsyncFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner, int failures, Func<Exception> error)
: IDbContextFactory<OtOpcUaConfigDbContext>
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext();
public Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default)
{
var call = Interlocked.Increment(ref _calls);
if (call <= failures) throw error();
return Task.FromResult(inner.CreateDbContext());
}
}
/// <summary>The audit write throws: the command still went out and the reply says so (success).</summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Audit_failure_does_not_turn_a_dispatched_command_into_a_failure(bool restart)
{
var (actor, router) = Create(new ThrowingAsyncFactory(NewInMemoryDbFactory()));
var correlation = Guid.NewGuid();
if (restart) actor.Tell(new RestartDriver("MAIN", "drv-1", "joe", correlation));
else actor.Tell(new ReconnectDriver("MAIN", "drv-1", "joe", correlation));
var command = router.ExpectMsg<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
if (restart) command.Message.ShouldBeOfType<RestartDriver>();
else command.Message.ShouldBeOfType<ReconnectDriver>();
if (restart)
{
var reply = ExpectMsg<RestartDriverResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
reply.Ok.ShouldBeTrue();
reply.CorrelationId.ShouldBe(correlation);
}
else
{
var reply = ExpectMsg<ReconnectDriverResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
reply.Ok.ShouldBeTrue();
reply.CorrelationId.ShouldBe(correlation);
}
}
/// <summary>
/// While the audit write is parked on a gated DB, the reply is already out and an alarm ack is answered; releasing the
/// gate writes the row (positive control: the audit is not skipped, only moved off the mailbox).
/// </summary>
[Fact]
public void Audit_write_does_not_hold_the_mailbox_and_is_still_recorded()
{
var inner = NewInMemoryDbFactory();
var gated = new GatedAsyncFactory(inner);
var (actor, router) = Create(gated);
gated.Hold();
actor.Tell(new RestartDriver("MAIN", "drv-2", "joe", Guid.NewGuid()));
ExpectMsg<RestartDriverResult>(AckBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
gated.Entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue("the audit write must be parked");
// The mailbox is free: a second operation is dispatched and answered while the first audit is still parked.
actor.Tell(new ReconnectDriver("MAIN", "drv-3", "kim", Guid.NewGuid()));
ExpectMsg<ReconnectDriverResult>(AckBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
using (var db = inner.CreateDbContext()) db.ConfigEdits.ShouldBeEmpty();
gated.Release();
AwaitAssert(() =>
{
using var db = inner.CreateDbContext();
db.ConfigEdits.Count().ShouldBe(2);
db.ConfigEdits.Select(e => e.EditedBy).OrderBy(x => x).ToList().ShouldBe(["joe", "kim"]);
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
router.ExpectMsg<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
private sealed class ThrowingAsyncFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext();
public Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default) =>
throw new InvalidOperationException("ConfigDb unreachable (simulated)");
}
private sealed class GatedAsyncFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
private volatile TaskCompletionSource? _gate;
public ManualResetEventSlim Entered { get; } = new();
public void Hold() => _gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
public void Release() => _gate?.TrySetResult();
public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext();
public async Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default)
{
Entered.Set();
if (_gate is { } gate) await gate.Task.WaitAsync(cancellationToken);
return inner.CreateDbContext();
}
}
}