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;
///
/// 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.
///
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 factory)
{
var router = CreateTestProbe("router");
var coordinator = CreateTestProbe("coord");
var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Enumerable.Empty(), meshRouter: router.Ref,
driverAuditRetryDelay: FastRetry));
return (actor, router);
}
///
/// 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.
///
[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(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);
}
/// The retry is bounded: a ConfigDb that never answers costs attempts, then the record is logged and dropped.
[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(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);
}
/// A write the database REJECTS (a constraint / truncation) fails identically every time: not retried.
[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(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 inner, int failures, Func error)
: IDbContextFactory
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext();
public Task CreateDbContextAsync(CancellationToken cancellationToken = default)
{
var call = Interlocked.Increment(ref _calls);
if (call <= failures) throw error();
return Task.FromResult(inner.CreateDbContext());
}
}
/// The audit write throws: the command still went out and the reply says so (success).
[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(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
if (restart) command.Message.ShouldBeOfType();
else command.Message.ShouldBeOfType();
if (restart)
{
var reply = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
reply.Ok.ShouldBeTrue();
reply.CorrelationId.ShouldBe(correlation);
}
else
{
var reply = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
reply.Ok.ShouldBeTrue();
reply.CorrelationId.ShouldBe(correlation);
}
}
///
/// 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).
///
[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(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(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(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
private sealed class ThrowingAsyncFactory(IDbContextFactory inner) : IDbContextFactory
{
public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext();
public Task CreateDbContextAsync(CancellationToken cancellationToken = default) =>
throw new InvalidOperationException("ConfigDb unreachable (simulated)");
}
private sealed class GatedAsyncFactory(IDbContextFactory inner) : IDbContextFactory
{
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 CreateDbContextAsync(CancellationToken cancellationToken = default)
{
Entered.Set();
if (_gate is { } gate) await gate.Task.WaitAsync(cancellationToken);
return inner.CreateDbContext();
}
}
}