using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Server;
using System.Runtime.CompilerServices;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
///
/// #937: a scripted condition's Part 9 method returns the scripted-alarm engine's verdict, not the Good a fire-and-forget
/// topic publish implied.
///
///
///
/// Two layers. (1) — a lock-free read of this node's engine load
/// outcome — refuses BadInvalidState inside the handler, before the SDK applies anything, while the last load
/// failed (the common case: the engine stays blind until the next good deploy). (2) Everything it lets through is
/// asked of THIS node's engine (, bounded): the handler, still under Lock,
/// only STARTS the ask (it sends; nothing blocks) and returns Good so the SDK applies its node state and the method
/// wrapper reports its one event exactly as before; the Call service (, or
/// for a remote gRPC-data call) settles the verdict once the SDK released
/// Lock: a refusal becomes BadInvalidState AND reverts the node to its pre-call state with one
/// corrective event (review r1 — subscribers and gRPC-data consumers had seen the change); no answer becomes
/// BadTimeout (OutcomeUnknown — the node keeps the change, which the engine may still apply).
///
///
/// Consistency with the peer. The host broadcasts the command to the redundant peer only AFTER the local engine
/// applied it (or did not answer). A refused command therefore reached no engine anywhere, which is what makes the
/// revert and the definite BadInvalidState true.
///
///
/// Load bound. At most asks are outstanding node-wide; past it the
/// call is refused BadTooManyOperations before the SDK applies anything. One Call's requests are settled one at
/// a time, and each request's bound starts when its ask is sent, so a batch never times out its own tail.
///
///
/// Status codes. Part 9 defines no result code for "the condition's state owner cannot act" (its method
/// tables cover a bad EventId, an already-acked/confirmed/shelved condition, a disabled condition and an out-of-range
/// shelving time). Part 4's Bad_InvalidState — "the operation cannot be completed because the object is
/// closed, uninitialized or in some other invalid state" — is the general code for exactly that, and is what this
/// server already returns for a native ack off-Primary.
///
///
public sealed partial class OtOpcUaNodeManager
{
/// How long a scripted condition method waits for the engine's verdict by default (5 s).
internal static readonly TimeSpan DefaultScriptedCommandTimeout = TimeSpan.FromSeconds(5);
/// The default node-wide cap on outstanding scripted-command asks.
internal const int DefaultMaxScriptedCommandsInFlight = 64;
private static readonly AsyncLocal PendingScriptedCommandSlot = new();
private int _scriptedCommandsInFlight;
///
/// #937 review r2 L1: a per-condition-instance mutation counter, bumped (under Lock) by every projection, every
/// reported condition event and every accepted method — the proof a pending revert needs that nothing changed the
/// node since its method. A field comparison missed changes that leave every compared field equal (a Timed→Timed
/// re-shelve, a ClientUserId change). Keyed by instance, so a torn-down condition takes its counter with it.
///
private readonly System.Runtime.CompilerServices.ConditionalWeakTable> _conditionMutations = new();
/// Counts one mutation of . Caller holds Lock.
private void BumpConditionMutation(AlarmConditionState condition) => _conditionMutations.GetOrCreateValue(condition).Value++;
/// The mutation count of . Caller holds Lock.
private long ConditionMutationOf(AlarmConditionState condition) => _conditionMutations.GetOrCreateValue(condition).Value;
///
/// #937 layer 1: returns why this node's scripted-alarm engine would reject any operator command right now (its last
/// load failed), or null to proceed. Called under Lock: MUST be a lock-free read, no I/O. Null ⇒ no pre-check.
///
public Func? ScriptedAlarmCommandPreflight { get; set; }
///
/// #937 layer 2: hands one command to THIS node's scripted-alarm engine and completes with its verdict (the host
/// broadcasts it to the redundant peer once the local engine applied it). Called under Lock: it MUST only send
/// and return the pending task, and the task must complete (the timeout argument is the caller's bound). Null ⇒ the
/// fire-and-forget and an unconditional Good, as before #937.
///
public Func>? AlarmCommandAsker { get; set; }
/// The longest a scripted condition method waits for the engine's verdict (also capped by the request deadline).
internal TimeSpan ScriptedCommandTimeout { get; set; } = DefaultScriptedCommandTimeout;
/// The node-wide cap on outstanding scripted-command asks (past it: BadTooManyOperations, nothing applied).
internal int MaxScriptedCommandsInFlight { get; set; } = DefaultMaxScriptedCommandsInFlight;
/// Outstanding scripted-command asks (test/diagnostic observation).
internal int ScriptedCommandsInFlight => Volatile.Read(ref _scriptedCommandsInFlight);
///
/// The verdict slot of ONE Call request (installed only around that request's synchronous SDK call).
/// is set the moment that call returns: an AsyncLocal value is captured by anything the SDK starts inside it (a
/// TimedShelve's timer), so a later callback must find the slot closed rather than park an ask nobody awaits.
///
private sealed class PendingScriptedCommand(TimeSpan timeout, ServiceResult? refusal = null)
{
public TimeSpan Timeout { get; } = timeout;
/// Set ⇒ a scripted method in this request is refused with it in the handler, unsent and unapplied
/// (review r2 M1: the request deadline is too close, or an earlier scripted method of the batch got no answer).
public ServiceResult? Refusal { get; } = refusal;
public Task? Outcome { get; set; }
public ScriptedMethodRevert? Revert { get; set; }
public volatile bool Closed;
}
///
/// What a scripted method changed on the node, captured by ReportAfterMethod: the pre-call state to put back if
/// the engine refuses, and the post-call state that proves nothing else has changed the node since.
///
private sealed record ScriptedMethodRevert(RealmKey Key, AlarmConditionState Alarm, AlarmConditionSnapshot Before,
ushort BeforeSeverity, LocalizedText? BeforeComment, string? BeforeClientUserId, long AfterMutation);
/// The slot of the request being called on this flow, when it is still open.
private static PendingScriptedCommand? OpenScriptedSlot() => PendingScriptedCommandSlot.Value is { Closed: false } slot ? slot : null;
///
/// From (under Lock): when the current Call awaits a verdict, reserve an
/// in-flight slot and start the ask. Null ⇒ not inside such a call (route fire-and-forget); a Bad result ⇒ refused
/// before anything was sent or applied.
///
private ServiceResult? TryStartScriptedCommandAsk(AlarmCommand cmd)
{
if (OpenScriptedSlot() is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return null;
if (pending.Refusal is { } refused) return refused;
if (Interlocked.Increment(ref _scriptedCommandsInFlight) > MaxScriptedCommandsInFlight)
{
Interlocked.Decrement(ref _scriptedCommandsInFlight);
return new ServiceResult(StatusCodes.BadTooManyOperations,
new LocalizedText("Too many scripted-alarm commands are in progress on this server; the command was not applied."));
}
Task outcome;
try
{
outcome = asker(cmd with { CommandId = Guid.NewGuid().ToString("N") }, pending.Timeout);
}
catch (Exception ex)
{
// The asker is contracted not to throw; one that does may still have sent the command.
outcome = Task.FromException(ex);
}
// The slot is held until the ask itself completes (the asker's own bound), not just until the caller stops waiting.
outcome.ContinueWith(static (_, state) => Interlocked.Decrement(ref ((OtOpcUaNodeManager)state!)._scriptedCommandsInFlight), this,
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
pending.Outcome = outcome;
return ServiceResult.Good;
}
///
/// From ReportAfterMethod, under Lock, before the SDK handler runs: the state a refusal would restore —
/// only while a verdict slot is open (nothing is captured on the fire-and-forget path).
///
private Func? BeginScriptedMethodCapture(AlarmConditionState alarm, RealmKey key)
{
if (OpenScriptedSlot() is null) return null;
var delta = ReadConditionDelta(alarm);
var before = new AlarmConditionSnapshot(delta.Active, delta.Acknowledged, delta.Confirmed, delta.Enabled, delta.Shelving,
delta.MappedSeverity, delta.Message, delta.Quality.Code,
delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null);
var comment = alarm.Comment?.Value;
var clientUserId = alarm.ClientUserId?.Value;
var severity = alarm.Severity?.Value ?? (ushort)0;
return () => new ScriptedMethodRevert(key, alarm, before, severity, comment, clientUserId, ConditionMutationOf(alarm));
}
/// From ReportAfterMethod, under Lock, after a Good method applied and reported: park the revert
/// with the ask the handler started for this request.
private static void CompleteScriptedMethodCapture(Func? capture)
{
if (capture is null || OpenScriptedSlot() is not { Outcome: not null, Revert: null } pending) return;
pending.Revert = capture();
}
///
/// Puts the node back to its pre-call state with one corrective event, under Lock — only when the node is still
/// the instance called AND still exactly as the method left it (anything that changed it since is newer truth and
/// wins). Mirrors the #760 native-ack revert.
///
private void RevertScriptedMethod(ScriptedMethodRevert revert)
{
lock (Lock)
{
if (!_alarmConditions.TryGetValue(revert.Key, out var live) || !ReferenceEquals(live, revert.Alarm)
|| ConditionMutationOf(live) != revert.AfterMutation)
{
_logger.LogInformation(
"OtOpcUaNodeManager: refused scripted command on {Condition} not reverted — the condition changed since the call",
revert.Key.Id);
return;
}
var now = UtcNow;
if (revert.Before.Shelving == AlarmShelvingKind.Timed && revert.Before.UnshelveAtUtc is { } unshelveAt)
_conditionUnshelveAt[revert.Key] = unshelveAt;
else _conditionUnshelveAt.Remove(revert.Key);
ApplyConditionState(live, revert.Before, now);
// The raw captured severity: ApplyConditionState clamps to 1..1000, which would turn a 0 into 1.
if (live.Severity is not null && live.Severity.Value != revert.BeforeSeverity) live.Severity.Value = revert.BeforeSeverity;
if (live.Comment is not null) live.Comment.Value = revert.BeforeComment ?? LocalizedText.Null;
if (live.ClientUserId is not null) live.ClientUserId.Value = revert.BeforeClientUserId ?? string.Empty;
ReportConditionEvent(live, now);
}
}
///
/// The bound for one local request: , cut by the request deadline (less a grace, so
/// the answer still lands inside the client's TimeoutHint). Null ⇒ the deadline leaves less than the dispatch floor:
/// a scripted method in this request must be refused unsent (review r2 M1 — it used to be floored and sent anyway).
///
private TimeSpan? ScriptedCommandBound(DateTime deadline)
{
var bound = ScriptedCommandTimeout;
if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue)
{
var byDeadline = deadline - DateTime.UtcNow - ImportedMethodGrace;
if (byDeadline < bound) bound = byDeadline;
}
return bound < ImportedMethodMinimumDispatchBudget ? null : bound;
}
///
/// Runs the SDK's synchronous base.Call for ONE request with a verdict slot installed, and returns the slot when
/// the handler parked an ask in it (null when it routed nothing: a refusal, a native or non-condition method, or no
/// asker wired).
///
private PendingScriptedCommand? CallOneAwaitingVerdict(OperationContext context, ArrayOf methodsToCall, int index,
IList results, IList errors, TimeSpan bound, ServiceResult? refusal)
{
var request = methodsToCall[index];
var singleResults = new List { results[index] };
var singleErrors = new List { errors[index] };
var pending = new PendingScriptedCommand(bound, refusal);
PendingScriptedCommandSlot.Value = pending;
try
{
base.Call(context, (ArrayOf)new[] { request }, singleResults, singleErrors);
}
finally
{
pending.Closed = true;
PendingScriptedCommandSlot.Value = null;
}
if (!request.Processed) return null; // not this manager's node: left for the next manager, untouched
results[index] = singleResults[0];
errors[index] = singleErrors[0];
return pending.Outcome is not null && ServiceResult.IsGood(singleErrors[0]) ? pending : null;
}
/// The request's final status from its engine verdict (and whether it is an OutcomeUnknown), reverting the node
/// on a refusal. Never throws.
private async Task<(ServiceResult Status, bool Unknown)> SettleScriptedVerdictAsync(PendingScriptedCommand pending, TimeSpan bound)
{
var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome!, bound).ConfigureAwait(false);
if (!ServiceResult.IsGood(status) && !unknown && pending.Revert is { } revert)
{
try
{
RevertScriptedMethod(revert);
}
catch (Exception ex)
{
_logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused scripted command failed");
}
}
return (status, unknown);
}
///
/// The method's final status from the engine's verdict, and whether it is an OutcomeUnknown (the command may still
/// apply). Never throws. The asker answers its own timeout as an
/// outcome; the wait here (its bound plus a grace) is the backstop for one that never completes.
///
private async Task<(ServiceResult Status, bool Unknown)> AwaitScriptedVerdictAsync(Task pending, TimeSpan bound)
{
AlarmCommandOutcome outcome;
try
{
outcome = await pending.WaitAsync(bound + ImportedMethodGrace).ConfigureAwait(false);
}
catch (Exception ex) when (ex is TimeoutException or OperationCanceledException)
{
return (ScriptedUnknown(StatusCodes.BadTimeout,
$"OutcomeUnknown: the scripted-alarm engine did not answer within {bound.TotalSeconds:0.#} s; the command may still apply."), true);
}
catch (Exception ex)
{
// The command was (or may have been) sent: unknown, never "refused".
return (ScriptedUnknown(StatusCodes.BadInternalError, "OutcomeUnknown: " + ex.GetType().Name), true);
}
return outcome.Verdict switch
{
AlarmCommandVerdict.Applied => (ServiceResult.Good, false),
AlarmCommandVerdict.NotApplied => (new ServiceResult(StatusCodes.BadInvalidState,
new LocalizedText(outcome.Reason ?? "The scripted-alarm engine did not apply the command.")), false),
_ => (ScriptedUnknown(outcome.TimedOut ? StatusCodes.BadTimeout : StatusCodes.BadInternalError,
outcome.Reason ?? "OutcomeUnknown: the scripted-alarm engine could not confirm the command."), true),
};
}
private ServiceResult ScriptedUnknown(StatusCode status, string diagnostic)
{
_logger.LogWarning("OtOpcUaNodeManager: scripted condition method outcome unknown ({Status}): {Diagnostic}", status, diagnostic);
return new ServiceResult(status, new LocalizedText(diagnostic));
}
///
/// #937: plus the scripted engine's verdict (A2b remote calls). The node-manager
/// part runs under Lock exactly as before; the verdict is settled (a refusal reverts the node) after it is
/// released, within (capped at , never extended past it).
///
/// The call.
/// The caller's remaining budget.
/// The verdict: Applied only once the engine applied it; a refusal after dispatch carries
/// ; no answer carries .
public async Task ExecuteConditionMethodAsync(OriginConditionMethodCall call, TimeSpan budget)
{
// Review r1 L10: a budget too short to dispatch in is refused unsent — never stretched past what the caller allows.
if (budget < ImportedMethodMinimumDispatchBudget)
return new OriginConditionMethodOutcome(false, false, StatusCodes.BadTimeout.Code, "Budget below the dispatch floor; nothing was sent.");
var bound = budget < ScriptedCommandTimeout ? budget : ScriptedCommandTimeout;
var pending = new PendingScriptedCommand(bound);
PendingScriptedCommandSlot.Value = pending;
OriginConditionMethodOutcome decided;
try
{
decided = TryExecuteConditionMethod(call);
}
finally
{
pending.Closed = true;
PendingScriptedCommandSlot.Value = null;
}
if (!decided.Applied || pending.Outcome is null) return decided;
var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome, bound).ConfigureAwait(false);
if (ServiceResult.IsGood(status)) return decided;
if (!unknown && pending.Revert is { } revert)
{
try { RevertScriptedMethod(revert); }
catch (Exception ex) { _logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused remote scripted command failed"); }
}
var text = status.LocalizedText.IsNullOrEmpty ? null : status.LocalizedText.Text;
return new OriginConditionMethodOutcome(false, decided.Native, status.StatusCode.Code, text, Dispatched: true, Unknown: unknown);
}
}