6004a5a565
1. A post-dispatch refusal now puts the node back to its captured pre-call state with one corrective event (skipped when the node changed since) — the SDK had already applied and reported the change. Blank scripted AddComment is refused in the handler before the SDK runs. 2. ScriptedAlarmCommandDispatch: ask the local engine first, broadcast to the peer only on Applied/OutcomeUnknown — a refusal now reached no engine anywhere. 3. ApplyAsync no longer checks 'loaded' before _evalGate: a command racing the first load queues behind it; never loaded => refusal (nothing applied). 4. One Call's requests are settled sequentially (no request runs against a node state the engine refused); <= 64 asks in flight node-wide, else BadTooManyOperations before anything applies; per-request bound starts at send. Measured 300 acks through one host + LocalDb: 59 ms sequential, max 24 ms/ask with 64 outstanding. 5. Mixed-batch wire test (scripted refused + native + imported + scripted applied + core-manager method): per-item status in order, one scripted ask at a time. L6: readiness from the engine's HasCompleteGeneration on a load fault. L7: the verdict slot is closed when its SDK call returns (timer-captured AsyncLocal can no longer park an ask). L10: remote budget never stretched. Co-Authored-By: Claude <noreply@anthropic.com>
328 lines
19 KiB
C#
328 lines
19 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Server;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
|
|
/// <summary>
|
|
/// #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.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// <b>Two layers.</b> (1) <see cref="ScriptedAlarmCommandPreflight"/> — a lock-free read of this node's engine load
|
|
/// outcome — refuses <c>BadInvalidState</c> 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 (<see cref="AlarmCommandAsker"/>, bounded): the handler, still under <c>Lock</c>,
|
|
/// 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 (<see cref="CallAsync"/>, or
|
|
/// <see cref="ExecuteConditionMethodAsync"/> for a remote gRPC-data call) settles the verdict once the SDK released
|
|
/// <c>Lock</c>: a refusal becomes <c>BadInvalidState</c> 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
|
|
/// <c>BadTimeout</c> (OutcomeUnknown — the node keeps the change, which the engine may still apply).
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>Consistency with the peer.</b> 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 <c>BadInvalidState</c> true.
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>Load bound.</b> At most <see cref="MaxScriptedCommandsInFlight"/> asks are outstanding node-wide; past it the
|
|
/// call is refused <c>BadTooManyOperations</c> 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.
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>Status codes.</b> 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 <c>Bad_InvalidState</c> — "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.
|
|
/// </para>
|
|
/// </remarks>
|
|
public sealed partial class OtOpcUaNodeManager
|
|
{
|
|
/// <summary>How long a scripted condition method waits for the engine's verdict by default (5 s).</summary>
|
|
internal static readonly TimeSpan DefaultScriptedCommandTimeout = TimeSpan.FromSeconds(5);
|
|
|
|
/// <summary>The default node-wide cap on outstanding scripted-command asks.</summary>
|
|
internal const int DefaultMaxScriptedCommandsInFlight = 64;
|
|
|
|
/// <summary>The shortest bound a local call is given (the request deadline can be closer than this; the SDK then answers
|
|
/// the client's timeout itself).</summary>
|
|
private static readonly TimeSpan MinimumScriptedCommandBound = TimeSpan.FromMilliseconds(50);
|
|
|
|
private static readonly AsyncLocal<PendingScriptedCommand?> PendingScriptedCommandSlot = new();
|
|
|
|
private int _scriptedCommandsInFlight;
|
|
|
|
/// <summary>
|
|
/// #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 <c>Lock</c>: MUST be a lock-free read, no I/O. Null ⇒ no pre-check.
|
|
/// </summary>
|
|
public Func<string?>? ScriptedAlarmCommandPreflight { get; set; }
|
|
|
|
/// <summary>
|
|
/// #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 <c>Lock</c>: 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 <see cref="AlarmCommandRouter"/> and an unconditional Good, as before #937.
|
|
/// </summary>
|
|
public Func<AlarmCommand, TimeSpan, Task<AlarmCommandOutcome>>? AlarmCommandAsker { get; set; }
|
|
|
|
/// <summary>The longest a scripted condition method waits for the engine's verdict (also capped by the request deadline).</summary>
|
|
internal TimeSpan ScriptedCommandTimeout { get; set; } = DefaultScriptedCommandTimeout;
|
|
|
|
/// <summary>The node-wide cap on outstanding scripted-command asks (past it: <c>BadTooManyOperations</c>, nothing applied).</summary>
|
|
internal int MaxScriptedCommandsInFlight { get; set; } = DefaultMaxScriptedCommandsInFlight;
|
|
|
|
/// <summary>Outstanding scripted-command asks (test/diagnostic observation).</summary>
|
|
internal int ScriptedCommandsInFlight => Volatile.Read(ref _scriptedCommandsInFlight);
|
|
|
|
/// <summary>
|
|
/// The verdict slot of ONE Call request (installed only around that request's synchronous SDK call). <see cref="Closed"/>
|
|
/// is set the moment that call returns: an <c>AsyncLocal</c> 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.
|
|
/// </summary>
|
|
private sealed class PendingScriptedCommand(TimeSpan timeout)
|
|
{
|
|
public TimeSpan Timeout { get; } = timeout;
|
|
public Task<AlarmCommandOutcome>? Outcome { get; set; }
|
|
public ScriptedMethodRevert? Revert { get; set; }
|
|
public volatile bool Closed;
|
|
}
|
|
|
|
/// <summary>
|
|
/// What a scripted method changed on the node, captured by <c>ReportAfterMethod</c>: 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.
|
|
/// </summary>
|
|
private sealed record ScriptedMethodRevert(RealmKey Key, AlarmConditionState Alarm, AlarmConditionSnapshot Before,
|
|
LocalizedText? BeforeComment, string? BeforeClientUserId, AlarmConditionDelta After, LocalizedText? AfterComment);
|
|
|
|
/// <summary>The slot of the request being called on this flow, when it is still open.</summary>
|
|
private static PendingScriptedCommand? OpenScriptedSlot() => PendingScriptedCommandSlot.Value is { Closed: false } slot ? slot : null;
|
|
|
|
/// <summary>
|
|
/// From <see cref="HandleAlarmCommand"/> (under <c>Lock</c>): 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.
|
|
/// </summary>
|
|
private ServiceResult? TryStartScriptedCommandAsk(AlarmCommand cmd)
|
|
{
|
|
if (OpenScriptedSlot() is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return null;
|
|
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<AlarmCommandOutcome> 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<AlarmCommandOutcome>(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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// From <c>ReportAfterMethod</c>, under <c>Lock</c>, 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).
|
|
/// </summary>
|
|
private Func<ScriptedMethodRevert>? 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;
|
|
return () => new ScriptedMethodRevert(key, alarm, before, comment, clientUserId, ReadConditionDelta(alarm), alarm.Comment?.Value);
|
|
}
|
|
|
|
/// <summary>From <c>ReportAfterMethod</c>, under <c>Lock</c>, after a Good method applied and reported: park the revert
|
|
/// with the ask the handler started for this request.</summary>
|
|
private static void CompleteScriptedMethodCapture(Func<ScriptedMethodRevert>? capture)
|
|
{
|
|
if (capture is null || OpenScriptedSlot() is not { Outcome: not null, Revert: null } pending) return;
|
|
pending.Revert = capture();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Puts the node back to its pre-call state with one corrective event, under <c>Lock</c> — 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.
|
|
/// </summary>
|
|
private void RevertScriptedMethod(ScriptedMethodRevert revert)
|
|
{
|
|
lock (Lock)
|
|
{
|
|
if (!_alarmConditions.TryGetValue(revert.Key, out var live) || !ReferenceEquals(live, revert.Alarm)
|
|
|| ReadConditionDelta(live) != revert.After || !Equals(live.Comment?.Value, revert.AfterComment))
|
|
{
|
|
_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);
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>The bound for one local request: <see cref="ScriptedCommandTimeout"/>, cut by the request deadline (less a
|
|
/// grace, so the answer still lands inside the client's TimeoutHint).</summary>
|
|
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 < MinimumScriptedCommandBound ? MinimumScriptedCommandBound : bound;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Runs the SDK's synchronous <c>base.Call</c> 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).
|
|
/// </summary>
|
|
private PendingScriptedCommand? CallOneAwaitingVerdict(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall, int index,
|
|
IList<CallMethodResult> results, IList<ServiceResult> errors, TimeSpan bound)
|
|
{
|
|
var request = methodsToCall[index];
|
|
var singleResults = new List<CallMethodResult> { results[index] };
|
|
var singleErrors = new List<ServiceResult> { errors[index] };
|
|
var pending = new PendingScriptedCommand(bound);
|
|
PendingScriptedCommandSlot.Value = pending;
|
|
try
|
|
{
|
|
base.Call(context, (ArrayOf<CallMethodRequest>)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;
|
|
}
|
|
|
|
/// <summary>The request's final status from its engine verdict, reverting the node on a refusal. Never throws.</summary>
|
|
private async Task<ServiceResult> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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 <see cref="AlarmCommandVerdict.OutcomeUnknown"/>
|
|
/// outcome; the wait here (its bound plus a grace) is the backstop for one that never completes.
|
|
/// </summary>
|
|
private async Task<(ServiceResult Status, bool Unknown)> AwaitScriptedVerdictAsync(Task<AlarmCommandOutcome> 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));
|
|
}
|
|
|
|
/// <summary>
|
|
/// #937: <see cref="TryExecuteConditionMethod"/> plus the scripted engine's verdict (A2b remote calls). The node-manager
|
|
/// part runs under <c>Lock</c> exactly as before; the verdict is settled (a refusal reverts the node) after it is
|
|
/// released, within <paramref name="budget"/> (capped at <see cref="ScriptedCommandTimeout"/>, never extended past it).
|
|
/// </summary>
|
|
/// <param name="call">The call.</param>
|
|
/// <param name="budget">The caller's remaining budget.</param>
|
|
/// <returns>The verdict: Applied only once the engine applied it; a refusal after dispatch carries
|
|
/// <see cref="OriginConditionMethodOutcome.Dispatched"/>; no answer carries <see cref="OriginConditionMethodOutcome.Unknown"/>.</returns>
|
|
public async Task<OriginConditionMethodOutcome> 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);
|
|
}
|
|
}
|