using System.Collections.Concurrent; using System.Runtime.CompilerServices; 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; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] public sealed class GrpcDataAlarmEvidenceTests { private static ScriptedAlarmDefinition Definition() => new("alarm", "Plant", "alarm", AlarmKind.AlarmCondition, AlarmSeverity.High, "condition", "return (int)ctx.GetTag(\"Temp\").Value > 100;"); [Fact(Timeout = 20000)] public async Task A_later_authorized_input_cannot_authorize_an_older_async_evaluation() { var source = new Source(); var original = new Evidence(); source.Set(150, original); var runner = new Runner { Hold = true }; using var logger = new LoggerConfiguration().CreateLogger(); using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger, scriptRunner: runner); var events = new ConcurrentQueue(); engine.OnEvent += (_, value) => events.Enqueue(value); Task? loading = null; try { loading = engine.LoadAsync([Definition()], TestContext.Current.CancellationToken); await runner.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); original.Valid = false; source.Set(0, new Evidence()); runner.Release.TrySetResult(ScriptRunOutcome.Ok(true)); await loading.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); engine.GetState("alarm").ShouldNotBeNull().Active.ShouldBe(AlarmActiveState.Inactive); events.ShouldNotContain(value => value.Emission == EmissionKind.Activated && value.WorstInputStatusCode == 0); } finally { runner.Release.TrySetResult(ScriptRunOutcome.Ok(false)); if (loading is not null) await loading.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); } } [Fact(Timeout = 20000)] public async Task An_emission_keeps_its_original_evidence_after_the_cache_is_replaced() { var source = new Source(); var original = new Evidence(); source.Set(150, original); using var logger = new LoggerConfiguration().CreateLogger(); using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger, scriptRunner: new Runner()); var events = new ConcurrentQueue(); engine.OnEvent += (_, value) => events.Enqueue(value); await engine.LoadAsync([Definition()], TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); var emitted = events.Single(value => value.Emission == EmissionKind.Activated); emitted.InputEvidence.ShouldNotBeNull().IsValid.ShouldBeTrue(); original.Valid = false; source.Set(0, new Evidence()); emitted.InputEvidence.IsValid.ShouldBeFalse(); } [Fact(Timeout = 20000)] public async Task Physical_input_charge_survives_cache_replacement_until_runner_completion() { var source = new Source(); var original = new PhysicalEvidence(); source.Set(150, original); var runner = new Runner { Hold = true }; using var logger = new LoggerConfiguration().CreateLogger(); using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger, scriptRunner: runner); var loading = engine.LoadAsync([Definition()], TestContext.Current.CancellationToken); try { await runner.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); original.Active.ShouldBe(1); original.Valid = false; source.Set(0, new Evidence()); original.Active.ShouldBe(1); runner.Release.TrySetResult(ScriptRunOutcome.Ok(true)); await loading.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); original.Active.ShouldBe(0); engine.GetState("alarm").ShouldNotBeNull().Active.ShouldBe(AlarmActiveState.Inactive); } finally { runner.Release.TrySetResult(ScriptRunOutcome.Ok(false)); await loading.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); } } [Fact(Timeout = 20000)] public async Task Physical_input_is_not_dispatched_to_a_runner_without_lifetime_ownership() { var source = new Source(); var original = new PhysicalEvidence(); source.Set(150, original); var inner = new Runner(); using var logger = new LoggerConfiguration().CreateLogger(); using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger, scriptRunner: new UnownedRunner(inner)); await engine.LoadAsync([Definition()], TestContext.Current.CancellationToken) .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); inner.Entered.Task.IsCompleted.ShouldBeFalse(); original.Active.ShouldBe(0); engine.GetState("alarm").ShouldNotBeNull().Active.ShouldBe(AlarmActiveState.Inactive); } [Fact(Timeout = 20000)] public async Task Recovery_and_ack_preserve_condition_but_redact_transient_projected_values() { var source = new Source(); var original = new Evidence(); source.Set(150, original); using var logger = new LoggerConfiguration().CreateLogger(); using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger, scriptRunner: new Runner()); var events = new ConcurrentQueue(); engine.OnEvent += (_, value) => events.Enqueue(value); await engine.LoadAsync([Definition() with { MessageTemplate = "Temp={Temp}" }], TestContext.Current.CancellationToken); original.Valid = false; var projection = engine.GetProjections().Single(); projection.Message.ShouldBe("Temp={?}"); (projection.WorstInputStatusCode & 0x80000000u).ShouldNotBe(0u); await engine.AcknowledgeAsync("alarm", "operator", "accepted", TestContext.Current.CancellationToken); var acknowledgement = events.Single(value => value.Emission == EmissionKind.Acknowledged); acknowledgement.Message.ShouldBe("Temp={?}"); acknowledgement.Condition.Active.ShouldBe(AlarmActiveState.Active); } [Theory(Timeout = 20000)] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] public async Task Shadow_copies_only_local_inputs_including_template_only_snapshots(bool projected, bool templateOnly) { var source = new Source(); if (projected) source.Set(150, new Evidence()); else source.SetLocal(150); var shadow = new Shadow(); using var logger = new LoggerConfiguration().CreateLogger(); using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger, scriptTimeout: TimeSpan.FromSeconds(5), scriptRunner: shadow); var definition = Definition() with { MessageTemplate = "Temp={Temp}", PredicateScriptSource = templateOnly ? "return true;" : Definition().PredicateScriptSource }; await engine.LoadAsync([definition], TestContext.Current.CancellationToken); shadow.Mirrors.ShouldBe(projected ? 0 : 1); engine.GetState("alarm").ShouldNotBeNull().Active.ShouldBe(AlarmActiveState.Active); } private sealed class Shadow : IScriptRunner, IScriptShadow { public int Mirrors; public void Mirror(ScriptInvocation invocation, ScriptRunOutcome published) => Mirrors++; public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) => throw new InvalidOperationException(); public void Reset(ScriptContextKind kind) { } public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; } private sealed class PhysicalEvidence : Evidence, IAlarmInputPhysicalEvidence { public int Active; public bool TryRetainPhysical(DataValueSnapshot snapshot, out IDisposable? lease) { Interlocked.Increment(ref Active); lease = new ReleaseLease(this); return true; } private sealed class ReleaseLease(PhysicalEvidence owner) : IDisposable { private PhysicalEvidence? _owner = owner; public void Dispose() { if (Interlocked.Exchange(ref _owner, null) is { } held) Interlocked.Decrement(ref held.Active); } } } private sealed class UnownedRunner(Runner inner) : IScriptRunner { public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) => inner.RunAsync(invocation, ct); public void Reset(ScriptContextKind kind) { } public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; } private class Evidence : IAlarmInputEvidence { public volatile bool Valid = true; public bool IsValid => Valid; } private sealed class Source : ITagUpstreamSource, IAlarmInputEvidenceSource { private readonly ConditionalWeakTable _evidence = new(); private DataValueSnapshot _snapshot = new(null, 0x80320000, null, null); internal void Set(int value, Evidence evidence) { var next = new DataValueSnapshot(value, 0, null, null); _evidence.Add(next, evidence); Volatile.Write(ref _snapshot, next); } internal void SetLocal(int value) => Volatile.Write(ref _snapshot, new DataValueSnapshot(value, 0, null, null)); public DataValueSnapshot ReadTag(string path) => Volatile.Read(ref _snapshot); public IAlarmInputEvidence? CaptureEvidence(DataValueSnapshot snapshot) => _evidence.TryGetValue(snapshot, out var evidence) ? evidence : null; public IDisposable SubscribeTag(string path, Action observer) => new Empty(); private sealed class Empty : IDisposable { public void Dispose() { } } } private sealed class Runner : IPhysicalScriptRunner { public bool Hold; internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously); public async Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) { Entered.TrySetResult(); try { return Hold ? await Release.Task : ScriptRunOutcome.Ok(true); } finally { invocation.PhysicalLease?.Dispose(); } } public IReadOnlyList> RunBatch(IReadOnlyList invocations, CancellationToken ct = default) => invocations.Select(invocation => RunAsync(invocation, ct)).ToArray(); public void Reset(ScriptContextKind kind) { } public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; } }