6004a5a565
1. A post-dispatch refusal now puts the node back to its captured pre-call state with one corrective event (skipped when the node changed since) — the SDK had already applied and reported the change. Blank scripted AddComment is refused in the handler before the SDK runs. 2. ScriptedAlarmCommandDispatch: ask the local engine first, broadcast to the peer only on Applied/OutcomeUnknown — a refusal now reached no engine anywhere. 3. ApplyAsync no longer checks 'loaded' before _evalGate: a command racing the first load queues behind it; never loaded => refusal (nothing applied). 4. One Call's requests are settled sequentially (no request runs against a node state the engine refused); <= 64 asks in flight node-wide, else BadTooManyOperations before anything applies; per-request bound starts at send. Measured 300 acks through one host + LocalDb: 59 ms sequential, max 24 ms/ask with 64 outstanding. 5. Mixed-batch wire test (scripted refused + native + imported + scripted applied + core-manager method): per-item status in order, one scripted ask at a time. L6: readiness from the engine's HasCompleteGeneration on a load fault. L7: the verdict slot is closed when its SDK call returns (timer-captured AsyncLocal can no longer park an ask). L10: remote budget never stretched. Co-Authored-By: Claude <noreply@anthropic.com>
1124 lines
68 KiB
C#
1124 lines
68 KiB
C#
using Akka.Actor;
|
||
using Akka.Cluster.Tools.PublishSubscribe;
|
||
using Akka.Event;
|
||
using ZB.MOM.WW.OtOpcUa.Cluster;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Alerts;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
|
||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
||
using ZB.MOM.WW.OtOpcUa.Runtime.Telemetry;
|
||
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
|
||
|
||
namespace ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
|
||
|
||
/// <summary>
|
||
/// Akka host that owns one <see cref="ScriptedAlarmEngine"/> for an Equipment-namespace
|
||
/// driver node, feeds it live tag values, and bridges its emissions to OPC UA publish + the
|
||
/// cluster <c>alerts</c> DistributedPubSub topic.
|
||
///
|
||
/// <para>
|
||
/// The host is the engine's lifecycle owner. The restart-safe shape (R02:H1) is the
|
||
/// <b>factory</b> <see cref="Props(IActorRef, IActorRef?, Func{ValueTuple{DependencyMuxTagUpstreamSource, ScriptedAlarmEngine}}, NodeId?, Func{int}?, ITelemetryLocalHub?, TimeSpan?)"/>:
|
||
/// every incarnation builds its own <see cref="DependencyMuxTagUpstreamSource"/> + a
|
||
/// <see cref="ScriptedAlarmEngine"/> around it, and disposes them in <see cref="PostStop"/>.
|
||
/// Akka's default restart runs <c>PostStop</c> then re-creates the actor from the SAME Props, so the
|
||
/// legacy instance-taking Props — a fixed engine captured in the Props — restarted around a
|
||
/// <em>disposed</em> engine and every later <c>LoadAsync</c> threw: the node's scripted alarms
|
||
/// silently died. The legacy overload is kept source-compatible but is restart-safe only in the
|
||
/// weaker sense that a restart now DETACHES rather than disposes its engine (see
|
||
/// <see cref="PreRestart"/>); production should spawn through the factory.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Data flow.</b> <see cref="DependencyMuxActor"/> delivers the values of every tag the
|
||
/// loaded alarms depend on — in production as a batched
|
||
/// <see cref="VirtualTagActor.DependencyValueBatch"/> per driver burst, with the per-value
|
||
/// <see cref="VirtualTagActor.DependencyValueChanged"/> receive retained for direct senders and
|
||
/// tests; the host pushes each into the upstream. The engine self-evaluates: its own
|
||
/// <see cref="ITagUpstreamSource.SubscribeTag"/> observer re-runs the predicates and raises
|
||
/// <see cref="ScriptedAlarmEngine.OnEvent"/>. The host does NOT call evaluate — it only
|
||
/// feeds values in and fans emissions out.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Thread-safety.</b> <see cref="ScriptedAlarmEngine.OnEvent"/> fires on the engine's
|
||
/// background worker thread (its fire-and-forget re-evaluation), NOT on the actor thread.
|
||
/// The ctor subscribes a handler that does nothing but <c>Self.Tell(new EngineEmission(e))</c>
|
||
/// — <see cref="ICanTell.Tell"/> is thread-safe. ALL sink work (touching <see cref="Context"/>,
|
||
/// the publish actor ref, the DPS mediator) then happens on the actor thread in
|
||
/// <see cref="OnEngineEmission"/>. No <see cref="Context"/> or actor state is ever read or
|
||
/// written from the OnEvent callback.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Historization.</b> The host publishes each transition as an
|
||
/// <see cref="AlarmTransitionEvent"/> to the <c>alerts</c> topic ONLY. That topic is the
|
||
/// historization path: <c>HistorianAdapterActor</c>'s upstream and the Admin UI Alerts page
|
||
/// both consume <c>alerts</c>. The host deliberately does NOT also <c>Tell</c> the historian
|
||
/// adapter directly — doing so would double-historize every transition. (T9 plan called for a
|
||
/// "direct historian tell"; that was dropped because the alerts topic already feeds the
|
||
/// historian path, so a direct tell would duplicate every row.)
|
||
/// </para>
|
||
/// </summary>
|
||
public sealed class ScriptedAlarmHostActor : ReceiveActor
|
||
{
|
||
/// <summary>The cluster DistributedPubSub topic every alarm transition is published to. Matches
|
||
/// the constant the (retired) <c>ScriptedAlarmActor</c> used so subscribers stay wired.</summary>
|
||
public const string AlertsTopic = "alerts";
|
||
|
||
/// <summary>The cluster DistributedPubSub topic inbound OPC UA Part 9 alarm method calls
|
||
/// (Acknowledge / Confirm / Shelve / AddComment) are routed onto as <see cref="AlarmCommand"/>s.
|
||
/// The OPC UA node manager's condition handlers build the command (after the <c>AlarmAck</c> role
|
||
/// gate, T18) or the AdminUI path republishes via <c>AdminOperationsActor</c> (T21); this host's
|
||
/// boot wiring subscribes; T19's engine-side handler consumes it. Re-exports the single Commons
|
||
/// const so every publisher/subscriber shares one literal.</summary>
|
||
public const string AlarmCommandsTopic = ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AlarmCommandsTopic.Name;
|
||
|
||
/// <summary>Reconcile the loaded alarm set to exactly the enabled subset of <paramref name="Plans"/>:
|
||
/// builds <see cref="ScriptedAlarmDefinition"/>s (skipping disabled plans), reloads the engine, and
|
||
/// re-registers mux interest for the union of dependency refs.</summary>
|
||
/// <param name="Plans">The desired Equipment-namespace scripted-alarm plans.</param>
|
||
public sealed record ApplyScriptedAlarms(IReadOnlyList<EquipmentScriptedAlarmPlan> Plans);
|
||
|
||
/// <summary>
|
||
/// #937: a NODE-LOCAL ask (never published, never serialized) — apply <paramref name="Command"/> to this host's
|
||
/// engine and reply an <see cref="AlarmCommandOutcome"/> to the sender, so the OPC UA Part 9 method that issued it
|
||
/// can return the engine's verdict instead of the Good a fire-and-forget topic publish implied. The same command
|
||
/// (same <see cref="AlarmCommand.CommandId"/>) is also broadcast on <see cref="AlarmCommandsTopic"/> for the
|
||
/// redundant peer; this host applies whichever copy arrives first and skips the other.
|
||
/// </summary>
|
||
/// <param name="Command">The command.</param>
|
||
public sealed record ExecuteAlarmCommand(AlarmCommand Command);
|
||
|
||
/// <summary>
|
||
/// Told to the parent from <see cref="PostRestart"/>. A supervision restart is otherwise invisible to the
|
||
/// parent, and the new incarnation has an EMPTY engine (factory Props) and no mux interest, so until the
|
||
/// next <see cref="ApplyScriptedAlarms"/> its inputs stop and every operator command is dropped as not
|
||
/// owned. The parent (<c>DriverHostActor</c>) answers by re-sending the last plans it applied, mirroring
|
||
/// how a driver child's <c>ReprovisionRequested</c> is answered.
|
||
/// </summary>
|
||
public sealed class ScriptedAlarmHostRestarted
|
||
{
|
||
/// <summary>The single instance.</summary>
|
||
public static readonly ScriptedAlarmHostRestarted Instance = new();
|
||
|
||
private ScriptedAlarmHostRestarted() { }
|
||
}
|
||
|
||
/// <summary>Marshals an engine emission off the engine's worker thread onto the actor thread.
|
||
/// Carries the <see cref="ScriptedAlarmEvent"/> the engine raised on <c>OnEvent</c>.</summary>
|
||
private sealed record EngineEmission(ScriptedAlarmEvent Event);
|
||
|
||
/// <summary>Pipe-back completion of an in-flight <see cref="ScriptedAlarmEngine.LoadAsync"/>:
|
||
/// carries the union of dependency refs to register mux interest for AFTER the load completed
|
||
/// (so the engine's upstream subscriptions exist before any value can arrive). <see cref="Generation"/>
|
||
/// is the load generation captured when <see cref="OnApply"/> kicked the load off; a stale
|
||
/// continuation (an earlier generation completing after a newer apply) is discarded in
|
||
/// <see cref="OnAlarmsLoaded"/> so out-of-order completions can't register stale dep refs.</summary>
|
||
private sealed record AlarmsLoaded(IReadOnlyList<string> DepRefs, int Generation);
|
||
|
||
/// <summary>Pipe-back marker for a <see cref="ScriptedAlarmEngine.LoadAsync"/> that was cancelled
|
||
/// because the actor is stopping (its <see cref="_cts"/> fired in <see cref="PostStop"/>). It is a
|
||
/// no-op — there is nothing to register and no fault to log — and exists only so a cancelled load
|
||
/// pipes back a quiet message instead of a <see cref="Status.Failure"/> that would log a spurious
|
||
/// Warning on every clean shutdown.</summary>
|
||
private sealed record AlarmsLoadCanceled;
|
||
|
||
/// <summary>Default bound on one inbound alarm command's engine op (<see cref="OnAlarmCommand"/>): 10 s.</summary>
|
||
public static readonly TimeSpan DefaultCommandTimeout = TimeSpan.FromSeconds(10);
|
||
|
||
private readonly IActorRef _publishActor;
|
||
private readonly IActorRef? _mux;
|
||
private readonly DependencyMuxTagUpstreamSource _upstream;
|
||
private readonly ScriptedAlarmEngine _engine;
|
||
private readonly NodeId? _localNode;
|
||
private readonly ILoggingAdapter _log = Context.GetLogger();
|
||
private readonly CancellationTokenSource _cts = new();
|
||
private readonly EventHandler<ScriptedAlarmEvent> _onEngineEvent;
|
||
private readonly EventHandler<ScriptedAlarmInputsEventArgs> _onInputsEstablished;
|
||
|
||
/// <summary>A1 (grpc-data §5.1 T2/F2): an engine input-establishment flip, marshaled onto the actor thread on the
|
||
/// SAME mailbox as <see cref="EngineEmission"/> (the engine raises it after that evaluation's emissions).</summary>
|
||
private sealed record EngineInputsEstablished(string AlarmId, bool Established);
|
||
|
||
// Flips that arrive while a load is in flight wait for that load's re-assert (OnAlarmsLoaded): a LoadAsync fires
|
||
// its flips before the AlarmsLoaded pipe-back, and marking a re-materialised node known before the re-assert of
|
||
// its persisted non-normal state lands would be a falsely-normal known (T2). Latest flip per alarm wins.
|
||
private readonly Dictionary<string, bool> _heldEstablishments = new(StringComparer.Ordinal);
|
||
private int _loadedGeneration;
|
||
private readonly TimeSpan _commandTimeout;
|
||
|
||
/// <summary>True when THIS incarnation built its engine (factory Props) and therefore disposes it on
|
||
/// every stop, restart included. False for the legacy instance-taking Props: the engine outlives the
|
||
/// incarnation, so a restart only detaches from it and a final stop disposes it.</summary>
|
||
private readonly bool _ownsEngine;
|
||
|
||
/// <summary>Set by <see cref="PreRestart"/> so the <see cref="PostStop"/> it triggers can tell a restart
|
||
/// (the next incarnation reuses a legacy engine) from a genuine stop.</summary>
|
||
private bool _restarting;
|
||
|
||
/// <summary>Cached local <see cref="RedundancyRole"/> from the latest <see cref="RedundancyStateChanged"/>
|
||
/// snapshot (null = unknown until the first snapshot arrives, or no <see cref="_localNode"/> wired). The
|
||
/// cluster-wide <c>alerts</c> publish in <see cref="OnEngineEmission"/> resolves this through
|
||
/// <see cref="Drivers.PrimaryGatePolicy"/>: only the Primary publishes; an unknown role default-emits on a
|
||
/// single-driver cluster but default-DENIES on a multi-driver one, so the dual-primary boot window can't
|
||
/// historize duplicate AVEVA alarm rows (archreview 03/S4).</summary>
|
||
private RedundancyRole? _localRole;
|
||
|
||
/// <summary>Test seam (archreview 03/S4): overrides the count of Up <c>driver</c>-role cluster members the
|
||
/// alerts-emit gate reads while the role is unknown. Null ⇒ read the live cluster state.</summary>
|
||
private readonly Func<int>? _driverMemberCountProvider;
|
||
|
||
/// <summary>Optional node-local live-telemetry hub (Phase 5): each cluster-wide <c>alerts</c> transition
|
||
/// is also emitted here for the gRPC streaming service. Null (tests / no hub wired) skips the emit.</summary>
|
||
private readonly ITelemetryLocalHub? _telemetryHub;
|
||
|
||
/// <summary>Monotonic load generation, bumped on every <see cref="OnApply"/>. The continuation that
|
||
/// pipes back an <see cref="AlarmsLoaded"/> captures the generation it was started under; a stale
|
||
/// completion (an earlier generation arriving after a newer apply) is discarded in
|
||
/// <see cref="OnAlarmsLoaded"/> so out-of-order loads never register superseded dep refs.</summary>
|
||
private int _loadGeneration;
|
||
|
||
/// <summary>#937: the published outcome of the latest completed load (null in tests).</summary>
|
||
private readonly ScriptedAlarmCommandReadinessView? _readiness;
|
||
|
||
/// <summary>#937: the enabled alarm ids of the latest <see cref="ApplyScriptedAlarms"/> — this host's alarms even while
|
||
/// the engine's own set is mid-load or (a failed load) half-built.</summary>
|
||
private HashSet<string> _plannedAlarmIds = new(StringComparer.Ordinal);
|
||
|
||
/// <summary>#937: the outcome of each recent command that carried a <see cref="AlarmCommand.CommandId"/>, so the
|
||
/// broadcast copy of a directly-asked command (or the other way round) is applied once. Bounded FIFO.</summary>
|
||
private readonly Dictionary<string, AlarmCommandOutcome> _recentCommands = new(StringComparer.Ordinal);
|
||
private readonly Queue<string> _recentCommandOrder = new();
|
||
internal const int RecentCommandCapacity = 1024;
|
||
|
||
/// <summary>Cached cluster DistributedPubSub mediator, resolved once in <see cref="PreStart"/> (on the
|
||
/// actor thread) and reused for every emission instead of re-resolving it per-publish.</summary>
|
||
private IActorRef _mediator = null!;
|
||
|
||
/// <summary>Factory method to create Props for a <see cref="ScriptedAlarmHostActor"/>.</summary>
|
||
/// <param name="publishActor">The OPC UA publish actor that consumes
|
||
/// <see cref="OpcUaPublishActor.AlarmStateUpdate"/> bridged from engine emissions.</param>
|
||
/// <param name="mux">Optional dependency multiplexer the host registers interest with so it receives
|
||
/// its dependency tags' values — a <see cref="VirtualTagActor.DependencyValueBatch"/> per burst in
|
||
/// production, or a per-value <see cref="VirtualTagActor.DependencyValueChanged"/> from a direct
|
||
/// sender or a test. Null on the dev/Mac path (no live values).</param>
|
||
/// <param name="upstream">The mux-fed upstream the engine reads + subscribes from. MUST be the
|
||
/// same instance the <paramref name="engine"/> was constructed around.</param>
|
||
/// <param name="engine">The scripted-alarm engine this host owns + disposes.</param>
|
||
/// <param name="localNode">The local cluster node id, used to read this node's <see cref="RedundancyRole"/>
|
||
/// from the <c>redundancy-state</c> topic so only the Primary publishes the cluster-wide <c>alerts</c>
|
||
/// transition. Null (the default) leaves the role unknown ⇒ default-emit (single-node deploys + tests).</param>
|
||
/// <param name="driverMemberCountProvider">Test seam (archreview 03/S4): overrides the count of Up
|
||
/// <c>driver</c>-role cluster members the alerts-emit gate reads while the role is unknown.</param>
|
||
/// <param name="telemetryHub">Optional node-local live-telemetry hub (Phase 5) each cluster-wide
|
||
/// <c>alerts</c> transition is also emitted into; null (tests) skips the emit.</param>
|
||
/// <returns>The <see cref="Akka.Actor.Props"/> used to instantiate the actor.</returns>
|
||
/// <remarks>Legacy, instance-taking shape — see the class remarks: a supervision restart re-creates the
|
||
/// actor around these SAME instances, so prefer the factory overload in production.</remarks>
|
||
public static Props Props(
|
||
IActorRef publishActor,
|
||
IActorRef? mux,
|
||
DependencyMuxTagUpstreamSource upstream,
|
||
ScriptedAlarmEngine engine,
|
||
NodeId? localNode = null,
|
||
Func<int>? driverMemberCountProvider = null,
|
||
ITelemetryLocalHub? telemetryHub = null) =>
|
||
Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, upstream, engine, localNode, driverMemberCountProvider, telemetryHub));
|
||
|
||
/// <summary>
|
||
/// Restart-safe factory Props (R02:H1): each incarnation of the actor calls
|
||
/// <paramref name="engineFactory"/> in its constructor and owns what it returns — the engine must
|
||
/// be constructed <b>around</b> the returned upstream — so a supervision restart gets a fresh,
|
||
/// undisposed engine and the next <see cref="ApplyScriptedAlarms"/> loads cleanly.
|
||
/// </summary>
|
||
/// <param name="publishActor">The OPC UA publish actor emissions are bridged to.</param>
|
||
/// <param name="mux">Optional dependency multiplexer the host registers interest with.</param>
|
||
/// <param name="engineFactory">Builds a fresh (upstream, engine) pair; called once per incarnation.</param>
|
||
/// <param name="localNode">The local cluster node id for the Primary alerts-emit gate; null ⇒ default-emit.</param>
|
||
/// <param name="driverMemberCountProvider">Test seam for the alerts-emit gate's driver-member count.</param>
|
||
/// <param name="telemetryHub">Optional node-local live-telemetry hub.</param>
|
||
/// <param name="commandTimeout">Bound on one inbound alarm command's engine op; null ⇒ <see cref="DefaultCommandTimeout"/>.</param>
|
||
/// <returns>The <see cref="Akka.Actor.Props"/> used to instantiate the actor.</returns>
|
||
public static Props Props(
|
||
IActorRef publishActor,
|
||
IActorRef? mux,
|
||
Func<(DependencyMuxTagUpstreamSource Upstream, ScriptedAlarmEngine Engine)> engineFactory,
|
||
NodeId? localNode = null,
|
||
Func<int>? driverMemberCountProvider = null,
|
||
ITelemetryLocalHub? telemetryHub = null,
|
||
TimeSpan? commandTimeout = null,
|
||
ScriptedAlarmCommandReadinessView? readiness = null) =>
|
||
Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout, readiness));
|
||
|
||
/// <summary>Factory-built incarnation: owns (and on every stop disposes) the engine it builds.</summary>
|
||
/// <param name="publishActor">The OPC UA publish actor emissions are bridged to.</param>
|
||
/// <param name="mux">Optional dependency multiplexer the host registers interest with.</param>
|
||
/// <param name="engineFactory">Builds this incarnation's (upstream, engine) pair.</param>
|
||
/// <param name="localNode">The local cluster node id for the Primary alerts-emit gate.</param>
|
||
/// <param name="driverMemberCountProvider">Test seam for the alerts-emit gate's driver-member count.</param>
|
||
/// <param name="telemetryHub">Optional node-local live-telemetry hub.</param>
|
||
/// <param name="commandTimeout">Bound on one inbound alarm command's engine op.</param>
|
||
/// <param name="readiness">#937: where the outcome of every completed load is published for the node manager's
|
||
/// synchronous pre-check. Null ⇒ none (tests).</param>
|
||
public ScriptedAlarmHostActor(
|
||
IActorRef publishActor,
|
||
IActorRef? mux,
|
||
Func<(DependencyMuxTagUpstreamSource Upstream, ScriptedAlarmEngine Engine)> engineFactory,
|
||
NodeId? localNode = null,
|
||
Func<int>? driverMemberCountProvider = null,
|
||
ITelemetryLocalHub? telemetryHub = null,
|
||
TimeSpan? commandTimeout = null,
|
||
ScriptedAlarmCommandReadinessView? readiness = null)
|
||
: this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout, readiness)
|
||
{
|
||
}
|
||
|
||
private static (DependencyMuxTagUpstreamSource Upstream, ScriptedAlarmEngine Engine) Build(
|
||
Func<(DependencyMuxTagUpstreamSource Upstream, ScriptedAlarmEngine Engine)> engineFactory)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(engineFactory);
|
||
var pair = engineFactory();
|
||
ArgumentNullException.ThrowIfNull(pair.Upstream, "engineFactory().Upstream");
|
||
ArgumentNullException.ThrowIfNull(pair.Engine, "engineFactory().Engine");
|
||
return pair;
|
||
}
|
||
|
||
/// <summary>Initializes a new instance of the <see cref="ScriptedAlarmHostActor"/> class.</summary>
|
||
/// <param name="publishActor">The OPC UA publish actor emissions are bridged to.</param>
|
||
/// <param name="mux">Optional dependency multiplexer the host registers dependency interest with.</param>
|
||
/// <param name="upstream">The mux-fed upstream the engine reads + subscribes from (same instance the engine wraps).</param>
|
||
/// <param name="engine">The scripted-alarm engine this host owns + disposes.</param>
|
||
/// <param name="localNode">The local cluster node id, used to read this node's <see cref="RedundancyRole"/>
|
||
/// from the <c>redundancy-state</c> topic so only the Primary publishes the cluster-wide <c>alerts</c>
|
||
/// transition. Null leaves the role unknown ⇒ default-emit (single-node deploys + tests).</param>
|
||
/// <param name="driverMemberCountProvider">Test seam (archreview 03/S4): overrides the count of Up
|
||
/// <c>driver</c>-role cluster members the alerts-emit gate reads while the role is unknown. Null reads
|
||
/// the live cluster state (0 on a non-cluster ActorRefProvider ⇒ single-node default-emit).</param>
|
||
/// <param name="telemetryHub">Optional node-local live-telemetry hub (Phase 5) each cluster-wide
|
||
/// <c>alerts</c> transition is also emitted into; null (tests) skips the emit.</param>
|
||
public ScriptedAlarmHostActor(
|
||
IActorRef publishActor,
|
||
IActorRef? mux,
|
||
DependencyMuxTagUpstreamSource upstream,
|
||
ScriptedAlarmEngine engine,
|
||
NodeId? localNode = null,
|
||
Func<int>? driverMemberCountProvider = null,
|
||
ITelemetryLocalHub? telemetryHub = null)
|
||
: this(publishActor, mux, (upstream, engine), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: false, commandTimeout: null, readiness: null)
|
||
{
|
||
}
|
||
|
||
private ScriptedAlarmHostActor(
|
||
IActorRef publishActor,
|
||
IActorRef? mux,
|
||
(DependencyMuxTagUpstreamSource Upstream, ScriptedAlarmEngine Engine) pair,
|
||
NodeId? localNode,
|
||
Func<int>? driverMemberCountProvider,
|
||
ITelemetryLocalHub? telemetryHub,
|
||
bool ownsEngine,
|
||
TimeSpan? commandTimeout,
|
||
ScriptedAlarmCommandReadinessView? readiness)
|
||
{
|
||
_readiness = readiness;
|
||
// A new incarnation has not loaded yet: whatever the previous one published no longer describes this engine.
|
||
_readiness?.Reset();
|
||
ArgumentNullException.ThrowIfNull(publishActor);
|
||
ArgumentNullException.ThrowIfNull(pair.Upstream);
|
||
ArgumentNullException.ThrowIfNull(pair.Engine);
|
||
_publishActor = publishActor;
|
||
_mux = mux;
|
||
_upstream = pair.Upstream;
|
||
_engine = pair.Engine;
|
||
_ownsEngine = ownsEngine;
|
||
_commandTimeout = commandTimeout is { } t && t > TimeSpan.Zero ? t : DefaultCommandTimeout;
|
||
_localNode = localNode;
|
||
_driverMemberCountProvider = driverMemberCountProvider;
|
||
_telemetryHub = telemetryHub;
|
||
|
||
// OnEvent fires on the engine's worker thread. NEVER touch Context / actor state here —
|
||
// marshal onto the actor thread via the thread-safe Self.Tell. Keep the handler in a field
|
||
// so PostStop can unsubscribe it. (Self is captured once; it is stable for the actor's life.)
|
||
var self = Self;
|
||
_onEngineEvent = (_, e) => self.Tell(new EngineEmission(e));
|
||
_engine.OnEvent += _onEngineEvent;
|
||
_onInputsEstablished = (_, e) => self.Tell(new EngineInputsEstablished(e.AlarmId, e.Established));
|
||
_engine.OnInputsEstablished += _onInputsEstablished;
|
||
|
||
Receive<ApplyScriptedAlarms>(OnApply);
|
||
Receive<AlarmsLoaded>(OnAlarmsLoaded);
|
||
Receive<VirtualTagActor.DependencyValueChanged>(OnDependencyChanged);
|
||
// The mux's batched delivery: one message carrying this host's whole matched slice of a driver
|
||
// burst. The engine upstream is fed per value, so push each item in order — the saving is the
|
||
// mailbox hop, not the push.
|
||
Receive<VirtualTagActor.DependencyValueBatch>(OnDependencyBatch);
|
||
Receive<DependencyMuxActor.ProjectedDependencyWake>(wake => wake.Consume(items => OnDependencyBatch(new(items))));
|
||
Receive<EngineEmission>(OnEngineEmission);
|
||
Receive<EngineInputsEstablished>(OnEngineInputsEstablished);
|
||
// Cluster redundancy snapshots (published on the `redundancy-state` topic, subscribed in PreStart)
|
||
// cache this node's role so OnEngineEmission can gate the cluster-wide alerts publish to the Primary.
|
||
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
|
||
// Inbound OPC UA Part 9 alarm method calls arrive as AlarmCommands on the cluster
|
||
// `alarm-commands` DPS topic (T18 publishes them after the AlarmAck role gate). The topic is a
|
||
// cluster-wide broadcast — every host node receives every command — so OnAlarmCommand filters to
|
||
// the alarms THIS host's engine owns before driving the matching engine op. The engine ops are
|
||
// async, and this project's Akka analyzer (AK2003) forbids an async-void Receive delegate, so
|
||
// the handler is a Task-returning ReceiveAsync: Akka suspends the mailbox until the op completes
|
||
// (ordered, awaited on the actor thread) and routes any escaped fault through supervision.
|
||
ReceiveAsync<AlarmCommand>(OnAlarmCommand);
|
||
// #937: the node-local ask behind an OPC UA Part 9 method — same op, plus a reply carrying the verdict.
|
||
ReceiveAsync<ExecuteAlarmCommand>(OnExecuteAlarmCommand);
|
||
// A faulted LoadAsync pipes back a Status.Failure (see OnApply) — log it and stay inert so the
|
||
// failure doesn't hit the dead-letter log.
|
||
Receive<Status.Failure>(OnLoadFailed);
|
||
// A LoadAsync cancelled by PostStop's _cts pipes back this marker. The actor is stopping, so
|
||
// there's nothing to do — swallow it quietly (no Warning, no dead letter).
|
||
Receive<AlarmsLoadCanceled>(_ => { });
|
||
// The redundancy-state topic also carries OpcUaProbeResult (OpcUaPublishActor peer-probes).
|
||
// We don't consume it here — drop it so it doesn't dead-letter (matches PeerProbeSupervisor).
|
||
Receive<ZB.MOM.WW.OtOpcUa.Runtime.Health.PeerOpcUaProbeActor.OpcUaProbeResult>(_ => { });
|
||
// DPS Subscribe (PreStart) acks back here once the mediator has registered Self on the topic.
|
||
// No-op — the subscription is live the moment the ack arrives; we only need to keep it off the
|
||
// dead-letter log. Matches OpcUaPublishActor / DriverHostActor's SubscribeAck convention.
|
||
Receive<SubscribeAck>(_ => { /* PubSub ack */ });
|
||
}
|
||
|
||
private void OnApply(ApplyScriptedAlarms msg)
|
||
{
|
||
// Bump the load generation and capture it into this apply's continuation. Rapid back-to-back
|
||
// applies kick off concurrent LoadAsyncs whose continuations may complete out of order; tagging
|
||
// each with its generation lets OnAlarmsLoaded discard any but the latest.
|
||
var gen = ++_loadGeneration;
|
||
// The new load clears the engine's established set and re-raises every flip; any held from the load this one
|
||
// supersedes would describe that load, not this one.
|
||
_heldEstablishments.Clear();
|
||
|
||
// Skip disabled plans entirely — the engine has no Enabled flag, so a disabled alarm is simply
|
||
// not loaded (no predicate, no upstream subscription, no events).
|
||
var enabled = msg.Plans.Where(p => p.Enabled).ToList();
|
||
_plannedAlarmIds = new HashSet<string>(enabled.Select(p => p.ScriptedAlarmId), StringComparer.Ordinal);
|
||
|
||
var defs = enabled.Select(ToDefinition).ToList();
|
||
|
||
// Union of dependency refs across the loaded (enabled) alarms — interest is registered with
|
||
// the mux only AFTER LoadAsync completes (see OnAlarmsLoaded), because the engine establishes
|
||
// its upstream SubscribeTag subscriptions inside LoadAsync; values must not arrive before then.
|
||
var depRefs = enabled
|
||
.SelectMany(p => p.DependencyRefs)
|
||
.Distinct(StringComparer.Ordinal)
|
||
.ToList();
|
||
|
||
// PipeTo marshals the completion back onto the actor thread. The continuation runs with
|
||
// CancellationToken.None so it ALWAYS executes (even after _cts fired on stop) and branches on
|
||
// the load's outcome: a clean cancel (actor stopping) pipes back a quiet AlarmsLoadCanceled; a
|
||
// genuine fault pipes back a Status.Failure we log as Warning (the prior generation's mux
|
||
// subscription stays — a failed reload should not silently drop live values); success pipes back
|
||
// AlarmsLoaded carrying the refs + the generation it was loaded under.
|
||
_engine.LoadAsync(defs, _cts.Token)
|
||
.ContinueWith(
|
||
t => t.IsCanceled ? (object)new AlarmsLoadCanceled()
|
||
: t.IsFaulted ? new Status.Failure(t.Exception!.GetBaseException())
|
||
: new AlarmsLoaded(depRefs, gen),
|
||
CancellationToken.None,
|
||
TaskContinuationOptions.ExecuteSynchronously,
|
||
TaskScheduler.Default)
|
||
.PipeTo(Self);
|
||
|
||
_log.Debug("ScriptedAlarmHost: applying (enabled={Enabled}/{Total}, depRefs={Refs})",
|
||
enabled.Count, msg.Plans.Count, depRefs.Count);
|
||
}
|
||
|
||
private void OnLoadFailed(Status.Failure msg)
|
||
{
|
||
// #937: loads serialize on the engine's gate, so completions arrive in start order — this is the latest completed
|
||
// load. Publish what the ENGINE says rather than infer it from the fault (review r1 L6): a load can fault after it
|
||
// completed its generation (e.g. subscribing), and then the engine still accepts commands.
|
||
_readiness?.SetLoadOutcome(loaded: _engine.HasCompleteGeneration);
|
||
_log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded; operator commands are refused until the next successful deploy");
|
||
}
|
||
|
||
private void OnAlarmsLoaded(AlarmsLoaded msg)
|
||
{
|
||
// #937: ANY completed load — even one a newer apply superseded — left the engine holding a complete generation
|
||
// until that newer load finishes (which then publishes its own outcome).
|
||
_readiness?.SetLoadOutcome(loaded: true);
|
||
|
||
// Discard a stale completion: if a newer apply has since bumped the generation, this load's
|
||
// dep refs are superseded and registering them would re-introduce the old set. The latest
|
||
// generation's continuation will (or already did) register the current interest set.
|
||
if (msg.Generation != _loadGeneration)
|
||
{
|
||
return;
|
||
}
|
||
|
||
// Register mux interest only now that LoadAsync has returned — the engine's upstream
|
||
// subscriptions exist, so any DependencyValueChanged the mux delivers will be observed by the
|
||
// engine. RegisterInterest replaces a subscriber's prior interest set (see DependencyMuxActor),
|
||
// so a re-Apply with a fresh union simply supersedes the old one — no explicit unregister needed.
|
||
// ReplayRetained: the mux replays the last value it saw for each ref, so a freshly loaded engine
|
||
// converges immediately instead of waiting for every input to change again. That includes the engine
|
||
// a supervision restart builds around an EMPTY upstream, but only once the parent has re-sent
|
||
// ApplyScriptedAlarms in answer to ScriptedAlarmHostRestarted (PostRestart); nothing reloads it before.
|
||
_mux?.Tell(new DependencyMuxActor.RegisterInterest(msg.DepRefs, Self, ReplayRetained: true));
|
||
// Prune the upstream's retained snapshots to the loaded set (R02:L3): a path no alarm references
|
||
// any more will never be pushed again, so its last value is dead weight for the process lifetime.
|
||
var dropped = _upstream.RetainOnly(new HashSet<string>(msg.DepRefs, StringComparer.Ordinal));
|
||
_log.Debug("ScriptedAlarmHost: loaded; registered mux interest for {Count} dep refs (pruned {Dropped} retained path(s))",
|
||
msg.DepRefs.Count, dropped);
|
||
|
||
ReassertConditionNodes();
|
||
|
||
// A1: the re-assert above is queued to the publish actor first, so a held "known" lands after it.
|
||
_loadedGeneration = msg.Generation;
|
||
foreach (var (alarmId, established) in _heldEstablishments) SendEstablishment(alarmId, established);
|
||
_heldEstablishments.Clear();
|
||
}
|
||
|
||
private void OnEngineInputsEstablished(EngineInputsEstablished msg)
|
||
{
|
||
if (_loadedGeneration != _loadGeneration)
|
||
{
|
||
_heldEstablishments[msg.AlarmId] = msg.Established;
|
||
return;
|
||
}
|
||
|
||
SendEstablishment(msg.AlarmId, msg.Established);
|
||
}
|
||
|
||
/// <summary>Same actor → publish-actor chain as the <see cref="OpcUaPublishActor.AlarmStateUpdate"/>s, so the mark is
|
||
/// applied after every projection this host sent before it (F2). Scripted conditions live in the UNS realm.</summary>
|
||
private void SendEstablishment(string alarmId, bool established) =>
|
||
_publishActor.Tell(new OpcUaPublishActor.MarkConditionsKnown(
|
||
OpcUaPublishActor.ScriptedSource, [alarmId], AddressSpaceRealm.Uns, established));
|
||
|
||
/// <summary>
|
||
/// re-project every loaded alarm that is NOT in the Part 9 "no-event" position back onto
|
||
/// its condition node, right after a (re)load.
|
||
///
|
||
/// <para>
|
||
/// <b>The bug this closes.</b> A deploy that triggers a FULL address-space rebuild clears
|
||
/// <c>_alarmConditions</c> and re-materialises every condition node fresh — inactive, acked,
|
||
/// confirmed, unshelved. The engine, meanwhile, restores each alarm's persisted state and
|
||
/// re-derives Active from the predicate, so a still-active alarm ends the reload
|
||
/// <i>correctly Active in the engine</i> but produces <see cref="EmissionKind.None"/> (there
|
||
/// is no transition to report) — and <see cref="OnEngineEmission"/> drops None. Nothing then
|
||
/// writes the node, so an active alarm with static dependencies reads NORMAL to every OPC UA
|
||
/// client until its next real transition, which may never come. Same shape as the VirtualTag
|
||
/// redeploy-reset the <c>ReassertValue</c> fix closed.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Node-only, by construction.</b> This sends <see cref="OpcUaPublishActor.AlarmStateUpdate"/>
|
||
/// and nothing else — it never publishes to the <c>alerts</c> topic and never touches the
|
||
/// telemetry hub. That is the whole reason it reads <see cref="ScriptedAlarmEngine.GetProjections"/>
|
||
/// (a plain read returning <see cref="ScriptedAlarmProjection"/>) rather than re-emitting: an
|
||
/// <c>alerts</c> row per alarm per deploy would append a duplicate historian / AVEVA record
|
||
/// every time anyone deploys — the alarm analogue of the VirtualTag historian issue.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Ordering.</b> <c>DriverHostActor</c> Tells <c>RebuildAddressSpace</c> to the publish
|
||
/// actor BEFORE it Tells <see cref="ApplyScriptedAlarms"/> here, and this runs later still —
|
||
/// after an <c>await</c>ed <see cref="ScriptedAlarmEngine.LoadAsync"/> pipes back. Both Tells
|
||
/// enqueue synchronously into the publish actor's local mailbox, so the re-materialise is
|
||
/// already queued ahead of these writes: the node exists by the time they are handled.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Why only non-normal alarms.</b> An alarm sitting in the no-event position already
|
||
/// matches what the materialise just built, so writing it would be a pure no-op on state —
|
||
/// but it would still overwrite the node's Message (the materialise seeds it with the alarm's
|
||
/// display name; a projection carries the resolved template). Skipping them keeps a
|
||
/// never-fired alarm byte-identical to a deploy without this pass, and keeps the write count
|
||
/// at zero on the overwhelmingly common all-normal deploy.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Duplicate events.</b> None. <c>WriteAlarmCondition</c>'s delta-gate compares the
|
||
/// incoming snapshot against the node's CURRENT state, so a re-assert onto a freshly
|
||
/// materialised (normal) node is a genuine delta and fires one Part 9 event — correct, since
|
||
/// the rebuild reset what clients see — while a re-assert onto a surgically-preserved node
|
||
/// that already holds the same state is suppressed. This write is ungated by redundancy role,
|
||
/// like every other node write here: the Secondary keeps its address space warm for failover.
|
||
/// </para>
|
||
/// </summary>
|
||
private void ReassertConditionNodes()
|
||
{
|
||
var reasserted = 0;
|
||
foreach (var projection in _engine.GetProjections())
|
||
{
|
||
if (IsInNoEventPosition(projection.Condition))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
_publishActor.Tell(new OpcUaPublishActor.AlarmStateUpdate(
|
||
AlarmNodeId: projection.AlarmId,
|
||
State: ToSnapshot(projection),
|
||
// The instant the state we are re-asserting actually came about — NOT the deploy time.
|
||
// A client reading Time/ReceiveTime after a rebuild should still see when the alarm went
|
||
// active, not when the address space happened to be rebuilt.
|
||
TimestampUtc: projection.Condition.LastTransitionUtc,
|
||
Realm: AddressSpaceRealm.Uns,
|
||
Source: OpcUaPublishActor.ScriptedSource));
|
||
reasserted++;
|
||
}
|
||
|
||
if (reasserted > 0)
|
||
{
|
||
_log.Info("ScriptedAlarmHost: re-asserted {Count} non-normal condition node(s) after (re)load", reasserted);
|
||
}
|
||
}
|
||
|
||
/// <summary>Whether <paramref name="condition"/> sits in the Part 9 "no-event" position — exactly the
|
||
/// state <see cref="AlarmConditionState.Fresh"/> produces and a freshly materialised condition node
|
||
/// already carries. Anything else (active, unacknowledged, unconfirmed, disabled, or shelved) is state
|
||
/// a rebuild would silently lose, so it is what <see cref="ReassertConditionNodes"/> re-projects.</summary>
|
||
/// <param name="condition">The engine's current condition state.</param>
|
||
/// <returns><c>true</c> when the condition carries nothing a rebuild could lose.</returns>
|
||
private static bool IsInNoEventPosition(AlarmConditionState condition)
|
||
=> condition.Enabled == AlarmEnabledState.Enabled
|
||
&& condition.Active == AlarmActiveState.Inactive
|
||
&& condition.Acked == AlarmAckedState.Acknowledged
|
||
&& condition.Confirmed == AlarmConfirmedState.Confirmed
|
||
&& condition.Shelving.Kind == ShelvingKind.Unshelved;
|
||
|
||
private void OnDependencyChanged(VirtualTagActor.DependencyValueChanged msg)
|
||
{
|
||
// Feed the live value into the upstream the engine subscribes from. Carry the source
|
||
// driver's quality (mapped to an OPC UA StatusCode) so the engine can derive a scripted
|
||
// condition's worst-of-input quality; a Bad/Uncertain input is no longer silently treated as Good.
|
||
// the status code rides through verbatim. This used to convert the incoming value onto a
|
||
// 3-state enum and straight back again through a pair of mutually-inverse mappers, which is where
|
||
// the input's sub-code was lost before the engine ever cached it.
|
||
var snapshot = new DataValueSnapshot(msg.Value, msg.StatusCode, msg.TimestampUtc, msg.TimestampUtc);
|
||
if (msg.PublicationProof is { } proof) _upstream.Push(msg.TagId, snapshot, proof);
|
||
else _upstream.Push(msg.TagId, snapshot);
|
||
}
|
||
|
||
/// <summary>One batched mux delivery — every item already matched this host's registered interest.
|
||
/// Loops the per-value handler, preserving in-burst order.</summary>
|
||
/// <remarks>
|
||
/// <b>Mid-batch exception policy: unguarded, deliberately.</b> An exception escaping
|
||
/// <see cref="OnDependencyChanged"/> drops the remaining items of this burst and restarts the actor.
|
||
/// That IS wider than the per-message path — Akka restarts do not flush the mailbox, only the
|
||
/// failing message is dropped, so as N separate messages the same fault would cost one value rather
|
||
/// than the burst's tail. Accepted: the engine tolerates a missed intermediate value (the next
|
||
/// delivery for that tag re-converges its state). Catching per item is deliberately NOT done: the
|
||
/// handler is a single
|
||
/// <c>IUpstreamValueSource.Push</c> into an in-memory cache, so a throw means the upstream itself is
|
||
/// broken and swallowing it would feed the engine a silently truncated burst. Contrast
|
||
/// <c>ContinuousHistorizationRecorder.IngestAsync</c>, which DOES catch per item because its
|
||
/// per-item step runs value coercion.
|
||
/// </remarks>
|
||
/// <param name="msg">The batch of matched dependency values.</param>
|
||
private void OnDependencyBatch(VirtualTagActor.DependencyValueBatch msg)
|
||
{
|
||
var items = msg.Items;
|
||
for (var i = 0; i < items.Count; i++)
|
||
{
|
||
OnDependencyChanged(items[i]);
|
||
}
|
||
}
|
||
|
||
private void OnEngineEmission(EngineEmission msg)
|
||
{
|
||
var e = msg.Event;
|
||
if (e.InputEvidence is { } evidence)
|
||
{
|
||
try { if (!evidence.IsValid) return; }
|
||
catch (Exception) { return; }
|
||
}
|
||
|
||
// None = no meaningful change; Suppressed = shelving ate the emission. Neither should reach a
|
||
// sink. (The engine already filters these out of BuildEmission, but guard defensively.)
|
||
if (e.Emission is EmissionKind.None or EmissionKind.Suppressed)
|
||
{
|
||
return;
|
||
}
|
||
|
||
// QualityChanged is a source-quality annotation (worst-of-input bucket moved with no Part 9
|
||
// state transition — e.g. an input went Bad, freezing the condition). Route it to the dedicated
|
||
// WriteAlarmQuality node path (sets ONLY Quality, one Part 9 event on a bucket change): NO full-state
|
||
// projection (would clobber severity/message) and NO /alerts row (it is not a state transition, so it
|
||
// must not historize). Same out-of-band quality path native comms-loss uses.
|
||
if (e.Emission == EmissionKind.QualityChanged)
|
||
{
|
||
_publishActor.Tell(new OpcUaPublishActor.AlarmQualityUpdate(
|
||
AlarmNodeId: e.AlarmId,
|
||
StatusCode: e.WorstInputStatusCode,
|
||
TimestampUtc: e.TimestampUtc,
|
||
Realm: AddressSpaceRealm.Uns));
|
||
return;
|
||
}
|
||
|
||
// Bridge to OPC UA: project the FULL Part 9 condition state (enabled/active/acked/confirmed/
|
||
// shelving/severity/message) onto the materialised condition node via the Commons snapshot.
|
||
// e.AlarmId is the materialised condition's NodeId (T14 aligned it to the ScriptedAlarmId).
|
||
// Scripted alarms are per-equipment condition nodes in the UNS realm.
|
||
_publishActor.Tell(new OpcUaPublishActor.AlarmStateUpdate(
|
||
AlarmNodeId: e.AlarmId,
|
||
State: ToSnapshot(e),
|
||
TimestampUtc: e.TimestampUtc,
|
||
Realm: AddressSpaceRealm.Uns,
|
||
Source: OpcUaPublishActor.ScriptedSource));
|
||
|
||
// Publish the transition to the cluster `alerts` topic — the single historization + live
|
||
// fan-out path. The mediator was cached on the ACTOR thread in PreStart; we only Tell it here.
|
||
var evt = new AlarmTransitionEvent(
|
||
AlarmId: e.AlarmId,
|
||
EquipmentPath: e.EquipmentPath,
|
||
AlarmName: e.AlarmName,
|
||
TransitionKind: e.Emission.ToString(),
|
||
Severity: SeverityToInt(e.Severity),
|
||
Message: e.Message,
|
||
User: TransitionUser(e),
|
||
TimestampUtc: e.TimestampUtc,
|
||
// Historian feed prep: carry the Part-9 subtype name (e.Kind.ToString() yields
|
||
// LimitAlarm/DiscreteAlarm/OffNormalAlarm/AlarmCondition) + any operator comment.
|
||
AlarmTypeName: e.Kind.ToString(),
|
||
Comment: e.Comment,
|
||
// Per-alarm DURABLE-historization opt-out — honored downstream by HistorianAdapterActor to
|
||
// suppress only the sink write. This publish (and the live `/alerts` fan-out) is NOT gated on it.
|
||
HistorizeToAveva: e.HistorizeToAveva);
|
||
|
||
// Warm-standby dedup: only the Primary publishes the cluster-wide transition (archreview 03/S4 —
|
||
// same PrimaryGatePolicy as DriverHostActor). A KNOWN Secondary/Detached is denied; an UNKNOWN role
|
||
// default-emits on a single-driver cluster but default-DENIES on a multi-driver one (so the
|
||
// dual-primary boot window can't historize duplicate AVEVA alarm rows). The OPC UA node write above +
|
||
// inbound command processing stay ungated (the secondary keeps its state warm for failover).
|
||
if (!PrimaryGatePolicy.ShouldServiceAsPrimary(_localRole, DriverMemberCount()))
|
||
{
|
||
OtOpcUaTelemetry.PrimaryGateDenied.Add(1,
|
||
new KeyValuePair<string, object?>("site", "alarm-emit"),
|
||
new KeyValuePair<string, object?>("reason", _localRole switch
|
||
{
|
||
RedundancyRole.Secondary => "secondary",
|
||
RedundancyRole.Detached => "detached",
|
||
_ => "role-unknown",
|
||
}));
|
||
return;
|
||
}
|
||
|
||
_mediator.Tell(new Publish(AlertsTopic, evt));
|
||
// Phase 5: fan the same transition into the node-local live-telemetry hub (no-op until a gRPC
|
||
// client subscribes). The DPS publish above is unchanged — a strictly additive tap, and it rides
|
||
// the same Primary gate as the publish (only the Primary reaches this line).
|
||
_telemetryHub?.Emit(new TelemetryItem.Alarm(evt));
|
||
}
|
||
|
||
/// <summary>Count of Up cluster members carrying the <c>driver</c> role, for the alerts-emit gate. Uses
|
||
/// the injected test seam when present; otherwise reads the live cluster state guarded by try/catch so a
|
||
/// non-cluster ActorRefProvider yields 0 ⇒ the single-node default-emit posture (archreview 03/S4).</summary>
|
||
/// <returns>The number of Up driver-role members, or 0 when the cluster extension is unavailable.</returns>
|
||
private int DriverMemberCount()
|
||
{
|
||
if (_driverMemberCountProvider is not null) return _driverMemberCountProvider();
|
||
try
|
||
{
|
||
// GossipedRolesHave, not ordinal Contains — a peer gossiping a miscased
|
||
// 'Driver' (rolling-upgrade window) must still count toward the alerts-emit gate.
|
||
return Akka.Cluster.Cluster.Get(Context.System).State.Members
|
||
.Count(m => m.Status == Akka.Cluster.MemberStatus.Up
|
||
&& RoleParser.GossipedRolesHave(m.Roles, ServiceCollectionExtensions.DriverRole));
|
||
}
|
||
catch (Exception)
|
||
{
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
/// <summary>Caches this node's <see cref="RedundancyRole"/> from a cluster redundancy snapshot so
|
||
/// <see cref="OnEngineEmission"/> can gate the cluster-wide <c>alerts</c> publish to the Primary. A
|
||
/// snapshot that doesn't mention <see cref="_localNode"/> (or no local node wired) leaves the cached
|
||
/// role unchanged ⇒ default-emit. Mirrors <see cref="OpcUaPublishActor"/>'s handler.</summary>
|
||
/// <param name="msg">The cluster redundancy snapshot.</param>
|
||
private void OnRedundancyStateChanged(RedundancyStateChanged msg)
|
||
{
|
||
if (_localNode is null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
var local = msg.Nodes.FirstOrDefault(n => n.NodeId == _localNode.Value);
|
||
if (local is not null)
|
||
{
|
||
_localRole = local.Role;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Drives an inbound OPC UA Part 9 alarm method call (delivered as an <see cref="AlarmCommand"/>
|
||
/// on the cluster <c>alarm-commands</c> topic) onto the matching <see cref="ScriptedAlarmEngine"/>
|
||
/// operation.
|
||
///
|
||
/// <para>
|
||
/// <b>Ownership filter.</b> The topic is a cluster-wide broadcast; every host node receives
|
||
/// every command, but each owns a disjoint subset of alarms (its engine's loaded set). A
|
||
/// command for an alarm this engine does NOT own is a no-op — the owning node will act on it.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>No re-projection.</b> The engine op raises <see cref="ScriptedAlarmEngine.OnEvent"/> on
|
||
/// success, which already marshals back to <see cref="OnEngineEmission"/> and re-projects the
|
||
/// condition to the OPC UA node + the alerts topic. So this handler just calls the op and
|
||
/// awaits; it never touches the publish actor directly.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Async on the actor thread.</b> The handler is a <c>Task</c>-returning
|
||
/// <c>ReceiveAsync</c> (this project's AK2003 analyzer forbids an async-void Receive
|
||
/// delegate). Akka suspends the actor's mailbox until the returned task completes, so the op
|
||
/// runs ordered + awaited on the actor thread — never overlapping the next message. The engine
|
||
/// also serialises every operation behind its own <c>_evalGate</c> and marshals every emission
|
||
/// back via <c>Self.Tell</c> (never touching <see cref="Context"/> off-thread). The whole body
|
||
/// is wrapped in a try/catch so a faulting op can never escape the handler and fault the actor
|
||
/// — failures are logged like <see cref="OnLoadFailed"/> and swallowed.
|
||
/// </para>
|
||
/// </summary>
|
||
/// <param name="cmd">The inbound alarm command.</param>
|
||
private async Task OnAlarmCommand(AlarmCommand cmd)
|
||
{
|
||
// #937: the broadcast copy of a command this host already took through ExecuteAlarmCommand (or the other way
|
||
// round) is applied once.
|
||
if (cmd.CommandId is { } id && _recentCommands.ContainsKey(id))
|
||
{
|
||
_log.Debug("ScriptedAlarmHost: skipping duplicate AlarmCommand {Op} for {AlarmId} (command {CommandId})",
|
||
cmd.Operation, cmd.AlarmId, id);
|
||
return;
|
||
}
|
||
|
||
// Ownership filter FIRST: ignore commands for alarms this engine doesn't own. The topic is a
|
||
// cluster-wide broadcast, so the same command lands on every host — only the owner acts.
|
||
if (!Owns(cmd.AlarmId))
|
||
{
|
||
_log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}",
|
||
cmd.Operation, cmd.AlarmId);
|
||
return;
|
||
}
|
||
|
||
Remember(cmd, await ApplyCommandAsync(cmd));
|
||
}
|
||
|
||
/// <summary>
|
||
/// #937: the node-local ask behind an OPC UA Part 9 method. Applies the command exactly as
|
||
/// <see cref="OnAlarmCommand"/> does (once — a broadcast copy that already arrived is not re-applied; its recorded
|
||
/// outcome is the answer) and replies the verdict to the sender. Unlike the broadcast, an alarm this host does not
|
||
/// own is answered (<see cref="AlarmCommandVerdict.NotApplied"/>): the caller's condition node is on this node.
|
||
/// </summary>
|
||
private async Task OnExecuteAlarmCommand(ExecuteAlarmCommand msg)
|
||
{
|
||
var replyTo = Sender;
|
||
var cmd = msg.Command;
|
||
if (cmd.CommandId is { } id && _recentCommands.TryGetValue(id, out var known))
|
||
{
|
||
replyTo.Tell(known);
|
||
return;
|
||
}
|
||
|
||
var outcome = Owns(cmd.AlarmId)
|
||
? await ApplyCommandAsync(cmd)
|
||
: new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
|
||
_readiness?.Refusal() ?? NotLoadedRefusal);
|
||
|
||
Remember(cmd, outcome);
|
||
replyTo.Tell(outcome);
|
||
}
|
||
|
||
private const string NotYetLoadedRefusal =
|
||
"This server's scripted-alarm engine has not completed loading its configuration yet; the command was not applied.";
|
||
|
||
private const string NotLoadedRefusal =
|
||
"The alarm is not loaded by this server's scripted-alarm engine; the command was not applied.";
|
||
|
||
/// <summary>Whether this host owns <paramref name="alarmId"/>: in the latest plan (stable across a load in flight and
|
||
/// a failed load's half-built set) or loaded by the engine (a legacy, externally loaded engine).</summary>
|
||
private bool Owns(string alarmId) => _plannedAlarmIds.Contains(alarmId) || _engine.LoadedAlarmIds.Contains(alarmId);
|
||
|
||
private void Remember(AlarmCommand cmd, AlarmCommandOutcome outcome)
|
||
{
|
||
if (cmd.CommandId is not { } id || !_recentCommands.TryAdd(id, outcome)) return;
|
||
_recentCommandOrder.Enqueue(id);
|
||
while (_recentCommandOrder.Count > RecentCommandCapacity) _recentCommands.Remove(_recentCommandOrder.Dequeue());
|
||
}
|
||
|
||
/// <summary>
|
||
/// Runs one owned command against the engine and classifies the result (#937). Never throws: every failure is
|
||
/// logged like <see cref="OnLoadFailed"/> and becomes a verdict.
|
||
/// </summary>
|
||
private async Task<AlarmCommandOutcome> ApplyCommandAsync(AlarmCommand cmd)
|
||
{
|
||
AlarmCommandOutcome Refused(string reason) => new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, reason);
|
||
|
||
// Bounded (R02:H3): every op ends in IAlarmStateStore.SaveAsync (LocalDb/SQLite), and this is a
|
||
// ReceiveAsync — the mailbox is suspended until the op returns, so an unbounded await on a hung
|
||
// file lock stalled dependency-value ingestion for the duration. Linked to the actor's lifetime
|
||
// token so a stop still cancels promptly.
|
||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token);
|
||
cts.CancelAfter(_commandTimeout);
|
||
var ct = cts.Token;
|
||
try
|
||
{
|
||
switch (cmd.Operation)
|
||
{
|
||
case "Acknowledge":
|
||
await _engine.AcknowledgeAsync(cmd.AlarmId, cmd.User, cmd.Comment, ct);
|
||
break;
|
||
case "Confirm":
|
||
await _engine.ConfirmAsync(cmd.AlarmId, cmd.User, cmd.Comment, ct);
|
||
break;
|
||
case "OneShotShelve":
|
||
await _engine.OneShotShelveAsync(cmd.AlarmId, cmd.User, ct);
|
||
break;
|
||
case "TimedShelve":
|
||
// A timed shelve needs the absolute unshelve instant. T18 derives it from the OPC UA
|
||
// Duration (UtcNow + shelvingTime); a command missing it is malformed — log + reject
|
||
// rather than throw (a fault escaping the async Task would trigger a supervision restart).
|
||
if (cmd.UnshelveAtUtc is not { } unshelveAt)
|
||
{
|
||
_log.Warning("ScriptedAlarmHost: rejecting TimedShelve for {AlarmId} — missing UnshelveAtUtc",
|
||
cmd.AlarmId);
|
||
return Refused("TimedShelve requires an unshelve time; the command was not applied.");
|
||
}
|
||
await _engine.TimedShelveAsync(cmd.AlarmId, cmd.User, unshelveAt, ct);
|
||
break;
|
||
case "Unshelve":
|
||
await _engine.UnshelveAsync(cmd.AlarmId, cmd.User, ct);
|
||
break;
|
||
case "Enable":
|
||
await _engine.EnableAsync(cmd.AlarmId, cmd.User, ct);
|
||
break;
|
||
case "Disable":
|
||
await _engine.DisableAsync(cmd.AlarmId, cmd.User, ct);
|
||
break;
|
||
case "AddComment":
|
||
if (string.IsNullOrWhiteSpace(cmd.Comment))
|
||
{
|
||
_log.Warning("ScriptedAlarmHost: rejecting AddComment for {AlarmId} — empty comment text", cmd.AlarmId);
|
||
return Refused("AddComment requires comment text; the command was not applied.");
|
||
}
|
||
await _engine.AddCommentAsync(cmd.AlarmId, cmd.User, cmd.Comment, ct);
|
||
break;
|
||
default:
|
||
_log.Warning("ScriptedAlarmHost: ignoring AlarmCommand with unknown operation {Op} for {AlarmId}",
|
||
cmd.Operation, cmd.AlarmId);
|
||
return Refused($"Unknown alarm operation '{cmd.Operation}'; the command was not applied.");
|
||
}
|
||
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied);
|
||
}
|
||
catch (OperationCanceledException) when (!_cts.IsCancellationRequested)
|
||
{
|
||
// The op may have been cancelled inside SaveAsync after the store committed: unknown, never "not applied".
|
||
_log.Warning("ScriptedAlarmHost: engine op {Op} for alarm {AlarmId} timed out after {Timeout} — the condition-state store is stalled",
|
||
cmd.Operation, cmd.AlarmId, _commandTimeout);
|
||
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
|
||
$"OutcomeUnknown: the alarm engine did not finish the command within {_commandTimeout.TotalSeconds:0.#} s.", TimedOut: true);
|
||
}
|
||
catch (ScriptedAlarmCommandRejectedException ex)
|
||
{
|
||
// #935 review S3: the last LoadAsync failed, so the engine holds no trusted state and refuses the
|
||
// command (thrown before anything is saved) rather than persist one derived from a Fresh seed. #937: a
|
||
// directly-asked command reports this to its OPC UA caller; a broadcast-only copy (the AdminUI, the
|
||
// redundant peer's copy) has only this Warning. The next successful deploy re-asserts the node from the store.
|
||
_log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} NOT applied — {Reason}",
|
||
cmd.Operation, cmd.AlarmId, ex.Message);
|
||
// Before the first load completes there is no failure to name (the readiness view is clear then).
|
||
return Refused(_readiness?.Refusal() ?? (_loadedGeneration == 0 && _readiness is not null ? NotYetLoadedRefusal
|
||
: ScriptedAlarmCommandReadinessView.LoadFailedRefusal));
|
||
}
|
||
catch (ArgumentException ex)
|
||
{
|
||
// The engine's lookup (under its gate, before any save): the alarm is not in the generation the command
|
||
// ran against — e.g. the deploy queued ahead of it removed the alarm.
|
||
_log.Warning(ex, "ScriptedAlarmHost: engine op {Op} refused for alarm {AlarmId}", cmd.Operation, cmd.AlarmId);
|
||
return Refused(NotLoadedRefusal);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
// A failing engine op must not crash the actor — mirror OnLoadFailed's log-and-stay-inert style. A store
|
||
// fault may have left the row written, so this is unknown, not a refusal.
|
||
_log.Warning(ex, "ScriptedAlarmHost: engine op {Op} failed for alarm {AlarmId}",
|
||
cmd.Operation, cmd.AlarmId);
|
||
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
|
||
"OutcomeUnknown: the alarm engine failed while applying the command.");
|
||
}
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
protected override void PreStart()
|
||
{
|
||
// Resolve the cluster DPS mediator once, on the actor thread, so emissions only Tell it.
|
||
_mediator = DistributedPubSub.Get(Context.System).Mediator;
|
||
// Subscribe to the `alarm-commands` topic so inbound OPC UA Part 9 method calls (published by
|
||
// the node manager's condition handlers, T18) land here as AlarmCommands. The Subscribe is sent
|
||
// from Self so the SubscribeAck returns to this actor (handled as a no-op in the ctor wiring).
|
||
_mediator.Tell(new Subscribe(AlarmCommandsTopic, Self));
|
||
// Also subscribe to the `redundancy-state` topic so cluster role changes land as
|
||
// RedundancyStateChanged and cache this node's role — OnEngineEmission gates the cluster-wide
|
||
// alerts publish to the Primary so a 2-node single-cluster deploy doesn't double-emit transitions.
|
||
_mediator.Tell(new Subscribe(OpcUaPublishActor.RedundancyStateTopic, Self));
|
||
|
||
// Per-cluster mesh Phase 2 dark switch. An AdminUI-originated ack/shelve arrives from
|
||
// NodeCommunicationActor on the node-local EventStream under
|
||
// MeshTransport:Mode = Grpc; the DPS subscribe above still carries the node-LOCAL
|
||
// publisher (OtOpcUaServerHostedService, the OPC UA Part 9 method calls), which never
|
||
// crosses the boundary and stays on DPS in both modes. Subscribing to both is safe: exactly
|
||
// one publisher feeds each path.
|
||
Context.System.EventStream.Subscribe(Self, typeof(AlarmCommand));
|
||
|
||
base.PreStart();
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
/// <remarks>Akka's default <c>PreRestart</c> stops the children and calls <see cref="PostStop"/>. The flag
|
||
/// lets that <see cref="PostStop"/> keep a legacy (Props-captured) engine alive for the next incarnation
|
||
/// instead of disposing the instance it is about to be re-created around.</remarks>
|
||
protected override void PreRestart(Exception reason, object message)
|
||
{
|
||
_restarting = true;
|
||
base.PreRestart(reason, message);
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
/// <remarks>Tells the parent <see cref="ScriptedAlarmHostRestarted"/> so it re-sends the last
|
||
/// <see cref="ApplyScriptedAlarms"/>: the new incarnation has nothing loaded and no mux interest.</remarks>
|
||
protected override void PostRestart(Exception reason)
|
||
{
|
||
base.PostRestart(reason);
|
||
Context.Parent.Tell(ScriptedAlarmHostRestarted.Instance);
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
protected override void PostStop()
|
||
{
|
||
// Unregister mux interest first so no further DependencyValueChanged arrives while we tear down.
|
||
_mux?.Tell(new DependencyMuxActor.UnregisterInterest(Self));
|
||
// Cancel any in-flight LoadAsync, detach the OnEvent handler (so a late engine emission can't
|
||
// Tell a stopping actor), then dispose the engine (which drains its background work + clears) —
|
||
// unless this is a RESTART around a legacy Props-captured engine, which the next incarnation will
|
||
// re-attach to (R02:H1).
|
||
_cts.Cancel();
|
||
_engine.OnEvent -= _onEngineEvent;
|
||
_engine.OnInputsEstablished -= _onInputsEstablished;
|
||
if (_ownsEngine || !_restarting) _engine.Dispose();
|
||
_cts.Dispose();
|
||
// #937: this engine's load outcome describes nothing once it is gone (the ask path answers for a missing host).
|
||
_readiness?.Reset();
|
||
base.PostStop();
|
||
}
|
||
|
||
/// <summary>Maps an <see cref="EquipmentScriptedAlarmPlan"/> to the engine's
|
||
/// <see cref="ScriptedAlarmDefinition"/>. <see cref="EquipmentScriptedAlarmPlan.AlarmType"/> is a
|
||
/// string that must parse to a defined <see cref="AlarmKind"/> NAME; an unrecognised type — including
|
||
/// a numeric string like "5" or "-1", which <see cref="Enum.TryParse{TEnum}(string, out TEnum)"/>
|
||
/// would otherwise accept as an undefined value — falls back to <see cref="AlarmKind.AlarmCondition"/>
|
||
/// rather than dropping the alarm.</summary>
|
||
private static ScriptedAlarmDefinition ToDefinition(EquipmentScriptedAlarmPlan p) => new(
|
||
AlarmId: p.ScriptedAlarmId,
|
||
EquipmentPath: p.EquipmentId,
|
||
AlarmName: p.Name,
|
||
Kind: Enum.TryParse<AlarmKind>(p.AlarmType, out var k) && Enum.IsDefined(k) ? k : AlarmKind.AlarmCondition,
|
||
Severity: SeverityFromInt(p.Severity),
|
||
MessageTemplate: p.MessageTemplate,
|
||
PredicateScriptSource: p.PredicateSource,
|
||
HistorizeToAveva: p.HistorizeToAveva,
|
||
Retain: p.Retain);
|
||
|
||
/// <summary>Maps a <see cref="ScriptedAlarmEvent"/>'s Core <see cref="AlarmConditionState"/> +
|
||
/// severity/message down to the Commons <see cref="AlarmConditionSnapshot"/> the SDK sink projects.
|
||
/// Severity is the OPC UA 1..1000 value <see cref="SeverityToInt"/> derives from the coarse engine
|
||
/// bucket, cast to the <c>ushort</c> the SDK <c>SetSeverity</c> expects. Shelving's 3-way Core kind
|
||
/// maps 1:1 onto the Commons <see cref="AlarmShelvingKind"/>.</summary>
|
||
private static AlarmConditionSnapshot ToSnapshot(ScriptedAlarmEvent e)
|
||
=> ToSnapshot(e.Condition, e.Severity, e.Message, e.WorstInputStatusCode);
|
||
|
||
/// <summary>The same projection for a <see cref="ScriptedAlarmProjection"/>: a state READ used
|
||
/// to restore a condition node after a rebuild, never an emission. Shares
|
||
/// <see cref="ToSnapshot(AlarmConditionState, AlarmSeverity, string, uint)"/> with the transition path
|
||
/// so a re-asserted node is byte-identical to what the alarm's own transition would have written.</summary>
|
||
/// <param name="p">The engine projection to map.</param>
|
||
/// <returns>The Commons snapshot the SDK sink projects onto the condition node.</returns>
|
||
private static AlarmConditionSnapshot ToSnapshot(ScriptedAlarmProjection p)
|
||
=> ToSnapshot(p.Condition, p.Severity, p.Message, p.WorstInputStatusCode);
|
||
|
||
/// <summary>The single Core → Commons condition projection, shared by the emission and re-assert
|
||
/// paths.</summary>
|
||
/// <param name="condition">The Part 9 condition state.</param>
|
||
/// <param name="severity">The engine's coarse severity bucket.</param>
|
||
/// <param name="message">The resolved condition message.</param>
|
||
/// <param name="worstInputStatusCode">The worst OPC UA StatusCode across the script's input tags.</param>
|
||
/// <returns>The Commons snapshot the SDK sink projects onto the condition node.</returns>
|
||
private static AlarmConditionSnapshot ToSnapshot(
|
||
AlarmConditionState condition, AlarmSeverity severity, string message, uint worstInputStatusCode) => new(
|
||
Active: condition.Active == AlarmActiveState.Active,
|
||
Acknowledged: condition.Acked == AlarmAckedState.Acknowledged,
|
||
Confirmed: condition.Confirmed == AlarmConfirmedState.Confirmed,
|
||
Enabled: condition.Enabled == AlarmEnabledState.Enabled,
|
||
Shelving: MapShelving(condition.Shelving.Kind),
|
||
Severity: (ushort)SeverityToInt(severity),
|
||
Message: message,
|
||
// the condition's status is the worst status across the script's input tags at evaluation
|
||
// time (carried on the event by the engine). A transition fired while an input is Uncertain projects
|
||
// Uncertain here so the full-snapshot write doesn't clobber quality back to Good.
|
||
StatusCode: worstInputStatusCode,
|
||
// the engine's own expiry, so the node's UnshelveTime counts down to it.
|
||
UnshelveAtUtc: condition.Shelving.Kind == ShelvingKind.Timed ? condition.Shelving.UnshelveAtUtc : null);
|
||
|
||
/// <summary>Maps the Core <see cref="ShelvingKind"/> onto the Commons <see cref="AlarmShelvingKind"/>
|
||
/// mirror (the Commons assembly can't see the Core enum).</summary>
|
||
private static AlarmShelvingKind MapShelving(ShelvingKind kind) => kind switch
|
||
{
|
||
ShelvingKind.OneShot => AlarmShelvingKind.OneShot,
|
||
ShelvingKind.Timed => AlarmShelvingKind.Timed,
|
||
_ => AlarmShelvingKind.Unshelved,
|
||
};
|
||
|
||
/// <summary>The acting user for an <see cref="AlarmTransitionEvent"/>. Engine-driven
|
||
/// Activated / Cleared transitions are <c>"system"</c>; operator Acknowledged / Confirmed carry the
|
||
/// recorded user from the condition state, falling back to <c>"system"</c> when none was recorded.
|
||
/// CommentAdded carries the commenter's identity from the last entry in
|
||
/// <see cref="AlarmConditionState.Comments"/>.</summary>
|
||
private static string TransitionUser(ScriptedAlarmEvent e) => e.Emission switch
|
||
{
|
||
EmissionKind.Acknowledged => e.Condition.LastAckUser ?? "system",
|
||
EmissionKind.Confirmed => e.Condition.LastConfirmUser ?? "system",
|
||
// Shelve / unshelve / enable / disable / comment ops each append the acting user as the LAST audit
|
||
// entry on the emitted condition (engine auto-unshelve appends "system"); read it from there.
|
||
EmissionKind.CommentAdded
|
||
or EmissionKind.Shelved
|
||
or EmissionKind.Unshelved
|
||
or EmissionKind.Enabled
|
||
or EmissionKind.Disabled => e.Condition.Comments.Count > 0 ? e.Condition.Comments[^1].User : "system",
|
||
_ => "system",
|
||
};
|
||
|
||
// Severity conversion convention: the engine + plan disagree on type (engine = AlarmSeverity enum,
|
||
// plan + AlarmTransitionEvent = OPC UA 1–1000 int). We bucket the int into quartiles on the way IN
|
||
// and emit the quartile ceiling on the way OUT, so a round-trip is stable within a bucket.
|
||
|
||
/// <summary>Buckets an OPC UA 1–1000 severity into the engine's coarse <see cref="AlarmSeverity"/>
|
||
/// enum: ≤250 Low, ≤500 Medium, ≤750 High, else Critical.</summary>
|
||
private static AlarmSeverity SeverityFromInt(int s) =>
|
||
s <= 250 ? AlarmSeverity.Low
|
||
: s <= 500 ? AlarmSeverity.Medium
|
||
: s <= 750 ? AlarmSeverity.High
|
||
: AlarmSeverity.Critical;
|
||
|
||
/// <summary>Maps the engine's coarse <see cref="AlarmSeverity"/> back to an OPC UA 1–1000 severity
|
||
/// at each bucket's ceiling: Low=250, Medium=500, High=750, Critical=1000.</summary>
|
||
private static int SeverityToInt(AlarmSeverity s) => s switch
|
||
{
|
||
AlarmSeverity.Low => 250,
|
||
AlarmSeverity.Medium => 500,
|
||
AlarmSeverity.High => 750,
|
||
AlarmSeverity.Critical => 1000,
|
||
_ => 500,
|
||
};
|
||
}
|