using System.Text.Json;
using Akka.Actor;
using Akka.TestKit;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
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.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
///
/// A1 (plan §5.1) reusable rig for native "standing alarms delivered" signal tests: a real
/// + real around a
/// , with the OPC UA publish actor replaced by a probe so the exact order of
/// and is
/// observable. The driver agent's per-driver tests (ii, iii, vi–ix) inherit this and swap the fake for each real
/// driver's shape.
///
public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase
{
/// The driver instance id the rig deploys.
protected const string DriverId = "drv-sig";
private static readonly NodeId RigNode = NodeId.Parse("a1-signal-rig");
private static readonly RevisionHash Rev = RevisionHash.Parse(new string('c', 64));
private IDbContextFactory? _rigDb;
private TestProbe? _rigCoordinator;
private string? _rigDriverType;
private int _redeploys;
/// The RawPath of alarm tag under the rig's folder/driver/device.
/// The tag name.
/// The RawPath (= the driver ConditionId = the condition NodeId).
protected static string RawPathOf(string tag) => $"Plant/Drv/dev1/{tag}";
/// One started rig.
/// The driver host.
/// The publish-actor probe (rebuild already drained).
/// The fake driver the host spawned.
/// The hub the F5 diagnostic is raised on.
protected sealed record Rig(IActorRef Host, TestProbe Publish, FakeSignallingAlarmDriver Driver, ConditionStateHub Hub);
/// Deploys as native alarm tags of one enabled driver of
/// , waits for the apply, the driver's connection and its alarm subscription.
/// The driver type (decides the backstop / F5 timeout).
/// The alarm tag names.
/// Adjusts the signal options (timeouts).
/// A pre-built fake (e.g. with a subscribe delay), or null for a default one.
/// The rig.
protected Rig StartRig(string driverType, IReadOnlyList alarmTags,
Func? configure = null, FakeSignallingAlarmDriver? driver = null)
{
driver ??= new FakeSignallingAlarmDriver(DriverId, driverType);
var fake = driver;
var (host, publish, hub) = StartRig(driver, driverType, alarmTags, configure, () => fake.Subscribed);
return new Rig(host, publish, driver, hub);
}
///
/// The same rig over ANY (a REAL driver over a fake device): deploys
/// on it and waits for the apply, then for (e.g. the real
/// driver's alarm subscription) when given.
///
/// The driver the host spawns (its must be ).
/// The driver type.
/// The alarm tag names (RawPaths per ).
/// Adjusts the signal options (timeouts).
/// Optional readiness predicate awaited after the apply.
/// The host, the publish probe and the hub.
protected (IActorRef Host, TestProbe Publish, ConditionStateHub Hub) StartRig(IDriver driver, string driverType,
IReadOnlyList alarmTags, Func? configure = null,
Func? ready = null)
{
var db = NewInMemoryDbFactory();
var deploymentId = Seed(db, driverType, alarmTags, Rev);
_rigDb = db;
_rigDriverType = driverType;
var hub = new ConditionStateHub();
var options = new ConditionSignalOptions { Hub = hub };
options = configure?.Invoke(options) ?? options;
var coordinator = _rigCoordinator = CreateTestProbe();
var publish = this.CreateCleanOutcomePublishProbe();
var host = Sys.ActorOf(DriverHostActor.Props(
db, RigNode, coordinator.Ref,
driverFactory: new SingleDriverFactory(driver),
localRoles: new HashSet { "driver" },
dependencyMux: CreateTestProbe().Ref,
opcUaPublishActor: publish.Ref,
virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref,
conditionSignals: options));
host.Tell(new DispatchDeployment(deploymentId, Rev, CorrelationId.NewId()));
coordinator.FishForMessage(_ => true, TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
if (ready is not null) AwaitCondition(ready, TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
return (host, publish, hub);
}
/// Re-deploys the last started rig with (a new revision) and waits for the apply.
/// The rig.
/// The alarm tag names the new revision carries.
protected void Redeploy(Rig rig, IReadOnlyList alarmTags)
{
var rev = RevisionHash.Parse(new string((char)('d' + _redeploys++ % 3), 64));
var deploymentId = Seed(_rigDb!, _rigDriverType!, alarmTags, rev);
rig.Host.Tell(new DispatchDeployment(deploymentId, rev, CorrelationId.NewId()));
_rigCoordinator!.FishForMessage(a => a.DeploymentId == deploymentId, TimeSpan.FromSeconds(10),
cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
}
/// The rig's current driver child (the DriverInstanceActor the host spawned).
/// The rig.
/// Its actor ref.
protected IActorRef ChildOf(Rig rig) =>
Sys.ActorSelection(rig.Host.Path + "/drv-*").ResolveOne(TimeSpan.FromSeconds(5)).GetAwaiter().GetResult();
/// Negative control: for , the probe receives no
/// that marks known (other traffic — quality annotations,
/// withdrawals — is ignored).
/// The probe.
/// How long to watch.
protected static void AssertNoMark(TestProbe publish, TimeSpan duration)
{
var deadline = DateTime.UtcNow + duration;
while (DateTime.UtcNow < deadline)
{
var m = publish.ReceiveOne(deadline - DateTime.UtcNow);
if (m is OpcUaPublishActor.MarkConditionsKnown { Known: true } mark)
throw new ShouldAssertException($"unexpected MarkConditionsKnown({string.Join(",", mark.ConditionIds)})");
}
}
/// The publish-actor messages that are alarm-state updates or KNOWN marks (withdrawals skipped), in arrival order, until
/// matches (inclusive).
/// The probe.
/// Stop condition.
/// Overall wait.
/// The ordered messages.
protected static List