Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/AlarmsAccessorTests.cs
T
Joseph Doherty d3067ca036 fix(dcl): key OPC UA alarms on ConditionId (#147)
OtOpcUa now exposes conditions imported over gRPC data connections in the
namespace https://zb.com/otopcua/mapped/conditions. Their ConditionId is
an opaque c1. NodeId stable for the life of the connection, but their
SourceName (<anchor>/<placement path>) moves when the primary placement
mapping changes. ScadaBridge keyed every condition on
SourceName.ConditionName, so a mapping change read as one alarm clearing
and a new one raising.

- Event filter selects ConditionId (select clause 19: ConditionType,
  empty browse path, AttributeId = NodeId).
- When the ConditionId (or SourceNode, which OtOpcUa sets to it) is in the
  mapped/conditions namespace, the per-condition key is its durable
  nsu=... string (index-proof across an OtOpcUa pair / upgrade). Every
  other OPC UA condition keeps the SourceName.ConditionName key, so no
  existing persisted row, MES script or operator view is re-keyed.
- The old SourceName.ConditionName text becomes an additive, display-only
  DisplayName: NativeAlarmTransition -> AlarmStateChanged ->
  AlarmStateUpdate.display_name (26) / DebugAlarmStateDto.display_name
  (22) -> ScriptAlarm.DisplayName. Persisted in native_alarm_state
  metadata_json (no column, no CDC trigger change); updates in place on
  every transition under the fixed key. Protos regenerated.
- Alarm Summary and Debug View show DisplayName (key as tooltip) and
  filter on it; site event log writes "label [key]".
- Upgrade: a pre-#147 row for an imported condition is retired by the
  first completed refresh snapshot (one return-to-normal + drop), then the
  condition continues under its ConditionId.

Tests: RealOpcUaImportedConditionKeyTests, OpcUaAlarmMapperTests,
NativeAlarmActorTests (DisplayName, rehydration, legacy-row retirement),
StreamRelayActorTests, SiteCommand golden sample, AlarmsAccessorTests,
DebugTreeBuilderTests; filter select-clause count 19 -> 20.
Docs: Component-DataConnectionLayer/Commons/Communication/SiteRuntime.
2026-11-28 09:14:49 -05:00

295 lines
13 KiB
C#

using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Instance;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts;
/// <summary>
/// MES alarm-status API §5.2: the script-facing <c>Alarms.CurrentAsync()</c> accessor.
/// Routes a real <see cref="ScriptRuntimeContext"/> against a TestProbe standing in for the
/// Instance Actor (the same harness shape <c>AttributeAccessorWaitAsyncTests</c> uses), so
/// the Ask contract and the <see cref="AlarmStateChanged"/> → <c>ScriptAlarm</c> projection
/// are both exercised for real.
/// </summary>
public class AlarmsAccessorTests : TestKit, IDisposable
{
private ScriptRuntimeContext MakeContext(IActorRef instanceActor) =>
new(
instanceActor,
sharedScriptLibrary: null!,
currentCallDepth: 0,
maxCallDepth: 10,
askTimeout: TimeSpan.FromSeconds(5),
instanceName: "CvdReactor01",
logger: NullLogger<ScriptRuntimeContext>.Instance);
/// <inheritdoc />
void IDisposable.Dispose() => Shutdown();
private static readonly DateTimeOffset RaisedAt = new(2026, 8, 1, 10, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset AckedAt = new(2026, 8, 1, 10, 5, 0, TimeSpan.Zero);
private static readonly DateTimeOffset ObservedAt = new(2026, 8, 1, 10, 6, 0, TimeSpan.Zero);
/// <summary>An acknowledged native condition mirrored from a source binding.</summary>
private static AlarmStateChanged NativeAcked() =>
new("CvdReactor01", "Z28061.HeartbeatTimeoutAlarm", AlarmState.Active, 950, ObservedAt)
{
Kind = AlarmKind.NativeMxAccess,
Condition = new AlarmConditionState(
Active: true, Acknowledged: true, Confirmed: null,
// AVEVA priority 950 (inside the MES 900-999 band) banded to Low = 250 (#129).
Shelve: AlarmShelveState.TimedShelved, Suppressed: true, Severity: 250, Priority: 950),
SourceReference = "Z28061.HeartbeatTimeoutAlarm",
NativeSourceCanonicalName = "ReactorAlarms",
AlarmTypeName = "DiscreteAlarm",
Category = "Process",
Message = "Heartbeat lost",
OperatorUser = "op1",
OperatorComment = "investigating",
OriginalRaiseTime = RaisedAt,
AckTime = AckedAt,
CurrentValue = "FAULT",
LimitValue = "0",
};
/// <summary>Replies to the accessor's Ask with the supplied alarm rows.</summary>
private void RespondWith(Akka.TestKit.TestProbe probe, params AlarmStateChanged[] alarms)
{
var request = probe.ExpectMsg<GetAlarmSnapshotRequest>(TimeSpan.FromSeconds(5));
probe.Reply(new GetAlarmSnapshotResponse(
request.CorrelationId, request.InstanceUniqueName, alarms, DateTimeOffset.UtcNow));
}
/// <summary>Verifies that the current-alarms call asks the instance actor for its own instance.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CurrentAsync_AsksTheInstanceActor_ForItsOwnInstance()
{
// The script runs inside its own instance's context, so the read is a LOCAL Ask
// stamped with that instance's name — never a cross-instance or cross-cluster hop.
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var pending = ctx.Alarms.CurrentAsync();
var request = probe.ExpectMsg<GetAlarmSnapshotRequest>(TimeSpan.FromSeconds(5));
Assert.Equal("CvdReactor01", request.InstanceUniqueName);
Assert.NotEmpty(request.CorrelationId);
probe.Reply(new GetAlarmSnapshotResponse(
request.CorrelationId, request.InstanceUniqueName,
Array.Empty<AlarmStateChanged>(), DateTimeOffset.UtcNow));
Assert.Empty(await pending);
}
/// <summary>Verifies that the current-alarms call projects every native alarm field, including the acknowledgement time.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CurrentAsync_ProjectsEveryNativeField_IncludingAckTime()
{
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var pending = ctx.Alarms.CurrentAsync();
RespondWith(probe, NativeAcked());
var alarm = Assert.Single(await pending);
Assert.Equal("Z28061.HeartbeatTimeoutAlarm", alarm.Name);
Assert.Equal("Z28061.HeartbeatTimeoutAlarm", alarm.SourceReference);
Assert.Equal("ReactorAlarms", alarm.NativeSourceCanonicalName);
Assert.True(alarm.Active);
Assert.True(alarm.Acknowledged);
Assert.Null(alarm.Confirmed);
Assert.True(alarm.Shelved); // TimedShelved collapses to a single boolean
Assert.True(alarm.Suppressed);
Assert.Equal(250, alarm.Severity);
Assert.Equal(950, alarm.Priority); // the MES band keys off the raw priority (#129)
Assert.Equal("NativeMxAccess", alarm.Kind);
Assert.Equal("Heartbeat lost", alarm.Message);
Assert.Equal("DiscreteAlarm", alarm.AlarmTypeName);
Assert.Equal("Process", alarm.Category);
Assert.Equal("op1", alarm.OperatorUser);
Assert.Equal("investigating", alarm.OperatorComment);
Assert.Equal(RaisedAt, alarm.OriginalRaiseTime);
Assert.Equal(ObservedAt, alarm.Timestamp);
Assert.Equal(AckedAt, alarm.AckTime); // §6.4 — the whole point of the enrichment
Assert.Equal("FAULT", alarm.CurrentValue);
Assert.Equal("0", alarm.LimitValue);
Assert.False(alarm.IsConfiguredPlaceholder);
}
/// <summary>Verifies that an unacknowledged native alarm reports no acknowledgement time.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CurrentAsync_UnackedNativeAlarm_ReportsNoAckTime()
{
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var pending = ctx.Alarms.CurrentAsync();
RespondWith(probe, NativeAcked() with
{
Condition = new AlarmConditionState(
true, Acknowledged: false, null, AlarmShelveState.Unshelved, false, 950),
AckTime = null,
});
var alarm = Assert.Single(await pending);
Assert.False(alarm.Acknowledged);
Assert.Null(alarm.AckTime);
Assert.False(alarm.Shelved);
}
/// <summary>Verifies that a computed alarm reads its state from the derived condition.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CurrentAsync_ComputedAlarm_ReadsFromTheDerivedCondition()
{
// A computed alarm sets no explicit Condition — it is derived from State + Priority.
// Scripts must still see a coherent Active/Acknowledged/Severity triple so one
// filter expression works across computed and native alarms alike.
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var pending = ctx.Alarms.CurrentAsync();
RespondWith(probe,
new AlarmStateChanged("CvdReactor01", "HighTemp", AlarmState.Active, 700, ObservedAt));
var alarm = Assert.Single(await pending);
Assert.Equal("HighTemp", alarm.Name);
Assert.Equal("Computed", alarm.Kind);
Assert.True(alarm.Active);
Assert.True(alarm.Acknowledged); // computed alarms are auto-acked…
Assert.Null(alarm.AckTime); // …but carry no ack instant
Assert.Equal(500, alarm.Severity); // PriorityLevel 700 banded: Medium → 500 (#129)
Assert.Equal(700, alarm.Priority);
Assert.Equal(string.Empty, alarm.NativeSourceCanonicalName);
}
/// <summary>Verifies that placeholder rows are surfaced so that quiet bindings can be told apart.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CurrentAsync_SurfacesPlaceholderRows_SoQuietBindingsAreDistinguishable()
{
// The accessor deliberately does NOT pre-filter placeholders: a caller needs to tell
// "this binding is configured and quiet" from "this binding does not exist".
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var pending = ctx.Alarms.CurrentAsync();
RespondWith(probe,
NativeAcked(),
new AlarmStateChanged("CvdReactor01", "LeftSideAlarms", AlarmState.Normal, 0, ObservedAt)
{
Kind = AlarmKind.NativeMxAccess,
NativeSourceCanonicalName = "LeftSideAlarms",
IsConfiguredPlaceholder = true,
});
var alarms = await pending;
Assert.Equal(2, alarms.Count);
// …and the documented caller-side filter yields only the real alarm.
var real = Assert.Single(alarms, a => a.Active && !a.IsConfiguredPlaceholder);
Assert.Equal("Z28061.HeartbeatTimeoutAlarm", real.Name);
}
/// <summary>Verifies that the current-alarms call projects the MES-reportable flag.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CurrentAsync_ProjectsIsMesReportable()
{
// The deployed configuration's MES-reportable flag rides the snapshot row and must
// reach the script projection verbatim — a row without it reads false.
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var pending = ctx.Alarms.CurrentAsync();
RespondWith(probe,
NativeAcked() with { IsMesReportable = true },
new AlarmStateChanged("CvdReactor01", "HighTemp", AlarmState.Active, 700, ObservedAt));
var alarms = await pending;
Assert.Equal(2, alarms.Count);
Assert.True(Assert.Single(alarms, a => a.Name == "Z28061.HeartbeatTimeoutAlarm").IsMesReportable);
Assert.False(Assert.Single(alarms, a => a.Name == "HighTemp").IsMesReportable);
}
/// <summary>Verifies that a native condition's DisplayName reaches the script (Gitea #147).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CurrentAsync_ProjectsDisplayName()
{
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var pending = ctx.Alarms.CurrentAsync();
RespondWith(probe, NativeAcked() with { DisplayName = "Plant/remote-a/Z28061.Heartbeat" });
Assert.Equal("Plant/remote-a/Z28061.Heartbeat", Assert.Single(await pending).DisplayName);
}
/// <summary>Verifies that the MES-reportable call returns only the flagged rows.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task MesReportableAsync_FiltersToFlaggedRows()
{
// The convenience accessor is CurrentAsync restricted to the flagged subset, so a
// script does not have to repeat the filter (and cannot get it subtly wrong).
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var pending = ctx.Alarms.MesReportableAsync();
RespondWith(probe,
NativeAcked() with { IsMesReportable = true },
NativeAcked() with { AlarmName = "Z28061.UnflaggedAlarm", SourceReference = "Z28061.UnflaggedAlarm" });
var alarm = Assert.Single(await pending);
Assert.Equal("Z28061.HeartbeatTimeoutAlarm", alarm.Name);
Assert.True(alarm.IsMesReportable);
}
/// <summary>Verifies that the current-alarms call is not scope-prefixed, so every scope sees the same list.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CurrentAsync_IsNotScopePrefixed_EveryScopeSeesTheSameList()
{
// Unlike Attributes, alarm identity is not a scope-relative name. A composed script
// must not silently receive a truncated alarm set.
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var pending = new AlarmsAccessor(ctx).CurrentAsync();
RespondWith(probe, NativeAcked());
Assert.Single(await pending);
}
/// <summary>
/// The helper's continuation must not capture the script scheduler: a script that blocks its
/// only worker on the task (<c>.Wait()</c>) still completes (review 2026-10-21 01/SR-U2).
/// </summary>
[Fact]
public async Task CurrentAsync_ContinuationDoesNotNeedTheScriptScheduler_BlockingWaitCompletes()
{
using var scheduler = new ScriptExecutionScheduler(1);
var probe = CreateTestProbe();
var ctx = MakeContext(probe.Ref);
var run = Task.Factory.StartNew(
() => ctx.Alarms.CurrentAsync().Wait(TimeSpan.FromSeconds(10)),
CancellationToken.None, TaskCreationOptions.None, scheduler);
RespondWith(probe);
Assert.True(await run.WaitAsync(TimeSpan.FromSeconds(15)), "CurrentAsync continuation was queued back onto the blocked script scheduler");
}
}