using System.Collections.Concurrent;
using Serilog;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests;
///
/// A1 (grpc-data plan §5.1 T2/F2): — a scripted condition is
/// known only when none of its inputs is still never-pushed, the flip fires after that evaluation's own emission,
/// and an input reverting to never-pushed withdraws it.
///
[Trait("Feature", "GrpcData")]
[Trait("Phase", "A1")]
[Trait("Category", "Unit")]
public sealed class ScriptedAlarmEngineInputsEstablishedTests
{
private const string Predicate = """return (int)ctx.GetTag("Temp").Value > 100;""";
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static (ScriptedAlarmEngine Engine, ConcurrentQueue Log) Build(FakeUpstream up)
{
var logger = new LoggerConfiguration().CreateLogger();
var engine = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger);
var log = new ConcurrentQueue();
engine.OnEvent += (_, e) => log.Enqueue($"emit:{e.AlarmId}:{e.Emission}");
engine.OnInputsEstablished += (_, e) => log.Enqueue($"inputs:{e.AlarmId}:{e.Established}");
return (engine, log);
}
private static ScriptedAlarmDefinition Alarm(string id) => new(
AlarmId: id, EquipmentPath: "Plant/Line1/Reactor", AlarmName: id, Kind: AlarmKind.AlarmCondition,
Severity: AlarmSeverity.High, MessageTemplate: "hot", PredicateScriptSource: Predicate);
/// T2 (i): a standing alarm whose input arrives late ⇒ nothing says "established" before the first real
/// evaluation, and the flip follows that evaluation's Active emission.
[Fact]
public async Task A_late_input_is_established_only_after_the_first_real_evaluation_and_after_its_emission()
{
var up = new FakeUpstream();
var (engine, log) = Build(up);
using var _ = engine;
await engine.LoadAsync([Alarm("a1")], Ct);
log.ShouldBeEmpty(); // input never pushed: no known-inactive
up.Push("Temp", 150);
await WaitForAsync(() => log.Count >= 2);
log.ShouldBe(["emit:a1:Activated", "inputs:a1:True"]);
}
[Fact]
public async Task An_input_seeded_at_load_is_established_at_load_after_the_load_emission()
{
var up = new FakeUpstream();
up.Set("Temp", 150);
var (engine, log) = Build(up);
using var _ = engine;
await engine.LoadAsync([Alarm("a1")], Ct);
log.Last().ShouldBe("inputs:a1:True");
log.Count(l => l.StartsWith("inputs:", StringComparison.Ordinal)).ShouldBe(1);
}
/// An input reverting to never-pushed (a tag re-created by a deploy) makes the condition unknown again; its
/// next real value re-establishes it.
[Fact]
public async Task An_input_reverting_to_never_pushed_withdraws_and_a_new_value_reestablishes()
{
var up = new FakeUpstream();
up.Set("Temp", 50);
var (engine, log) = Build(up);
using var _ = engine;
await engine.LoadAsync([Alarm("a1")], Ct);
log.ShouldBe(["inputs:a1:True"]);
up.Push("Temp", null, FakeUpstream.StatusNeverPushed);
await WaitForAsync(() => log.Count >= 2);
log.Last().ShouldBe("inputs:a1:False");
up.Push("Temp", 60);
await WaitForAsync(() => log.Count >= 3);
log.Last().ShouldBe("inputs:a1:True");
// Repeats are silent: another value with inputs still established raises nothing new.
up.Push("Temp", 70);
await Task.Delay(200, Ct);
log.Count.ShouldBe(3);
}
[Fact]
public async Task A_reload_reraises_the_flip_for_every_established_alarm()
{
var up = new FakeUpstream();
up.Set("Temp", 50);
var (engine, log) = Build(up);
using var _ = engine;
await engine.LoadAsync([Alarm("a1")], Ct);
await engine.LoadAsync([Alarm("a1")], Ct);
log.Count(l => l == "inputs:a1:True").ShouldBe(2);
}
// ---------------------------------------------------------------- review S1: established = a COMPLETED predicate
private const uint StatusBad = 0x80000000u;
/// Review S1: an input that is pushed but Bad (driver down) holds the condition; no predicate ran, so the
/// state is not established. The first Good value runs the predicate and only then establishes it.
[Fact]
public async Task A_Bad_input_never_establishes_and_the_first_good_evaluation_does()
{
var up = new FakeUpstream();
up.Set("Temp", 150, StatusBad);
var (engine, log) = Build(up);
using var _ = engine;
await engine.LoadAsync([Alarm("a1")], Ct);
up.Push("Temp", 150, StatusBad);
await Task.Delay(200, Ct);
log.ShouldNotContain(l => l.StartsWith("inputs:", StringComparison.Ordinal));
up.Push("Temp", 150);
await WaitForAsync(() => log.Contains("inputs:a1:True"));
log.Last().ShouldBe("inputs:a1:True");
log.ShouldContain("emit:a1:Activated");
}
/// Review S1: a predicate that times out (or a runner that is not up) never completed, so nothing is
/// established; the first evaluation that completes establishes it.
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task A_predicate_timeout_or_an_unavailable_runner_never_establishes(bool timeout)
{
var up = new FakeUpstream();
up.Set("Temp", 150);
var runner = new AnsweringRunner
{
Answer = timeout
? ScriptRunOutcome.Failed($"{ZB.MOM.WW.OtOpcUa.Commons.Engines.ScriptEvalFailureReasons.TimedOutPrefix}0.2s")
: ScriptRunOutcome.Unavailable(ScriptRunOutcome.WorkerRestartedReason),
};
var logger = new LoggerConfiguration().CreateLogger();
using var engine = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger,
scriptTimeout: TimeSpan.FromMilliseconds(250), scriptRunner: runner);
var log = new ConcurrentQueue();
engine.OnEvent += (_, e) => log.Enqueue($"emit:{e.AlarmId}:{e.Emission}");
engine.OnInputsEstablished += (_, e) => log.Enqueue($"inputs:{e.AlarmId}:{e.Established}");
await engine.LoadAsync([Alarm("a1")], Ct);
up.Push("Temp", 160);
await Task.Delay(200, Ct);
log.ShouldNotContain(l => l.StartsWith("inputs:", StringComparison.Ordinal));
runner.Answer = ScriptRunOutcome.Ok(true);
up.Push("Temp", 170);
await WaitForAsync(() => log.Contains("inputs:a1:True"));
log.Last().ShouldBe("inputs:a1:True");
}
/// A runner that answers every predicate with .
private sealed class AnsweringRunner : IScriptRunner
{
public volatile ScriptRunOutcome Answer = ScriptRunOutcome.Ok(false);
public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) =>
Task.FromResult(Answer);
public IReadOnlyList> RunBatch(IReadOnlyList invocations, CancellationToken ct = default) =>
invocations.Select(_ => Task.FromResult(Answer)).ToArray();
public void Reset(ScriptContextKind kind) { }
public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => [];
}
private static async Task WaitForAsync(Func cond, int timeoutMs = 3000)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (!cond())
{
if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not met");
await Task.Delay(10, Ct);
}
}
}