From 09aaabbeefd31a9a0858302c7f2451460f2b4a05 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 1 Dec 2026 19:45:17 -0500 Subject: [PATCH] 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: ; 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 --- .claude/rules/alarms.md | 7 +- .claude/rules/cluster-topology.md | 4 + docs/ScriptedAlarms.md | 32 +- .../Messages/Admin/AcknowledgeAlarmCommand.cs | 13 +- .../Messages/Admin/ShelveAlarmCommand.cs | 13 +- .../Messages/Mesh/MeshCommand.cs | 8 +- .../Messages/Mesh/MeshTransportDtoMapper.cs | 60 +++- .../OpcUa/AlarmCommand.cs | 20 +- .../Protos/mesh_transport.proto | 42 ++- .../Components/Pages/Alerts.razor | 35 +- .../AdminOperations/AdminOperationsActor.cs | 52 ++- .../AdminOperations/AlarmCommandVerdicts.cs | 310 ++++++++++++++++++ .../CentralCommunicationActor.cs | 66 +++- .../Communication/MeshGrpcCommandDialer.cs | 25 +- .../Grpc/NodeCommandGrpcService.cs | 70 ++++ .../Drivers/DriverHostActor.cs | 2 +- .../ScriptedAlarms/ScriptedAlarmHostActor.cs | 16 +- .../MeshTransportDtoMapperTests.cs | 40 +++ .../AlertsAckPathTests.cs | 38 ++- .../Pages/AlarmOperationFormTests.cs | 12 + .../AdminOperationsActorMailboxTests.cs | 26 +- .../AdminOperationsActorTests.cs | 22 +- .../AlarmCommandVerdictTests.cs | 252 ++++++++++++++ .../CentralCommunicationActorTests.cs | 79 +++++ .../Communication/MeshRouterDispatchTests.cs | 6 +- .../MeshGrpcBoundaryTests.cs | 67 +++- .../Grpc/NodeCommandGrpcServiceTests.cs | 90 +++++ .../ScriptedAlarmBroadcastVerdictTests.cs | 116 +++++++ 28 files changed, 1451 insertions(+), 72 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AlarmCommandVerdicts.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AlarmCommandVerdictTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmBroadcastVerdictTests.cs diff --git a/.claude/rules/alarms.md b/.claude/rules/alarms.md index 5e154ff40..5b30408de 100644 --- a/.claude/rules/alarms.md +++ b/.claude/rules/alarms.md @@ -105,5 +105,8 @@ deadline leaving < 250 ms, or an earlier unanswered scripted method in the same unsent; `OpcUa:Quotas:MaxNodesPerMethodCall` (1000) bounds a Call; an ask expired in the host mailbox skips the engine and is not remembered (its broadcast copy applies); the revert is guarded by a per-condition mutation counter, not field equality. Remote gRPC-data methods ride `ExecuteConditionMethodAsync` (⇒ `DriverConfirmedFailure` / `OutcomeUnknown`). Never await the verdict inside the handler -(it runs under `Lock`). The sync `base.Call` path (no asker) keeps the old fire-and-forget router. The AdminUI `/alerts` path is -still fire-and-forget. A plain SDK client sees only the status code (diagnostic text needs ReturnDiagnostics). +(it runs under `Lock`). The sync `base.Call` path (no asker) keeps the old fire-and-forget router. The AdminUI `/alerts` path +reports the verdict too since #950: `AdminOperationsActor` spawns an `AlarmCommandVerdictCollector` (7 s window) that sends +the command with `AlarmCommand.VerdictRequested`; over gRPC a node asks its driver host (`ExecuteAlarmCommand`, no ask deadline) +and answers in the additive `ExecuteAck.alarm_verdict`; over DPS each `ScriptedAlarmHostActor` answers the publish's sender +(non-owners `NotOwned`). Any owner applied ⇒ Applied; else any unknown/silent/pre-#950 node ⇒ Outcome unknown; else Refused. A plain SDK client sees only the status code (diagnostic text needs ReturnDiagnostics). diff --git a/.claude/rules/cluster-topology.md b/.claude/rules/cluster-topology.md index 88689705e..36a2d1c10 100644 --- a/.claude/rules/cluster-topology.md +++ b/.claude/rules/cluster-topology.md @@ -141,6 +141,10 @@ Things that carried over unchanged from the `ClusterClient` era, because they we nodes — the deploy coordinator's apply deadline and a node's boot-time replay are the only recovery. The old `buffer-size = 0` decision this section used to describe is gone with the HOCON block that set it; the gRPC transport has nothing to buffer in the first place — a dial either lands or doesn't. +- **One exception to one-way (#950):** an `alarm-commands` `AlarmCommandMessage` carrying `verdict_requested` (the + AdminUI `/alerts` path) is handed to the node's driver host directly and the scripted-alarm verdict rides back in the + additive `ExecuteAck.alarm_verdict`; an empty ack (pre-#950 node) is "delivered, outcome unknown". Every other command + is unchanged. See `docs/ScriptedAlarms.md` §"AdminUI path". - **Inbound commands re-emit on the node's `EventStream`, not back onto DPS.** DPS is mesh-wide, so a DPS re-publish would deliver N copies to every subscriber. Node-side subscribers (`DriverHostActor`, `ScriptedAlarmHostActor`) accept a command from either transport identically. diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md index ee9b6d1f7..375fb31bc 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -191,8 +191,8 @@ after a full rebuild, carrying the unchanged `LastTransitionUtc`. Decisions: SDK applies anything (no event, nothing routed); a call that passed that pre-check and then met a rejection (it was queued behind a load that failed) also returns `BadInvalidState` and the node is reverted — see [Operator command verdicts](#operator-command-verdicts-937). - The AdminUI `/alerts` buttons still publish fire-and-forget ("Ack sent"), so for them the only record remains the host's - Warning `… NOT applied — …`. The next good load re-asserts every node from the store. + Since #950 the AdminUI `/alerts` buttons report it too ("Refused: …" — see [AdminUI path](#adminui-path)). + The next good load re-asserts every node from the store. **Accepted trade-off:** because the next good load after a failed one reads the store (which has no `Active` column), each alarm whose predicate is still true is a new occurrence — **one transient failed deploy costs one duplicate activation (`Activated` + `Unacknowledged`, one `alerts` row) per still-true alarm** on the next good deploy. @@ -478,8 +478,7 @@ Timed→Timed re-shelve or a ClientUserId change. The captured raw severity is r **Residual.** Only the pre-check stops the SDK from applying the node change, so a refusal that arrives through the ask shows subscribers two events: the method's, then the corrective one. An OutcomeUnknown leaves the node changed (the engine may still apply it). A command racing the engine's first load queues behind it rather than failing. -**Not covered:** the AdminUI `/alerts` buttons are still fire-and-forget across the central→node transport (they report -"Ack sent", not "applied"). +The AdminUI `/alerts` buttons report the engine's verdict too since #950 — see [AdminUI path](#adminui-path). `OnTimedUnshelve` (the SDK's internal auto-unshelve timer, armed for the real remaining time since Gitea #597) is a **no-op**: the engine owns timed-shelve expiry via `ApplyShelvingCheck` (`system / AutoUnshelve`), and routing an `Unshelve` from the timer pre-empted that on every expiry as an operator-style unshelve from both pair nodes (review R1 M2). @@ -489,7 +488,30 @@ may still apply it). A command racing the engine's first load queues behind it r ### AdminUI path -The AdminUI `/alerts` page (`Alerts.razor`) shows per-row **Acknowledge / Shelve / Unshelve** buttons. These are gated by the `DriverOperator` AdminUI policy and routed through the `AdminOperationsActor` cluster singleton (`AcknowledgeAlarmCommand` / `ShelveAlarmCommand`), which publishes onto the same `alarm-commands` topic. Cross-node routing is handled by the cluster singleton — the command always reaches the driver-role node hosting the engine that owns the alarm regardless of which AdminUI instance the operator is connected to. The Shelve button accepts a duration (minutes) and passes it to `ShelveAlarmAsync(Timed, unshelveAtUtc)`; result chips auto-clear after ~8 s. The `/alerts` and `/script-log` live-status pills reflect real feed health driven by the SignalR bridge actors' DPS subscription state. +The AdminUI `/alerts` page (`Alerts.razor`) shows per-row **Acknowledge / Shelve / Unshelve** buttons. These are gated by the `DriverOperator` AdminUI policy and routed through the `AdminOperationsActor` cluster singleton (`AcknowledgeAlarmCommand` / `ShelveAlarmCommand`), which publishes onto the same `alarm-commands` topic. Cross-node routing is handled by the cluster singleton — the command always reaches the driver-role node hosting the engine that owns the alarm regardless of which AdminUI instance the operator is connected to. The Shelve button accepts a duration (minutes) and passes it to `ShelveAlarmAsync(Timed, unshelveAtUtc)`; result chips auto-clear after ~8 s. + +**The result chip is the engine's verdict (#950), not "sent".** For each request `AdminOperationsActor` spawns an +`AlarmCommandVerdictCollector`, which sends the command with `AlarmCommand.VerdictRequested` set and gathers every node's +answer for up to **7 s** (`AlarmCommandVerdictCollector.DefaultWindow`, under the client's 10 s ask), finishing early once +each node it sent to has answered: + +- **gRPC command plane** (`MeshTransport:Mode=Grpc`, every split-topology deployment): `CentralCommunicationActor` tells the + collector the dialled `ClusterNode` set, then one verdict per node. A node handles a `verdict_requested` + `AlarmCommandMessage` by asking its driver host (`ScriptedAlarmHostActor.ExecuteAlarmCommand`, the #937 path, **no ask + deadline** — nothing else carries the command to that node, so a late engine still applies it), bounded at 5 s, and + returns the outcome in the additive `ExecuteAck.alarm_verdict`. A transport failure, a timed-out engine, or an **empty + ack (a node built before #950, which takes the old one-way path)** is that node's *unknown*. +- **DistributedPubSub** (`Dps`, single mesh): the command is published with the collector as the sender; each + `ScriptedAlarmHostActor` answers it — non-owners with `AlarmCommandOutcome.NotOwned` — and the collector expects one answer + per Up `driver` member. A node built before #950 (or a driver node with no scripted-alarm host) stays silent: that node is + *unknown* and the reply waits the full window. + +Aggregation (`AlarmCommandVerdictAggregator`): **any owner applied ⇒ Applied** (green; "Applied on n of m servers" when a +peer owner refused or did not answer); else **any unknown ⇒ Outcome unknown** (amber — never "refused": that node may still +apply it); else an owner's refusal ⇒ **Refused: ** (red); else no node owns the alarm ⇒ **Not applied**. The +per-node breakdown is in the chip's "Request details". A result with no verdict (a validation failure, a server fault, or a +pre-#950 admin singleton during a rolling upgrade) renders as before. Wire changes are additive both ways: a pre-#950 +central never sets `verdict_requested`, so a new node serves it exactly as before. The `/alerts` and `/script-log` live-status pills reflect real feed health driven by the SignalR bridge actors' DPS subscription state. Under redundancy, the `alerts` topic rows are deduplicated to the Primary node — see [Redundancy.md §Primary-gated alarm emission and historization](Redundancy.md#primary-gated-alarm-emission-and-historization). diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/AcknowledgeAlarmCommand.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/AcknowledgeAlarmCommand.cs index afdc0e1ec..2395c9071 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/AcknowledgeAlarmCommand.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/AcknowledgeAlarmCommand.cs @@ -21,10 +21,17 @@ public sealed record AcknowledgeAlarmCommand( CorrelationId CorrelationId); /// Reply for . -/// True iff the command was published without error. -/// Failure reason; null on success. +/// True iff the scripted-alarm engine applied the command (#950: is Applied). +/// Detail — the per-node verdicts, or the failure reason. /// Echoes the request's correlation token. +/// +/// #950: the fleet-wide engine verdict; when the request failed before reaching any node +/// (validation, server fault). +/// +/// #950: short operator-facing text for ("Applied", "Refused: …", "Outcome unknown"). public sealed record AcknowledgeAlarmResult( bool Ok, string? Message, - CorrelationId CorrelationId); + CorrelationId CorrelationId, + OpcUa.AlarmCommandVerdict? Verdict = null, + string? Summary = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/ShelveAlarmCommand.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/ShelveAlarmCommand.cs index a5fe0012b..dec18d601 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/ShelveAlarmCommand.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Admin/ShelveAlarmCommand.cs @@ -45,10 +45,17 @@ public sealed record ShelveAlarmCommand( CorrelationId CorrelationId); /// Reply for . -/// True iff the command was published without error. -/// Failure reason; null on success. +/// True iff the scripted-alarm engine applied the command (#950: is Applied). +/// Detail — the per-node verdicts, or the failure reason. /// Echoes the request's correlation token. +/// +/// #950: the fleet-wide engine verdict; when the request failed before reaching any node +/// (validation, server fault). +/// +/// #950: short operator-facing text for . public sealed record ShelveAlarmResult( bool Ok, string? Message, - CorrelationId CorrelationId); + CorrelationId CorrelationId, + OpcUa.AlarmCommandVerdict? Verdict = null, + string? Summary = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshCommand.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshCommand.cs index 010b7c761..db589a3b3 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshCommand.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshCommand.cs @@ -25,4 +25,10 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh; /// and needs no additive-evolution discipline. /// /// -public sealed record MeshCommand(string Topic, object Message); +/// +/// #950: for an AlarmCommand whose publisher collects per-node verdicts (the AdminUI /alerts path), the +/// collector. The router tells it which nodes the command went to (AlarmVerdictFanOut) and — on the gRPC +/// plane — each node's answer; over DistributedPubSub it publishes with the collector as the sender so nodes answer +/// it directly. ⇒ the one-way behaviour, unchanged. +/// +public sealed record MeshCommand(string Topic, object Message, Akka.Actor.IActorRef? VerdictReplyTo = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs index dd3f2d6bf..1dc4af290 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Messages/Mesh/MeshTransportDtoMapper.cs @@ -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 /// Rebuilds the domain record from its wire form. /// The wire alarm command. /// The domain . + /// is node-local de-duplication state and never crosses this wire. 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) + + /// Projects a node's scripted-alarm verdict onto its ExecuteAck.alarm_verdict wire form. + /// The local host's verdict. + /// The wire . + 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; + } + + /// Rebuilds a node's verdict from ExecuteAck.alarm_verdict. + /// The wire verdict. + /// The command's alarm (the caller holds it; the wire does not repeat it). + /// The command's operation. + /// The domain outcome. + /// + /// The one decode in this file that does NOT throw on an unrecognised enum: an UNSPECIFIED or newer verdict + /// becomes . 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. + /// + 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 diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs index db6e2a1af..e39b9a39e 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs @@ -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. /// +/// +/// #950: the publisher (central's AdminUI /alerts path) collects each node's verdict. Over DistributedPubSub a +/// node's ScriptedAlarmHostActor answers the publish's sender with an +/// ( when it does not own the alarm); over the gRPC command plane the node +/// asks its local host and returns the outcome in ExecuteAck. 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. +/// public sealed record AlarmCommand( string AlarmId, string Operation, string User, string? Comment, DateTime? UnshelveAtUtc, - string? CommandId = null); + string? CommandId = null, + bool VerdictRequested = false); /// #937: what a scripted-alarm engine did with one . public enum AlarmCommandVerdict @@ -88,9 +97,16 @@ public enum AlarmCommandVerdict /// What the engine did. /// Operator-facing text for a verdict other than . /// For : the bound expired (vs. a fault). +/// +/// #950: with , 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 +/// , where a non-owner is a refusal as before. +/// public sealed record AlarmCommandOutcome( string AlarmId, string Operation, AlarmCommandVerdict Verdict, string? Reason = null, - bool TimedOut = false); + bool TimedOut = false, + bool NotOwned = false); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/mesh_transport.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/mesh_transport.proto index 848d45d28..4e8d6336b 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/mesh_transport.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/mesh_transport.proto @@ -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. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Alerts.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Alerts.razor index cc8d1e800..f527d1454 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Alerts.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Alerts.razor @@ -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 Alarms @inject AuthenticationStateProvider AuthState @inject IAuthorizationService AuthorizationService @@ -44,7 +45,7 @@ else if (_opResultMessage is not null) {
-

@_opResultSummary

+

@_opResultSummary

Last request for @_opResultAlarmId

@@ -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 diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs index 5b40d7cf1..9e6722373 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs @@ -42,6 +42,9 @@ public sealed class AdminOperationsActor : ReceiveActor private readonly ILoggingAdapter _log = Context.GetLogger(); + /// #950: how long an /alerts ack/shelve waits for the nodes' verdicts. + private readonly TimeSpan _alarmVerdictWindow; + /// The StartDeployment whose compose is running off-actor, or null. See . private StartDeployment? _composeInFlight; @@ -55,6 +58,7 @@ public sealed class AdminOperationsActor : ReceiveActor /// DistributedPubSub mediator directly (the behaviour before the per-cluster mesh). /// /// The coordinator's apply deadline; defaults to (the coordinator's default source). + /// #950: how long an /alerts ack/shelve waits for the nodes' verdicts; defaults to . /// Props configured to create an AdminOperationsActor. public static Props Props( IDbContextFactory dbFactory, @@ -62,9 +66,10 @@ public sealed class AdminOperationsActor : ReceiveActor IEnumerable 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)); /// Initializes a new instance of the AdminOperationsActor. /// Factory for creating config database contexts. @@ -73,14 +78,17 @@ public sealed class AdminOperationsActor : ReceiveActor /// Deploy-gate TagConfig strictness mode (Warn default | Error opt-in). /// Central comm actor, or for the mediator. /// The coordinator's apply deadline; defaults to (the coordinator's default source). + /// #950: the /alerts verdict collection window. public AdminOperationsActor( IDbContextFactory dbFactory, IActorRef coordinator, IEnumerable 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)); } + /// + /// #950: spawns the per-request verdict collector, which sends (via the mesh router, or + /// DistributedPubSub when none is wired) and answers with . + /// + private void CollectVerdict(AlarmCommand command, IActorRef replyTo, Func reply) => + Context.ActorOf(AlarmCommandVerdictCollector.Props(command, _meshRouter, replyTo, reply, _alarmVerdictWindow)); + /// /// AdminUI Acknowledge path. Maps the control-plane command to a - /// (Operation = "Acknowledge") and publishes it onto the - /// cluster alarm-commands topic. The broadcast lands on every driver node's - /// ScriptedAlarmHostActor; 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. + /// (Operation = "Acknowledge") and hands it to an + /// , which sends it to every driver node (the ownership filter on each + /// node's ScriptedAlarmHostActor 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. /// 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 to the matching /// operation (OneShotShelve / TimedShelve / /// Unshelve), threading for the timed kind, - /// and publishes onto the cluster alarm-commands topic. Ownership filtering happens on the - /// owning node exactly as for Acknowledge. + /// and sends it exactly as does — ownership filtered on the nodes, verdicts + /// collected and reported (#950). /// 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) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AlarmCommandVerdicts.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AlarmCommandVerdicts.cs new file mode 100644 index 000000000..033834814 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AlarmCommandVerdicts.cs @@ -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; + +/// +/// #950: router → collector. Which nodes an AdminUI alarm command went to — the set the +/// waits on. +/// +/// +/// The nodes expected to answer (gRPC: the dialled ClusterNode ids; DistributedPubSub: the Up driver +/// members' host:port). Empty with a null ⇒ the set is unknown and the +/// collector waits out its window. +/// +/// Set when the command reached no node at all (no targets, no dialer, unencodable). +public sealed record AlarmVerdictFanOut(IReadOnlyList Nodes, string? NotDeliveredReason = null); + +/// #950: one node's answer to an AdminUI alarm command, as the gRPC router saw it. +/// The node (its ClusterNode id). +/// Its verdict; transport failures and pre-#950 nodes arrive as . +public sealed record AlarmNodeVerdict(string Node, AlarmCommandOutcome Outcome); + +/// #950: the fleet-wide verdict on one AdminUI alarm command. +/// Applied when any owning node applied it; OutcomeUnknown when none did but one may have; else NotApplied. +/// Short operator-facing text (the /alerts result chip). +/// Per-node breakdown (the result's details pane). +public sealed record AlarmCommandFleetOutcome(AlarmCommandVerdict Verdict, string Summary, string Detail); + +/// +/// #950: folds the per-node answers to one AdminUI alarm command into the verdict the operator sees. +/// +/// +/// +/// 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: any owner applied ⇒ Applied +/// (other owners' refusals/unknowns are listed, and the summary says it was partial); otherwise any unknown — an +/// owner that timed out, a node that did not answer, a transport failure, a pre-#950 node — ⇒ OutcomeUnknown, +/// 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. +/// +/// +public static class AlarmCommandVerdictAggregator +{ + /// Aggregates the answers. + /// Node → its verdict (non-owners carry ). + /// Expected nodes that did not answer within the window. + /// Whether the set of nodes the command reached is known (false ⇒ silence may hide an owner). + /// Set when the command reached no node at all. + /// The collection window, for the "no answer" text. + /// The fleet verdict. + public static AlarmCommandFleetOutcome Aggregate( + IReadOnlyDictionary answers, + IReadOnlyCollection 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."), + }; +} + +/// +/// #950: the DistributedPubSub leg of an AdminUI alarm command that wants verdicts — used by the router under +/// MeshTransport:Mode = Dps and by when no router is wired. +/// +public static class AlarmVerdictDps +{ + /// + /// Publishes on with 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 driver role, keyed as keys them. + /// + /// The actor system. + /// The DPS topic. + /// The command (with set). + /// Who the nodes answer. + /// The expected node keys; empty when the membership could not be read. + public static IReadOnlyList Publish(ActorSystem system, string topic, AlarmCommand command, IActorRef collector) + { + IReadOnlyList 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; + } + + /// The key a DPS-answering node is known by: its host:port (a local-scope address is this node). + /// The member or reply-sender address. + /// This node's cluster address, or null when there is no cluster. + /// The key. + 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(); + } +} + +/// +/// #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 (mapped by the caller's +/// reply) to the original requester. Stops itself after replying. +/// +public sealed class AlarmCommandVerdictCollector : ReceiveActor, IWithTimers +{ + /// The default collection window — under AdminOperationsClient's 10 s ask. + 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 _reply; + private readonly TimeSpan _window; + private readonly ILoggingAdapter _log = Context.GetLogger(); + private readonly Dictionary _answers = new(StringComparer.Ordinal); + private HashSet? _expected; + private string? _notDelivered; + private Address? _self; + + /// Gets or sets the timer scheduler. + public ITimerScheduler Timers { get; set; } = null!; + + /// Creates the props. + /// The command; is forced on. + /// The central comm actor, or null to publish on DistributedPubSub directly. + /// The requester. + /// Maps the fleet verdict to the requester's reply message. + /// The collection window. + /// The props. + public static Props Props(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo, + Func reply, TimeSpan window) => + Akka.Actor.Props.Create(() => new AlarmCommandVerdictCollector(command, meshRouter, replyTo, reply, window)); + + /// Initializes a new instance of the class. + /// The command. + /// The router, or null. + /// The requester. + /// Maps the verdict to the reply. + /// The collection window. + public AlarmCommandVerdictCollector(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo, + Func reply, TimeSpan window) + { + _command = command with { VerdictRequested = true }; + _meshRouter = meshRouter; + _replyTo = replyTo; + _reply = reply; + _window = window; + + Receive(msg => + { + _expected = new HashSet(msg.Nodes, StringComparer.Ordinal); + _notDelivered = msg.NotDeliveredReason; + FinishIfComplete(); + }); + Receive(msg => + { + _answers[msg.Node] = msg.Outcome; + FinishIfComplete(); + }); + // A DistributedPubSub answer straight from a node's ScriptedAlarmHostActor: the node is the sender. + Receive(outcome => + { + if (!string.Equals(outcome.AlarmId, _command.AlarmId, StringComparison.Ordinal)) return; + _answers[AlarmVerdictDps.NodeKey(Sender.Path.Address, _self)] = outcome; + FinishIfComplete(); + }); + Receive(_ => Finish()); + } + + /// + 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(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/CentralCommunicationActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/CentralCommunicationActor.cs index 16f7b5d46..14ab094fa 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/CentralCommunicationActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/CentralCommunicationActor.cs @@ -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)); } + /// #950: tells a verdict collector the command reached no node, so it answers at once instead of at its window. + private static void ReportNotDelivered(MeshCommand cmd, string reason) => + cmd.VerdictReplyTo?.Tell(new AlarmVerdictFanOut([], reason)); + /// /// Encodes one command once and fans it to every target node, one unary gRPC call each. /// @@ -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); } + /// + /// #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. + /// + 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. /// + /// #950: the node's reply on success (carries an alarm verdict when one was requested). + /// #950: the AdminUI alarm command's verdict collector, when one is waiting. + /// #950: the alarm command, when is set. 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); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/MeshGrpcCommandDialer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/MeshGrpcCommandDialer.cs index 31a19b132..f55278955 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/MeshGrpcCommandDialer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Communication/MeshGrpcCommandDialer.cs @@ -35,6 +35,22 @@ public interface IMeshCommandDialer /// Task DispatchAsync(string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct); + /// + /// #950: returning the node's , whose alarm_verdict + /// carries a scripted-alarm verdict when the command asked for one. The default (a dialer that only implements + /// ) answers an empty ack — "delivered, no verdict". + /// + /// The node's gRPC base address. + /// The wire envelope. + /// The target node's application Cluster. + /// Cancels the dial. + /// The node's ack. + async Task ExecuteAsync(string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct) + { + await DispatchAsync(nodeEndpoint, envelope, clusterId, ct).ConfigureAwait(false); + return new ExecuteAck(); + } + /// /// Releases any per-endpoint resources for endpoints NOT in /// (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; /// - public async Task DispatchAsync( + public Task DispatchAsync( + string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct) + => ExecuteAsync(nodeEndpoint, envelope, clusterId, ct); + + /// + public async Task 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); } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/NodeCommandGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/NodeCommandGrpcService.cs index 961a03571..365e03026 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/NodeCommandGrpcService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/NodeCommandGrpcService.cs @@ -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(out var comm)) { _log.LogWarning( @@ -107,4 +112,69 @@ public sealed class NodeCommandGrpcService : GeneratedServiceBase return Task.FromResult(new ExecuteAck()); } + + /// + /// #950: an AdminUI alarm command that wants this node's verdict. Asks the local driver host (which forwards to its + /// ScriptedAlarmHostActor — the same ExecuteAlarmCommand path the OPC UA Part 9 methods use, #937) and + /// returns the verdict in . Never re-emitted on the EventStream as well: this + /// node's host gets exactly one copy, as on the one-way path. + /// + /// + /// + /// No deadline on the ask message. 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 + /// must still apply (the one-way semantic it replaces); the caller is told + /// OutcomeUnknown, never "not applied". + /// + /// + /// 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 ⇒ + /// , as for every other command. + /// + /// + private async Task ExecuteForVerdictAsync(AlarmCommand alarm, string correlationId, CancellationToken ct) + { + AlarmCommandOutcome outcome; + if (!_registry.TryGet(out var driverHost)) + { + if (!_registry.TryGet(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( + 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) }; + } + + /// + /// #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. + /// + internal TimeSpan VerdictWait { get; init; } = TimeSpan.FromSeconds(5); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 998c5ef06..54b1f747e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -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) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs index 427cac6f4..04d3b183f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs @@ -788,12 +788,18 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor /// The inbound alarm command. 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); } /// @@ -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); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs index ce19d0daa..262d04565 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/MeshTransportDtoMapperTests.cs @@ -96,6 +96,46 @@ public class MeshTransportDtoMapperTests MeshTransportDtoMapper.FromProto(Wire(MeshTransportDtoMapper.ToProto(domain))).ShouldBe(domain); } + /// #950: the verdict request survives the wire; an absent field (a pre-#950 central) reads false. + [Fact] + public void AlarmCommand_VerdictRequested_RoundTrips_and_defaults_false() + { + var domain = new AlarmCommand("alarm-42", "Acknowledge", "jdoe", null, null, VerdictRequested: true); + MeshTransportDtoMapper.FromProto(Wire(MeshTransportDtoMapper.ToProto(domain))).ShouldBe(domain); + + var legacy = new AlarmCommandMessage { AlarmId = "alarm-42", Operation = "Acknowledge", User = "jdoe" }; + MeshTransportDtoMapper.FromProto(Wire(legacy)).VerdictRequested.ShouldBeFalse(); + } + + /// #950: every verdict shape round-trips through ExecuteAck.alarm_verdict. + [Theory] + [InlineData(AlarmCommandVerdict.Applied, null, false, false)] + [InlineData(AlarmCommandVerdict.NotApplied, "last load failed", false, false)] + [InlineData(AlarmCommandVerdict.NotApplied, "not loaded here", false, true)] + [InlineData(AlarmCommandVerdict.OutcomeUnknown, "store stalled", true, false)] + [InlineData(AlarmCommandVerdict.NotApplied, "", false, false)] + public void AlarmVerdict_RoundTrips(AlarmCommandVerdict verdict, string? reason, bool timedOut, bool notOwned) + { + var outcome = new AlarmCommandOutcome("alarm-42", "Acknowledge", verdict, reason, timedOut, notOwned); + + var ack = Wire(new ExecuteAck { AlarmVerdict = MeshTransportDtoMapper.ToProto(outcome) }); + + MeshTransportDtoMapper.FromProto(ack.AlarmVerdict, "alarm-42", "Acknowledge").ShouldBe(outcome); + } + + /// + /// #950: an empty ExecuteAck (every pre-#950 node) carries no verdict, and an UNSPECIFIED verdict never + /// decodes as applied — it is unknown. + /// + [Fact] + public void AlarmVerdict_absent_or_unspecified_is_never_applied() + { + Wire(new ExecuteAck()).AlarmVerdict.ShouldBeNull(); + + var decoded = MeshTransportDtoMapper.FromProto(new AlarmVerdictMessage(), "alarm-42", "Acknowledge"); + decoded.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + } + [Fact] public void AlarmCommand_RoundTrips_WithNullComment() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AlertsAckPathTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AlertsAckPathTests.cs index 7f5f69dc5..5972eb901 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AlertsAckPathTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AlertsAckPathTests.cs @@ -1,3 +1,4 @@ +using Akka.Actor; using Akka.Hosting; using Akka.TestKit.Xunit; using Shouldly; @@ -28,9 +29,22 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests; /// public sealed class AlertsAckPathTests : TestKit { - private (AdminOperationsClient Client, Akka.TestKit.TestProbe Mesh) Wire() + private (AdminOperationsClient Client, Akka.TestKit.TestProbe Mesh) Wire( + Func? answer = null) { var mesh = CreateTestProbe("mesh-router"); + // #950: the router's one node answers each alarm command (Applied by default), as the gRPC fan reports it. + answer ??= cmd => new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied); + mesh.SetAutoPilot(new Akka.TestKit.DelegateAutoPilot((_, msg) => + { + if (msg is MeshCommand { VerdictReplyTo: { } collector, Message: AlarmCommand cmd }) + { + collector.Tell(new AlarmVerdictFanOut(["node-1"])); + collector.Tell(new AlarmNodeVerdict("node-1", answer(cmd))); + } + + return Akka.TestKit.AutoPilot.KeepRunning; + })); var actor = Sys.ActorOf(AdminOperationsActor.Props( AclScopeTestDb.Factory($"alerts-ack-{Guid.NewGuid():N}"), coordinator: CreateTestProbe("coordinator").Ref, @@ -42,16 +56,18 @@ public sealed class AlertsAckPathTests : TestKit } /// The page's Acknowledge reaches the cluster as an Acknowledge AlarmCommand on the - /// alarm-commands topic carrying the alarm id and the operator, and the page is told it was sent. + /// alarm-commands topic carrying the alarm id and the operator, and the page is told the engine applied it + /// (#950 — it used to be told only that it was sent). [Fact] - public async Task Acknowledge_from_the_alerts_page_dispatches_an_Acknowledge_command_and_reports_sent() + public async Task Acknowledge_from_the_alerts_page_dispatches_an_Acknowledge_command_and_reports_applied() { var (client, mesh) = Wire(); var result = await client.AcknowledgeAlarmAsync("alarm-42", "operator-jo", comment: null, CancellationToken.None); result.Ok.ShouldBeTrue(); - result.Message.ShouldBeNull(); + result.Verdict.ShouldBe(AlarmCommandVerdict.Applied); + result.Summary.ShouldBe("Applied"); var sent = mesh.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); sent.Topic.ShouldBe(AlarmCommandsTopic.Name); var command = sent.Message.ShouldBeOfType(); @@ -78,4 +94,18 @@ public sealed class AlertsAckPathTests : TestKit command.Operation.ShouldBe("TimedShelve"); command.UnshelveAtUtc.ShouldBe(until); } + + /// #950: the engine's refusal reaches the page as a refusal with its reason, not as "sent". + [Fact] + public async Task A_refused_acknowledge_reaches_the_page_with_the_engines_reason() + { + var (client, _) = Wire(cmd => new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, + "The last configuration load failed; the command was not applied.")); + + var result = await client.AcknowledgeAlarmAsync("alarm-42", "operator-jo", comment: null, CancellationToken.None); + + result.Ok.ShouldBeFalse(); + result.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + result.Summary.ShouldBe("Refused: The last configuration load failed; the command was not applied."); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/AlarmOperationFormTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/AlarmOperationFormTests.cs index 46d952479..a36488742 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/AlarmOperationFormTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/AlarmOperationFormTests.cs @@ -83,6 +83,18 @@ public sealed class AlarmOperationFormTests:BunitContext cut.WaitForAssertion(()=>cut.FindAll("[role=status]").Count(x=>x.TextContent.Contains("Ack sent")).ShouldBe(1)); cut.FindAll("details").ShouldContain(x=>x.TextContent.Contains("Request details")); } + // #950: the chip shows the engine's verdict — green Applied, red Refused (reason), amber Outcome unknown. + [Theory] + [InlineData(ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AlarmCommandVerdict.Applied,true,"Applied","chip-ok")] + [InlineData(ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AlarmCommandVerdict.NotApplied,false,"Refused: the last load failed","chip-bad")] + [InlineData(ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AlarmCommandVerdict.OutcomeUnknown,false,"Outcome unknown","chip-warn")] + public void AcknowledgeOutcome_ShowsTheEngineVerdict(ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AlarmCommandVerdict verdict,bool ok,string summary,string chip) + { + Service.Ack=_=>Task.FromResult(new AcknowledgeAlarmResult(ok,"site-a-1: per-node detail",new(Guid.Empty),verdict,summary));var cut=Page("alarm-a"); + cut.Find("tbody button").Click(); + cut.WaitForAssertion(()=>{var c=cut.Find("[role=status] .chip");c.TextContent.ShouldBe(summary);c.ClassList.ShouldContain(chip);}); + cut.Markup.ShouldContain("site-a-1: per-node detail");cut.Markup.ShouldNotContain("Ack sent"); + } [Fact] public async Task DisposedPage_DoesNotRenderLateAcknowledgementOutcome() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorMailboxTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorMailboxTests.cs index 2d14b2c09..fb32e137f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorMailboxTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorMailboxTests.cs @@ -22,6 +22,27 @@ public sealed class AdminOperationsActorMailboxTests : ControlPlaneActorTestBase { private static readonly TimeSpan AckBudget = TimeSpan.FromSeconds(1); + /// + /// #950: a mesh router whose one node applies every alarm command at once — so the ack's reply measures the + /// admin mailbox, not a verdict window. + /// + private IActorRef AnsweringRouter() + { + var router = CreateTestProbe(); + router.SetAutoPilot(new Akka.TestKit.DelegateAutoPilot((_, msg) => + { + if (msg is Commons.Messages.Mesh.MeshCommand { VerdictReplyTo: { } collector, Message: Commons.OpcUa.AlarmCommand cmd }) + { + collector.Tell(new AlarmVerdictFanOut(["node-1"])); + collector.Tell(new AlarmNodeVerdict("node-1", + new Commons.OpcUa.AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, Commons.OpcUa.AlarmCommandVerdict.Applied))); + } + + return Akka.TestKit.AutoPilot.KeepRunning; + })); + return router.Ref; + } + /// An alarm ack completes in under a second while a 60 s Test Connect is still pending. [Fact] public void Alarm_ack_completes_while_a_60s_test_connect_is_pending() @@ -29,7 +50,8 @@ public sealed class AdminOperationsActorMailboxTests : ControlPlaneActorTestBase var dbFactory = NewInMemoryDbFactory(); var coordinator = CreateTestProbe("coord"); var probe = new BlockingProbe(); - var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, new IDriverProbe[] { probe })); + var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, new IDriverProbe[] { probe }, + meshRouter: AnsweringRouter())); var connectClient = CreateTestProbe("connect-client"); connectClient.Send(actor, new TestDriverConnect("Blocking", "{}", TimeoutSeconds: 60, Guid.NewGuid())); @@ -74,7 +96,7 @@ public sealed class AdminOperationsActorMailboxTests : ControlPlaneActorTestBase { var gated = new GatedDbFactory(NewInMemoryDbFactory()); var coordinator = CreateTestProbe("coord"); - var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty())); + var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty(), meshRouter: AnsweringRouter())); var deployer = CreateTestProbe("deployer"); gated.Hold(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorTests.cs index 237f68dd2..16892d117 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorTests.cs @@ -29,9 +29,19 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase // message sender, not to the subscribed ref). Mirrors ScriptedAlarmHostActor's self-subscribe. probe.Send(mediator, new Subscribe(AlarmCommandsTopic.Name, probe.Ref)); probe.ExpectMsg(TimeSpan.FromSeconds(5)); + // #950: play a node's ScriptedAlarmHostActor — answer the publish's sender (the verdict collector) Applied. + probe.SetAutoPilot(new DelegateAutoPilot((sender, msg) => + { + if (msg is AlarmCommand { VerdictRequested: true } cmd) + sender.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied), probe.Ref); + return AutoPilot.KeepRunning; + })); return probe; } + /// #950: the verdict window; the test system has no driver members, so the collector waits it out. + private static readonly TimeSpan VerdictWindow = TimeSpan.FromSeconds(1); + /// Verifies an publishes a correctly-mapped /// (Operation="Acknowledge", AlarmId/User/Comment threaded, no /// UnshelveAtUtc) onto the alarm-commands topic and replies Ok. @@ -40,7 +50,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase { var dbFactory = NewInMemoryDbFactory(); var coordinator = CreateTestProbe("coord"); - var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty())); + var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty(), alarmVerdictWindow: VerdictWindow)); var topicProbe = SubscribeAlarmCommandsProbe(); var correlationId = CorrelationId.NewId(); @@ -55,7 +65,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase var reply = ExpectMsg(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken); reply.Ok.ShouldBeTrue(); - reply.Message.ShouldBeNull(); + reply.Verdict.ShouldBe(AlarmCommandVerdict.Applied); reply.CorrelationId.ShouldBe(correlationId); } @@ -66,7 +76,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase { var dbFactory = NewInMemoryDbFactory(); var coordinator = CreateTestProbe("coord"); - var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty())); + var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty(), alarmVerdictWindow: VerdictWindow)); var topicProbe = SubscribeAlarmCommandsProbe(); var correlationId = CorrelationId.NewId(); @@ -90,7 +100,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase { var dbFactory = NewInMemoryDbFactory(); var coordinator = CreateTestProbe("coord"); - var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty())); + var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty(), alarmVerdictWindow: VerdictWindow)); var topicProbe = SubscribeAlarmCommandsProbe(); var unshelveAt = DateTime.UtcNow.AddMinutes(15); @@ -113,7 +123,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase { var dbFactory = NewInMemoryDbFactory(); var coordinator = CreateTestProbe("coord"); - var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty())); + var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty(), alarmVerdictWindow: VerdictWindow)); var topicProbe = SubscribeAlarmCommandsProbe(); actor.Tell(new ShelveAlarmCommand("alarm-3", "op-sam", ShelveKind.Unshelve, UnshelveAtUtc: null, Comment: null, CorrelationId.NewId())); @@ -132,7 +142,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase { var dbFactory = NewInMemoryDbFactory(); var coordinator = CreateTestProbe("coord"); - var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty())); + var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty(), alarmVerdictWindow: VerdictWindow)); var topicProbe = SubscribeAlarmCommandsProbe(); actor.Tell(new ShelveAlarmCommand("alarm-1", "op-zoe", ShelveKind.Timed, UnshelveAtUtc: null, Comment: null, CorrelationId.NewId())); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AlarmCommandVerdictTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AlarmCommandVerdictTests.cs new file mode 100644 index 000000000..a4e43ce14 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AlarmCommandVerdictTests.cs @@ -0,0 +1,252 @@ +using Akka.Actor; +using Akka.Cluster.Tools.PublishSubscribe; +using Akka.TestKit; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Cluster; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Communication; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; + +/// +/// #950 — the AdminUI /alerts ack/shelve reports the scripted-alarm engine's verdict instead of "sent": the +/// per-request , the fleet aggregation, and both router legs. +/// +public sealed class AlarmCommandVerdictTests : ControlPlaneActorTestBase +{ + private static readonly TimeSpan Window = TimeSpan.FromSeconds(7); + + private static AlarmCommandOutcome Applied => new("alarm-1", "Acknowledge", AlarmCommandVerdict.Applied); + + private static AlarmCommandOutcome Refused(string reason) => + new("alarm-1", "Acknowledge", AlarmCommandVerdict.NotApplied, reason); + + private static AlarmCommandOutcome NotOwned => + new("alarm-1", "Acknowledge", AlarmCommandVerdict.NotApplied, "not loaded", NotOwned: true); + + private static AlarmCommandOutcome Unknown => new("alarm-1", "Acknowledge", AlarmCommandVerdict.OutcomeUnknown, "store stalled", TimedOut: true); + + private static AlarmCommandFleetOutcome Aggregate( + Dictionary answers, string[]? unanswered = null, bool expectedKnown = true, + string? notDelivered = null) => + AlarmCommandVerdictAggregator.Aggregate(answers, unanswered ?? [], expectedKnown, notDelivered, Window); + + // ------------------------------------------------------------------ aggregation + + [Fact] + public void Every_owner_applied_is_Applied() + { + var o = Aggregate(new() { ["a1"] = Applied, ["a2"] = Applied, ["b1"] = NotOwned }); + o.Verdict.ShouldBe(AlarmCommandVerdict.Applied); + o.Summary.ShouldBe("Applied"); + o.Detail.ShouldContain("b1: does not own this alarm."); + } + + [Fact] + public void One_owner_applied_and_its_peer_refused_is_a_partial_Applied() + { + var o = Aggregate(new() { ["a1"] = Applied, ["a2"] = Refused("last load failed") }); + o.Verdict.ShouldBe(AlarmCommandVerdict.Applied); + o.Summary.ShouldBe("Applied on 1 of 2 servers"); + o.Detail.ShouldContain("a2: refused — last load failed"); + } + + [Fact] + public void An_owner_refusal_with_no_applier_and_no_unknown_is_Refused_with_its_reason() + { + var o = Aggregate(new() { ["a1"] = Refused("last load failed"), ["b1"] = NotOwned }); + o.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + o.Summary.ShouldBe("Refused: last load failed"); + } + + [Fact] + public void A_refusal_beside_an_unknown_is_unknown_never_refused() + { + // The unknown node may still apply it: claiming "refused" would be the exact lie #937 removed from the OPC UA path. + var o = Aggregate(new() { ["a1"] = Refused("last load failed"), ["a2"] = Unknown }); + o.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + o.Summary.ShouldBe("Outcome unknown"); + } + + [Fact] + public void A_silent_expected_node_is_unknown() + { + var o = Aggregate(new() { ["b1"] = NotOwned }, unanswered: ["a1"]); + o.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + o.Detail.ShouldContain("a1: no answer within 7 s"); + } + + [Fact] + public void No_owner_anywhere_is_NotApplied() + { + var o = Aggregate(new() { ["a1"] = NotOwned, ["b1"] = NotOwned }); + o.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + o.Summary.ShouldBe("Not applied: no server owns this alarm"); + } + + [Fact] + public void No_owner_among_answers_from_an_unknown_node_set_is_unknown() + { + // DPS with no readable membership: a silent pre-#950 owner is indistinguishable from no owner. + var o = Aggregate(new() { ["b1"] = NotOwned }, expectedKnown: false); + o.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + } + + [Fact] + public void A_command_that_reached_no_node_is_NotApplied_Not_delivered() + { + var o = Aggregate(new(), notDelivered: "no enabled, non-maintenance ClusterNode row carries a GrpcPort."); + o.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + o.Summary.ShouldBe("Not delivered"); + o.Detail.ShouldContain("GrpcPort"); + } + + // ------------------------------------------------------------------ collector, via a router + + private (IActorRef Admin, TestProbe Router) WireAdmin(TimeSpan? window = null) + { + var router = CreateTestProbe("router"); + var admin = Sys.ActorOf(AdminOperationsActor.Props( + NewInMemoryDbFactory(), CreateTestProbe().Ref, Enumerable.Empty(), + TagConfigValidationMode.Warn, router.Ref, alarmVerdictWindow: window ?? TimeSpan.FromSeconds(10))); + return (admin, router); + } + + [Fact] + public void Ack_reports_Applied_as_soon_as_every_dialled_node_has_answered() + { + var (admin, router) = WireAdmin(); + var correlation = CorrelationId.NewId(); + + admin.Tell(new AcknowledgeAlarmCommand("alarm-1", "alice", null, correlation)); + + var sent = router.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + sent.Topic.ShouldBe(AlarmCommandsTopic.Name); + sent.Message.ShouldBeOfType().VerdictRequested.ShouldBeTrue(); + var collector = sent.VerdictReplyTo.ShouldNotBeNull(); + collector.Tell(new AlarmVerdictFanOut(["site-a-1", "site-a-2", "main-1"])); + collector.Tell(new AlarmNodeVerdict("site-a-1", Applied)); + collector.Tell(new AlarmNodeVerdict("main-1", NotOwned)); + ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken); // site-a-2 still owed + collector.Tell(new AlarmNodeVerdict("site-a-2", Applied)); + + // Well inside the 10 s window: the reply does not wait it out once everyone answered. + var reply = ExpectMsg(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken); + reply.Ok.ShouldBeTrue(); + reply.Verdict.ShouldBe(AlarmCommandVerdict.Applied); + reply.Summary.ShouldBe("Applied"); + reply.CorrelationId.ShouldBe(correlation); + } + + [Fact] + public void Shelve_reports_the_owners_refusal_reason() + { + var (admin, router) = WireAdmin(); + + admin.Tell(new ShelveAlarmCommand("alarm-1", "alice", ShelveKind.OneShot, null, null, CorrelationId.NewId())); + + var collector = router.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).VerdictReplyTo!; + collector.Tell(new AlarmVerdictFanOut(["a1", "b1"])); + collector.Tell(new AlarmNodeVerdict("a1", Refused("The last configuration load failed; the command was not applied."))); + collector.Tell(new AlarmNodeVerdict("b1", NotOwned)); + + var reply = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + reply.Ok.ShouldBeFalse(); + reply.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + reply.Summary.ShouldBe("Refused: The last configuration load failed; the command was not applied."); + } + + [Fact] + public void A_node_that_never_answers_makes_the_outcome_unknown_at_the_window() + { + var (admin, router) = WireAdmin(TimeSpan.FromSeconds(1)); + + admin.Tell(new AcknowledgeAlarmCommand("alarm-1", "alice", null, CorrelationId.NewId())); + + var collector = router.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).VerdictReplyTo!; + collector.Tell(new AlarmVerdictFanOut(["a1", "a2"])); + collector.Tell(new AlarmNodeVerdict("a2", NotOwned)); + + var reply = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + reply.Ok.ShouldBeFalse(); + reply.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + reply.Message.ShouldNotBeNull().ShouldContain("a1: no answer within 1 s"); + } + + [Fact] + public void A_command_the_router_could_not_deliver_is_reported_at_once() + { + var (admin, router) = WireAdmin(); + + admin.Tell(new AcknowledgeAlarmCommand("alarm-1", "alice", null, CorrelationId.NewId())); + + router.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .VerdictReplyTo!.Tell(new AlarmVerdictFanOut([], "no enabled, non-maintenance ClusterNode row carries a GrpcPort.")); + + var reply = ExpectMsg(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken); + reply.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + reply.Summary.ShouldBe("Not delivered"); + } + + // ------------------------------------------------------------------ DistributedPubSub legs + + /// Subscribes a probe that plays a node's ScriptedAlarmHostActor: answers to the publish's sender. + private TestProbe SubscribeAnsweringHost(Func answer) + { + var host = CreateTestProbe("host"); + host.SetAutoPilot(new DelegateAutoPilot((sender, msg) => + { + if (msg is AlarmCommand cmd && answer(cmd) is { } outcome) sender.Tell(outcome, host.Ref); + return AutoPilot.KeepRunning; + })); + var mediator = DistributedPubSub.Get(Sys).Mediator; + var subscriber = CreateTestProbe(); + mediator.Tell(new Subscribe(AlarmCommandsTopic.Name, host.Ref), subscriber.Ref); + subscriber.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + return host; + } + + [Fact] + public void With_no_router_the_publish_carries_the_collector_as_sender_and_the_hosts_answer_counts() + { + AlarmCommand? seen = null; + SubscribeAnsweringHost(cmd => + { + seen = cmd; + return cmd.VerdictRequested ? Applied : null; + }); + var admin = Sys.ActorOf(AdminOperationsActor.Props( + NewInMemoryDbFactory(), CreateTestProbe().Ref, Enumerable.Empty(), + alarmVerdictWindow: TimeSpan.FromSeconds(1))); + + admin.Tell(new AcknowledgeAlarmCommand("alarm-1", "alice", null, CorrelationId.NewId())); + + var reply = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + reply.Verdict.ShouldBe(AlarmCommandVerdict.Applied); + seen.ShouldNotBeNull().VerdictRequested.ShouldBeTrue(); + } + + [Fact] + public void Dps_router_publishes_with_the_collector_as_sender() + { + SubscribeAnsweringHost(cmd => cmd.VerdictRequested ? Refused("nope") : null); + var router = Sys.ActorOf(CentralCommunicationActor.Props( + NewInMemoryDbFactory(), new MeshTransportOptions(), () => null)); + var collector = CreateTestProbe("collector"); + + router.Tell(new MeshCommand(AlarmCommandsTopic.Name, + new AlarmCommand("alarm-1", "Acknowledge", "alice", null, null, VerdictRequested: true), collector.Ref)); + + collector.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .NotDeliveredReason.ShouldBeNull(); + collector.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Reason.ShouldBe("nope"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/CentralCommunicationActorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/CentralCommunicationActorTests.cs index 39c1747c1..b28eba9fb 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/CentralCommunicationActorTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/CentralCommunicationActorTests.cs @@ -414,6 +414,75 @@ public class CentralCommunicationActorTests : ControlPlaneActorTestBase rig.Dialer.Calls[0].Envelope.AlarmCommand.AlarmId.ShouldBe("alarm-1"); } + /// + /// #950: an alarm command with a verdict collector tells it the dialled set first, then one verdict per node — + /// the node's own (from ExecuteAck.alarm_verdict), "no verdict" (an empty ack: a pre-#950 node), or the + /// transport failure, each of the last two UNKNOWN, never refused. + /// + [Fact] + public void An_alarm_command_with_a_collector_reports_each_nodes_verdict() + { + var factory = NewInMemoryDbFactory(); + SeedGrpcCluster( + factory, + "C1", + ("node-a", "host-a", 4056, true, false), + ("node-b", "host-b", 4056, true, false), + ("node-c", "host-c", 4056, true, false)); + var dialer = new RecordingDialer + { + FailEndpointsContaining = "host-c", + Fault = new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Unavailable, "connection refused")), + Answer = endpoint => endpoint.Contains("host-a") + ? new ExecuteAck { AlarmVerdict = new AlarmVerdictMessage { Verdict = AlarmVerdict.Applied } } + : new ExecuteAck(), + }; + var rig = SpawnGrpcRig(factory, dialer); + AwaitContactsLoaded(rig); + var collector = CreateTestProbe("collector"); + + rig.Actor.Tell(new MeshCommand( + "alarm-commands", + new AlarmCommand("alarm-1", "Acknowledge", "operator", null, null, VerdictRequested: true), + collector.Ref)); + + collector.ExpectMsg( + PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Nodes.ShouldBe(new[] { "node-a", "node-b", "node-c" }, ignoreOrder: true); + var verdicts = Enumerable.Range(0, 3) + .Select(_ => collector.ExpectMsg( + PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)) + .ToDictionary(v => v.Node, v => v.Outcome); + + verdicts["node-a"].Verdict.ShouldBe(AlarmCommandVerdict.Applied); + verdicts["node-b"].Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + verdicts["node-b"].Reason.ShouldNotBeNull().ShouldContain("older than #950"); + verdicts["node-c"].Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + verdicts["node-c"].Reason.ShouldNotBeNull().ShouldContain("Unavailable"); + rig.Dialer.Calls.ShouldAllBe(c => c.Envelope.AlarmCommand.VerdictRequested); + } + + /// #950: with nothing to dial, the collector hears "not delivered" at once rather than waiting out its window. + [Fact] + public void An_alarm_command_with_a_collector_and_no_targets_is_reported_not_delivered() + { + var factory = NewInMemoryDbFactory(); + SeedGrpcCluster(factory, "C1", ("node-a", "host-a", null, true, false)); + var rig = SpawnGrpcRig(factory); + AwaitContactsLoaded(rig); + var collector = CreateTestProbe("collector"); + + rig.Actor.Tell(new MeshCommand( + "alarm-commands", + new AlarmCommand("alarm-1", "Acknowledge", "operator", null, null, VerdictRequested: true), + collector.Ref)); + + var fan = collector.ExpectMsg( + PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + fan.Nodes.ShouldBeEmpty(); + fan.NotDeliveredReason.ShouldNotBeNull().ShouldContain("GrpcPort"); + } + [Fact] public void The_contact_refresh_publishes_the_known_cluster_set_and_drops_cached_psks() { @@ -1042,6 +1111,16 @@ public class CentralCommunicationActorTests : ControlPlaneActorTestBase : Task.CompletedTask; } + /// #950: what a successful dial answers, per endpoint; null ⇒ an empty ack. + public Func? Answer { get; set; } + + public async Task ExecuteAsync( + string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct) + { + await DispatchAsync(nodeEndpoint, envelope, clusterId, ct); + return Answer?.Invoke(nodeEndpoint) ?? new ExecuteAck(); + } + /// Every endpoint set handed to , in order. public IReadOnlyList> RetainCalls { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/MeshRouterDispatchTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/MeshRouterDispatchTests.cs index d5a1fcaaf..92813cb33 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/MeshRouterDispatchTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Communication/MeshRouterDispatchTests.cs @@ -113,7 +113,8 @@ public class MeshRouterDispatchTests : ControlPlaneActorTestBase var cmd = router.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); cmd.Topic.ShouldBe(AlarmCommandsTopic.Name); - cmd.Message.ShouldBeOfType(); + cmd.Message.ShouldBeOfType().VerdictRequested.ShouldBeTrue(); + cmd.VerdictReplyTo.ShouldNotBeNull(); // #950: the per-request verdict collector } [Fact] @@ -131,6 +132,7 @@ public class MeshRouterDispatchTests : ControlPlaneActorTestBase var cmd = router.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); cmd.Topic.ShouldBe(AlarmCommandsTopic.Name); - cmd.Message.ShouldBeOfType(); + cmd.Message.ShouldBeOfType().VerdictRequested.ShouldBeTrue(); + cmd.VerdictReplyTo.ShouldNotBeNull(); // #950: the per-request verdict collector } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/MeshGrpcBoundaryTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/MeshGrpcBoundaryTests.cs index 735646885..a498f44ba 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/MeshGrpcBoundaryTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/MeshGrpcBoundaryTests.cs @@ -85,7 +85,8 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime public async ValueTask InitializeAsync() { _central = StartSelfSeededSystem(); - _siteA = await SiteNode.StartAsync("SITE-A", SiteAKey); + // #950: site-A runs a scripted-alarm owner that applies every command; site-B runs no driver host at all. + _siteA = await SiteNode.StartAsync("SITE-A", SiteAKey, withAlarmOwner: true); _siteB = await SiteNode.StartAsync("SITE-B", SiteBKey); await Task.WhenAll( @@ -214,6 +215,43 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime await _siteA.Inbox.Task.WaitAsync(Arrival, TestContext.Current.CancellationToken); } + /// + /// #950, end to end over the real wire: the AdminUI ack path (real AdminOperationsActor → real + /// CentralCommunicationActor → real dialer → real interceptor → real NodeCommandGrpcService) comes back + /// with each node's engine verdict in ExecuteAck.alarm_verdict: site-A's owner applied it, site-B owns + /// nothing — so the operator is told Applied, not "sent". + /// + [Fact] + public async Task An_AdminUI_ack_reports_the_owning_nodes_verdict_across_the_gRPC_boundary() + { + var dbFactory = SeedTwoClusterDb(_siteA, _siteB); + var router = _central.ActorOf(CentralCommunicationActor.Props( + dbFactory, GrpcOptions(), () => null, () => Dialer(), () => new FixedPskProvider())); + var admin = _central.ActorOf(ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations.AdminOperationsActor.Props( + dbFactory, _central.DeadLetters, [], meshRouter: router)); + + AcknowledgeAlarmResult? result = null; + var deadline = DateTime.UtcNow + Arrival; + while (DateTime.UtcNow < deadline) + { + // Re-asked only while central has not loaded its contacts yet ("Not delivered") — see the dispatch test above. + result = await admin.Ask( + new AcknowledgeAlarmCommand("alarm-1", "alice", null, Commons.Types.CorrelationId.NewId()), + TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken); + if (result.Summary != "Not delivered") break; + await Task.Delay(250, TestContext.Current.CancellationToken); + } + + result.ShouldNotBeNull(); + result.Verdict.ShouldBe(Commons.OpcUa.AlarmCommandVerdict.Applied, result.Message); + result.Ok.ShouldBeTrue(); + result.Summary.ShouldBe("Applied"); + result.Message.ShouldNotBeNull().ShouldContain("node-a: applied."); + result.Message.ShouldContain("node-b: does not own this alarm."); + // Delivered by the verdict path only — never ALSO re-emitted on site-A's EventStream (one copy per engine). + _siteA.AlarmEventStreamCopies.ShouldBe(0); + } + // ---- harness --------------------------------------------------------------------------------- private static MeshGrpcCommandDialer Dialer(IMeshPskProvider? psk = null) => @@ -316,7 +354,12 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime public TaskCompletionSource Inbox { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - public static async Task StartAsync(string clusterId, string psk) + /// #950: how many AlarmCommands reached this node's EventStream (the one-way path). + public int AlarmEventStreamCopies => _alarmCopies; + + private int _alarmCopies; + + public static async Task StartAsync(string clusterId, string psk, bool withAlarmOwner = false) { var node = new SiteNode { System = StartSelfSeededSystem(), Port = GetFreePort() }; @@ -329,6 +372,11 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime var registry = new ActorRegistry(); registry.Register(comm); + node.System.EventStream.Subscribe( + node.System.ActorOf(Akka.Actor.Props.Create(() => new CountActor(() => Interlocked.Increment(ref node._alarmCopies)))), + typeof(Commons.OpcUa.AlarmCommand)); + if (withAlarmOwner) + registry.Register(node.System.ActorOf(Akka.Actor.Props.Create(() => new ApplyingDriverHost()))); var builder = WebApplication.CreateBuilder(); builder.Environment.ApplicationName = typeof(MeshGrpcBoundaryTests).Assembly.GetName().Name!; @@ -411,6 +459,21 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime return port; } + /// #950: stands in for a driver host whose scripted-alarm engine owns and applies every command. + private sealed class ApplyingDriverHost : ReceiveActor + { + public ApplyingDriverHost() => + Receive(m => + Sender.Tell(new Commons.OpcUa.AlarmCommandOutcome( + m.Command.AlarmId, m.Command.Operation, Commons.OpcUa.AlarmCommandVerdict.Applied))); + } + + /// Counts what it receives. + private sealed class CountActor : ReceiveActor + { + public CountActor(Action onMessage) => ReceiveAny(_ => onMessage()); + } + /// Completes an inbox with the first message it receives. private sealed class CaptureActor : ReceiveActor { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Grpc/NodeCommandGrpcServiceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Grpc/NodeCommandGrpcServiceTests.cs index 301128686..9cfb5ea25 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Grpc/NodeCommandGrpcServiceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Grpc/NodeCommandGrpcServiceTests.cs @@ -66,6 +66,96 @@ public sealed class NodeCommandGrpcServiceTests : TestKit probe.ExpectMsg(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(alarm); } + /// + /// #950: an alarm command asking for a verdict goes to the driver host as an ExecuteAlarmCommand (no ask + /// deadline — nothing else carries it here), NOT to the comm actor, and the host's answer rides the ack. + /// + [Fact] + public async Task A_verdict_request_asks_the_driver_host_and_returns_its_answer() + { + var comm = CreateTestProbe(); + var driverHost = CreateTestProbe(); + driverHost.SetAutoPilot(new Akka.TestKit.DelegateAutoPilot((sender, msg) => + { + if (msg is ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmHostActor.ExecuteAlarmCommand ask) + { + sender.Tell(new AlarmCommandOutcome(ask.Command.AlarmId, ask.Command.Operation, + AlarmCommandVerdict.NotApplied, "last load failed"), Akka.Actor.ActorRefs.NoSender); + } + + return Akka.TestKit.AutoPilot.KeepRunning; + })); + var registry = new ActorRegistry(); + registry.Register(comm.Ref); + registry.Register(driverHost.Ref); + var service = NewService(registry); + var alarm = new AlarmCommand("alarm-7", "Acknowledge", "carol", null, null, VerdictRequested: true); + + var ack = await service.Execute(MeshTransportDtoMapper.ToEnvelope(alarm, AlarmCorrelation), Ctx()); + + var asked = driverHost.ExpectMsg( + cancellationToken: TestContext.Current.CancellationToken); + asked.Command.AlarmId.ShouldBe("alarm-7"); + asked.DeadlineUtc.ShouldBeNull(); + ack.AlarmVerdict.ShouldNotBeNull(); + var outcome = MeshTransportDtoMapper.FromProto(ack.AlarmVerdict, "alarm-7", "Acknowledge"); + outcome.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + outcome.Reason.ShouldBe("last load failed"); + comm.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken); + } + + /// #950: an engine that does not answer in time is an unknown (timed-out) verdict, never a failed call. + [Fact] + public async Task A_silent_driver_host_is_a_timed_out_unknown() + { + var registry = new ActorRegistry(); + registry.Register(CreateTestProbe().Ref); + registry.Register(CreateTestProbe().Ref); + var service = new NodeCommandGrpcService(registry, NullLogger.Instance) + { + VerdictWait = TimeSpan.FromMilliseconds(300), + }; + var alarm = new AlarmCommand("alarm-7", "Acknowledge", "carol", null, null, VerdictRequested: true); + + var ack = await service.Execute(MeshTransportDtoMapper.ToEnvelope(alarm, AlarmCorrelation), Ctx()); + + ack.AlarmVerdict.Verdict.ShouldBe(AlarmVerdict.OutcomeUnknown); + ack.AlarmVerdict.TimedOut.ShouldBeTrue(); + } + + /// #950: a node with no driver host owns no scripted alarm — answered NotApplied/NotOwned. + [Fact] + public async Task A_verdict_request_on_a_node_without_a_driver_host_is_not_owned() + { + var registry = new ActorRegistry(); + registry.Register(CreateTestProbe().Ref); + var service = NewService(registry); + var alarm = new AlarmCommand("alarm-7", "Acknowledge", "carol", null, null, VerdictRequested: true); + + var ack = await service.Execute(MeshTransportDtoMapper.ToEnvelope(alarm, AlarmCorrelation), Ctx()); + + ack.AlarmVerdict.Verdict.ShouldBe(AlarmVerdict.NotApplied); + ack.AlarmVerdict.NotOwned.ShouldBeTrue(); + } + + /// #950: without the request (a pre-#950 central) the one-way path is untouched — an empty ack. + [Fact] + public async Task An_alarm_command_without_a_verdict_request_stays_one_way() + { + var comm = CreateTestProbe(); + var driverHost = CreateTestProbe(); + var registry = new ActorRegistry(); + registry.Register(comm.Ref); + registry.Register(driverHost.Ref); + var alarm = new AlarmCommand("alarm-7", "Acknowledge", "carol", null, null); + + var ack = await NewService(registry).Execute(MeshTransportDtoMapper.ToEnvelope(alarm, AlarmCorrelation), Ctx()); + + ack.AlarmVerdict.ShouldBeNull(); + comm.ExpectMsg(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(alarm); + driverHost.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken); + } + [Fact] public async Task A_call_in_the_boot_window_before_the_actor_is_registered_is_unavailable() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmBroadcastVerdictTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmBroadcastVerdictTests.cs new file mode 100644 index 000000000..0a7416fa4 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmBroadcastVerdictTests.cs @@ -0,0 +1,116 @@ +using Akka.Actor; +using Akka.TestKit; +using Serilog; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms; + +/// +/// Gitea #950 — a broadcast from central's AdminUI path (VerdictRequested) is answered +/// to its sender with the engine's verdict, non-owners included (NotOwned); every other broadcast stays one-way. +/// +public sealed class ScriptedAlarmBroadcastVerdictTests : RuntimeActorTestBase +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static EquipmentScriptedAlarmPlan Plan(string id, string source = "return (int)ctx.GetTag(\"M.T\").Value > 90;") => + new(ScriptedAlarmId: id, EquipmentId: "Plant/Line1/M", Name: id, AlarmType: "AlarmCondition", Severity: 800, + MessageTemplate: "condition", PredicateScriptId: $"{id}-script", PredicateSource: source, + DependencyRefs: ["M.T"], HistorizeToAveva: false, Retain: true, Enabled: true); + + private (IActorRef Host, ScriptedAlarmEngine Engine) SpawnLoaded(params EquipmentScriptedAlarmPlan[] plans) + { + var publish = CreateTestProbe(); + var mux = CreateTestProbe(); + var upstream = new DependencyMuxTagUpstreamSource(); + var logger = new LoggerConfiguration().CreateLogger(); + var engine = new ScriptedAlarmEngine(upstream, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger); + var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, () => (upstream, engine), + readiness: new ScriptedAlarmCommandReadinessView())); + host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(plans)); + mux.ExpectMsg(Timeout, cancellationToken: Ct); + return (host, engine); + } + + private static AlarmCommand Broadcast(string alarmId, string text, bool verdictRequested) => + new(alarmId, "AddComment", "alice", text, null, VerdictRequested: verdictRequested); + + [Fact] + public void An_owner_answers_its_verdict_to_the_publisher() + { + var (host, engine) = SpawnLoaded(Plan("alm-1")); + var collector = CreateTestProbe(); + + host.Tell(Broadcast("alm-1", "from the AdminUI", verdictRequested: true), collector.Ref); + + var outcome = collector.ExpectMsg(Timeout, cancellationToken: Ct); + outcome.Verdict.ShouldBe(AlarmCommandVerdict.Applied); + outcome.NotOwned.ShouldBeFalse(); + engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["from the AdminUI"]); + } + + [Fact] + public void A_non_owner_answers_not_owned_and_applies_nothing() + { + var (host, _) = SpawnLoaded(Plan("alm-1")); + var collector = CreateTestProbe(); + + host.Tell(Broadcast("someone-elses", "x", verdictRequested: true), collector.Ref); + + var outcome = collector.ExpectMsg(Timeout, cancellationToken: Ct); + outcome.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + outcome.NotOwned.ShouldBeTrue(); + } + + [Fact] + public void An_owner_refusal_is_answered_as_a_refusal_not_as_not_owned() + { + var (host, _) = SpawnLoaded(Plan("alm-1")); + var collector = CreateTestProbe(); + + // AddComment without text is refused by the host before the engine runs. + host.Tell(Broadcast("alm-1", " ", verdictRequested: true), collector.Ref); + + var outcome = collector.ExpectMsg(Timeout, cancellationToken: Ct); + outcome.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + outcome.NotOwned.ShouldBeFalse(); + outcome.Reason.ShouldNotBeNull().ShouldContain("comment text"); + } + + [Fact] + public void A_broadcast_that_did_not_ask_for_a_verdict_is_not_answered() + { + var (host, engine) = SpawnLoaded(Plan("alm-1")); + var publisher = CreateTestProbe(); + + host.Tell(Broadcast("alm-1", "one-way", verdictRequested: false), publisher.Ref); + host.Tell(Broadcast("someone-elses", "one-way", verdictRequested: false), publisher.Ref); + // Positive control queued behind both: a verdict request IS answered, so the silence above is not a slow mailbox. + host.Tell(Broadcast("alm-1", "asked", verdictRequested: true), publisher.Ref); + + publisher.ExpectMsg(Timeout, cancellationToken: Ct).Verdict.ShouldBe(AlarmCommandVerdict.Applied); + publisher.ExpectNoMsg(TimeSpan.FromMilliseconds(200), Ct); + engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["one-way", "asked"]); + } + + [Fact] + public async Task A_direct_ask_for_an_unowned_alarm_is_flagged_not_owned() + { + var (host, _) = SpawnLoaded(Plan("alm-1")); + + var outcome = await host.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand( + new AlarmCommand("someone-elses", "Acknowledge", "alice", null, null)), Timeout, Ct); + + outcome.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + outcome.NotOwned.ShouldBeTrue(); + } +}