fix(alarms): AdminUI /alerts ack/shelve reports the scripted engine's verdict (#950)
The /alerts buttons went central->node fire-and-forget and always showed "Ack sent". AdminOperationsActor now spawns a per-request AlarmCommandVerdictCollector (7 s window, under the client's 10 s ask) that sends the command with AlarmCommand.VerdictRequested and gathers each node's answer, finishing early once every node it sent to has answered. - gRPC plane: CentralCommunicationActor tells the collector the dialled ClusterNode set and one verdict per node. A node handles a verdict_requested AlarmCommandMessage by asking its driver host (ScriptedAlarmHostActor.ExecuteAlarmCommand, the #937 path, no ask deadline, bounded 5 s) and returns it in the ADDITIVE ExecuteAck.alarm_verdict. Transport failure / timeout / empty ack (pre-#950 node) => that node unknown. - DPS: published with the collector as sender; each ScriptedAlarmHostActor answers (non-owners NotOwned); expected set = Up driver members. - Aggregation: any owner applied => Applied (partial noted); else any unknown/silent node => Outcome unknown (never "refused"); else owner refusal => Refused: <reason>; else no owner => Not applied. - UI: green Applied / red Refused (reason) / amber Outcome unknown, per-node detail in the details pane; a verdict-less reply (validation, server fault, pre-#950 singleton) renders as before. Wire is back-compatible both ways (new proto fields only; VerdictRequested and NotOwned default false). Real-wire test through the real router, dialer, interceptor and NodeCommandGrpcService (red without the node change). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
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
|
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
|
`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
|
(it runs under `Lock`). The sync `base.Call` path (no asker) keeps the old fire-and-forget router. The AdminUI `/alerts` path
|
||||||
still fire-and-forget. A plain SDK client sees only the status code (diagnostic text needs ReturnDiagnostics).
|
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).
|
||||||
|
|||||||
@@ -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.
|
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
|
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.
|
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
|
- **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`,
|
DPS re-publish would deliver N copies to every subscriber. Node-side subscribers (`DriverHostActor`,
|
||||||
`ScriptedAlarmHostActor`) accept a command from either transport identically.
|
`ScriptedAlarmHostActor`) accept a command from either transport identically.
|
||||||
|
|||||||
+27
-5
@@ -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
|
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
|
behind a load that failed) also returns `BadInvalidState` and the node is reverted — see
|
||||||
[Operator command verdicts](#operator-command-verdicts-937).
|
[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
|
Since #950 the AdminUI `/alerts` buttons report it too ("Refused: …" — see [AdminUI path](#adminui-path)).
|
||||||
Warning `… NOT applied — …`. The next good load re-asserts every node from the store.
|
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
|
**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
|
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.
|
(`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
|
**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
|
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.
|
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
|
The AdminUI `/alerts` buttons report the engine's verdict too since #950 — see [AdminUI path](#adminui-path).
|
||||||
"Ack sent", not "applied").
|
|
||||||
|
|
||||||
`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).
|
`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
|
### 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: <reason>** (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).
|
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).
|
||||||
|
|
||||||
|
|||||||
@@ -21,10 +21,17 @@ public sealed record AcknowledgeAlarmCommand(
|
|||||||
CorrelationId CorrelationId);
|
CorrelationId CorrelationId);
|
||||||
|
|
||||||
/// <summary>Reply for <see cref="AcknowledgeAlarmCommand"/>.</summary>
|
/// <summary>Reply for <see cref="AcknowledgeAlarmCommand"/>.</summary>
|
||||||
/// <param name="Ok">True iff the command was published without error.</param>
|
/// <param name="Ok">True iff the scripted-alarm engine applied the command (#950: <see cref="Verdict"/> is Applied).</param>
|
||||||
/// <param name="Message">Failure reason; null on success.</param>
|
/// <param name="Message">Detail — the per-node verdicts, or the failure reason.</param>
|
||||||
/// <param name="CorrelationId">Echoes the request's correlation token.</param>
|
/// <param name="CorrelationId">Echoes the request's correlation token.</param>
|
||||||
|
/// <param name="Verdict">
|
||||||
|
/// #950: the fleet-wide engine verdict; <see langword="null"/> when the request failed before reaching any node
|
||||||
|
/// (validation, server fault).
|
||||||
|
/// </param>
|
||||||
|
/// <param name="Summary">#950: short operator-facing text for <see cref="Verdict"/> ("Applied", "Refused: …", "Outcome unknown").</param>
|
||||||
public sealed record AcknowledgeAlarmResult(
|
public sealed record AcknowledgeAlarmResult(
|
||||||
bool Ok,
|
bool Ok,
|
||||||
string? Message,
|
string? Message,
|
||||||
CorrelationId CorrelationId);
|
CorrelationId CorrelationId,
|
||||||
|
OpcUa.AlarmCommandVerdict? Verdict = null,
|
||||||
|
string? Summary = null);
|
||||||
|
|||||||
@@ -45,10 +45,17 @@ public sealed record ShelveAlarmCommand(
|
|||||||
CorrelationId CorrelationId);
|
CorrelationId CorrelationId);
|
||||||
|
|
||||||
/// <summary>Reply for <see cref="ShelveAlarmCommand"/>.</summary>
|
/// <summary>Reply for <see cref="ShelveAlarmCommand"/>.</summary>
|
||||||
/// <param name="Ok">True iff the command was published without error.</param>
|
/// <param name="Ok">True iff the scripted-alarm engine applied the command (#950: <see cref="Verdict"/> is Applied).</param>
|
||||||
/// <param name="Message">Failure reason; null on success.</param>
|
/// <param name="Message">Detail — the per-node verdicts, or the failure reason.</param>
|
||||||
/// <param name="CorrelationId">Echoes the request's correlation token.</param>
|
/// <param name="CorrelationId">Echoes the request's correlation token.</param>
|
||||||
|
/// <param name="Verdict">
|
||||||
|
/// #950: the fleet-wide engine verdict; <see langword="null"/> when the request failed before reaching any node
|
||||||
|
/// (validation, server fault).
|
||||||
|
/// </param>
|
||||||
|
/// <param name="Summary">#950: short operator-facing text for <see cref="Verdict"/>.</param>
|
||||||
public sealed record ShelveAlarmResult(
|
public sealed record ShelveAlarmResult(
|
||||||
bool Ok,
|
bool Ok,
|
||||||
string? Message,
|
string? Message,
|
||||||
CorrelationId CorrelationId);
|
CorrelationId CorrelationId,
|
||||||
|
OpcUa.AlarmCommandVerdict? Verdict = null,
|
||||||
|
string? Summary = null);
|
||||||
|
|||||||
@@ -25,4 +25,10 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
|
|||||||
/// and needs no additive-evolution discipline.
|
/// and needs no additive-evolution discipline.
|
||||||
/// </para>
|
/// </para>
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public sealed record MeshCommand(string Topic, object Message);
|
/// <param name="VerdictReplyTo">
|
||||||
|
/// #950: for an <c>AlarmCommand</c> whose publisher collects per-node verdicts (the AdminUI <c>/alerts</c> path), the
|
||||||
|
/// collector. The router tells it which nodes the command went to (<c>AlarmVerdictFanOut</c>) and — on the gRPC
|
||||||
|
/// plane — each node's answer; over DistributedPubSub it publishes with the collector as the sender so nodes answer
|
||||||
|
/// it directly. <see langword="null"/> ⇒ the one-way behaviour, unchanged.
|
||||||
|
/// </param>
|
||||||
|
public sealed record MeshCommand(string Topic, object Message, Akka.Actor.IActorRef? VerdictReplyTo = null);
|
||||||
|
|||||||
@@ -168,6 +168,7 @@ public static class MeshTransportDtoMapper
|
|||||||
proto.Comment = message.Comment;
|
proto.Comment = message.Comment;
|
||||||
if (message.UnshelveAtUtc is { } unshelveAt)
|
if (message.UnshelveAtUtc is { } unshelveAt)
|
||||||
proto.UnshelveAtUtc = ToUtcTimestamp(unshelveAt);
|
proto.UnshelveAtUtc = ToUtcTimestamp(unshelveAt);
|
||||||
|
proto.VerdictRequested = message.VerdictRequested;
|
||||||
|
|
||||||
return proto;
|
return proto;
|
||||||
}
|
}
|
||||||
@@ -175,6 +176,7 @@ public static class MeshTransportDtoMapper
|
|||||||
/// <summary>Rebuilds the domain record from its wire form.</summary>
|
/// <summary>Rebuilds the domain record from its wire form.</summary>
|
||||||
/// <param name="proto">The wire alarm command.</param>
|
/// <param name="proto">The wire alarm command.</param>
|
||||||
/// <returns>The domain <see cref="AlarmCommand"/>.</returns>
|
/// <returns>The domain <see cref="AlarmCommand"/>.</returns>
|
||||||
|
/// <remarks><see cref="AlarmCommand.CommandId"/> is node-local de-duplication state and never crosses this wire.</remarks>
|
||||||
public static AlarmCommand FromProto(AlarmCommandMessage proto)
|
public static AlarmCommand FromProto(AlarmCommandMessage proto)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(proto);
|
ArgumentNullException.ThrowIfNull(proto);
|
||||||
@@ -184,7 +186,63 @@ public static class MeshTransportDtoMapper
|
|||||||
proto.Operation,
|
proto.Operation,
|
||||||
proto.User,
|
proto.User,
|
||||||
proto.HasComment ? proto.Comment : null,
|
proto.HasComment ? proto.Comment : null,
|
||||||
proto.UnshelveAtUtc?.ToDateTime());
|
proto.UnshelveAtUtc?.ToDateTime(),
|
||||||
|
VerdictRequested: proto.VerdictRequested);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- AlarmCommandOutcome (#950)
|
||||||
|
|
||||||
|
/// <summary>Projects a node's scripted-alarm verdict onto its <c>ExecuteAck.alarm_verdict</c> wire form.</summary>
|
||||||
|
/// <param name="outcome">The local host's verdict.</param>
|
||||||
|
/// <returns>The wire <see cref="AlarmVerdictMessage"/>.</returns>
|
||||||
|
public static AlarmVerdictMessage ToProto(AlarmCommandOutcome outcome)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(outcome);
|
||||||
|
|
||||||
|
var proto = new AlarmVerdictMessage
|
||||||
|
{
|
||||||
|
Verdict = outcome.Verdict switch
|
||||||
|
{
|
||||||
|
AlarmCommandVerdict.Applied => AlarmVerdict.Applied,
|
||||||
|
AlarmCommandVerdict.NotApplied => AlarmVerdict.NotApplied,
|
||||||
|
AlarmCommandVerdict.OutcomeUnknown => AlarmVerdict.OutcomeUnknown,
|
||||||
|
_ => throw new ArgumentOutOfRangeException(
|
||||||
|
nameof(outcome), outcome.Verdict, "Not a declared AlarmCommandVerdict."),
|
||||||
|
},
|
||||||
|
TimedOut = outcome.TimedOut,
|
||||||
|
NotOwned = outcome.NotOwned,
|
||||||
|
};
|
||||||
|
if (outcome.Reason is not null)
|
||||||
|
proto.Reason = outcome.Reason;
|
||||||
|
return proto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Rebuilds a node's verdict from <c>ExecuteAck.alarm_verdict</c>.</summary>
|
||||||
|
/// <param name="proto">The wire verdict.</param>
|
||||||
|
/// <param name="alarmId">The command's alarm (the caller holds it; the wire does not repeat it).</param>
|
||||||
|
/// <param name="operation">The command's operation.</param>
|
||||||
|
/// <returns>The domain outcome.</returns>
|
||||||
|
/// <remarks>
|
||||||
|
/// The one decode in this file that does NOT throw on an unrecognised enum: an <c>UNSPECIFIED</c> or newer verdict
|
||||||
|
/// becomes <see cref="AlarmCommandVerdict.OutcomeUnknown"/>. That is not a guess in either direction — it claims
|
||||||
|
/// neither "applied" nor "refused", which is exactly what central knows — and throwing would turn a delivered
|
||||||
|
/// command into a transport failure.
|
||||||
|
/// </remarks>
|
||||||
|
public static AlarmCommandOutcome FromProto(AlarmVerdictMessage proto, string alarmId, string operation)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(proto);
|
||||||
|
|
||||||
|
var reason = proto.HasReason ? proto.Reason : null;
|
||||||
|
return proto.Verdict switch
|
||||||
|
{
|
||||||
|
AlarmVerdict.Applied => new AlarmCommandOutcome(alarmId, operation, AlarmCommandVerdict.Applied, reason),
|
||||||
|
AlarmVerdict.NotApplied => new AlarmCommandOutcome(
|
||||||
|
alarmId, operation, AlarmCommandVerdict.NotApplied, reason, NotOwned: proto.NotOwned),
|
||||||
|
AlarmVerdict.OutcomeUnknown => new AlarmCommandOutcome(
|
||||||
|
alarmId, operation, AlarmCommandVerdict.OutcomeUnknown, reason, TimedOut: proto.TimedOut),
|
||||||
|
_ => new AlarmCommandOutcome(alarmId, operation, AlarmCommandVerdict.OutcomeUnknown,
|
||||||
|
$"The node reported an unrecognised verdict ({proto.Verdict}); the outcome is unknown."),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- ApplyAck
|
// ---------------------------------------------------------------- ApplyAck
|
||||||
|
|||||||
@@ -52,13 +52,22 @@ public static class AlarmCommandsTopic
|
|||||||
/// direct copy and skips the broadcast copy carrying the same id. Null (every other publisher, and the gRPC mesh
|
/// 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.
|
/// wire, which does not carry it) ⇒ no de-duplication. Wire-compatible: a peer built before #937 ignores it.
|
||||||
/// </param>
|
/// </param>
|
||||||
|
/// <param name="VerdictRequested">
|
||||||
|
/// #950: the publisher (central's AdminUI <c>/alerts</c> path) collects each node's verdict. Over DistributedPubSub a
|
||||||
|
/// node's <c>ScriptedAlarmHostActor</c> answers the publish's sender with an <see cref="AlarmCommandOutcome"/>
|
||||||
|
/// (<see cref="AlarmCommandOutcome.NotOwned"/> when it does not own the alarm); over the gRPC command plane the node
|
||||||
|
/// asks its local host and returns the outcome in <c>ExecuteAck</c>. False (every other publisher) ⇒ no reply, exactly
|
||||||
|
/// as before. Wire-compatible both ways: a node built before #950 ignores it and simply does not answer, which central
|
||||||
|
/// reports as an unknown outcome for that node.
|
||||||
|
/// </param>
|
||||||
public sealed record AlarmCommand(
|
public sealed record AlarmCommand(
|
||||||
string AlarmId,
|
string AlarmId,
|
||||||
string Operation,
|
string Operation,
|
||||||
string User,
|
string User,
|
||||||
string? Comment,
|
string? Comment,
|
||||||
DateTime? UnshelveAtUtc,
|
DateTime? UnshelveAtUtc,
|
||||||
string? CommandId = null);
|
string? CommandId = null,
|
||||||
|
bool VerdictRequested = false);
|
||||||
|
|
||||||
/// <summary>#937: what a scripted-alarm engine did with one <see cref="AlarmCommand"/>.</summary>
|
/// <summary>#937: what a scripted-alarm engine did with one <see cref="AlarmCommand"/>.</summary>
|
||||||
public enum AlarmCommandVerdict
|
public enum AlarmCommandVerdict
|
||||||
@@ -88,9 +97,16 @@ public enum AlarmCommandVerdict
|
|||||||
/// <param name="Verdict">What the engine did.</param>
|
/// <param name="Verdict">What the engine did.</param>
|
||||||
/// <param name="Reason">Operator-facing text for a verdict other than <see cref="AlarmCommandVerdict.Applied"/>.</param>
|
/// <param name="Reason">Operator-facing text for a verdict other than <see cref="AlarmCommandVerdict.Applied"/>.</param>
|
||||||
/// <param name="TimedOut">For <see cref="AlarmCommandVerdict.OutcomeUnknown"/>: the bound expired (vs. a fault).</param>
|
/// <param name="TimedOut">For <see cref="AlarmCommandVerdict.OutcomeUnknown"/>: the bound expired (vs. a fault).</param>
|
||||||
|
/// <param name="NotOwned">
|
||||||
|
/// #950: with <see cref="AlarmCommandVerdict.NotApplied"/>, the answering node does not own the alarm at all (it is not in
|
||||||
|
/// its scripted-alarm plan, or the node runs no scripted-alarm engine) — as opposed to an owner refusing it. Central's
|
||||||
|
/// fleet-wide aggregation of an AdminUI command ignores non-owners; the OPC UA method path reads only
|
||||||
|
/// <see cref="Verdict"/>, where a non-owner is a refusal as before.
|
||||||
|
/// </param>
|
||||||
public sealed record AlarmCommandOutcome(
|
public sealed record AlarmCommandOutcome(
|
||||||
string AlarmId,
|
string AlarmId,
|
||||||
string Operation,
|
string Operation,
|
||||||
AlarmCommandVerdict Verdict,
|
AlarmCommandVerdict Verdict,
|
||||||
string? Reason = null,
|
string? Reason = null,
|
||||||
bool TimedOut = false);
|
bool TimedOut = false,
|
||||||
|
bool NotOwned = false);
|
||||||
|
|||||||
@@ -23,7 +23,9 @@ import "google/protobuf/timestamp.proto";
|
|||||||
// on the node's EventStream. ONE-WAY semantics, matching the node-local DistributedPubSub leg: the
|
// 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
|
// 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,
|
// 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 {
|
service NodeCommandService {
|
||||||
rpc Execute (CommandEnvelope) returns (ExecuteAck);
|
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
|
// A non-OK gRPC status is the ONLY transport-failure signal on this call — there is deliberately no
|
||||||
// success flag in the body would invite a caller to read OK+false as a distinct outcome the
|
// success flag in the body, which would invite a caller to read OK+false as a distinct delivery outcome
|
||||||
// fire-and-forget contract does not have. Extensible later without a version bump.
|
// 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 {
|
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 {
|
message ReportAck {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,6 +123,11 @@ message AlarmCommandMessage {
|
|||||||
string user = 3;
|
string user = 3;
|
||||||
optional string comment = 4; // nullable in the record — presence distinguishes null from ""
|
optional string comment = 4; // nullable in the record — presence distinguishes null from ""
|
||||||
google.protobuf.Timestamp unshelve_at_utc = 5; // DateTime? — absent Timestamp encodes null
|
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.
|
// Mirrors ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.ApplyAck.
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
@using ZB.MOM.WW.OtOpcUa.Commons.Interfaces
|
@using ZB.MOM.WW.OtOpcUa.Commons.Interfaces
|
||||||
@using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin
|
@using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin
|
||||||
@using ZB.MOM.WW.OtOpcUa.Commons.Messages.Alerts
|
@using ZB.MOM.WW.OtOpcUa.Commons.Messages.Alerts
|
||||||
|
@using ZB.MOM.WW.OtOpcUa.Commons.OpcUa
|
||||||
@inject IInProcessBroadcaster<AlarmTransitionEvent> Alarms
|
@inject IInProcessBroadcaster<AlarmTransitionEvent> Alarms
|
||||||
@inject AuthenticationStateProvider AuthState
|
@inject AuthenticationStateProvider AuthState
|
||||||
@inject IAuthorizationService AuthorizationService
|
@inject IAuthorizationService AuthorizationService
|
||||||
@@ -44,7 +45,7 @@
|
|||||||
else if (_opResultMessage is not null)
|
else if (_opResultMessage is not null)
|
||||||
{
|
{
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<p role="status" aria-live="polite" class="mb-1"><span class="chip @(_opResultOk ? "chip-ok" : "chip-bad")">@_opResultSummary</span></p>
|
<p role="status" aria-live="polite" class="mb-1"><span class="chip @_opResultChip">@_opResultSummary</span></p>
|
||||||
<p class="small text-muted mb-1">Last request for <span class="mono text-break">@_opResultAlarmId</span></p>
|
<p class="small text-muted mb-1">Last request for <span class="mono text-break">@_opResultAlarmId</span></p>
|
||||||
<DiagnosticDetails Summary="Request details" Text="@_opResultMessage" />
|
<DiagnosticDetails Summary="Request details" Text="@_opResultMessage" />
|
||||||
</div>
|
</div>
|
||||||
@@ -167,7 +168,7 @@ else
|
|||||||
private string _busyAlarmId = "";
|
private string _busyAlarmId = "";
|
||||||
private string _opResultAlarmId = "";
|
private string _opResultAlarmId = "";
|
||||||
private string? _opResultMessage;
|
private string? _opResultMessage;
|
||||||
private bool _opResultOk;
|
private string _opResultChip = "chip-bad";
|
||||||
private string? _opResultSummary;
|
private string? _opResultSummary;
|
||||||
|
|
||||||
// Auto-clear timer for the single request outcome (mirrors DriverStatusPanel): the chip is set in
|
// 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));
|
using var cts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||||||
var result = await AdminOps.AcknowledgeAlarmAsync(
|
var result = await AdminOps.AcknowledgeAlarmAsync(
|
||||||
alarmId, user, comment: null, cts.Token);
|
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)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -264,7 +265,7 @@ else
|
|||||||
var result = await AdminOps.ShelveAlarmAsync(
|
var result = await AdminOps.ShelveAlarmAsync(
|
||||||
alarmId, user, kind, unshelveAtUtc: unshelveAtUtc, comment: null, cts.Token);
|
alarmId, user, kind, unshelveAtUtc: unshelveAtUtc, comment: null, cts.Token);
|
||||||
var verb = kind == ShelveKind.Unshelve ? "Unshelve" : "Shelve";
|
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)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -298,12 +299,34 @@ else
|
|||||||
?? "unknown";
|
?? "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;
|
if (_disposed) return;
|
||||||
_opResultSummary = summary ?? (ok ? message : "Request rejected");
|
_opResultSummary = summary ?? (ok ? message : "Request rejected");
|
||||||
_opResultAlarmId = alarmId;
|
_opResultAlarmId = alarmId;
|
||||||
_opResultOk = ok;
|
_opResultChip = chip ?? (ok ? "chip-ok" : "chip-bad");
|
||||||
_opResultMessage = message;
|
_opResultMessage = message;
|
||||||
StateHasChanged();
|
StateHasChanged();
|
||||||
// Auto-clear the result chip after 8 s (mirrors DriverStatusPanel). System.Threading.Timer
|
// Auto-clear the result chip after 8 s (mirrors DriverStatusPanel). System.Threading.Timer
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ public sealed class AdminOperationsActor : ReceiveActor
|
|||||||
|
|
||||||
private readonly ILoggingAdapter _log = Context.GetLogger();
|
private readonly ILoggingAdapter _log = Context.GetLogger();
|
||||||
|
|
||||||
|
/// <summary>#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts.</summary>
|
||||||
|
private readonly TimeSpan _alarmVerdictWindow;
|
||||||
|
|
||||||
/// <summary>The StartDeployment whose compose is running off-actor, or null. See <see cref="HandleStartDeployment"/>.</summary>
|
/// <summary>The StartDeployment whose compose is running off-actor, or null. See <see cref="HandleStartDeployment"/>.</summary>
|
||||||
private StartDeployment? _composeInFlight;
|
private StartDeployment? _composeInFlight;
|
||||||
|
|
||||||
@@ -55,6 +58,7 @@ public sealed class AdminOperationsActor : ReceiveActor
|
|||||||
/// DistributedPubSub mediator directly (the behaviour before the per-cluster mesh).
|
/// DistributedPubSub mediator directly (the behaviour before the per-cluster mesh).
|
||||||
/// </param>
|
/// </param>
|
||||||
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
|
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
|
||||||
|
/// <param name="alarmVerdictWindow">#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts; defaults to <see cref="AlarmCommandVerdictCollector.DefaultWindow"/>.</param>
|
||||||
/// <returns>Props configured to create an AdminOperationsActor.</returns>
|
/// <returns>Props configured to create an AdminOperationsActor.</returns>
|
||||||
public static Props Props(
|
public static Props Props(
|
||||||
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
|
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
|
||||||
@@ -62,9 +66,10 @@ public sealed class AdminOperationsActor : ReceiveActor
|
|||||||
IEnumerable<IDriverProbe> probes,
|
IEnumerable<IDriverProbe> probes,
|
||||||
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
|
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
|
||||||
IActorRef? meshRouter = null,
|
IActorRef? meshRouter = null,
|
||||||
TimeSpan? applyDeadline = null) =>
|
TimeSpan? applyDeadline = null,
|
||||||
|
TimeSpan? alarmVerdictWindow = null) =>
|
||||||
Akka.Actor.Props.Create(() =>
|
Akka.Actor.Props.Create(() =>
|
||||||
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline));
|
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline, alarmVerdictWindow));
|
||||||
|
|
||||||
/// <summary>Initializes a new instance of the AdminOperationsActor.</summary>
|
/// <summary>Initializes a new instance of the AdminOperationsActor.</summary>
|
||||||
/// <param name="dbFactory">Factory for creating config database contexts.</param>
|
/// <param name="dbFactory">Factory for creating config database contexts.</param>
|
||||||
@@ -73,14 +78,17 @@ public sealed class AdminOperationsActor : ReceiveActor
|
|||||||
/// <param name="tagConfigValidationMode">Deploy-gate TagConfig strictness mode (Warn default | Error opt-in).</param>
|
/// <param name="tagConfigValidationMode">Deploy-gate TagConfig strictness mode (Warn default | Error opt-in).</param>
|
||||||
/// <param name="meshRouter">Central comm actor, or <see langword="null"/> for the mediator.</param>
|
/// <param name="meshRouter">Central comm actor, or <see langword="null"/> for the mediator.</param>
|
||||||
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
|
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
|
||||||
|
/// <param name="alarmVerdictWindow">#950: the <c>/alerts</c> verdict collection window.</param>
|
||||||
public AdminOperationsActor(
|
public AdminOperationsActor(
|
||||||
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
|
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
|
||||||
IActorRef coordinator,
|
IActorRef coordinator,
|
||||||
IEnumerable<IDriverProbe> probes,
|
IEnumerable<IDriverProbe> probes,
|
||||||
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
|
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
|
||||||
IActorRef? meshRouter = null,
|
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
|
// 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.
|
// DeployTimings.ApplyDeadline), so the lost-dispatch closure and the coordinator's own deadline agree.
|
||||||
_applyDeadline = applyDeadline ?? DeployTimings.ApplyDeadline;
|
_applyDeadline = applyDeadline ?? DeployTimings.ApplyDeadline;
|
||||||
@@ -134,13 +142,21 @@ public sealed class AdminOperationsActor : ReceiveActor
|
|||||||
else DistributedPubSub.Get(Context.System).Mediator.Tell(new Publish(topic, message));
|
else DistributedPubSub.Get(Context.System).Mediator.Tell(new Publish(topic, message));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: spawns the per-request verdict collector, which sends <paramref name="command"/> (via the mesh router, or
|
||||||
|
/// DistributedPubSub when none is wired) and answers <paramref name="replyTo"/> with <paramref name="reply"/>.
|
||||||
|
/// </summary>
|
||||||
|
private void CollectVerdict(AlarmCommand command, IActorRef replyTo, Func<AlarmCommandFleetOutcome, object> reply) =>
|
||||||
|
Context.ActorOf(AlarmCommandVerdictCollector.Props(command, _meshRouter, replyTo, reply, _alarmVerdictWindow));
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// AdminUI Acknowledge path. Maps the control-plane command to a
|
/// AdminUI Acknowledge path. Maps the control-plane command to a
|
||||||
/// <see cref="AlarmCommand"/> (<c>Operation = "Acknowledge"</c>) and publishes it onto the
|
/// <see cref="AlarmCommand"/> (<c>Operation = "Acknowledge"</c>) and hands it to an
|
||||||
/// cluster <c>alarm-commands</c> topic. The broadcast lands on every driver node's
|
/// <see cref="AlarmCommandVerdictCollector"/>, which sends it to every driver node (the ownership filter on each
|
||||||
/// <c>ScriptedAlarmHostActor</c>; only the node owning the alarm acts (ownership filter), so the
|
/// node's <c>ScriptedAlarmHostActor</c> decides who acts, so the admin singleton needs no knowledge of placement),
|
||||||
/// admin singleton needs no knowledge of placement. Synchronous — the publish is fire-and-forget
|
/// collects each node's verdict within a bounded window and replies Applied / Refused (reason) / Outcome unknown
|
||||||
/// via the mediator, so there is no awaitable work and no DB write.
|
/// (#950 — this was a fire-and-forget publish that always answered "sent"). The mailbox is not held: the collector
|
||||||
|
/// is a child actor that answers the requester itself.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private void HandleAcknowledgeAlarm(AcknowledgeAlarmCommand msg)
|
private void HandleAcknowledgeAlarm(AcknowledgeAlarmCommand msg)
|
||||||
{
|
{
|
||||||
@@ -154,10 +170,10 @@ public sealed class AdminOperationsActor : ReceiveActor
|
|||||||
Comment: msg.Comment,
|
Comment: msg.Comment,
|
||||||
UnshelveAtUtc: null);
|
UnshelveAtUtc: null);
|
||||||
|
|
||||||
Dispatch(AlarmCommandsTopic.Name, alarmCmd);
|
var correlationId = msg.CorrelationId;
|
||||||
|
CollectVerdict(alarmCmd, replyTo, o => new AcknowledgeAlarmResult(
|
||||||
_log.Info("AdminOps: Acknowledge published for alarm {AlarmId} by {User}", msg.AlarmId, msg.User);
|
o.Verdict == AlarmCommandVerdict.Applied, o.Detail, correlationId, o.Verdict, o.Summary));
|
||||||
replyTo.Tell(new AcknowledgeAlarmResult(true, null, msg.CorrelationId));
|
_log.Info("AdminOps: Acknowledge sent for alarm {AlarmId} by {User}; collecting node verdicts", msg.AlarmId, msg.User);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -170,8 +186,8 @@ public sealed class AdminOperationsActor : ReceiveActor
|
|||||||
/// AdminUI Shelve / Unshelve path. Maps <see cref="ShelveAlarmCommand.Kind"/> to the matching
|
/// AdminUI Shelve / Unshelve path. Maps <see cref="ShelveAlarmCommand.Kind"/> to the matching
|
||||||
/// <see cref="AlarmCommand"/> operation (<c>OneShotShelve</c> / <c>TimedShelve</c> /
|
/// <see cref="AlarmCommand"/> operation (<c>OneShotShelve</c> / <c>TimedShelve</c> /
|
||||||
/// <c>Unshelve</c>), threading <see cref="ShelveAlarmCommand.UnshelveAtUtc"/> for the timed kind,
|
/// <c>Unshelve</c>), threading <see cref="ShelveAlarmCommand.UnshelveAtUtc"/> for the timed kind,
|
||||||
/// and publishes onto the cluster <c>alarm-commands</c> topic. Ownership filtering happens on the
|
/// and sends it exactly as <see cref="HandleAcknowledgeAlarm"/> does — ownership filtered on the nodes, verdicts
|
||||||
/// owning node exactly as for Acknowledge.
|
/// collected and reported (#950).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private void HandleShelveAlarm(ShelveAlarmCommand msg)
|
private void HandleShelveAlarm(ShelveAlarmCommand msg)
|
||||||
{
|
{
|
||||||
@@ -201,10 +217,10 @@ public sealed class AdminOperationsActor : ReceiveActor
|
|||||||
Comment: msg.Comment,
|
Comment: msg.Comment,
|
||||||
UnshelveAtUtc: unshelveAt);
|
UnshelveAtUtc: unshelveAt);
|
||||||
|
|
||||||
Dispatch(AlarmCommandsTopic.Name, alarmCmd);
|
var correlationId = msg.CorrelationId;
|
||||||
|
CollectVerdict(alarmCmd, replyTo, o => new ShelveAlarmResult(
|
||||||
_log.Info("AdminOps: {Operation} published for alarm {AlarmId} by {User}", operation, msg.AlarmId, msg.User);
|
o.Verdict == AlarmCommandVerdict.Applied, o.Detail, correlationId, o.Verdict, o.Summary));
|
||||||
replyTo.Tell(new ShelveAlarmResult(true, null, msg.CorrelationId));
|
_log.Info("AdminOps: {Operation} sent for alarm {AlarmId} by {User}; collecting node verdicts", operation, msg.AlarmId, msg.User);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,310 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Akka.Actor;
|
||||||
|
using Akka.Cluster.Tools.PublishSubscribe;
|
||||||
|
using Akka.Event;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Cluster;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: router → collector. Which nodes an AdminUI alarm command went to — the set the
|
||||||
|
/// <see cref="AlarmCommandVerdictCollector"/> waits on.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Nodes">
|
||||||
|
/// The nodes expected to answer (gRPC: the dialled <c>ClusterNode</c> ids; DistributedPubSub: the Up <c>driver</c>
|
||||||
|
/// members' <c>host:port</c>). Empty with a null <paramref name="NotDeliveredReason"/> ⇒ the set is unknown and the
|
||||||
|
/// collector waits out its window.
|
||||||
|
/// </param>
|
||||||
|
/// <param name="NotDeliveredReason">Set when the command reached no node at all (no targets, no dialer, unencodable).</param>
|
||||||
|
public sealed record AlarmVerdictFanOut(IReadOnlyList<string> Nodes, string? NotDeliveredReason = null);
|
||||||
|
|
||||||
|
/// <summary>#950: one node's answer to an AdminUI alarm command, as the gRPC router saw it.</summary>
|
||||||
|
/// <param name="Node">The node (its <c>ClusterNode</c> id).</param>
|
||||||
|
/// <param name="Outcome">Its verdict; transport failures and pre-#950 nodes arrive as <see cref="AlarmCommandVerdict.OutcomeUnknown"/>.</param>
|
||||||
|
public sealed record AlarmNodeVerdict(string Node, AlarmCommandOutcome Outcome);
|
||||||
|
|
||||||
|
/// <summary>#950: the fleet-wide verdict on one AdminUI alarm command.</summary>
|
||||||
|
/// <param name="Verdict">Applied when any owning node applied it; OutcomeUnknown when none did but one may have; else NotApplied.</param>
|
||||||
|
/// <param name="Summary">Short operator-facing text (the <c>/alerts</c> result chip).</param>
|
||||||
|
/// <param name="Detail">Per-node breakdown (the result's details pane).</param>
|
||||||
|
public sealed record AlarmCommandFleetOutcome(AlarmCommandVerdict Verdict, string Summary, string Detail);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: folds the per-node answers to one AdminUI alarm command into the verdict the operator sees.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <para>
|
||||||
|
/// Every driver node receives the command and only the alarm's owners act — two in a redundant pair, each with its
|
||||||
|
/// own engine (the condition state is then replicated last-writer-wins). So: <b>any owner applied ⇒ Applied</b>
|
||||||
|
/// (other owners' refusals/unknowns are listed, and the summary says it was partial); otherwise <b>any unknown — an
|
||||||
|
/// owner that timed out, a node that did not answer, a transport failure, a pre-#950 node — ⇒ OutcomeUnknown</b>,
|
||||||
|
/// never "refused", because that node may still apply it; otherwise an owner's refusal ⇒ NotApplied with its
|
||||||
|
/// reason; otherwise no node owns the alarm ⇒ NotApplied.
|
||||||
|
/// </para>
|
||||||
|
/// </remarks>
|
||||||
|
public static class AlarmCommandVerdictAggregator
|
||||||
|
{
|
||||||
|
/// <summary>Aggregates the answers.</summary>
|
||||||
|
/// <param name="answers">Node → its verdict (non-owners carry <see cref="AlarmCommandOutcome.NotOwned"/>).</param>
|
||||||
|
/// <param name="unanswered">Expected nodes that did not answer within the window.</param>
|
||||||
|
/// <param name="expectedKnown">Whether the set of nodes the command reached is known (false ⇒ silence may hide an owner).</param>
|
||||||
|
/// <param name="notDeliveredReason">Set when the command reached no node at all.</param>
|
||||||
|
/// <param name="window">The collection window, for the "no answer" text.</param>
|
||||||
|
/// <returns>The fleet verdict.</returns>
|
||||||
|
public static AlarmCommandFleetOutcome Aggregate(
|
||||||
|
IReadOnlyDictionary<string, AlarmCommandOutcome> answers,
|
||||||
|
IReadOnlyCollection<string> unanswered,
|
||||||
|
bool expectedKnown,
|
||||||
|
string? notDeliveredReason,
|
||||||
|
TimeSpan window)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(answers);
|
||||||
|
ArgumentNullException.ThrowIfNull(unanswered);
|
||||||
|
|
||||||
|
if (notDeliveredReason is not null && answers.Count == 0)
|
||||||
|
return new AlarmCommandFleetOutcome(AlarmCommandVerdict.NotApplied, "Not delivered",
|
||||||
|
$"The command was not delivered to any server, so nothing applied it: {notDeliveredReason}");
|
||||||
|
|
||||||
|
var applied = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.Applied);
|
||||||
|
var refused = answers.Where(a => a.Value is { Verdict: AlarmCommandVerdict.NotApplied, NotOwned: false })
|
||||||
|
.OrderBy(a => a.Key, StringComparer.Ordinal).ToList();
|
||||||
|
var unknown = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.OutcomeUnknown) + unanswered.Count;
|
||||||
|
|
||||||
|
AlarmCommandVerdict verdict;
|
||||||
|
string summary;
|
||||||
|
if (applied > 0)
|
||||||
|
{
|
||||||
|
verdict = AlarmCommandVerdict.Applied;
|
||||||
|
summary = refused.Count + unknown == 0
|
||||||
|
? "Applied"
|
||||||
|
: $"Applied on {applied} of {applied + refused.Count + unknown} servers";
|
||||||
|
}
|
||||||
|
else if (unknown > 0)
|
||||||
|
{
|
||||||
|
verdict = AlarmCommandVerdict.OutcomeUnknown;
|
||||||
|
summary = "Outcome unknown";
|
||||||
|
}
|
||||||
|
else if (refused.Count > 0)
|
||||||
|
{
|
||||||
|
verdict = AlarmCommandVerdict.NotApplied;
|
||||||
|
summary = "Refused: " + (refused[0].Value.Reason ?? "the alarm engine did not apply the command.");
|
||||||
|
}
|
||||||
|
else if (!expectedKnown)
|
||||||
|
{
|
||||||
|
// Silence from a node we could not enumerate may be an owner that did not answer (a pre-#950 node).
|
||||||
|
verdict = AlarmCommandVerdict.OutcomeUnknown;
|
||||||
|
summary = "Outcome unknown";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
verdict = AlarmCommandVerdict.NotApplied;
|
||||||
|
summary = "Not applied: no server owns this alarm";
|
||||||
|
}
|
||||||
|
|
||||||
|
var detail = new StringBuilder(verdict switch
|
||||||
|
{
|
||||||
|
AlarmCommandVerdict.Applied => "The alarm engine applied the command.",
|
||||||
|
AlarmCommandVerdict.OutcomeUnknown =>
|
||||||
|
"No server confirmed the command and at least one did not give a definite answer — it may still apply. "
|
||||||
|
+ "Check the alarm's state before retrying.",
|
||||||
|
_ => "The command was not applied anywhere.",
|
||||||
|
});
|
||||||
|
foreach (var (node, outcome) in answers.OrderBy(a => a.Key, StringComparer.Ordinal))
|
||||||
|
detail.AppendLine().Append(node).Append(": ").Append(Describe(outcome));
|
||||||
|
foreach (var node in unanswered.OrderBy(n => n, StringComparer.Ordinal))
|
||||||
|
detail.AppendLine().Append(node).Append($": no answer within {window.TotalSeconds:0.#} s — outcome unknown.");
|
||||||
|
if (answers.Count == 0 && unanswered.Count == 0)
|
||||||
|
detail.AppendLine().Append($"No server answered within {window.TotalSeconds:0.#} s.");
|
||||||
|
if (notDeliveredReason is not null)
|
||||||
|
detail.AppendLine().Append("Delivery: ").Append(notDeliveredReason);
|
||||||
|
|
||||||
|
return new AlarmCommandFleetOutcome(verdict, summary, detail.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Describe(AlarmCommandOutcome outcome) => outcome switch
|
||||||
|
{
|
||||||
|
{ Verdict: AlarmCommandVerdict.Applied } => "applied.",
|
||||||
|
{ Verdict: AlarmCommandVerdict.NotApplied, NotOwned: true } => "does not own this alarm.",
|
||||||
|
{ Verdict: AlarmCommandVerdict.NotApplied } => "refused — " + (outcome.Reason ?? "no reason given."),
|
||||||
|
_ => "outcome unknown — " + (outcome.Reason ?? "no reason given."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: the DistributedPubSub leg of an AdminUI alarm command that wants verdicts — used by the router under
|
||||||
|
/// <c>MeshTransport:Mode = Dps</c> and by <see cref="AdminOperationsActor"/> when no router is wired.
|
||||||
|
/// </summary>
|
||||||
|
public static class AlarmVerdictDps
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Publishes <paramref name="command"/> on <paramref name="topic"/> with <paramref name="collector"/> as the sender
|
||||||
|
/// (DistributedPubSub preserves it, so each node's scripted-alarm host answers the collector) and returns the nodes
|
||||||
|
/// expected to answer: the Up members carrying the <c>driver</c> role, keyed as <see cref="NodeKey"/> keys them.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="system">The actor system.</param>
|
||||||
|
/// <param name="topic">The DPS topic.</param>
|
||||||
|
/// <param name="command">The command (with <see cref="AlarmCommand.VerdictRequested"/> set).</param>
|
||||||
|
/// <param name="collector">Who the nodes answer.</param>
|
||||||
|
/// <returns>The expected node keys; empty when the membership could not be read.</returns>
|
||||||
|
public static IReadOnlyList<string> Publish(ActorSystem system, string topic, AlarmCommand command, IActorRef collector)
|
||||||
|
{
|
||||||
|
IReadOnlyList<string> expected;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var cluster = Akka.Cluster.Cluster.Get(system);
|
||||||
|
expected = cluster.State.Members
|
||||||
|
.Where(m => m.Status == Akka.Cluster.MemberStatus.Up && RoleParser.GossipedRolesHave(m.Roles, RoleParser.Driver))
|
||||||
|
.Select(m => NodeKey(m.Address, cluster.SelfAddress))
|
||||||
|
.Distinct(StringComparer.Ordinal)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
expected = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
DistributedPubSub.Get(system).Mediator.Tell(new Publish(topic, command), collector);
|
||||||
|
return expected;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The key a DPS-answering node is known by: its <c>host:port</c> (a local-scope address is this node).</summary>
|
||||||
|
/// <param name="address">The member or reply-sender address.</param>
|
||||||
|
/// <param name="self">This node's cluster address, or null when there is no cluster.</param>
|
||||||
|
/// <returns>The key.</returns>
|
||||||
|
public static string NodeKey(Address address, Address? self)
|
||||||
|
{
|
||||||
|
var effective = address.HasGlobalScope || self is null ? address : self;
|
||||||
|
return effective.Host is not null && effective.Port is not null ? effective.HostPort() : effective.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: one AdminUI alarm command's verdict collection. Sends the command (via the mesh router, or straight onto
|
||||||
|
/// DistributedPubSub when none is wired), gathers each node's answer until every expected node has answered or the
|
||||||
|
/// window closes, and replies the aggregated <see cref="AlarmCommandFleetOutcome"/> (mapped by the caller's
|
||||||
|
/// <c>reply</c>) to the original requester. Stops itself after replying.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class AlarmCommandVerdictCollector : ReceiveActor, IWithTimers
|
||||||
|
{
|
||||||
|
/// <summary>The default collection window — under <c>AdminOperationsClient</c>'s 10 s ask.</summary>
|
||||||
|
public static readonly TimeSpan DefaultWindow = TimeSpan.FromSeconds(7);
|
||||||
|
|
||||||
|
private const string WindowTimerKey = "window";
|
||||||
|
|
||||||
|
private readonly AlarmCommand _command;
|
||||||
|
private readonly IActorRef? _meshRouter;
|
||||||
|
private readonly IActorRef _replyTo;
|
||||||
|
private readonly Func<AlarmCommandFleetOutcome, object> _reply;
|
||||||
|
private readonly TimeSpan _window;
|
||||||
|
private readonly ILoggingAdapter _log = Context.GetLogger();
|
||||||
|
private readonly Dictionary<string, AlarmCommandOutcome> _answers = new(StringComparer.Ordinal);
|
||||||
|
private HashSet<string>? _expected;
|
||||||
|
private string? _notDelivered;
|
||||||
|
private Address? _self;
|
||||||
|
|
||||||
|
/// <summary>Gets or sets the timer scheduler.</summary>
|
||||||
|
public ITimerScheduler Timers { get; set; } = null!;
|
||||||
|
|
||||||
|
/// <summary>Creates the props.</summary>
|
||||||
|
/// <param name="command">The command; <see cref="AlarmCommand.VerdictRequested"/> is forced on.</param>
|
||||||
|
/// <param name="meshRouter">The central comm actor, or null to publish on DistributedPubSub directly.</param>
|
||||||
|
/// <param name="replyTo">The requester.</param>
|
||||||
|
/// <param name="reply">Maps the fleet verdict to the requester's reply message.</param>
|
||||||
|
/// <param name="window">The collection window.</param>
|
||||||
|
/// <returns>The props.</returns>
|
||||||
|
public static Props Props(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
|
||||||
|
Func<AlarmCommandFleetOutcome, object> reply, TimeSpan window) =>
|
||||||
|
Akka.Actor.Props.Create(() => new AlarmCommandVerdictCollector(command, meshRouter, replyTo, reply, window));
|
||||||
|
|
||||||
|
/// <summary>Initializes a new instance of the <see cref="AlarmCommandVerdictCollector"/> class.</summary>
|
||||||
|
/// <param name="command">The command.</param>
|
||||||
|
/// <param name="meshRouter">The router, or null.</param>
|
||||||
|
/// <param name="replyTo">The requester.</param>
|
||||||
|
/// <param name="reply">Maps the verdict to the reply.</param>
|
||||||
|
/// <param name="window">The collection window.</param>
|
||||||
|
public AlarmCommandVerdictCollector(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
|
||||||
|
Func<AlarmCommandFleetOutcome, object> reply, TimeSpan window)
|
||||||
|
{
|
||||||
|
_command = command with { VerdictRequested = true };
|
||||||
|
_meshRouter = meshRouter;
|
||||||
|
_replyTo = replyTo;
|
||||||
|
_reply = reply;
|
||||||
|
_window = window;
|
||||||
|
|
||||||
|
Receive<AlarmVerdictFanOut>(msg =>
|
||||||
|
{
|
||||||
|
_expected = new HashSet<string>(msg.Nodes, StringComparer.Ordinal);
|
||||||
|
_notDelivered = msg.NotDeliveredReason;
|
||||||
|
FinishIfComplete();
|
||||||
|
});
|
||||||
|
Receive<AlarmNodeVerdict>(msg =>
|
||||||
|
{
|
||||||
|
_answers[msg.Node] = msg.Outcome;
|
||||||
|
FinishIfComplete();
|
||||||
|
});
|
||||||
|
// A DistributedPubSub answer straight from a node's ScriptedAlarmHostActor: the node is the sender.
|
||||||
|
Receive<AlarmCommandOutcome>(outcome =>
|
||||||
|
{
|
||||||
|
if (!string.Equals(outcome.AlarmId, _command.AlarmId, StringComparison.Ordinal)) return;
|
||||||
|
_answers[AlarmVerdictDps.NodeKey(Sender.Path.Address, _self)] = outcome;
|
||||||
|
FinishIfComplete();
|
||||||
|
});
|
||||||
|
Receive<WindowClosed>(_ => Finish());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void PreStart()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_self = Akka.Cluster.Cluster.Get(Context.System).SelfAddress;
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
_self = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Timers.StartSingleTimer(WindowTimerKey, WindowClosed.Instance, _window);
|
||||||
|
if (_meshRouter is not null)
|
||||||
|
{
|
||||||
|
_meshRouter.Tell(new MeshCommand(AlarmCommandsTopic.Name, _command, Self));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var expected = AlarmVerdictDps.Publish(Context.System, AlarmCommandsTopic.Name, _command, Self);
|
||||||
|
Self.Tell(new AlarmVerdictFanOut(expected));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FinishIfComplete()
|
||||||
|
{
|
||||||
|
if (_expected is null) return;
|
||||||
|
if (_notDelivered is not null && _expected.Count == 0)
|
||||||
|
{
|
||||||
|
Finish();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_expected.Count > 0 && _expected.All(_answers.ContainsKey)) Finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Finish()
|
||||||
|
{
|
||||||
|
var expectedKnown = _expected is { Count: > 0 } || _notDelivered is not null;
|
||||||
|
var unanswered = _expected?.Where(n => !_answers.ContainsKey(n)).ToList() ?? [];
|
||||||
|
var outcome = AlarmCommandVerdictAggregator.Aggregate(_answers, unanswered, expectedKnown, _notDelivered, _window);
|
||||||
|
_log.Info("AdminOps: {Operation} for alarm {AlarmId} by {User} → {Outcome}",
|
||||||
|
_command.Operation, _command.AlarmId, _command.User,
|
||||||
|
$"{outcome.Verdict} ({outcome.Summary}; {_answers.Count} answered, {unanswered.Count} silent)");
|
||||||
|
_replyTo.Tell(_reply(outcome));
|
||||||
|
Timers.CancelAll();
|
||||||
|
Context.Stop(Self);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class WindowClosed
|
||||||
|
{
|
||||||
|
public static readonly WindowClosed Instance = new();
|
||||||
|
}
|
||||||
|
}
|
||||||
+62
-4
@@ -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.Deploy;
|
||||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
|
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
|
||||||
using ZB.MOM.WW.OtOpcUa.Commons.Protos.MeshTransport.V1;
|
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.Commons.Types;
|
||||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
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
|
// 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
|
// 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.
|
// ever reached through an RpcException instance.
|
||||||
@@ -392,9 +394,21 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
|
|||||||
return;
|
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));
|
DistributedPubSub.Get(Context.System).Mediator.Tell(new Publish(cmd.Topic, cmd.Message));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: tells a verdict collector the command reached no node, so it answers at once instead of at its window.</summary>
|
||||||
|
private static void ReportNotDelivered(MeshCommand cmd, string reason) =>
|
||||||
|
cmd.VerdictReplyTo?.Tell(new AlarmVerdictFanOut([], reason));
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Encodes one command once and fans it to every target node, one unary gRPC call each.
|
/// Encodes one command once and fans it to every target node, one unary gRPC call each.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -432,6 +446,7 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
|
|||||||
"Mesh transport is Grpc but no command dialer is wired — dropping {MessageType}. The "
|
"Mesh transport is Grpc but no command dialer is wired — dropping {MessageType}. The "
|
||||||
+ "command is not buffered and will not be retried",
|
+ "command is not buffered and will not be retried",
|
||||||
commandType);
|
commandType);
|
||||||
|
ReportNotDelivered(cmd, "central's mesh transport is Grpc but no command dialer is wired.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -449,6 +464,7 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
|
|||||||
+ "enabled, non-maintenance ClusterNode row carrying a GrpcPort in any cluster; the "
|
+ "enabled, non-maintenance ClusterNode row carrying a GrpcPort in any cluster; the "
|
||||||
+ "command is not buffered and will not be retried",
|
+ "command is not buffered and will not be retried",
|
||||||
commandType);
|
commandType);
|
||||||
|
ReportNotDelivered(cmd, "no enabled, non-maintenance ClusterNode row carries a GrpcPort.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -467,6 +483,7 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
|
|||||||
"Cannot encode {MessageType} for the gRPC command plane; the command is dropped and "
|
"Cannot encode {MessageType} for the gRPC command plane; the command is dropped and "
|
||||||
+ "was NOT delivered to any node",
|
+ "was NOT delivered to any node",
|
||||||
commandType);
|
commandType);
|
||||||
|
ReportNotDelivered(cmd, "the command could not be encoded for the gRPC command plane.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -477,11 +494,17 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
|
|||||||
}
|
}
|
||||||
catch (ObjectDisposedException)
|
catch (ObjectDisposedException)
|
||||||
{
|
{
|
||||||
|
ReportNotDelivered(cmd, "central is shutting down.");
|
||||||
return; // Stopping.
|
return; // Stopping.
|
||||||
}
|
}
|
||||||
|
|
||||||
var self = Self;
|
var self = Self;
|
||||||
var correlationId = envelope.CorrelationId;
|
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)
|
foreach (var target in targets)
|
||||||
{
|
{
|
||||||
var node = target;
|
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
|
// passed into the dial instead, where it cancels the call and comes back as an ordinary
|
||||||
// per-node outcome.
|
// per-node outcome.
|
||||||
Task.Run(
|
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)
|
CancellationToken.None)
|
||||||
.PipeTo(self);
|
.PipeTo(self);
|
||||||
}
|
}
|
||||||
@@ -524,9 +552,9 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await dialer.DispatchAsync(target.Endpoint, envelope, target.ClusterId, ct)
|
var ack = await dialer.ExecuteAsync(target.Endpoint, envelope, target.ClusterId, ct)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
return new CommandDispatched(target.NodeId, commandType, correlationId, null, null);
|
return new CommandDispatched(target.NodeId, commandType, correlationId, null, null, ack);
|
||||||
}
|
}
|
||||||
catch (RpcException ex)
|
catch (RpcException ex)
|
||||||
{
|
{
|
||||||
@@ -572,6 +600,9 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
|
|||||||
|
|
||||||
private void HandleCommandDispatched(CommandDispatched result)
|
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)
|
if (result.FailureStatus is null)
|
||||||
{
|
{
|
||||||
_log.Debug(
|
_log.Debug(
|
||||||
@@ -606,6 +637,27 @@ public sealed class CentralCommunicationActor : ReceiveActor, IWithTimers
|
|||||||
coordinator.Forward(ack);
|
coordinator.Forward(ack);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: one node's dial result as a verdict. A transport failure is UNKNOWN, never "not applied" — a call that
|
||||||
|
/// timed out or was cut may have been handled — and an ack with no verdict is a pre-#950 node that took the
|
||||||
|
/// command down its one-way path.
|
||||||
|
/// </summary>
|
||||||
|
private static AlarmCommandOutcome NodeVerdict(CommandDispatched result, AlarmCommand alarm)
|
||||||
|
{
|
||||||
|
if (result.FailureStatus is not null)
|
||||||
|
{
|
||||||
|
// The status code only: the detail can name endpoints and this text reaches any DriverOperator's browser
|
||||||
|
// (the R03:4.1 rule). The detail is in the Warning HandleCommandDispatched logs under the same correlation id.
|
||||||
|
return new AlarmCommandOutcome(alarm.AlarmId, alarm.Operation, AlarmCommandVerdict.OutcomeUnknown,
|
||||||
|
$"the command was not confirmed delivered (gRPC {result.FailureStatus}; see the central log for correlation {result.CorrelationId}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.Ack?.AlarmVerdict is { } verdict
|
||||||
|
? MeshTransportDtoMapper.FromProto(verdict, alarm.AlarmId, alarm.Operation)
|
||||||
|
: new AlarmCommandOutcome(alarm.AlarmId, alarm.Operation, AlarmCommandVerdict.OutcomeUnknown,
|
||||||
|
"the node took the command but reports no verdict (it runs a build older than #950); it applies the command if it owns the alarm.");
|
||||||
|
}
|
||||||
|
|
||||||
private void LoadContactsFromDb()
|
private void LoadContactsFromDb()
|
||||||
{
|
{
|
||||||
var self = Self;
|
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,
|
/// The gRPC status detail, or the exception's type name for a non-gRPC fault. Never a key,
|
||||||
/// and never a raw exception message.
|
/// and never a raw exception message.
|
||||||
/// </param>
|
/// </param>
|
||||||
|
/// <param name="Ack">#950: the node's reply on success (carries an alarm verdict when one was requested).</param>
|
||||||
|
/// <param name="VerdictReplyTo">#950: the AdminUI alarm command's verdict collector, when one is waiting.</param>
|
||||||
|
/// <param name="Alarm">#950: the alarm command, when <paramref name="VerdictReplyTo"/> is set.</param>
|
||||||
public sealed record CommandDispatched(
|
public sealed record CommandDispatched(
|
||||||
string NodeId,
|
string NodeId,
|
||||||
string CommandType,
|
string CommandType,
|
||||||
string CorrelationId,
|
string CorrelationId,
|
||||||
string? FailureStatus,
|
string? FailureStatus,
|
||||||
string? FailureDetail);
|
string? FailureDetail,
|
||||||
|
ExecuteAck? Ack = null,
|
||||||
|
IActorRef? VerdictReplyTo = null,
|
||||||
|
AlarmCommand? Alarm = null);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,22 @@ public interface IMeshCommandDialer
|
|||||||
/// </exception>
|
/// </exception>
|
||||||
Task DispatchAsync(string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct);
|
Task DispatchAsync(string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: <see cref="DispatchAsync"/> returning the node's <see cref="ExecuteAck"/>, whose <c>alarm_verdict</c>
|
||||||
|
/// carries a scripted-alarm verdict when the command asked for one. The default (a dialer that only implements
|
||||||
|
/// <see cref="DispatchAsync"/>) answers an empty ack — "delivered, no verdict".
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="nodeEndpoint">The node's gRPC base address.</param>
|
||||||
|
/// <param name="envelope">The wire envelope.</param>
|
||||||
|
/// <param name="clusterId">The target node's application <c>Cluster</c>.</param>
|
||||||
|
/// <param name="ct">Cancels the dial.</param>
|
||||||
|
/// <returns>The node's ack.</returns>
|
||||||
|
async Task<ExecuteAck> ExecuteAsync(string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await DispatchAsync(nodeEndpoint, envelope, clusterId, ct).ConfigureAwait(false);
|
||||||
|
return new ExecuteAck();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Releases any per-endpoint resources for endpoints NOT in <paramref name="nodeEndpoints"/>
|
/// Releases any per-endpoint resources for endpoints NOT in <paramref name="nodeEndpoints"/>
|
||||||
/// (R03:1.3). Central calls it on every contact refresh with the current dispatch set, so a
|
/// (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 int CachedChannelCount => _channels.Count;
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task DispatchAsync(
|
public Task DispatchAsync(
|
||||||
|
string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct)
|
||||||
|
=> ExecuteAsync(nodeEndpoint, envelope, clusterId, ct);
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<ExecuteAck> ExecuteAsync(
|
||||||
string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct)
|
string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct)
|
||||||
{
|
{
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(nodeEndpoint);
|
ArgumentException.ThrowIfNullOrWhiteSpace(nodeEndpoint);
|
||||||
@@ -187,7 +208,7 @@ public sealed class MeshGrpcCommandDialer : IMeshCommandDialer, IDisposable
|
|||||||
|
|
||||||
var client = _clientFactory(nodeEndpoint);
|
var client = _clientFactory(nodeEndpoint);
|
||||||
using var call = client.ExecuteAsync(envelope, headers, cancellationToken: deadlineCts.Token);
|
using var call = client.ExecuteAsync(envelope, headers, cancellationToken: deadlineCts.Token);
|
||||||
await call.ResponseAsync.ConfigureAwait(false);
|
return await call.ResponseAsync.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
|
|||||||
@@ -3,8 +3,10 @@ using Akka.Hosting;
|
|||||||
using Grpc.Core;
|
using Grpc.Core;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
|
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.Commons.Protos.MeshTransport.V1;
|
||||||
using ZB.MOM.WW.OtOpcUa.Runtime;
|
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
|
// 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.
|
// this impl can keep the natural name without colliding with the generated type.
|
||||||
using GeneratedServiceBase =
|
using GeneratedServiceBase =
|
||||||
@@ -87,6 +89,9 @@ public sealed class NodeCommandGrpcService : GeneratedServiceBase
|
|||||||
StatusCode.InvalidArgument, "Command envelope could not be decoded."));
|
StatusCode.InvalidArgument, "Command envelope could not be decoded."));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (command is AlarmCommand { VerdictRequested: true } alarm)
|
||||||
|
return ExecuteForVerdictAsync(alarm, request.CorrelationId, context.CancellationToken);
|
||||||
|
|
||||||
if (!_registry.TryGet<NodeCommunicationActorKey>(out var comm))
|
if (!_registry.TryGet<NodeCommunicationActorKey>(out var comm))
|
||||||
{
|
{
|
||||||
_log.LogWarning(
|
_log.LogWarning(
|
||||||
@@ -107,4 +112,69 @@ public sealed class NodeCommandGrpcService : GeneratedServiceBase
|
|||||||
|
|
||||||
return Task.FromResult(new ExecuteAck());
|
return Task.FromResult(new ExecuteAck());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: an AdminUI alarm command that wants this node's verdict. Asks the local driver host (which forwards to its
|
||||||
|
/// <c>ScriptedAlarmHostActor</c> — the same <c>ExecuteAlarmCommand</c> path the OPC UA Part 9 methods use, #937) and
|
||||||
|
/// returns the verdict in <see cref="ExecuteAck.AlarmVerdict"/>. Never re-emitted on the EventStream as well: this
|
||||||
|
/// node's host gets exactly one copy, as on the one-way path.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <para>
|
||||||
|
/// <b>No deadline on the ask message.</b> The OPC UA path stamps one so an expired ask skips the engine — its
|
||||||
|
/// broadcast copy still applies. Nothing else carries this command to this node, so an ask that outlives
|
||||||
|
/// <see cref="VerdictWait"/> must still apply (the one-way semantic it replaces); the caller is told
|
||||||
|
/// OutcomeUnknown, never "not applied".
|
||||||
|
/// </para>
|
||||||
|
/// <para>
|
||||||
|
/// No driver host registered while the comm actor is ⇒ this node runs no driver role (or no scripted-alarm
|
||||||
|
/// host could exist): answered NotApplied/NotOwned. Neither registered ⇒ still booting ⇒
|
||||||
|
/// <see cref="StatusCode.Unavailable"/>, as for every other command.
|
||||||
|
/// </para>
|
||||||
|
/// </remarks>
|
||||||
|
private async Task<ExecuteAck> ExecuteForVerdictAsync(AlarmCommand alarm, string correlationId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
AlarmCommandOutcome outcome;
|
||||||
|
if (!_registry.TryGet<DriverHostActorKey>(out var driverHost))
|
||||||
|
{
|
||||||
|
if (!_registry.TryGet<NodeCommunicationActorKey>(out _))
|
||||||
|
{
|
||||||
|
_log.LogWarning(
|
||||||
|
"Rejected a mesh alarm command (correlationId={CorrelationId}): this node is still starting; the "
|
||||||
|
+ "command was NOT delivered.", correlationId);
|
||||||
|
throw new RpcException(new Status(
|
||||||
|
StatusCode.Unavailable, "Node is still starting: the command endpoint is not ready."));
|
||||||
|
}
|
||||||
|
|
||||||
|
outcome = new AlarmCommandOutcome(alarm.AlarmId, alarm.Operation, AlarmCommandVerdict.NotApplied,
|
||||||
|
"This server runs no scripted-alarm engine; the command was not applied.", NotOwned: true);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
outcome = await driverHost.Ask<AlarmCommandOutcome>(
|
||||||
|
new ScriptedAlarmHostActor.ExecuteAlarmCommand(alarm with { VerdictRequested = false }),
|
||||||
|
VerdictWait, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is AskTimeoutException or TaskCanceledException or TimeoutException
|
||||||
|
&& !ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
outcome = new AlarmCommandOutcome(alarm.AlarmId, alarm.Operation, AlarmCommandVerdict.OutcomeUnknown,
|
||||||
|
$"the scripted-alarm engine did not answer within {VerdictWait.TotalSeconds:0.#} s; the command may still apply.",
|
||||||
|
TimedOut: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_log.LogDebug(
|
||||||
|
"Mesh: {Operation} for alarm {AlarmId} (correlationId={CorrelationId}) answered {Verdict} (notOwned={NotOwned}).",
|
||||||
|
alarm.Operation, alarm.AlarmId, correlationId, outcome.Verdict, outcome.NotOwned);
|
||||||
|
return new ExecuteAck { AlarmVerdict = MeshTransportDtoMapper.ToProto(outcome) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: how long the node waits for its scripted-alarm host — under central's default 10 s dispatch deadline and
|
||||||
|
/// 7 s collection window, so a slow engine reads as a timed-out unknown rather than a failed dial.
|
||||||
|
/// </summary>
|
||||||
|
internal TimeSpan VerdictWait { get; init; } = TimeSpan.FromSeconds(5);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2609,7 +2609,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
|||||||
}
|
}
|
||||||
|
|
||||||
Sender.Tell(new AlarmCommandOutcome(msg.Command.AlarmId, msg.Command.Operation, AlarmCommandVerdict.NotApplied,
|
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)
|
private void HandleRouteNativeAlarmAck(RouteNativeAlarmAck msg)
|
||||||
|
|||||||
@@ -788,12 +788,18 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
|
|||||||
/// <param name="cmd">The inbound alarm command.</param>
|
/// <param name="cmd">The inbound alarm command.</param>
|
||||||
private async Task OnAlarmCommand(AlarmCommand cmd)
|
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
|
// #937: the broadcast copy of a command this host already took through ExecuteAlarmCommand (or the other way
|
||||||
// round) is applied once.
|
// 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})",
|
_log.Debug("ScriptedAlarmHost: skipping duplicate AlarmCommand {Op} for {AlarmId} (command {CommandId})",
|
||||||
cmd.Operation, cmd.AlarmId, id);
|
cmd.Operation, cmd.AlarmId, id);
|
||||||
|
replyTo?.Tell(known);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -803,10 +809,14 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
|
|||||||
{
|
{
|
||||||
_log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}",
|
_log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}",
|
||||||
cmd.Operation, cmd.AlarmId);
|
cmd.Operation, cmd.AlarmId);
|
||||||
|
replyTo?.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
|
||||||
|
NotLoadedRefusal, NotOwned: true));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Remember(cmd, await ApplyCommandAsync(cmd));
|
var outcome = await ApplyCommandAsync(cmd);
|
||||||
|
Remember(cmd, outcome);
|
||||||
|
replyTo?.Tell(outcome);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -840,7 +850,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
|
|||||||
var outcome = Owns(cmd.AlarmId)
|
var outcome = Owns(cmd.AlarmId)
|
||||||
? await ApplyCommandAsync(cmd)
|
? await ApplyCommandAsync(cmd)
|
||||||
: new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
|
: new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
|
||||||
_readiness?.Refusal() ?? NotLoadedRefusal);
|
_readiness?.Refusal() ?? NotLoadedRefusal, NotOwned: true);
|
||||||
|
|
||||||
Remember(cmd, outcome);
|
Remember(cmd, outcome);
|
||||||
replyTo.Tell(outcome);
|
replyTo.Tell(outcome);
|
||||||
|
|||||||
@@ -96,6 +96,46 @@ public class MeshTransportDtoMapperTests
|
|||||||
MeshTransportDtoMapper.FromProto(Wire(MeshTransportDtoMapper.ToProto(domain))).ShouldBe(domain);
|
MeshTransportDtoMapper.FromProto(Wire(MeshTransportDtoMapper.ToProto(domain))).ShouldBe(domain);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: the verdict request survives the wire; an absent field (a pre-#950 central) reads false.</summary>
|
||||||
|
[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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: every verdict shape round-trips through <c>ExecuteAck.alarm_verdict</c>.</summary>
|
||||||
|
[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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: an empty <c>ExecuteAck</c> (every pre-#950 node) carries no verdict, and an UNSPECIFIED verdict never
|
||||||
|
/// decodes as applied — it is unknown.
|
||||||
|
/// </summary>
|
||||||
|
[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]
|
[Fact]
|
||||||
public void AlarmCommand_RoundTrips_WithNullComment()
|
public void AlarmCommand_RoundTrips_WithNullComment()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using Akka.Actor;
|
||||||
using Akka.Hosting;
|
using Akka.Hosting;
|
||||||
using Akka.TestKit.Xunit;
|
using Akka.TestKit.Xunit;
|
||||||
using Shouldly;
|
using Shouldly;
|
||||||
@@ -28,9 +29,22 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests;
|
|||||||
/// </remarks>
|
/// </remarks>
|
||||||
public sealed class AlertsAckPathTests : TestKit
|
public sealed class AlertsAckPathTests : TestKit
|
||||||
{
|
{
|
||||||
private (AdminOperationsClient Client, Akka.TestKit.TestProbe Mesh) Wire()
|
private (AdminOperationsClient Client, Akka.TestKit.TestProbe Mesh) Wire(
|
||||||
|
Func<AlarmCommand, AlarmCommandOutcome>? answer = null)
|
||||||
{
|
{
|
||||||
var mesh = CreateTestProbe("mesh-router");
|
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(
|
var actor = Sys.ActorOf(AdminOperationsActor.Props(
|
||||||
AclScopeTestDb.Factory($"alerts-ack-{Guid.NewGuid():N}"),
|
AclScopeTestDb.Factory($"alerts-ack-{Guid.NewGuid():N}"),
|
||||||
coordinator: CreateTestProbe("coordinator").Ref,
|
coordinator: CreateTestProbe("coordinator").Ref,
|
||||||
@@ -42,16 +56,18 @@ public sealed class AlertsAckPathTests : TestKit
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The page's Acknowledge reaches the cluster as an <c>Acknowledge</c> AlarmCommand on the
|
/// <summary>The page's Acknowledge reaches the cluster as an <c>Acknowledge</c> AlarmCommand on the
|
||||||
/// <c>alarm-commands</c> topic carrying the alarm id and the operator, and the page is told it was sent.</summary>
|
/// <c>alarm-commands</c> 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).</summary>
|
||||||
[Fact]
|
[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 (client, mesh) = Wire();
|
||||||
|
|
||||||
var result = await client.AcknowledgeAlarmAsync("alarm-42", "operator-jo", comment: null, CancellationToken.None);
|
var result = await client.AcknowledgeAlarmAsync("alarm-42", "operator-jo", comment: null, CancellationToken.None);
|
||||||
|
|
||||||
result.Ok.ShouldBeTrue();
|
result.Ok.ShouldBeTrue();
|
||||||
result.Message.ShouldBeNull();
|
result.Verdict.ShouldBe(AlarmCommandVerdict.Applied);
|
||||||
|
result.Summary.ShouldBe("Applied");
|
||||||
var sent = mesh.ExpectMsg<MeshCommand>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
|
var sent = mesh.ExpectMsg<MeshCommand>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
|
||||||
sent.Topic.ShouldBe(AlarmCommandsTopic.Name);
|
sent.Topic.ShouldBe(AlarmCommandsTopic.Name);
|
||||||
var command = sent.Message.ShouldBeOfType<AlarmCommand>();
|
var command = sent.Message.ShouldBeOfType<AlarmCommand>();
|
||||||
@@ -78,4 +94,18 @@ public sealed class AlertsAckPathTests : TestKit
|
|||||||
command.Operation.ShouldBe("TimedShelve");
|
command.Operation.ShouldBe("TimedShelve");
|
||||||
command.UnshelveAtUtc.ShouldBe(until);
|
command.UnshelveAtUtc.ShouldBe(until);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: the engine's refusal reaches the page as a refusal with its reason, not as "sent".</summary>
|
||||||
|
[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.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.WaitForAssertion(()=>cut.FindAll("[role=status]").Count(x=>x.TextContent.Contains("Ack sent")).ShouldBe(1));
|
||||||
cut.FindAll("details").ShouldContain(x=>x.TextContent.Contains("Request details"));
|
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]
|
[Fact]
|
||||||
public async Task DisposedPage_DoesNotRenderLateAcknowledgementOutcome()
|
public async Task DisposedPage_DoesNotRenderLateAcknowledgementOutcome()
|
||||||
{
|
{
|
||||||
|
|||||||
+24
-2
@@ -22,6 +22,27 @@ public sealed class AdminOperationsActorMailboxTests : ControlPlaneActorTestBase
|
|||||||
{
|
{
|
||||||
private static readonly TimeSpan AckBudget = TimeSpan.FromSeconds(1);
|
private static readonly TimeSpan AckBudget = TimeSpan.FromSeconds(1);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>An alarm ack completes in under a second while a 60 s Test Connect is still pending.</summary>
|
/// <summary>An alarm ack completes in under a second while a 60 s Test Connect is still pending.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Alarm_ack_completes_while_a_60s_test_connect_is_pending()
|
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 dbFactory = NewInMemoryDbFactory();
|
||||||
var coordinator = CreateTestProbe("coord");
|
var coordinator = CreateTestProbe("coord");
|
||||||
var probe = new BlockingProbe();
|
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");
|
var connectClient = CreateTestProbe("connect-client");
|
||||||
|
|
||||||
connectClient.Send(actor, new TestDriverConnect("Blocking", "{}", TimeoutSeconds: 60, Guid.NewGuid()));
|
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 gated = new GatedDbFactory(NewInMemoryDbFactory());
|
||||||
var coordinator = CreateTestProbe("coord");
|
var coordinator = CreateTestProbe("coord");
|
||||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
|
var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty<IDriverProbe>(), meshRouter: AnsweringRouter()));
|
||||||
var deployer = CreateTestProbe("deployer");
|
var deployer = CreateTestProbe("deployer");
|
||||||
|
|
||||||
gated.Hold();
|
gated.Hold();
|
||||||
|
|||||||
@@ -29,9 +29,19 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase
|
|||||||
// message sender, not to the subscribed ref). Mirrors ScriptedAlarmHostActor's self-subscribe.
|
// message sender, not to the subscribed ref). Mirrors ScriptedAlarmHostActor's self-subscribe.
|
||||||
probe.Send(mediator, new Subscribe(AlarmCommandsTopic.Name, probe.Ref));
|
probe.Send(mediator, new Subscribe(AlarmCommandsTopic.Name, probe.Ref));
|
||||||
probe.ExpectMsg<SubscribeAck>(TimeSpan.FromSeconds(5));
|
probe.ExpectMsg<SubscribeAck>(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;
|
return probe;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: the verdict window; the test system has no driver members, so the collector waits it out.</summary>
|
||||||
|
private static readonly TimeSpan VerdictWindow = TimeSpan.FromSeconds(1);
|
||||||
|
|
||||||
/// <summary>Verifies an <see cref="AcknowledgeAlarmCommand"/> publishes a correctly-mapped
|
/// <summary>Verifies an <see cref="AcknowledgeAlarmCommand"/> publishes a correctly-mapped
|
||||||
/// <see cref="AlarmCommand"/> (Operation="Acknowledge", AlarmId/User/Comment threaded, no
|
/// <see cref="AlarmCommand"/> (Operation="Acknowledge", AlarmId/User/Comment threaded, no
|
||||||
/// UnshelveAtUtc) onto the <c>alarm-commands</c> topic and replies Ok.</summary>
|
/// UnshelveAtUtc) onto the <c>alarm-commands</c> topic and replies Ok.</summary>
|
||||||
@@ -40,7 +50,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase
|
|||||||
{
|
{
|
||||||
var dbFactory = NewInMemoryDbFactory();
|
var dbFactory = NewInMemoryDbFactory();
|
||||||
var coordinator = CreateTestProbe("coord");
|
var coordinator = CreateTestProbe("coord");
|
||||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
|
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(), alarmVerdictWindow: VerdictWindow));
|
||||||
var topicProbe = SubscribeAlarmCommandsProbe();
|
var topicProbe = SubscribeAlarmCommandsProbe();
|
||||||
|
|
||||||
var correlationId = CorrelationId.NewId();
|
var correlationId = CorrelationId.NewId();
|
||||||
@@ -55,7 +65,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase
|
|||||||
|
|
||||||
var reply = ExpectMsg<AcknowledgeAlarmResult>(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken);
|
var reply = ExpectMsg<AcknowledgeAlarmResult>(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken);
|
||||||
reply.Ok.ShouldBeTrue();
|
reply.Ok.ShouldBeTrue();
|
||||||
reply.Message.ShouldBeNull();
|
reply.Verdict.ShouldBe(AlarmCommandVerdict.Applied);
|
||||||
reply.CorrelationId.ShouldBe(correlationId);
|
reply.CorrelationId.ShouldBe(correlationId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +76,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase
|
|||||||
{
|
{
|
||||||
var dbFactory = NewInMemoryDbFactory();
|
var dbFactory = NewInMemoryDbFactory();
|
||||||
var coordinator = CreateTestProbe("coord");
|
var coordinator = CreateTestProbe("coord");
|
||||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
|
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(), alarmVerdictWindow: VerdictWindow));
|
||||||
var topicProbe = SubscribeAlarmCommandsProbe();
|
var topicProbe = SubscribeAlarmCommandsProbe();
|
||||||
|
|
||||||
var correlationId = CorrelationId.NewId();
|
var correlationId = CorrelationId.NewId();
|
||||||
@@ -90,7 +100,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase
|
|||||||
{
|
{
|
||||||
var dbFactory = NewInMemoryDbFactory();
|
var dbFactory = NewInMemoryDbFactory();
|
||||||
var coordinator = CreateTestProbe("coord");
|
var coordinator = CreateTestProbe("coord");
|
||||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
|
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(), alarmVerdictWindow: VerdictWindow));
|
||||||
var topicProbe = SubscribeAlarmCommandsProbe();
|
var topicProbe = SubscribeAlarmCommandsProbe();
|
||||||
|
|
||||||
var unshelveAt = DateTime.UtcNow.AddMinutes(15);
|
var unshelveAt = DateTime.UtcNow.AddMinutes(15);
|
||||||
@@ -113,7 +123,7 @@ public sealed class AdminOperationsActorTests : ControlPlaneActorTestBase
|
|||||||
{
|
{
|
||||||
var dbFactory = NewInMemoryDbFactory();
|
var dbFactory = NewInMemoryDbFactory();
|
||||||
var coordinator = CreateTestProbe("coord");
|
var coordinator = CreateTestProbe("coord");
|
||||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
|
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(), alarmVerdictWindow: VerdictWindow));
|
||||||
var topicProbe = SubscribeAlarmCommandsProbe();
|
var topicProbe = SubscribeAlarmCommandsProbe();
|
||||||
|
|
||||||
actor.Tell(new ShelveAlarmCommand("alarm-3", "op-sam", ShelveKind.Unshelve, UnshelveAtUtc: null, Comment: null, CorrelationId.NewId()));
|
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 dbFactory = NewInMemoryDbFactory();
|
||||||
var coordinator = CreateTestProbe("coord");
|
var coordinator = CreateTestProbe("coord");
|
||||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>()));
|
var actor = Sys.ActorOf(AdminOperationsActor.Props(dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(), alarmVerdictWindow: VerdictWindow));
|
||||||
var topicProbe = SubscribeAlarmCommandsProbe();
|
var topicProbe = SubscribeAlarmCommandsProbe();
|
||||||
|
|
||||||
actor.Tell(new ShelveAlarmCommand("alarm-1", "op-zoe", ShelveKind.Timed, UnshelveAtUtc: null, Comment: null, CorrelationId.NewId()));
|
actor.Tell(new ShelveAlarmCommand("alarm-1", "op-zoe", ShelveKind.Timed, UnshelveAtUtc: null, Comment: null, CorrelationId.NewId()));
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950 — the AdminUI <c>/alerts</c> ack/shelve reports the scripted-alarm engine's verdict instead of "sent": the
|
||||||
|
/// per-request <see cref="AlarmCommandVerdictCollector"/>, the fleet aggregation, and both router legs.
|
||||||
|
/// </summary>
|
||||||
|
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<string, AlarmCommandOutcome> 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<IDriverProbe>(),
|
||||||
|
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<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
sent.Topic.ShouldBe(AlarmCommandsTopic.Name);
|
||||||
|
sent.Message.ShouldBeOfType<AlarmCommand>().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<AcknowledgeAlarmResult>(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<MeshCommand>(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<ShelveAlarmResult>(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<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).VerdictReplyTo!;
|
||||||
|
collector.Tell(new AlarmVerdictFanOut(["a1", "a2"]));
|
||||||
|
collector.Tell(new AlarmNodeVerdict("a2", NotOwned));
|
||||||
|
|
||||||
|
var reply = ExpectMsg<AcknowledgeAlarmResult>(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<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||||
|
.VerdictReplyTo!.Tell(new AlarmVerdictFanOut([], "no enabled, non-maintenance ClusterNode row carries a GrpcPort."));
|
||||||
|
|
||||||
|
var reply = ExpectMsg<AcknowledgeAlarmResult>(TimeSpan.FromSeconds(3), cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
reply.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
|
||||||
|
reply.Summary.ShouldBe("Not delivered");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ DistributedPubSub legs
|
||||||
|
|
||||||
|
/// <summary>Subscribes a probe that plays a node's ScriptedAlarmHostActor: answers <paramref name="answer"/> to the publish's sender.</summary>
|
||||||
|
private TestProbe SubscribeAnsweringHost(Func<AlarmCommand, AlarmCommandOutcome?> 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<SubscribeAck>(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<IDriverProbe>(),
|
||||||
|
alarmVerdictWindow: TimeSpan.FromSeconds(1)));
|
||||||
|
|
||||||
|
admin.Tell(new AcknowledgeAlarmCommand("alarm-1", "alice", null, CorrelationId.NewId()));
|
||||||
|
|
||||||
|
var reply = ExpectMsg<AcknowledgeAlarmResult>(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<AlarmVerdictFanOut>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||||
|
.NotDeliveredReason.ShouldBeNull();
|
||||||
|
collector.ExpectMsg<AlarmCommandOutcome>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||||
|
.Reason.ShouldBe("nope");
|
||||||
|
}
|
||||||
|
}
|
||||||
+79
@@ -414,6 +414,75 @@ public class CentralCommunicationActorTests : ControlPlaneActorTestBase
|
|||||||
rig.Dialer.Calls[0].Envelope.AlarmCommand.AlarmId.ShouldBe("alarm-1");
|
rig.Dialer.Calls[0].Envelope.AlarmCommand.AlarmId.ShouldBe("alarm-1");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: an alarm command with a verdict collector tells it the dialled set first, then one verdict per node —
|
||||||
|
/// the node's own (from <c>ExecuteAck.alarm_verdict</c>), "no verdict" (an empty ack: a pre-#950 node), or the
|
||||||
|
/// transport failure, each of the last two UNKNOWN, never refused.
|
||||||
|
/// </summary>
|
||||||
|
[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<ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations.AlarmVerdictFanOut>(
|
||||||
|
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<ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations.AlarmNodeVerdict>(
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: with nothing to dial, the collector hears "not delivered" at once rather than waiting out its window.</summary>
|
||||||
|
[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<ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations.AlarmVerdictFanOut>(
|
||||||
|
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
fan.Nodes.ShouldBeEmpty();
|
||||||
|
fan.NotDeliveredReason.ShouldNotBeNull().ShouldContain("GrpcPort");
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void The_contact_refresh_publishes_the_known_cluster_set_and_drops_cached_psks()
|
public void The_contact_refresh_publishes_the_known_cluster_set_and_drops_cached_psks()
|
||||||
{
|
{
|
||||||
@@ -1042,6 +1111,16 @@ public class CentralCommunicationActorTests : ControlPlaneActorTestBase
|
|||||||
: Task.CompletedTask;
|
: Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: what a successful dial answers, per endpoint; null ⇒ an empty ack.</summary>
|
||||||
|
public Func<string, ExecuteAck?>? Answer { get; set; }
|
||||||
|
|
||||||
|
public async Task<ExecuteAck> ExecuteAsync(
|
||||||
|
string nodeEndpoint, CommandEnvelope envelope, string clusterId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await DispatchAsync(nodeEndpoint, envelope, clusterId, ct);
|
||||||
|
return Answer?.Invoke(nodeEndpoint) ?? new ExecuteAck();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Every endpoint set handed to <see cref="RetainOnly"/>, in order.</summary>
|
/// <summary>Every endpoint set handed to <see cref="RetainOnly"/>, in order.</summary>
|
||||||
public IReadOnlyList<IReadOnlyCollection<string>> RetainCalls
|
public IReadOnlyList<IReadOnlyCollection<string>> RetainCalls
|
||||||
{
|
{
|
||||||
|
|||||||
+4
-2
@@ -113,7 +113,8 @@ public class MeshRouterDispatchTests : ControlPlaneActorTestBase
|
|||||||
|
|
||||||
var cmd = router.ExpectMsg<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
var cmd = router.ExpectMsg<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||||
cmd.Topic.ShouldBe(AlarmCommandsTopic.Name);
|
cmd.Topic.ShouldBe(AlarmCommandsTopic.Name);
|
||||||
cmd.Message.ShouldBeOfType<AlarmCommand>();
|
cmd.Message.ShouldBeOfType<AlarmCommand>().VerdictRequested.ShouldBeTrue();
|
||||||
|
cmd.VerdictReplyTo.ShouldNotBeNull(); // #950: the per-request verdict collector
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -131,6 +132,7 @@ public class MeshRouterDispatchTests : ControlPlaneActorTestBase
|
|||||||
|
|
||||||
var cmd = router.ExpectMsg<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
var cmd = router.ExpectMsg<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||||
cmd.Topic.ShouldBe(AlarmCommandsTopic.Name);
|
cmd.Topic.ShouldBe(AlarmCommandsTopic.Name);
|
||||||
cmd.Message.ShouldBeOfType<AlarmCommand>();
|
cmd.Message.ShouldBeOfType<AlarmCommand>().VerdictRequested.ShouldBeTrue();
|
||||||
|
cmd.VerdictReplyTo.ShouldNotBeNull(); // #950: the per-request verdict collector
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,7 +85,8 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime
|
|||||||
public async ValueTask InitializeAsync()
|
public async ValueTask InitializeAsync()
|
||||||
{
|
{
|
||||||
_central = StartSelfSeededSystem();
|
_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);
|
_siteB = await SiteNode.StartAsync("SITE-B", SiteBKey);
|
||||||
|
|
||||||
await Task.WhenAll(
|
await Task.WhenAll(
|
||||||
@@ -214,6 +215,43 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime
|
|||||||
await _siteA.Inbox.Task.WaitAsync(Arrival, TestContext.Current.CancellationToken);
|
await _siteA.Inbox.Task.WaitAsync(Arrival, TestContext.Current.CancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950, end to end over the real wire: the AdminUI ack path (real <c>AdminOperationsActor</c> → real
|
||||||
|
/// <c>CentralCommunicationActor</c> → real dialer → real interceptor → real <c>NodeCommandGrpcService</c>) comes back
|
||||||
|
/// with each node's engine verdict in <c>ExecuteAck.alarm_verdict</c>: site-A's owner applied it, site-B owns
|
||||||
|
/// nothing — so the operator is told Applied, not "sent".
|
||||||
|
/// </summary>
|
||||||
|
[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<AcknowledgeAlarmResult>(
|
||||||
|
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 ---------------------------------------------------------------------------------
|
// ---- harness ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
private static MeshGrpcCommandDialer Dialer(IMeshPskProvider? psk = null) =>
|
private static MeshGrpcCommandDialer Dialer(IMeshPskProvider? psk = null) =>
|
||||||
@@ -316,7 +354,12 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime
|
|||||||
public TaskCompletionSource<object> Inbox { get; } =
|
public TaskCompletionSource<object> Inbox { get; } =
|
||||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
|
||||||
public static async Task<SiteNode> StartAsync(string clusterId, string psk)
|
/// <summary>#950: how many AlarmCommands reached this node's EventStream (the one-way path).</summary>
|
||||||
|
public int AlarmEventStreamCopies => _alarmCopies;
|
||||||
|
|
||||||
|
private int _alarmCopies;
|
||||||
|
|
||||||
|
public static async Task<SiteNode> StartAsync(string clusterId, string psk, bool withAlarmOwner = false)
|
||||||
{
|
{
|
||||||
var node = new SiteNode { System = StartSelfSeededSystem(), Port = GetFreePort() };
|
var node = new SiteNode { System = StartSelfSeededSystem(), Port = GetFreePort() };
|
||||||
|
|
||||||
@@ -329,6 +372,11 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime
|
|||||||
|
|
||||||
var registry = new ActorRegistry();
|
var registry = new ActorRegistry();
|
||||||
registry.Register<NodeCommunicationActorKey>(comm);
|
registry.Register<NodeCommunicationActorKey>(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<DriverHostActorKey>(node.System.ActorOf(Akka.Actor.Props.Create(() => new ApplyingDriverHost())));
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder();
|
var builder = WebApplication.CreateBuilder();
|
||||||
builder.Environment.ApplicationName = typeof(MeshGrpcBoundaryTests).Assembly.GetName().Name!;
|
builder.Environment.ApplicationName = typeof(MeshGrpcBoundaryTests).Assembly.GetName().Name!;
|
||||||
@@ -411,6 +459,21 @@ public sealed class MeshGrpcBoundaryTests : IAsyncLifetime
|
|||||||
return port;
|
return port;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: stands in for a driver host whose scripted-alarm engine owns and applies every command.</summary>
|
||||||
|
private sealed class ApplyingDriverHost : ReceiveActor
|
||||||
|
{
|
||||||
|
public ApplyingDriverHost() =>
|
||||||
|
Receive<ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmHostActor.ExecuteAlarmCommand>(m =>
|
||||||
|
Sender.Tell(new Commons.OpcUa.AlarmCommandOutcome(
|
||||||
|
m.Command.AlarmId, m.Command.Operation, Commons.OpcUa.AlarmCommandVerdict.Applied)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Counts what it receives.</summary>
|
||||||
|
private sealed class CountActor : ReceiveActor
|
||||||
|
{
|
||||||
|
public CountActor(Action onMessage) => ReceiveAny(_ => onMessage());
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Completes an inbox with the first message it receives.</summary>
|
/// <summary>Completes an inbox with the first message it receives.</summary>
|
||||||
private sealed class CaptureActor : ReceiveActor
|
private sealed class CaptureActor : ReceiveActor
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -66,6 +66,96 @@ public sealed class NodeCommandGrpcServiceTests : TestKit
|
|||||||
probe.ExpectMsg<AlarmCommand>(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(alarm);
|
probe.ExpectMsg<AlarmCommand>(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(alarm);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// #950: an alarm command asking for a verdict goes to the driver host as an <c>ExecuteAlarmCommand</c> (no ask
|
||||||
|
/// deadline — nothing else carries it here), NOT to the comm actor, and the host's answer rides the ack.
|
||||||
|
/// </summary>
|
||||||
|
[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<NodeCommunicationActorKey>(comm.Ref);
|
||||||
|
registry.Register<DriverHostActorKey>(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<ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmHostActor.ExecuteAlarmCommand>(
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: an engine that does not answer in time is an unknown (timed-out) verdict, never a failed call.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task A_silent_driver_host_is_a_timed_out_unknown()
|
||||||
|
{
|
||||||
|
var registry = new ActorRegistry();
|
||||||
|
registry.Register<NodeCommunicationActorKey>(CreateTestProbe().Ref);
|
||||||
|
registry.Register<DriverHostActorKey>(CreateTestProbe().Ref);
|
||||||
|
var service = new NodeCommandGrpcService(registry, NullLogger<NodeCommandGrpcService>.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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: a node with no driver host owns no scripted alarm — answered NotApplied/NotOwned.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task A_verdict_request_on_a_node_without_a_driver_host_is_not_owned()
|
||||||
|
{
|
||||||
|
var registry = new ActorRegistry();
|
||||||
|
registry.Register<NodeCommunicationActorKey>(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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#950: without the request (a pre-#950 central) the one-way path is untouched — an empty ack.</summary>
|
||||||
|
[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<NodeCommunicationActorKey>(comm.Ref);
|
||||||
|
registry.Register<DriverHostActorKey>(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<AlarmCommand>(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(alarm);
|
||||||
|
driverHost.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task A_call_in_the_boot_window_before_the_actor_is_registered_is_unavailable()
|
public async Task A_call_in_the_boot_window_before_the_actor_is_registered_is_unavailable()
|
||||||
{
|
{
|
||||||
|
|||||||
+116
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gitea #950 — a broadcast <see cref="AlarmCommand"/> from central's AdminUI path (<c>VerdictRequested</c>) is answered
|
||||||
|
/// to its sender with the engine's verdict, non-owners included (<c>NotOwned</c>); every other broadcast stays one-way.
|
||||||
|
/// </summary>
|
||||||
|
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<DependencyMuxActor.RegisterInterest>(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<AlarmCommandOutcome>(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<AlarmCommandOutcome>(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<AlarmCommandOutcome>(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<AlarmCommandOutcome>(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<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(
|
||||||
|
new AlarmCommand("someone-elses", "Acknowledge", "alice", null, null)), Timeout, Ct);
|
||||||
|
|
||||||
|
outcome.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
|
||||||
|
outcome.NotOwned.ShouldBeTrue();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user