using Akka.Actor;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
///
/// #937: how an OPC UA Part 9 method on a scripted condition reaches the engines — this node's first, the redundant peer's
/// only after this node's engine applied it (or did not answer).
///
///
///
/// Why the peer goes second (review r1). Broadcasting first let the peer apply a command the local engine then
/// refused: the caller was told a definite failure, the local node was reverted, and the peer's save came back to this
/// node through the last-writer-wins condition-state replication. Asking first makes a refusal true pair-wide
/// (no engine saw the command) — which is what lets the node manager revert the node and answer
/// BadInvalidState. An applied or unknown verdict is broadcast so the peer converges exactly as before (an
/// unknown local outcome may still apply locally, so the peer must not be left behind).
///
///
/// No local engine (no driver host, or it runs no scripted-alarm host) ⇒
/// and nothing is broadcast: this node's condition node is driven by no engine, and a command for it is refused.
///
///
internal static class ScriptedAlarmCommandDispatch
{
///
/// Asks the local engine, then broadcasts unless it refused. Starts the ask synchronously (safe under the SDK's Lock);
/// never faults — no answer within is an OutcomeUnknown outcome.
///
/// The command (with its CommandId, which de-duplicates the broadcast copy on the local host).
/// The caller's bound.
/// The ask to this node's scripted-alarm host; null ⇒ none on this node.
/// Publishes the command on the alarm-commands topic.
/// Logger.
/// The local verdict.
internal static async Task AskThenBroadcastAsync(AlarmCommand cmd, TimeSpan timeout,
Func>? askLocal, Action broadcast, ILogger logger)
{
if (askLocal is null)
{
return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
"This server runs no scripted-alarm engine; the command was not applied.");
}
AlarmCommandOutcome outcome;
try
{
outcome = await askLocal(cmd, timeout).ConfigureAwait(false);
}
catch (Exception ex) when (ex is AskTimeoutException or TaskCanceledException or TimeoutException)
{
outcome = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
$"OutcomeUnknown: the scripted-alarm engine did not answer within {timeout.TotalSeconds:0.#} s; the command may still apply.",
TimedOut: true);
}
catch (Exception ex)
{
outcome = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: " + ex.GetType().Name);
}
if (outcome.Verdict != AlarmCommandVerdict.NotApplied)
{
try
{
broadcast(cmd);
}
catch (Exception ex)
{
// The peer's copy only; the caller's answer is the local verdict.
logger.LogWarning(ex, "Failed to broadcast alarm command {Operation} for {AlarmId} to the redundant peer",
cmd.Operation, cmd.AlarmId);
}
}
return outcome;
}
}