using System.Diagnostics;
using Akka.Actor;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Serilog;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LocalDb;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms;
///
/// #937 review r1 (item 4): what an "acknowledge all" costs through the ONE host mailbox with the production LocalDb
/// (SQLite) condition-state store — 300 active alarms, acknowledged one at a time (one Call's requests are settled
/// sequentially) and with the node manager's default in-flight cap of 64 asks outstanding at once. Asserts that no ask
/// waits anywhere near the 5 s verdict bound; the measured numbers are printed for the evidence file.
///
public sealed class ScriptedAlarmCommandThroughputTests : RuntimeActorTestBase, IDisposable
{
private const int Alarms = 300;
private const int Cap = 64; // OtOpcUaNodeManager.DefaultMaxScriptedCommandsInFlight
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"otopcua-937-throughput-{Guid.NewGuid():N}.db");
private readonly ServiceProvider _provider;
private readonly ITestOutputHelper _output;
public ScriptedAlarmCommandThroughputTests(ITestOutputHelper output)
{
_output = output;
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary { ["LocalDb:Path"] = _dbPath }).Build();
_provider = new ServiceCollection()
.AddZbLocalDb(configuration, db =>
{
using (var connection = db.CreateConnection()) AlarmConditionStateSchema.Apply(connection);
db.RegisterReplicated(AlarmConditionStateSchema.StateTable);
db.RegisterReplicated(AlarmConditionStateSchema.CommentsTable);
})
.BuildServiceProvider();
}
void IDisposable.Dispose()
{
_provider.Dispose();
SqliteConnection.ClearAllPools();
foreach (var path in new[] { _dbPath, $"{_dbPath}-wal", $"{_dbPath}-shm" })
try { if (File.Exists(path)) File.Delete(path); } catch { /* best effort */ }
}
private static EquipmentScriptedAlarmPlan Plan(int i) =>
new(ScriptedAlarmId: $"alm-{i:D3}", EquipmentId: "Plant/Line1/M", Name: $"alm-{i:D3}", AlarmType: "AlarmCondition",
Severity: 800, MessageTemplate: "m", PredicateScriptId: "always", PredicateSource: "return true;",
DependencyRefs: [], HistorizeToAveva: false, Retain: true, Enabled: true);
[Fact]
public async Task Three_hundred_acks_through_one_host_stay_far_inside_the_verdict_bound()
{
var ct = TestContext.Current.CancellationToken;
var store = new LocalDbAlarmConditionStateStore(_provider.GetRequiredService(), NullLogger.Instance);
var upstream = new DependencyMuxTagUpstreamSource();
var logger = new LoggerConfiguration().CreateLogger();
var engine = new ScriptedAlarmEngine(upstream, store, new ScriptLoggerFactory(logger), logger);
var readiness = new ScriptedAlarmCommandReadinessView();
var mux = CreateTestProbe();
var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(CreateTestProbe().Ref, mux.Ref, () => (upstream, engine), readiness: readiness));
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(Enumerable.Range(0, Alarms).Select(Plan).ToList()));
mux.ExpectMsg(TimeSpan.FromSeconds(60), cancellationToken: ct);
async Task Ack(int i, string op)
{
var started = Stopwatch.GetTimestamp();
var outcome = await host.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand(
new AlarmCommand($"alm-{i:D3}", op, "alice", op == "AddComment" ? "c" : null, null, Guid.NewGuid().ToString("N"))),
TimeSpan.FromSeconds(30), ct);
outcome.Verdict.ShouldBe(AlarmCommandVerdict.Applied);
return Stopwatch.GetElapsedTime(started);
}
// Sequential: one Call carrying 300 Acknowledge requests (each settled before the next).
var total = Stopwatch.StartNew();
var sequential = new List();
for (var i = 0; i < Alarms; i++) sequential.Add(await Ack(i, "Acknowledge"));
var sequentialTotal = total.Elapsed;
engine.GetState("alm-000")!.Active.ShouldBe(AlarmActiveState.Active, "precondition: every alarm is active");
engine.GetState("alm-299")!.Acked.ShouldBe(AlarmAckedState.Acknowledged, "each ack changed (and saved) its condition");
(await store.LoadAsync("alm-150", ct))!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
// Concurrent: many sessions, at most the cap outstanding at once (AddComment always writes a row).
total.Restart();
var gate = new SemaphoreSlim(Cap);
var concurrent = await Task.WhenAll(Enumerable.Range(0, Alarms).Select(async i =>
{
await gate.WaitAsync(ct);
try { return await Ack(i, "AddComment"); }
finally { gate.Release(); }
}));
var concurrentTotal = total.Elapsed;
static string Stats(IEnumerable s)
{
var ms = s.Select(x => x.TotalMilliseconds).Order().ToArray();
return $"p50 {ms[ms.Length / 2]:0.0} ms, p99 {ms[(int)(ms.Length * 0.99)]:0.0} ms, max {ms[^1]:0.0} ms";
}
_output.WriteLine($"sequential 300 acks: total {sequentialTotal.TotalMilliseconds:0} ms; per ask {Stats(sequential)}");
_output.WriteLine($"cap-{Cap} concurrent 300 comments: total {concurrentTotal.TotalMilliseconds:0} ms; per ask {Stats(concurrent)}");
// Far inside the 5 s verdict bound even with a full cap queued behind the one mailbox.
concurrent.Max().ShouldBeLessThan(TimeSpan.FromSeconds(2.5));
sequential.Max().ShouldBeLessThan(TimeSpan.FromSeconds(2.5));
}
}