using System.Text;
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Event;
using ZB.MOM.WW.OtOpcUa.Cluster;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
///
/// #950: router → collector. Which nodes an AdminUI alarm command went to — the set the
/// waits on.
///
///
/// The nodes expected to answer (gRPC: the dialled ClusterNode ids; DistributedPubSub: the Up driver
/// members' host:port). Empty with a null ⇒ the set is unknown and the
/// collector waits out its window.
///
/// Set when the command reached no node at all (no targets, no dialer, unencodable).
public sealed record AlarmVerdictFanOut(IReadOnlyList Nodes, string? NotDeliveredReason = null);
/// #950: one node's answer to an AdminUI alarm command, as the gRPC router saw it.
/// The node (its ClusterNode id).
/// Its verdict; transport failures and pre-#950 nodes arrive as .
public sealed record AlarmNodeVerdict(string Node, AlarmCommandOutcome Outcome);
/// #950: the fleet-wide verdict on one AdminUI alarm command.
/// Applied when any owning node applied it; OutcomeUnknown when none did but one may have; else NotApplied.
/// Short operator-facing text (the /alerts result chip).
/// Per-node breakdown (the result's details pane).
public sealed record AlarmCommandFleetOutcome(AlarmCommandVerdict Verdict, string Summary, string Detail);
///
/// #950: folds the per-node answers to one AdminUI alarm command into the verdict the operator sees.
///
///
///
/// Every driver node receives the command and only the alarm's owners act — two in a redundant pair, each with its
/// own engine (the condition state is then replicated last-writer-wins). So: any owner applied ⇒ Applied
/// (other owners' refusals/unknowns are listed, and the summary says it was partial); otherwise any unknown — an
/// owner that timed out, a node that did not answer, a transport failure, a pre-#950 node — ⇒ OutcomeUnknown,
/// never "refused", because that node may still apply it; otherwise an owner's refusal ⇒ NotApplied with its
/// reason; otherwise no node owns the alarm ⇒ NotApplied.
///
///
public static class AlarmCommandVerdictAggregator
{
/// Aggregates the answers.
/// Node → its verdict (non-owners carry ).
/// Expected nodes that did not answer within the window.
/// Whether the set of nodes the command reached is known (false ⇒ silence may hide an owner).
/// Set when the command reached no node at all.
/// The collection window, for the "no answer" text.
/// The fleet verdict.
public static AlarmCommandFleetOutcome Aggregate(
IReadOnlyDictionary answers,
IReadOnlyCollection unanswered,
bool expectedKnown,
string? notDeliveredReason,
TimeSpan window)
{
ArgumentNullException.ThrowIfNull(answers);
ArgumentNullException.ThrowIfNull(unanswered);
if (notDeliveredReason is not null && answers.Count == 0)
return new AlarmCommandFleetOutcome(AlarmCommandVerdict.NotApplied, "Not delivered",
$"The command was not delivered to any server, so nothing applied it: {notDeliveredReason}");
var applied = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.Applied);
var refused = answers.Where(a => a.Value is { Verdict: AlarmCommandVerdict.NotApplied, NotOwned: false })
.OrderBy(a => a.Key, StringComparer.Ordinal).ToList();
var unknown = answers.Count(a => a.Value.Verdict == AlarmCommandVerdict.OutcomeUnknown) + unanswered.Count;
AlarmCommandVerdict verdict;
string summary;
if (applied > 0)
{
verdict = AlarmCommandVerdict.Applied;
summary = refused.Count + unknown == 0
? "Applied"
: $"Applied on {applied} of {applied + refused.Count + unknown} servers";
}
else if (unknown > 0)
{
verdict = AlarmCommandVerdict.OutcomeUnknown;
summary = "Outcome unknown";
}
else if (refused.Count > 0)
{
verdict = AlarmCommandVerdict.NotApplied;
summary = "Refused: " + (refused[0].Value.Reason ?? "the alarm engine did not apply the command.");
}
else if (!expectedKnown)
{
// Silence from a node we could not enumerate may be an owner that did not answer (a pre-#950 node).
verdict = AlarmCommandVerdict.OutcomeUnknown;
summary = "Outcome unknown";
}
else
{
verdict = AlarmCommandVerdict.NotApplied;
summary = "Not applied: no server owns this alarm";
}
var detail = new StringBuilder(verdict switch
{
AlarmCommandVerdict.Applied => "The alarm engine applied the command.",
AlarmCommandVerdict.OutcomeUnknown =>
"No server confirmed the command and at least one did not give a definite answer — it may still apply. "
+ "Check the alarm's state before retrying.",
_ => "The command was not applied anywhere.",
});
foreach (var (node, outcome) in answers.OrderBy(a => a.Key, StringComparer.Ordinal))
detail.AppendLine().Append(node).Append(": ").Append(Describe(outcome));
foreach (var node in unanswered.OrderBy(n => n, StringComparer.Ordinal))
detail.AppendLine().Append(node).Append($": no answer within {window.TotalSeconds:0.#} s — outcome unknown.");
if (answers.Count == 0 && unanswered.Count == 0)
detail.AppendLine().Append($"No server answered within {window.TotalSeconds:0.#} s.");
if (notDeliveredReason is not null)
detail.AppendLine().Append("Delivery: ").Append(notDeliveredReason);
return new AlarmCommandFleetOutcome(verdict, summary, detail.ToString());
}
private static string Describe(AlarmCommandOutcome outcome) => outcome switch
{
{ Verdict: AlarmCommandVerdict.Applied } => "applied.",
{ Verdict: AlarmCommandVerdict.NotApplied, NotOwned: true } => "does not own this alarm.",
{ Verdict: AlarmCommandVerdict.NotApplied } => "refused — " + (outcome.Reason ?? "no reason given."),
_ => "outcome unknown — " + (outcome.Reason ?? "no reason given."),
};
}
///
/// #950: the DistributedPubSub leg of an AdminUI alarm command that wants verdicts — used by the router under
/// MeshTransport:Mode = Dps and by when no router is wired.
///
public static class AlarmVerdictDps
{
///
/// Publishes on with as the sender
/// (DistributedPubSub preserves it, so each node's scripted-alarm host answers the collector) and returns the nodes
/// expected to answer: the Up members carrying the driver role, keyed as keys them.
///
/// The actor system.
/// The DPS topic.
/// The command (with set).
/// Who the nodes answer.
/// The expected node keys; empty when the membership could not be read.
public static IReadOnlyList Publish(ActorSystem system, string topic, AlarmCommand command, IActorRef collector)
{
IReadOnlyList expected;
try
{
var cluster = Akka.Cluster.Cluster.Get(system);
expected = cluster.State.Members
.Where(m => m.Status == Akka.Cluster.MemberStatus.Up && RoleParser.GossipedRolesHave(m.Roles, RoleParser.Driver))
.Select(m => NodeKey(m.Address, cluster.SelfAddress))
.Distinct(StringComparer.Ordinal)
.ToList();
}
catch (Exception)
{
expected = [];
}
DistributedPubSub.Get(system).Mediator.Tell(new Publish(topic, command), collector);
return expected;
}
/// The key a DPS-answering node is known by: its host:port (a local-scope address is this node).
/// The member or reply-sender address.
/// This node's cluster address, or null when there is no cluster.
/// The key.
public static string NodeKey(Address address, Address? self)
{
var effective = address.HasGlobalScope || self is null ? address : self;
return effective.Host is not null && effective.Port is not null ? effective.HostPort() : effective.ToString();
}
}
///
/// #950: one AdminUI alarm command's verdict collection. Sends the command (via the mesh router, or straight onto
/// DistributedPubSub when none is wired), gathers each node's answer until every expected node has answered or the
/// window closes, and replies the aggregated (mapped by the caller's
/// reply) to the original requester. Stops itself after replying.
///
public sealed class AlarmCommandVerdictCollector : ReceiveActor, IWithTimers
{
/// The default collection window — under AdminOperationsClient's 10 s ask.
public static readonly TimeSpan DefaultWindow = TimeSpan.FromSeconds(7);
private const string WindowTimerKey = "window";
private readonly AlarmCommand _command;
private readonly IActorRef? _meshRouter;
private readonly IActorRef _replyTo;
private readonly Func _reply;
private readonly TimeSpan _window;
private readonly ILoggingAdapter _log = Context.GetLogger();
private readonly Dictionary _answers = new(StringComparer.Ordinal);
private HashSet? _expected;
private string? _notDelivered;
private Address? _self;
/// Gets or sets the timer scheduler.
public ITimerScheduler Timers { get; set; } = null!;
/// Creates the props.
/// The command; is forced on.
/// The central comm actor, or null to publish on DistributedPubSub directly.
/// The requester.
/// Maps the fleet verdict to the requester's reply message.
/// The collection window.
/// The props.
public static Props Props(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
Func reply, TimeSpan window) =>
Akka.Actor.Props.Create(() => new AlarmCommandVerdictCollector(command, meshRouter, replyTo, reply, window));
/// Initializes a new instance of the class.
/// The command.
/// The router, or null.
/// The requester.
/// Maps the verdict to the reply.
/// The collection window.
public AlarmCommandVerdictCollector(AlarmCommand command, IActorRef? meshRouter, IActorRef replyTo,
Func reply, TimeSpan window)
{
_command = command with { VerdictRequested = true };
_meshRouter = meshRouter;
_replyTo = replyTo;
_reply = reply;
_window = window;
Receive(msg =>
{
_expected = new HashSet(msg.Nodes, StringComparer.Ordinal);
_notDelivered = msg.NotDeliveredReason;
FinishIfComplete();
});
Receive(msg =>
{
_answers[msg.Node] = msg.Outcome;
FinishIfComplete();
});
// A DistributedPubSub answer straight from a node's ScriptedAlarmHostActor: the node is the sender.
Receive(outcome =>
{
if (!string.Equals(outcome.AlarmId, _command.AlarmId, StringComparison.Ordinal)) return;
_answers[AlarmVerdictDps.NodeKey(Sender.Path.Address, _self)] = outcome;
FinishIfComplete();
});
Receive(_ => Finish());
}
///
protected override void PreStart()
{
try
{
_self = Akka.Cluster.Cluster.Get(Context.System).SelfAddress;
}
catch (Exception)
{
_self = null;
}
Timers.StartSingleTimer(WindowTimerKey, WindowClosed.Instance, _window);
if (_meshRouter is not null)
{
_meshRouter.Tell(new MeshCommand(AlarmCommandsTopic.Name, _command, Self));
}
else
{
var expected = AlarmVerdictDps.Publish(Context.System, AlarmCommandsTopic.Name, _command, Self);
Self.Tell(new AlarmVerdictFanOut(expected));
}
}
private void FinishIfComplete()
{
if (_expected is null) return;
if (_notDelivered is not null && _expected.Count == 0)
{
Finish();
return;
}
if (_expected.Count > 0 && _expected.All(_answers.ContainsKey)) Finish();
}
private void Finish()
{
var expectedKnown = _expected is { Count: > 0 } || _notDelivered is not null;
var unanswered = _expected?.Where(n => !_answers.ContainsKey(n)).ToList() ?? [];
var outcome = AlarmCommandVerdictAggregator.Aggregate(_answers, unanswered, expectedKnown, _notDelivered, _window);
_log.Info("AdminOps: {Operation} for alarm {AlarmId} by {User} → {Outcome}",
_command.Operation, _command.AlarmId, _command.User,
$"{outcome.Verdict} ({outcome.Summary}; {_answers.Count} answered, {unanswered.Count} silent)");
_replyTo.Tell(_reply(outcome));
Timers.CancelAll();
Context.Stop(Self);
}
private sealed class WindowClosed
{
public static readonly WindowClosed Instance = new();
}
}