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
{
///
/// #951: how long past the caller's bound the local host's answer is still collected. The host bounds one engine op by
/// its command timeout (10 s) and skips an ask whose deadline passed before it started, so an answer that is coming at
/// all comes inside this window.
///
internal static readonly TimeSpan LateVerdictWindow = TimeSpan.FromSeconds(30);
///
/// 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. Its second argument is the
/// caller's bound (the host skips the command once it has passed); the returned task may complete later than that — up to
/// past it — and that late answer rides the timeout outcome's
/// (#951).
/// 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;
Task? ask = null;
try
{
ask = askLocal(cmd, timeout);
outcome = await ask.WaitAsync(timeout).ConfigureAwait(false);
}
catch (Exception ex) when (ex is AskTimeoutException or TaskCanceledException or TimeoutException)
{
// #951: the caller stops waiting, but the host's answer is still collected — a refusal arriving now lets the
// node manager put the node back. Only for the caller's bound expiring (an ask that faulted in time has no
// later answer); an ask completing in the same instant is still handed over, already complete.
var late = ex is TimeoutException ? ask : null;
// The late ask usually ends in an AskTimeoutException nobody may observe: observe it here.
late?.ContinueWith(static t => _ = t.Exception, CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
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) { LateOutcome = late };
}
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;
}
}