fix(alarms): #937 review r1 — revert a refused scripted method, broadcast to the peer only after the local verdict, settle a batch per request, in-flight cap
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>
This commit is contained in:
+164
-33
@@ -17,22 +17,27 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
/// 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) awaits the verdict once the SDK released
|
||||
/// <c>Lock</c>, and turns a refusal into <c>BadInvalidState</c> and no answer into <c>BadTimeout</c> (OutcomeUnknown).
|
||||
/// <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. A timeout is <c>Bad_Timeout</c> with "OutcomeUnknown" in the
|
||||
/// diagnostic, as the remote-condition path does: the command may still apply (the engine's own bound is longer),
|
||||
/// so it is never reported as refused.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Residual (documented).</b> In layer 2 the SDK has already applied and reported the node change when a refusal
|
||||
/// arrives (a load that was in flight when the command queued behind it, and then failed). The node keeps that state
|
||||
/// until the next successful deploy re-asserts every scripted condition from the store; the caller gets Bad.
|
||||
/// server already returns for a native ack off-Primary.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed partial class OtOpcUaNodeManager
|
||||
@@ -40,8 +45,17 @@ 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.
|
||||
@@ -49,43 +63,132 @@ public sealed partial class OtOpcUaNodeManager
|
||||
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 also
|
||||
/// broadcasts it to the redundant peer, as <see cref="AlarmCommandRouter"/> does). Called under <c>Lock</c>: it MUST
|
||||
/// only send and return the pending task. The timeout argument is the caller's bound. Null ⇒ the fire-and-forget
|
||||
/// <see cref="AlarmCommandRouter"/> and an unconditional Good, as before #937.
|
||||
/// #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 verdict slot one Call request's handler fills (one per request; flows into the synchronous SDK call).</summary>
|
||||
/// <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>
|
||||
/// From <see cref="HandleAlarmCommand"/> (under <c>Lock</c>): when the current Call awaits a verdict, start the ask
|
||||
/// and park its task. False ⇒ not inside such a call (route fire-and-forget).
|
||||
/// 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 bool TryStartScriptedCommandAsk(AlarmCommand cmd)
|
||||
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 (PendingScriptedCommandSlot.Value is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return false;
|
||||
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
|
||||
{
|
||||
pending.Outcome = asker(cmd with { CommandId = Guid.NewGuid().ToString("N") }, pending.Timeout);
|
||||
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.
|
||||
pending.Outcome = Task.FromException<AlarmCommandOutcome>(ex);
|
||||
outcome = Task.FromException<AlarmCommandOutcome>(ex);
|
||||
}
|
||||
return true;
|
||||
// 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>The bound for one request: <see cref="ScriptedCommandTimeout"/>, cut by the request deadline (less a grace).</summary>
|
||||
/// <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;
|
||||
@@ -94,14 +197,15 @@ public sealed partial class OtOpcUaNodeManager
|
||||
var byDeadline = deadline - DateTime.UtcNow - ImportedMethodGrace;
|
||||
if (byDeadline < bound) bound = byDeadline;
|
||||
}
|
||||
return bound < ImportedMethodMinimumDispatchBudget ? ImportedMethodMinimumDispatchBudget : bound;
|
||||
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 parked
|
||||
/// ask (null when the handler routed nothing: a refusal, a native or non-condition method, or no asker wired).
|
||||
/// 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 Task<AlarmCommandOutcome>? CallOneAwaitingVerdict(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall, int index,
|
||||
private PendingScriptedCommand? CallOneAwaitingVerdict(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall, int index,
|
||||
IList<CallMethodResult> results, IList<ServiceResult> errors, TimeSpan bound)
|
||||
{
|
||||
var request = methodsToCall[index];
|
||||
@@ -115,12 +219,31 @@ public sealed partial class OtOpcUaNodeManager
|
||||
}
|
||||
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 ServiceResult.IsGood(singleErrors[0]) ? pending.Outcome : null;
|
||||
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>
|
||||
@@ -164,8 +287,8 @@ public sealed partial class OtOpcUaNodeManager
|
||||
|
||||
/// <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 awaited after it is released, bounded by
|
||||
/// <paramref name="budget"/> (capped at <see cref="ScriptedCommandTimeout"/>).
|
||||
/// 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>
|
||||
@@ -173,8 +296,10 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// <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;
|
||||
if (bound < ImportedMethodMinimumDispatchBudget) bound = ImportedMethodMinimumDispatchBudget;
|
||||
var pending = new PendingScriptedCommand(bound);
|
||||
PendingScriptedCommandSlot.Value = pending;
|
||||
OriginConditionMethodOutcome decided;
|
||||
@@ -184,12 +309,18 @@ public sealed partial class OtOpcUaNodeManager
|
||||
}
|
||||
finally
|
||||
{
|
||||
pending.Closed = true;
|
||||
PendingScriptedCommandSlot.Value = null;
|
||||
}
|
||||
if (!decided.Applied || pending.Outcome is not { } outcome) return decided;
|
||||
if (!decided.Applied || pending.Outcome is null) return decided;
|
||||
|
||||
var (status, unknown) = await AwaitScriptedVerdictAsync(outcome, bound).ConfigureAwait(false);
|
||||
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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user