fix(alarms): AdminUI /alerts ack/shelve reports the scripted engine's verdict (#950)

The /alerts buttons went central->node fire-and-forget and always showed
"Ack sent". AdminOperationsActor now spawns a per-request
AlarmCommandVerdictCollector (7 s window, under the client's 10 s ask) that
sends the command with AlarmCommand.VerdictRequested and gathers each node's
answer, finishing early once every node it sent to has answered.

- gRPC plane: CentralCommunicationActor tells the collector the dialled
  ClusterNode set and one verdict per node. A node handles a
  verdict_requested AlarmCommandMessage by asking its driver host
  (ScriptedAlarmHostActor.ExecuteAlarmCommand, the #937 path, no ask deadline,
  bounded 5 s) and returns it in the ADDITIVE ExecuteAck.alarm_verdict.
  Transport failure / timeout / empty ack (pre-#950 node) => that node unknown.
- DPS: published with the collector as sender; each ScriptedAlarmHostActor
  answers (non-owners NotOwned); expected set = Up driver members.
- Aggregation: any owner applied => Applied (partial noted); else any
  unknown/silent node => Outcome unknown (never "refused"); else owner
  refusal => Refused: <reason>; else no owner => Not applied.
- UI: green Applied / red Refused (reason) / amber Outcome unknown, per-node
  detail in the details pane; a verdict-less reply (validation, server fault,
  pre-#950 singleton) renders as before.

Wire is back-compatible both ways (new proto fields only; VerdictRequested and
NotOwned default false). Real-wire test through the real router, dialer,
interceptor and NodeCommandGrpcService (red without the node change).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-01 19:45:17 -05:00
parent 6b60845931
commit 09aaabbeef
28 changed files with 1451 additions and 72 deletions
@@ -21,10 +21,17 @@ public sealed record AcknowledgeAlarmCommand(
CorrelationId CorrelationId);
/// <summary>Reply for <see cref="AcknowledgeAlarmCommand"/>.</summary>
/// <param name="Ok">True iff the command was published without error.</param>
/// <param name="Message">Failure reason; null on success.</param>
/// <param name="Ok">True iff the scripted-alarm engine applied the command (#950: <see cref="Verdict"/> is Applied).</param>
/// <param name="Message">Detail — the per-node verdicts, or the failure reason.</param>
/// <param name="CorrelationId">Echoes the request's correlation token.</param>
/// <param name="Verdict">
/// #950: the fleet-wide engine verdict; <see langword="null"/> when the request failed before reaching any node
/// (validation, server fault).
/// </param>
/// <param name="Summary">#950: short operator-facing text for <see cref="Verdict"/> ("Applied", "Refused: …", "Outcome unknown").</param>
public sealed record AcknowledgeAlarmResult(
bool Ok,
string? Message,
CorrelationId CorrelationId);
CorrelationId CorrelationId,
OpcUa.AlarmCommandVerdict? Verdict = null,
string? Summary = null);
@@ -45,10 +45,17 @@ public sealed record ShelveAlarmCommand(
CorrelationId CorrelationId);
/// <summary>Reply for <see cref="ShelveAlarmCommand"/>.</summary>
/// <param name="Ok">True iff the command was published without error.</param>
/// <param name="Message">Failure reason; null on success.</param>
/// <param name="Ok">True iff the scripted-alarm engine applied the command (#950: <see cref="Verdict"/> is Applied).</param>
/// <param name="Message">Detail — the per-node verdicts, or the failure reason.</param>
/// <param name="CorrelationId">Echoes the request's correlation token.</param>
/// <param name="Verdict">
/// #950: the fleet-wide engine verdict; <see langword="null"/> when the request failed before reaching any node
/// (validation, server fault).
/// </param>
/// <param name="Summary">#950: short operator-facing text for <see cref="Verdict"/>.</param>
public sealed record ShelveAlarmResult(
bool Ok,
string? Message,
CorrelationId CorrelationId);
CorrelationId CorrelationId,
OpcUa.AlarmCommandVerdict? Verdict = null,
string? Summary = null);
@@ -25,4 +25,10 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
/// and needs no additive-evolution discipline.
/// </para>
/// </remarks>
public sealed record MeshCommand(string Topic, object Message);
/// <param name="VerdictReplyTo">
/// #950: for an <c>AlarmCommand</c> whose publisher collects per-node verdicts (the AdminUI <c>/alerts</c> path), the
/// collector. The router tells it which nodes the command went to (<c>AlarmVerdictFanOut</c>) and — on the gRPC
/// plane — each node's answer; over DistributedPubSub it publishes with the collector as the sender so nodes answer
/// it directly. <see langword="null"/> ⇒ the one-way behaviour, unchanged.
/// </param>
public sealed record MeshCommand(string Topic, object Message, Akka.Actor.IActorRef? VerdictReplyTo = null);
@@ -168,6 +168,7 @@ public static class MeshTransportDtoMapper
proto.Comment = message.Comment;
if (message.UnshelveAtUtc is { } unshelveAt)
proto.UnshelveAtUtc = ToUtcTimestamp(unshelveAt);
proto.VerdictRequested = message.VerdictRequested;
return proto;
}
@@ -175,6 +176,7 @@ public static class MeshTransportDtoMapper
/// <summary>Rebuilds the domain record from its wire form.</summary>
/// <param name="proto">The wire alarm command.</param>
/// <returns>The domain <see cref="AlarmCommand"/>.</returns>
/// <remarks><see cref="AlarmCommand.CommandId"/> is node-local de-duplication state and never crosses this wire.</remarks>
public static AlarmCommand FromProto(AlarmCommandMessage proto)
{
ArgumentNullException.ThrowIfNull(proto);
@@ -184,7 +186,63 @@ public static class MeshTransportDtoMapper
proto.Operation,
proto.User,
proto.HasComment ? proto.Comment : null,
proto.UnshelveAtUtc?.ToDateTime());
proto.UnshelveAtUtc?.ToDateTime(),
VerdictRequested: proto.VerdictRequested);
}
// ---------------------------------------------------------------- AlarmCommandOutcome (#950)
/// <summary>Projects a node's scripted-alarm verdict onto its <c>ExecuteAck.alarm_verdict</c> wire form.</summary>
/// <param name="outcome">The local host's verdict.</param>
/// <returns>The wire <see cref="AlarmVerdictMessage"/>.</returns>
public static AlarmVerdictMessage ToProto(AlarmCommandOutcome outcome)
{
ArgumentNullException.ThrowIfNull(outcome);
var proto = new AlarmVerdictMessage
{
Verdict = outcome.Verdict switch
{
AlarmCommandVerdict.Applied => AlarmVerdict.Applied,
AlarmCommandVerdict.NotApplied => AlarmVerdict.NotApplied,
AlarmCommandVerdict.OutcomeUnknown => AlarmVerdict.OutcomeUnknown,
_ => throw new ArgumentOutOfRangeException(
nameof(outcome), outcome.Verdict, "Not a declared AlarmCommandVerdict."),
},
TimedOut = outcome.TimedOut,
NotOwned = outcome.NotOwned,
};
if (outcome.Reason is not null)
proto.Reason = outcome.Reason;
return proto;
}
/// <summary>Rebuilds a node's verdict from <c>ExecuteAck.alarm_verdict</c>.</summary>
/// <param name="proto">The wire verdict.</param>
/// <param name="alarmId">The command's alarm (the caller holds it; the wire does not repeat it).</param>
/// <param name="operation">The command's operation.</param>
/// <returns>The domain outcome.</returns>
/// <remarks>
/// The one decode in this file that does NOT throw on an unrecognised enum: an <c>UNSPECIFIED</c> or newer verdict
/// becomes <see cref="AlarmCommandVerdict.OutcomeUnknown"/>. That is not a guess in either direction — it claims
/// neither "applied" nor "refused", which is exactly what central knows — and throwing would turn a delivered
/// command into a transport failure.
/// </remarks>
public static AlarmCommandOutcome FromProto(AlarmVerdictMessage proto, string alarmId, string operation)
{
ArgumentNullException.ThrowIfNull(proto);
var reason = proto.HasReason ? proto.Reason : null;
return proto.Verdict switch
{
AlarmVerdict.Applied => new AlarmCommandOutcome(alarmId, operation, AlarmCommandVerdict.Applied, reason),
AlarmVerdict.NotApplied => new AlarmCommandOutcome(
alarmId, operation, AlarmCommandVerdict.NotApplied, reason, NotOwned: proto.NotOwned),
AlarmVerdict.OutcomeUnknown => new AlarmCommandOutcome(
alarmId, operation, AlarmCommandVerdict.OutcomeUnknown, reason, TimedOut: proto.TimedOut),
_ => new AlarmCommandOutcome(alarmId, operation, AlarmCommandVerdict.OutcomeUnknown,
$"The node reported an unrecognised verdict ({proto.Verdict}); the outcome is unknown."),
};
}
// ---------------------------------------------------------------- ApplyAck
@@ -52,13 +52,22 @@ public static class AlarmCommandsTopic
/// direct copy and skips the broadcast copy carrying the same id. Null (every other publisher, and the gRPC mesh
/// wire, which does not carry it) ⇒ no de-duplication. Wire-compatible: a peer built before #937 ignores it.
/// </param>
/// <param name="VerdictRequested">
/// #950: the publisher (central's AdminUI <c>/alerts</c> path) collects each node's verdict. Over DistributedPubSub a
/// node's <c>ScriptedAlarmHostActor</c> answers the publish's sender with an <see cref="AlarmCommandOutcome"/>
/// (<see cref="AlarmCommandOutcome.NotOwned"/> when it does not own the alarm); over the gRPC command plane the node
/// asks its local host and returns the outcome in <c>ExecuteAck</c>. False (every other publisher) ⇒ no reply, exactly
/// as before. Wire-compatible both ways: a node built before #950 ignores it and simply does not answer, which central
/// reports as an unknown outcome for that node.
/// </param>
public sealed record AlarmCommand(
string AlarmId,
string Operation,
string User,
string? Comment,
DateTime? UnshelveAtUtc,
string? CommandId = null);
string? CommandId = null,
bool VerdictRequested = false);
/// <summary>#937: what a scripted-alarm engine did with one <see cref="AlarmCommand"/>.</summary>
public enum AlarmCommandVerdict
@@ -88,9 +97,16 @@ public enum AlarmCommandVerdict
/// <param name="Verdict">What the engine did.</param>
/// <param name="Reason">Operator-facing text for a verdict other than <see cref="AlarmCommandVerdict.Applied"/>.</param>
/// <param name="TimedOut">For <see cref="AlarmCommandVerdict.OutcomeUnknown"/>: the bound expired (vs. a fault).</param>
/// <param name="NotOwned">
/// #950: with <see cref="AlarmCommandVerdict.NotApplied"/>, the answering node does not own the alarm at all (it is not in
/// its scripted-alarm plan, or the node runs no scripted-alarm engine) — as opposed to an owner refusing it. Central's
/// fleet-wide aggregation of an AdminUI command ignores non-owners; the OPC UA method path reads only
/// <see cref="Verdict"/>, where a non-owner is a refusal as before.
/// </param>
public sealed record AlarmCommandOutcome(
string AlarmId,
string Operation,
AlarmCommandVerdict Verdict,
string? Reason = null,
bool TimedOut = false);
bool TimedOut = false,
bool NotOwned = false);
@@ -23,7 +23,9 @@ import "google/protobuf/timestamp.proto";
// on the node's EventStream. ONE-WAY semantics, matching the node-local DistributedPubSub leg: the
// ack means "received and re-emitted", nothing more — not applied, not acknowledged by any
// subscriber. No retry is layered on a failure; a failed Execute is logged per node and dropped,
// which is an honest upgrade over a pub/sub publish nobody was listening for.
// which is an honest upgrade over a pub/sub publish nobody was listening for. The one exception
// (#950): an AlarmCommandMessage with verdict_requested set is handed to the node's scripted-alarm
// host directly and the ack carries that host's verdict (see ExecuteAck.alarm_verdict).
service NodeCommandService {
rpc Execute (CommandEnvelope) returns (ExecuteAck);
}
@@ -50,13 +52,38 @@ message CommandEnvelope {
}
}
// Deliberately empty. A non-OK gRPC status is the ONLY failure signal on this call — putting a
// success flag in the body would invite a caller to read OK+false as a distinct outcome the
// fire-and-forget contract does not have. Extensible later without a version bump.
// A non-OK gRPC status is the ONLY transport-failure signal on this call — there is deliberately no
// success flag in the body, which would invite a caller to read OK+false as a distinct delivery outcome
// the fire-and-forget contract does not have.
//
// #950 — ADDITIVE. `alarm_verdict` is a DOMAIN answer, not a delivery flag: it is set only for an
// AlarmCommandMessage carrying verdict_requested = true, and then says what this node's scripted-alarm
// engine did with the command (applied / not applied / unknown, or "not owned here"). Every other
// command — and every command answered by a node built before #950 — leaves it absent, which central
// reads as "delivered, outcome not reported".
message ExecuteAck {
AlarmVerdictMessage alarm_verdict = 1;
}
// Deliberately empty, for the same reason as ExecuteAck.
// #950: mirrors ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AlarmCommandOutcome (minus the alarm id / operation the
// caller already holds).
message AlarmVerdictMessage {
AlarmVerdict verdict = 1;
optional string reason = 2; // operator-facing; presence = set
bool timed_out = 3; // OUTCOME_UNKNOWN only: the node's bound expired
bool not_owned = 4; // NOT_APPLIED only: this node does not own the alarm
}
// Mirrors ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AlarmCommandVerdict, shifted by one so 0 stays meaningless:
// a verdict that lost the field must never decode as "applied" — central reads UNSPECIFIED as unknown.
enum AlarmVerdict {
ALARM_VERDICT_UNSPECIFIED = 0;
ALARM_VERDICT_APPLIED = 1;
ALARM_VERDICT_NOT_APPLIED = 2;
ALARM_VERDICT_OUTCOME_UNKNOWN = 3;
}
// Deliberately empty: a non-OK gRPC status is the only failure signal (see ExecuteAck).
message ReportAck {
}
@@ -96,6 +123,11 @@ message AlarmCommandMessage {
string user = 3;
optional string comment = 4; // nullable in the record — presence distinguishes null from ""
google.protobuf.Timestamp unshelve_at_utc = 5; // DateTime? — absent Timestamp encodes null
// #950 — ADDITIVE. Central's AdminUI path wants this node's verdict back in ExecuteAck.alarm_verdict:
// the node asks its scripted-alarm host directly (bounded) instead of re-emitting the command on its
// EventStream. A pre-#950 node ignores the field and keeps the one-way path; a pre-#950 central never
// sets it, so a new node handles that central's commands exactly as before.
bool verdict_requested = 6;
}
// Mirrors ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.ApplyAck.
@@ -8,6 +8,7 @@
@using ZB.MOM.WW.OtOpcUa.Commons.Interfaces
@using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin
@using ZB.MOM.WW.OtOpcUa.Commons.Messages.Alerts
@using ZB.MOM.WW.OtOpcUa.Commons.OpcUa
@inject IInProcessBroadcaster<AlarmTransitionEvent> Alarms
@inject AuthenticationStateProvider AuthState
@inject IAuthorizationService AuthorizationService
@@ -44,7 +45,7 @@
else if (_opResultMessage is not null)
{
<div class="mb-3">
<p role="status" aria-live="polite" class="mb-1"><span class="chip @(_opResultOk ? "chip-ok" : "chip-bad")">@_opResultSummary</span></p>
<p role="status" aria-live="polite" class="mb-1"><span class="chip @_opResultChip">@_opResultSummary</span></p>
<p class="small text-muted mb-1">Last request for <span class="mono text-break">@_opResultAlarmId</span></p>
<DiagnosticDetails Summary="Request details" Text="@_opResultMessage" />
</div>
@@ -167,7 +168,7 @@ else
private string _busyAlarmId = "";
private string _opResultAlarmId = "";
private string? _opResultMessage;
private bool _opResultOk;
private string _opResultChip = "chip-bad";
private string? _opResultSummary;
// Auto-clear timer for the single request outcome (mirrors DriverStatusPanel): the chip is set in
@@ -224,7 +225,7 @@ else
using var cts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(15));
var result = await AdminOps.AcknowledgeAlarmAsync(
alarmId, user, comment: null, cts.Token);
ShowOpResult(alarmId, result.Ok, result.Ok ? "Ack sent" : (result.Message ?? "Failed"));
ShowAlarmResult(alarmId, result.Ok, result.Verdict, result.Summary, result.Message, "Ack sent");
}
catch (Exception ex)
{
@@ -264,7 +265,7 @@ else
var result = await AdminOps.ShelveAlarmAsync(
alarmId, user, kind, unshelveAtUtc: unshelveAtUtc, comment: null, cts.Token);
var verb = kind == ShelveKind.Unshelve ? "Unshelve" : "Shelve";
ShowOpResult(alarmId, result.Ok, result.Ok ? $"{verb} sent" : (result.Message ?? "Failed"));
ShowAlarmResult(alarmId, result.Ok, result.Verdict, result.Summary, result.Message, $"{verb} sent");
}
catch (Exception ex)
{
@@ -298,12 +299,34 @@ else
?? "unknown";
}
private void ShowOpResult(string alarmId, bool ok, string message, string? summary = null)
// #950: the result carries the alarm engine's fleet-wide verdict — Applied (green), Refused (red, with the owner's
// reason) or Outcome unknown (amber: a node did not answer in time / timed out / runs an older build; it may still
// apply). A null verdict is a request that never reached a node (validation, server fault) — or a reply from a
// pre-#950 admin singleton during a rolling upgrade, which still means only "sent".
private void ShowAlarmResult(string alarmId, bool ok, AlarmCommandVerdict? verdict, string? summary, string? message,
string legacyOkText)
{
if (verdict is not { } v)
{
ShowOpResult(alarmId, ok, ok ? legacyOkText : (message ?? "Failed"));
return;
}
var chip = v switch
{
AlarmCommandVerdict.Applied => "chip-ok",
AlarmCommandVerdict.OutcomeUnknown => "chip-warn",
_ => "chip-bad",
};
ShowOpResult(alarmId, ok, message ?? summary ?? v.ToString(), summary ?? v.ToString(), chip);
}
private void ShowOpResult(string alarmId, bool ok, string message, string? summary = null, string? chip = null)
{
if (_disposed) return;
_opResultSummary = summary ?? (ok ? message : "Request rejected");
_opResultAlarmId = alarmId;
_opResultOk = ok;
_opResultChip = chip ?? (ok ? "chip-ok" : "chip-bad");
_opResultMessage = message;
StateHasChanged();
// Auto-clear the result chip after 8 s (mirrors DriverStatusPanel). System.Threading.Timer
@@ -42,6 +42,9 @@ public sealed class AdminOperationsActor : ReceiveActor
private readonly ILoggingAdapter _log = Context.GetLogger();
/// <summary>#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts.</summary>
private readonly TimeSpan _alarmVerdictWindow;
/// <summary>The StartDeployment whose compose is running off-actor, or null. See <see cref="HandleStartDeployment"/>.</summary>
private StartDeployment? _composeInFlight;
@@ -55,6 +58,7 @@ public sealed class AdminOperationsActor : ReceiveActor
/// DistributedPubSub mediator directly (the behaviour before the per-cluster mesh).
/// </param>
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
/// <param name="alarmVerdictWindow">#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts; defaults to <see cref="AlarmCommandVerdictCollector.DefaultWindow"/>.</param>
/// <returns>Props configured to create an AdminOperationsActor.</returns>
public static Props Props(
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
@@ -62,9 +66,10 @@ public sealed class AdminOperationsActor : ReceiveActor
IEnumerable<IDriverProbe> probes,
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
IActorRef? meshRouter = null,
TimeSpan? applyDeadline = null) =>
TimeSpan? applyDeadline = null,
TimeSpan? alarmVerdictWindow = null) =>
Akka.Actor.Props.Create(() =>
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline));
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline, alarmVerdictWindow));
/// <summary>Initializes a new instance of the AdminOperationsActor.</summary>
/// <param name="dbFactory">Factory for creating config database contexts.</param>
@@ -73,14 +78,17 @@ public sealed class AdminOperationsActor : ReceiveActor
/// <param name="tagConfigValidationMode">Deploy-gate TagConfig strictness mode (Warn default | Error opt-in).</param>
/// <param name="meshRouter">Central comm actor, or <see langword="null"/> for the mediator.</param>
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
/// <param name="alarmVerdictWindow">#950: the <c>/alerts</c> verdict collection window.</param>
public AdminOperationsActor(
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
IActorRef coordinator,
IEnumerable<IDriverProbe> probes,
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
IActorRef? meshRouter = null,
TimeSpan? applyDeadline = null)
TimeSpan? applyDeadline = null,
TimeSpan? alarmVerdictWindow = null)
{
_alarmVerdictWindow = alarmVerdictWindow ?? AlarmCommandVerdictCollector.DefaultWindow;
// The same source the coordinator's default reads (ConfigPublishCoordinator.DefaultApplyDeadline IS
// DeployTimings.ApplyDeadline), so the lost-dispatch closure and the coordinator's own deadline agree.
_applyDeadline = applyDeadline ?? DeployTimings.ApplyDeadline;
@@ -134,13 +142,21 @@ public sealed class AdminOperationsActor : ReceiveActor
else DistributedPubSub.Get(Context.System).Mediator.Tell(new Publish(topic, message));
}
/// <summary>
/// #950: spawns the per-request verdict collector, which sends <paramref name="command"/> (via the mesh router, or
/// DistributedPubSub when none is wired) and answers <paramref name="replyTo"/> with <paramref name="reply"/>.
/// </summary>
private void CollectVerdict(AlarmCommand command, IActorRef replyTo, Func<AlarmCommandFleetOutcome, object> reply) =>
Context.ActorOf(AlarmCommandVerdictCollector.Props(command, _meshRouter, replyTo, reply, _alarmVerdictWindow));
/// <summary>
/// AdminUI Acknowledge path. Maps the control-plane command to a
/// <see cref="AlarmCommand"/> (<c>Operation = "Acknowledge"</c>) and publishes it onto the
/// cluster <c>alarm-commands</c> topic. The broadcast lands on every driver node's
/// <c>ScriptedAlarmHostActor</c>; only the node owning the alarm acts (ownership filter), so the
/// admin singleton needs no knowledge of placement. Synchronous — the publish is fire-and-forget
/// via the mediator, so there is no awaitable work and no DB write.
/// <see cref="AlarmCommand"/> (<c>Operation = "Acknowledge"</c>) and hands it to an
/// <see cref="AlarmCommandVerdictCollector"/>, which sends it to every driver node (the ownership filter on each
/// node's <c>ScriptedAlarmHostActor</c> decides who acts, so the admin singleton needs no knowledge of placement),
/// collects each node's verdict within a bounded window and replies Applied / Refused (reason) / Outcome unknown
/// (#950 — this was a fire-and-forget publish that always answered "sent"). The mailbox is not held: the collector
/// is a child actor that answers the requester itself.
/// </summary>
private void HandleAcknowledgeAlarm(AcknowledgeAlarmCommand msg)
{
@@ -154,10 +170,10 @@ public sealed class AdminOperationsActor : ReceiveActor
Comment: msg.Comment,
UnshelveAtUtc: null);
Dispatch(AlarmCommandsTopic.Name, alarmCmd);
_log.Info("AdminOps: Acknowledge published for alarm {AlarmId} by {User}", msg.AlarmId, msg.User);
replyTo.Tell(new AcknowledgeAlarmResult(true, null, msg.CorrelationId));
var correlationId = msg.CorrelationId;
CollectVerdict(alarmCmd, replyTo, o => new AcknowledgeAlarmResult(
o.Verdict == AlarmCommandVerdict.Applied, o.Detail, correlationId, o.Verdict, o.Summary));
_log.Info("AdminOps: Acknowledge sent for alarm {AlarmId} by {User}; collecting node verdicts", msg.AlarmId, msg.User);
}
catch (Exception ex)
{
@@ -170,8 +186,8 @@ public sealed class AdminOperationsActor : ReceiveActor
/// AdminUI Shelve / Unshelve path. Maps <see cref="ShelveAlarmCommand.Kind"/> to the matching
/// <see cref="AlarmCommand"/> operation (<c>OneShotShelve</c> / <c>TimedShelve</c> /
/// <c>Unshelve</c>), threading <see cref="ShelveAlarmCommand.UnshelveAtUtc"/> for the timed kind,
/// and publishes onto the cluster <c>alarm-commands</c> topic. Ownership filtering happens on the
/// owning node exactly as for Acknowledge.
/// and sends it exactly as <see cref="HandleAcknowledgeAlarm"/> does — ownership filtered on the nodes, verdicts
/// collected and reported (#950).
/// </summary>
private void HandleShelveAlarm(ShelveAlarmCommand msg)
{
@@ -201,10 +217,10 @@ public sealed class AdminOperationsActor : ReceiveActor
Comment: msg.Comment,
UnshelveAtUtc: unshelveAt);
Dispatch(AlarmCommandsTopic.Name, alarmCmd);
_log.Info("AdminOps: {Operation} published for alarm {AlarmId} by {User}", operation, msg.AlarmId, msg.User);
replyTo.Tell(new ShelveAlarmResult(true, null, msg.CorrelationId));
var correlationId = msg.CorrelationId;
CollectVerdict(alarmCmd, replyTo, o => new ShelveAlarmResult(
o.Verdict == AlarmCommandVerdict.Applied, o.Detail, correlationId, o.Verdict, o.Summary));
_log.Info("AdminOps: {Operation} sent for alarm {AlarmId} by {User}; collecting node verdicts", operation, msg.AlarmId, msg.User);
}
catch (Exception ex)
{
@@ -0,0 +1,310 @@
using System.Text;
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Event;
using ZB.MOM.WW.OtOpcUa.Cluster;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
/// <summary>
/// #950: router → collector. Which nodes an AdminUI alarm command went to — the set the
/// <see cref="AlarmCommandVerdictCollector"/> waits on.
/// </summary>
/// <param name="Nodes">
/// The nodes expected to answer (gRPC: the dialled <c>ClusterNode</c> ids; DistributedPubSub: the Up <c>driver</c>
/// members' <c>host:port</c>). Empty with a null <paramref name="NotDeliveredReason"/> ⇒ the set is unknown and the
/// collector waits out its window.
/// </param>
/// <param name="NotDeliveredReason">Set when the command reached no node at all (no targets, no dialer, unencodable).</param>
public sealed record AlarmVerdictFanOut(IReadOnlyList<string> Nodes, string? NotDeliveredReason = null);
/// <summary>#950: one node's answer to an AdminUI alarm command, as the gRPC router saw it.</summary>
/// <param name="Node">The node (its <c>ClusterNode</c> id).</param>
/// <param name="Outcome">Its verdict; transport failures and pre-#950 nodes arrive as <see cref="AlarmCommandVerdict.OutcomeUnknown"/>.</param>
public sealed record AlarmNodeVerdict(string Node, AlarmCommandOutcome Outcome);
/// <summary>#950: the fleet-wide verdict on one AdminUI alarm command.</summary>
/// <param name="Verdict">Applied when any owning node applied it; OutcomeUnknown when none did but one may have; else NotApplied.</param>
/// <param name="Summary">Short operator-facing text (the <c>/alerts</c> result chip).</param>
/// <param name="Detail">Per-node breakdown (the result's details pane).</param>
public sealed record AlarmCommandFleetOutcome(AlarmCommandVerdict Verdict, string Summary, string Detail);
/// <summary>
/// #950: folds the per-node answers to one AdminUI alarm command into the verdict the operator sees.
/// </summary>
/// <remarks>
/// <para>
/// Every driver node receives the command and only the alarm's owners act — two in a redundant pair, each with its
/// own engine (the condition state is then replicated last-writer-wins). So: <b>any owner applied ⇒ Applied</b>
/// (other owners' refusals/unknowns are listed, and the summary says it was partial); otherwise <b>any unknown — an
/// owner that timed out, a node that did not answer, a transport failure, a pre-#950 node — ⇒ OutcomeUnknown</b>,
/// never "refused", because that node may still apply it; otherwise an owner's refusal ⇒ NotApplied with its
/// reason; otherwise no node owns the alarm ⇒ NotApplied.
/// </para>
/// </remarks>
public static class AlarmCommandVerdictAggregator
{
/// <summary>Aggregates the answers.</summary>
/// <param name="answers">Node → its verdict (non-owners carry <see cref="AlarmCommandOutcome.NotOwned"/>).</param>
/// <param name="unanswered">Expected nodes that did not answer within the window.</param>
/// <param name="expectedKnown">Whether the set of nodes the command reached is known (false ⇒ silence may hide an owner).</param>
/// <param name="notDeliveredReason">Set when the command reached no node at all.</param>
/// <param name="window">The collection window, for the "no answer" text.</param>
/// <returns>The fleet verdict.</returns>
public static AlarmCommandFleetOutcome Aggregate(
IReadOnlyDictionary<string, AlarmCommandOutcome> answers,
IReadOnlyCollection<string> unanswered,
bool expectedKnown,
string? notDeliveredReason,
TimeSpan window)
{
ArgumentNullException.ThrowIfNull(answers);
ArgumentNullException.ThrowIfNull(unanswered);
if (notDeliveredReason is not null && answers.Count == 0)
return new AlarmCommandFleetOutcome(AlarmCommandVerdict.NotApplied, "Not delivered",
$"The command was not delivered to any server, so nothing applied it: {notDeliveredReason}");
var applied = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.Applied);
var refused = answers.Where(a => a.Value is { Verdict: AlarmCommandVerdict.NotApplied, NotOwned: false })
.OrderBy(a => a.Key, StringComparer.Ordinal).ToList();
var unknown = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.OutcomeUnknown) + unanswered.Count;
AlarmCommandVerdict verdict;
string summary;
if (applied > 0)
{
verdict = AlarmCommandVerdict.Applied;
summary = refused.Count + unknown == 0
? "Applied"
: $"Applied on {applied} of {applied + refused.Count + unknown} servers";
}
else if (unknown > 0)
{
verdict = AlarmCommandVerdict.OutcomeUnknown;
summary = "Outcome unknown";
}
else if (refused.Count > 0)
{
verdict = AlarmCommandVerdict.NotApplied;
summary = "Refused: " + (refused[0].Value.Reason ?? "the alarm engine did not apply the command.");
}
else if (!expectedKnown)
{
// Silence from a node we could not enumerate may be an owner that did not answer (a pre-#950 node).
verdict = AlarmCommandVerdict.OutcomeUnknown;
summary = "Outcome unknown";
}
else
{
verdict = AlarmCommandVerdict.NotApplied;
summary = "Not applied: no server owns this alarm";
}
var detail = new StringBuilder(verdict switch
{
AlarmCommandVerdict.Applied => "The alarm engine applied the command.",
AlarmCommandVerdict.OutcomeUnknown =>
"No server confirmed the command and at least one did not give a definite answer — it may still apply. "
+ "Check the alarm's state before retrying.",
_ => "The command was not applied anywhere.",
});
foreach (var (node, outcome) in answers.OrderBy(a => a.Key, StringComparer.Ordinal))
detail.AppendLine().Append(node).Append(": ").Append(Describe(outcome));
foreach (var node in unanswered.OrderBy(n => n, StringComparer.Ordinal))
detail.AppendLine().Append(node).Append($": no answer within {window.TotalSeconds:0.#} s — outcome unknown.");
if (answers.Count == 0 && unanswered.Count == 0)
detail.AppendLine().Append($"No server answered within {window.TotalSeconds:0.#} s.");
if (notDeliveredReason is not null)
detail.AppendLine().Append("Delivery: ").Append(notDeliveredReason);
return new AlarmCommandFleetOutcome(verdict, summary, detail.ToString());
}
private static string Describe(AlarmCommandOutcome outcome) => outcome switch
{
{ Verdict: AlarmCommandVerdict.Applied } => "applied.",
{ Verdict: AlarmCommandVerdict.NotApplied, NotOwned: true } => "does not own this alarm.",
{ Verdict: AlarmCommandVerdict.NotApplied } => "refused — " + (outcome.Reason ?? "no reason given."),
_ => "outcome unknown — " + (outcome.Reason ?? "no reason given."),
};
}
/// <summary>
/// #950: the DistributedPubSub leg of an AdminUI alarm command that wants verdicts — used by the router under
/// <c>MeshTransport:Mode = Dps</c> and by <see cref="AdminOperationsActor"/> when no router is wired.
/// </summary>
public static class AlarmVerdictDps
{
/// <summary>
/// Publishes <paramref name="command"/> on <paramref name="topic"/> with <paramref name="collector"/> as the sender
/// (DistributedPubSub preserves it, so each node's scripted-alarm host answers the collector) and returns the nodes
/// expected to answer: the Up members carrying the <c>driver</c> role, keyed as <see cref="NodeKey"/> keys them.
/// </summary>
/// <param name="system">The actor system.</param>
/// <param name="topic">The DPS topic.</param>
/// <param name="command">The command (with <see cref="AlarmCommand.VerdictRequested"/> set).</param>
/// <param name="collector">Who the nodes answer.</param>
/// <returns>The expected node keys; empty when the membership could not be read.</returns>
public static IReadOnlyList<string> Publish(ActorSystem system, string topic, AlarmCommand command, IActorRef collector)
{
IReadOnlyList<string> expected;
try
{
var cluster = Akka.Cluster.Cluster.Get(system);
expected = cluster.State.Members
.Where(m => m.Status == Akka.Cluster.MemberStatus.Up && RoleParser.GossipedRolesHave(m.Roles, RoleParser.Driver))
.Select(m => NodeKey(m.Address, cluster.SelfAddress))
.Distinct(StringComparer.Ordinal)
.ToList();
}
catch (Exception)
{
expected = [];
}
DistributedPubSub.Get(system).Mediator.Tell(new Publish(topic, command), collector);
return expected;
}
/// <summary>The key a DPS-answering node is known by: its <c>host:port</c> (a local-scope address is this node).</summary>
/// <param name="address">The member or reply-sender address.</param>
/// <param name="self">This node's cluster address, or null when there is no cluster.</param>
/// <returns>The key.</returns>
public static string NodeKey(Address address, Address? self)
{
var effective = address.HasGlobalScope || self is null ? address : self;
return effective.Host is not null && effective.Port is not null ? effective.HostPort() : effective.ToString();
}
}
/// <summary>
/// #950: one AdminUI alarm command's verdict collection. Sends the command (via the mesh router, or straight onto
/// DistributedPubSub when none is wired), gathers each node's answer until every expected node has answered or the
/// window closes, and replies the aggregated <see cref="AlarmCommandFleetOutcome"/> (mapped by the caller's
/// <c>reply</c>) to the original requester. Stops itself after replying.
/// </summary>
public sealed class AlarmCommandVerdictCollector : ReceiveActor, IWithTimers
{
/// <summary>The default collection window — under <c>AdminOperationsClient</c>'s 10 s ask.</summary>
public static readonly TimeSpan DefaultWindow = TimeSpan.FromSeconds(7);
private const string WindowTimerKey = "window";
private readonly AlarmCommand _command;
private readonly IActorRef? _meshRouter;
private readonly IActorRef _replyTo;
private readonly Func<AlarmCommandFleetOutcome, object> _reply;
private readonly TimeSpan _window;
private readonly ILoggingAdapter _log = Context.GetLogger();
private readonly Dictionary<string, AlarmCommandOutcome> _answers = new(StringComparer.Ordinal);
private HashSet<string>? _expected;
private string? _notDelivered;
private Address? _self;
/// <summary>Gets or sets the timer scheduler.</summary>
public ITimerScheduler Timers { get; set; } = null!;
/// <summary>Creates the props.</summary>
/// <param name="command">The command; <see cref="AlarmCommand.VerdictRequested"/> is forced on.</param>
/// <param name="meshRouter">The central comm actor, or null to publish on DistributedPubSub directly.</param>
/// <param name="replyTo">The requester.</param>
/// <param name="reply">Maps the fleet verdict to the requester's reply message.</param>
/// <param name="window">The collection window.</param>
/// <returns>The props.</returns>
public static Props Props(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
Func<AlarmCommandFleetOutcome, object> reply, TimeSpan window) =>
Akka.Actor.Props.Create(() => new AlarmCommandVerdictCollector(command, meshRouter, replyTo, reply, window));
/// <summary>Initializes a new instance of the <see cref="AlarmCommandVerdictCollector"/> class.</summary>
/// <param name="command">The command.</param>
/// <param name="meshRouter">The router, or null.</param>
/// <param name="replyTo">The requester.</param>
/// <param name="reply">Maps the verdict to the reply.</param>
/// <param name="window">The collection window.</param>
public AlarmCommandVerdictCollector(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
Func<AlarmCommandFleetOutcome, object> reply, TimeSpan window)
{
_command = command with { VerdictRequested = true };
_meshRouter = meshRouter;
_replyTo = replyTo;
_reply = reply;
_window = window;
Receive<AlarmVerdictFanOut>(msg =>
{
_expected = new HashSet<string>(msg.Nodes, StringComparer.Ordinal);
_notDelivered = msg.NotDeliveredReason;
FinishIfComplete();
});
Receive<AlarmNodeVerdict>(msg =>
{
_answers[msg.Node] = msg.Outcome;
FinishIfComplete();
});
// A DistributedPubSub answer straight from a node's ScriptedAlarmHostActor: the node is the sender.
Receive<AlarmCommandOutcome>(outcome =>
{
if (!string.Equals(outcome.AlarmId, _command.AlarmId, StringComparison.Ordinal)) return;
_answers[AlarmVerdictDps.NodeKey(Sender.Path.Address, _self)] = outcome;
FinishIfComplete();
});
Receive<WindowClosed>(_ => Finish());
}
/// <inheritdoc />
protected override void PreStart()
{
try
{
_self = Akka.Cluster.Cluster.Get(Context.System).SelfAddress;
}
catch (Exception)
{
_self = null;
}
Timers.StartSingleTimer(WindowTimerKey, WindowClosed.Instance, _window);
if (_meshRouter is not null)
{
_meshRouter.Tell(new MeshCommand(AlarmCommandsTopic.Name, _command, Self));
}
else
{
var expected = AlarmVerdictDps.Publish(Context.System, AlarmCommandsTopic.Name, _command, Self);
Self.Tell(new AlarmVerdictFanOut(expected));
}
}
private void FinishIfComplete()
{
if (_expected is null) return;
if (_notDelivered is not null && _expected.Count == 0)
{
Finish();
return;
}
if (_expected.Count > 0 && _expected.All(_answers.ContainsKey)) Finish();
}
private void Finish()
{
var expectedKnown = _expected is { Count: > 0 } || _notDelivered is not null;
var unanswered = _expected?.Where(n => !_answers.ContainsKey(n)).ToList() ?? [];
var outcome = AlarmCommandVerdictAggregator.Aggregate(_answers, unanswered, expectedKnown, _notDelivered, _window);
_log.Info("AdminOps: {Operation} for alarm {AlarmId} by {User} → {Outcome}",
_command.Operation, _command.AlarmId, _command.User,
$"{outcome.Verdict} ({outcome.Summary}; {_answers.Count} answered, {unanswered.Count} silent)");
_replyTo.Tell(_reply(outcome));
Timers.CancelAll();
Context.Stop(Self);
}
private sealed class WindowClosed
{
public static readonly WindowClosed Instance = new();
}
}
@@ -7,8 +7,10 @@ using ZB.MOM.WW.OtOpcUa.Cluster;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
using ZB.MOM.WW.OtOpcUa.Commons.Protos.MeshTransport.V1;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
// Grpc.Core (imported for RpcException on the dial path) declares a Status of its own. This file's
// bare Status is Akka's — the Status.Failure a faulted piped task arrives as; the gRPC one is only
// ever reached through an RpcException instance.
@@ -392,9 +394,21 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
return;
}
// #950: an AdminUI alarm command that collects verdicts is published with the collector as the sender
// (DistributedPubSub keeps it), so each node's scripted-alarm host answers the collector directly.
if (cmd is { VerdictReplyTo: { } collector, Message: AlarmCommand alarm })
{
collector.Tell(new AlarmVerdictFanOut(AlarmVerdictDps.Publish(Context.System, cmd.Topic, alarm, collector)));
return;
}
DistributedPubSub.Get(Context.System).Mediator.Tell(new Publish(cmd.Topic, cmd.Message));
}
/// <summary>#950: tells a verdict collector the command reached no node, so it answers at once instead of at its window.</summary>
private static void ReportNotDelivered(MeshCommand cmd, string reason) =>
cmd.VerdictReplyTo?.Tell(new AlarmVerdictFanOut([], reason));
/// <summary>
/// Encodes one command once and fans it to every target node, one unary gRPC call each.
/// </summary>
@@ -432,6 +446,7 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
"Mesh transport is Grpc but no command dialer is wired — dropping {MessageType}. The "
+ "command is not buffered and will not be retried",
commandType);
ReportNotDelivered(cmd, "central's mesh transport is Grpc but no command dialer is wired.");
return;
}
@@ -449,6 +464,7 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
+ "enabled, non-maintenance ClusterNode row carrying a GrpcPort in any cluster; the "
+ "command is not buffered and will not be retried",
commandType);
ReportNotDelivered(cmd, "no enabled, non-maintenance ClusterNode row carries a GrpcPort.");
return;
}
@@ -467,6 +483,7 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
"Cannot encode {MessageType} for the gRPC command plane; the command is dropped and "
+ "was NOT delivered to any node",
commandType);
ReportNotDelivered(cmd, "the command could not be encoded for the gRPC command plane.");
return;
}
@@ -477,11 +494,17 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
}
catch (ObjectDisposedException)
{
ReportNotDelivered(cmd, "central is shutting down.");
return; // Stopping.
}
var self = Self;
var correlationId = envelope.CorrelationId;
// #950: the collector learns the recipient set before any answer can arrive (both are Tells from this actor).
var verdictReplyTo = cmd.VerdictReplyTo;
var alarm = verdictReplyTo is null ? null : cmd.Message as AlarmCommand;
if (alarm is not null)
verdictReplyTo!.Tell(new AlarmVerdictFanOut(targets.Select(t => t.NodeId).ToList()));
foreach (var target in targets)
{
var node = target;
@@ -492,7 +515,12 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
// passed into the dial instead, where it cancels the call and comes back as an ordinary
// per-node outcome.
Task.Run(
() => DispatchOneAsync(dialer, node, envelope, commandType, correlationId, ct),
async () =>
{
var result = await DispatchOneAsync(dialer, node, envelope, commandType, correlationId, ct)
.ConfigureAwait(false);
return alarm is null ? result : result with { VerdictReplyTo = verdictReplyTo, Alarm = alarm };
},
CancellationToken.None)
.PipeTo(self);
}
@@ -524,9 +552,9 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
{
try
{
await dialer.DispatchAsync(target.Endpoint, envelope, target.ClusterId, ct)
var ack = await dialer.ExecuteAsync(target.Endpoint, envelope, target.ClusterId, ct)
.ConfigureAwait(false);
return new CommandDispatched(target.NodeId, commandType, correlationId, null, null);
return new CommandDispatched(target.NodeId, commandType, correlationId, null, null, ack);
}
catch (RpcException ex)
{
@@ -572,6 +600,9 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
private void HandleCommandDispatched(CommandDispatched result)
{
if (result is { VerdictReplyTo: { } collector, Alarm: { } alarm })
collector.Tell(new AlarmNodeVerdict(result.NodeId, NodeVerdict(result, alarm)));
if (result.FailureStatus is null)
{
_log.Debug(
@@ -606,6 +637,27 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
coordinator.Forward(ack);
}
/// <summary>
/// #950: one node's dial result as a verdict. A transport failure is UNKNOWN, never "not applied" — a call that
/// timed out or was cut may have been handled — and an ack with no verdict is a pre-#950 node that took the
/// command down its one-way path.
/// </summary>
private static AlarmCommandOutcome NodeVerdict(CommandDispatched result, AlarmCommand alarm)
{
if (result.FailureStatus is not null)
{
// The status code only: the detail can name endpoints and this text reaches any DriverOperator's browser
// (the R03:4.1 rule). The detail is in the Warning HandleCommandDispatched logs under the same correlation id.
return new AlarmCommandOutcome(alarm.AlarmId, alarm.Operation, AlarmCommandVerdict.OutcomeUnknown,
$"the command was not confirmed delivered (gRPC {result.FailureStatus}; see the central log for correlation {result.CorrelationId}).");
}
return result.Ack?.AlarmVerdict is { } verdict
? MeshTransportDtoMapper.FromProto(verdict, alarm.AlarmId, alarm.Operation)
: new AlarmCommandOutcome(alarm.AlarmId, alarm.Operation, AlarmCommandVerdict.OutcomeUnknown,
"the node took the command but reports no verdict (it runs a build older than #950); it applies the command if it owns the alarm.");
}
private void LoadContactsFromDb()
{
var self = Self;
@@ -895,10 +947,16 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
/// The gRPC status detail, or the exception's type name for a non-gRPC fault. Never a key,
/// and never a raw exception message.
/// </param>
/// <param name="Ack">#950: the node's reply on success (carries an alarm verdict when one was requested).</param>
/// <param name="VerdictReplyTo">#950: the AdminUI alarm command's verdict collector, when one is waiting.</param>
/// <param name="Alarm">#950: the alarm command, when <paramref name="VerdictReplyTo"/> is set.</param>
public sealed record CommandDispatched(
string NodeId,
string CommandType,
string CorrelationId,
string? FailureStatus,
string? FailureDetail);
string? FailureDetail,
ExecuteAck? Ack = null,
IActorRef? VerdictReplyTo = null,
AlarmCommand? Alarm = null);
}
@@ -35,6 +35,22 @@ public interface IMeshCommandDialer
/// </exception>
Task DispatchAsync(string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct);
/// <summary>
/// #950: <see cref="DispatchAsync"/> returning the node's <see cref="ExecuteAck"/>, whose <c>alarm_verdict</c>
/// carries a scripted-alarm verdict when the command asked for one. The default (a dialer that only implements
/// <see cref="DispatchAsync"/>) answers an empty ack — "delivered, no verdict".
/// </summary>
/// <param name="nodeEndpoint">The node's gRPC base address.</param>
/// <param name="envelope">The wire envelope.</param>
/// <param name="clusterId">The target node's application <c>Cluster</c>.</param>
/// <param name="ct">Cancels the dial.</param>
/// <returns>The node's ack.</returns>
async Task<ExecuteAck> ExecuteAsync(string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct)
{
await DispatchAsync(nodeEndpoint, envelope, clusterId, ct).ConfigureAwait(false);
return new ExecuteAck();
}
/// <summary>
/// Releases any per-endpoint resources for endpoints NOT in <paramref name="nodeEndpoints"/>
/// (R03:1.3). Central calls it on every contact refresh with the current dispatch set, so a
@@ -154,7 +170,12 @@ public sealed class MeshGrpcCommandDialer : IMeshCommandDialer, IDisposable
public int CachedChannelCount => _channels.Count;
/// <inheritdoc />
public async Task DispatchAsync(
public Task DispatchAsync(
string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct)
=> ExecuteAsync(nodeEndpoint, envelope, clusterId, ct);
/// <inheritdoc />
public async Task<ExecuteAck> ExecuteAsync(
string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(nodeEndpoint);
@@ -187,7 +208,7 @@ public sealed class MeshGrpcCommandDialer : IMeshCommandDialer, IDisposable
var client = _clientFactory(nodeEndpoint);
using var call = client.ExecuteAsync(envelope, headers, cancellationToken: deadlineCts.Token);
await call.ResponseAsync.ConfigureAwait(false);
return await call.ResponseAsync.ConfigureAwait(false);
}
/// <inheritdoc />
@@ -3,8 +3,10 @@ using Akka.Hosting;
using Grpc.Core;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Protos.MeshTransport.V1;
using ZB.MOM.WW.OtOpcUa.Runtime;
using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
// The generated service container is itself named NodeCommandService; alias its nested server base so
// this impl can keep the natural name without colliding with the generated type.
using GeneratedServiceBase =
@@ -87,6 +89,9 @@ public sealed class NodeCommandGrpcService : GeneratedServiceBase
StatusCode.InvalidArgument, "Command envelope could not be decoded."));
}
if (command is AlarmCommand { VerdictRequested: true } alarm)
return ExecuteForVerdictAsync(alarm, request.CorrelationId, context.CancellationToken);
if (!_registry.TryGet<NodeCommunicationActorKey>(out var comm))
{
_log.LogWarning(
@@ -107,4 +112,69 @@ public sealed class NodeCommandGrpcService : GeneratedServiceBase
return Task.FromResult(new ExecuteAck());
}
/// <summary>
/// #950: an AdminUI alarm command that wants this node's verdict. Asks the local driver host (which forwards to its
/// <c>ScriptedAlarmHostActor</c> — the same <c>ExecuteAlarmCommand</c> path the OPC UA Part 9 methods use, #937) and
/// returns the verdict in <see cref="ExecuteAck.AlarmVerdict"/>. Never re-emitted on the EventStream as well: this
/// node's host gets exactly one copy, as on the one-way path.
/// </summary>
/// <remarks>
/// <para>
/// <b>No deadline on the ask message.</b> The OPC UA path stamps one so an expired ask skips the engine — its
/// broadcast copy still applies. Nothing else carries this command to this node, so an ask that outlives
/// <see cref="VerdictWait"/> must still apply (the one-way semantic it replaces); the caller is told
/// OutcomeUnknown, never "not applied".
/// </para>
/// <para>
/// No driver host registered while the comm actor is ⇒ this node runs no driver role (or no scripted-alarm
/// host could exist): answered NotApplied/NotOwned. Neither registered ⇒ still booting ⇒
/// <see cref="StatusCode.Unavailable"/>, as for every other command.
/// </para>
/// </remarks>
private async Task<ExecuteAck> ExecuteForVerdictAsync(AlarmCommand alarm, string correlationId, CancellationToken ct)
{
AlarmCommandOutcome outcome;
if (!_registry.TryGet<DriverHostActorKey>(out var driverHost))
{
if (!_registry.TryGet<NodeCommunicationActorKey>(out _))
{
_log.LogWarning(
"Rejected a mesh alarm command (correlationId={CorrelationId}): this node is still starting; the "
+ "command was NOT delivered.", correlationId);
throw new RpcException(new Status(
StatusCode.Unavailable, "Node is still starting: the command endpoint is not ready."));
}
outcome = new AlarmCommandOutcome(alarm.AlarmId, alarm.Operation, AlarmCommandVerdict.NotApplied,
"This server runs no scripted-alarm engine; the command was not applied.", NotOwned: true);
}
else
{
try
{
outcome = await driverHost.Ask<AlarmCommandOutcome>(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(alarm with { VerdictRequested = false }),
VerdictWait, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is AskTimeoutException or TaskCanceledException or TimeoutException
&& !ct.IsCancellationRequested)
{
outcome = new AlarmCommandOutcome(alarm.AlarmId, alarm.Operation, AlarmCommandVerdict.OutcomeUnknown,
$"the scripted-alarm engine did not answer within {VerdictWait.TotalSeconds:0.#} s; the command may still apply.",
TimedOut: true);
}
}
_log.LogDebug(
"Mesh: {Operation} for alarm {AlarmId} (correlationId={CorrelationId}) answered {Verdict} (notOwned={NotOwned}).",
alarm.Operation, alarm.AlarmId, correlationId, outcome.Verdict, outcome.NotOwned);
return new ExecuteAck { AlarmVerdict = MeshTransportDtoMapper.ToProto(outcome) };
}
/// <summary>
/// #950: how long the node waits for its scripted-alarm host — under central's default 10 s dispatch deadline and
/// 7 s collection window, so a slow engine reads as a timed-out unknown rather than a failed dial.
/// </summary>
internal TimeSpan VerdictWait { get; init; } = TimeSpan.FromSeconds(5);
}
@@ -2609,7 +2609,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
}
Sender.Tell(new AlarmCommandOutcome(msg.Command.AlarmId, msg.Command.Operation, AlarmCommandVerdict.NotApplied,
"This server runs no scripted-alarm engine; the command was not applied."));
"This server runs no scripted-alarm engine; the command was not applied.", NotOwned: true));
}
private void HandleRouteNativeAlarmAck(RouteNativeAlarmAck msg)
@@ -788,12 +788,18 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <param name="cmd">The inbound alarm command.</param>
private async Task OnAlarmCommand(AlarmCommand cmd)
{
// #950: central's AdminUI path publishes with its verdict collector as the sender and asks every host to answer —
// non-owners included, so the collector can stop waiting once each driver node has spoken. Any other publisher
// (the OPC UA broadcast, a pre-#950 central) gets no reply, exactly as before.
var replyTo = cmd.VerdictRequested && !Sender.IsNobody() ? Sender : null;
// #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))
if (cmd.CommandId is { } id && _recentCommands.TryGetValue(id, out var known))
{
_log.Debug("ScriptedAlarmHost: skipping duplicate AlarmCommand {Op} for {AlarmId} (command {CommandId})",
cmd.Operation, cmd.AlarmId, id);
replyTo?.Tell(known);
return;
}
@@ -803,10 +809,14 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
{
_log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}",
cmd.Operation, cmd.AlarmId);
replyTo?.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
NotLoadedRefusal, NotOwned: true));
return;
}
Remember(cmd, await ApplyCommandAsync(cmd));
var outcome = await ApplyCommandAsync(cmd);
Remember(cmd, outcome);
replyTo?.Tell(outcome);
}
/// <summary>
@@ -840,7 +850,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
var outcome = Owns(cmd.AlarmId)
? await ApplyCommandAsync(cmd)
: new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
_readiness?.Refusal() ?? NotLoadedRefusal);
_readiness?.Refusal() ?? NotLoadedRefusal, NotOwned: true);
Remember(cmd, outcome);
replyTo.Tell(outcome);