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:
@@ -604,54 +604,20 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #937: the node manager's <see cref="OtOpcUaNodeManager.AlarmCommandAsker"/>. Broadcasts the command on the
|
||||
/// <c>alarm-commands</c> topic (the redundant peer applies it, as before) and asks THIS node's scripted-alarm host,
|
||||
/// through the <c>DriverHostActor</c>, for its verdict; the command carries a fresh <c>CommandId</c>, so the local
|
||||
/// host applies whichever copy reaches it first and only once. Runs under the SDK's Lock: it only sends. Never
|
||||
/// faults — no answer inside <paramref name="timeout"/> is an OutcomeUnknown outcome.
|
||||
/// #937: the node manager's <see cref="OtOpcUaNodeManager.AlarmCommandAsker"/> — see
|
||||
/// <see cref="ScriptedAlarmCommandDispatch.AskThenBroadcastAsync"/>. Runs under the SDK's Lock: it only sends.
|
||||
/// </summary>
|
||||
/// <param name="cmd">The command (with its <c>CommandId</c>).</param>
|
||||
/// <param name="timeout">The caller's bound.</param>
|
||||
/// <returns>The verdict.</returns>
|
||||
private Task<AlarmCommandOutcome> AskScriptedAlarmCommand(AlarmCommand cmd, TimeSpan timeout)
|
||||
{
|
||||
try
|
||||
{
|
||||
DistributedPubSub.Get(_actorSystemAccessor()).Mediator.Tell(new Publish(ScriptedAlarmHostActor.AlarmCommandsTopic, cmd));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// The peer's copy only; the local ask below still decides this caller's answer.
|
||||
_logger.LogWarning(ex, "OtOpcUaServerHostedService: failed to broadcast inbound alarm command {Operation} for {AlarmId}",
|
||||
cmd.Operation, cmd.AlarmId);
|
||||
}
|
||||
|
||||
if (!_actorRegistry.TryGet<DriverHostActorKey>(out var driverHost))
|
||||
{
|
||||
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
|
||||
"This server runs no scripted-alarm engine; the command was not applied."));
|
||||
}
|
||||
|
||||
return AskAsync(driverHost, cmd, timeout);
|
||||
|
||||
static async Task<AlarmCommandOutcome> AskAsync(IActorRef host, AlarmCommand cmd, TimeSpan timeout)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await host.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd), timeout).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is AskTimeoutException or TaskCanceledException or TimeoutException)
|
||||
{
|
||||
return 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)
|
||||
{
|
||||
return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
|
||||
"OutcomeUnknown: " + ex.GetType().Name);
|
||||
}
|
||||
}
|
||||
Func<AlarmCommand, TimeSpan, Task<AlarmCommandOutcome>>? askLocal = _actorRegistry.TryGet<DriverHostActorKey>(out var driverHost)
|
||||
? (c, t) => driverHost.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c), t)
|
||||
: null;
|
||||
return ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(cmd, timeout, askLocal,
|
||||
c => DistributedPubSub.Get(_actorSystemAccessor()).Mediator.Tell(new Publish(ScriptedAlarmHostActor.AlarmCommandsTopic, c)),
|
||||
_logger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
using Akka.Actor;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
|
||||
|
||||
/// <summary>
|
||||
/// #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).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Why the peer goes second (review r1).</b> 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
|
||||
/// <c>BadInvalidState</c>. 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).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// No local engine (no driver host, or it runs no scripted-alarm host) ⇒ <see cref="AlarmCommandVerdict.NotApplied"/>
|
||||
/// and nothing is broadcast: this node's condition node is driven by no engine, and a command for it is refused.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class ScriptedAlarmCommandDispatch
|
||||
{
|
||||
/// <summary>
|
||||
/// Asks the local engine, then broadcasts unless it refused. Starts the ask synchronously (safe under the SDK's Lock);
|
||||
/// never faults — no answer within <paramref name="timeout"/> is an OutcomeUnknown outcome.
|
||||
/// </summary>
|
||||
/// <param name="cmd">The command (with its <c>CommandId</c>, which de-duplicates the broadcast copy on the local host).</param>
|
||||
/// <param name="timeout">The caller's bound.</param>
|
||||
/// <param name="askLocal">The ask to this node's scripted-alarm host; null ⇒ none on this node.</param>
|
||||
/// <param name="broadcast">Publishes the command on the <c>alarm-commands</c> topic.</param>
|
||||
/// <param name="logger">Logger.</param>
|
||||
/// <returns>The local verdict.</returns>
|
||||
internal static async Task<AlarmCommandOutcome> AskThenBroadcastAsync(AlarmCommand cmd, TimeSpan timeout,
|
||||
Func<AlarmCommand, TimeSpan, Task<AlarmCommandOutcome>>? askLocal, Action<AlarmCommand> 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;
|
||||
}
|
||||
}
|
||||
@@ -138,8 +138,10 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
|
||||
/// The local (non-imported) requests. Without an <see cref="AlarmCommandAsker"/> this is the unchanged batch
|
||||
/// <c>base.Call</c>. With one (#937), each request runs through <c>base.Call</c> alone — in batch order, each fully
|
||||
/// applied by the SDK under its own <c>Lock</c> hold — so a scripted condition method's handler can park the ask it
|
||||
/// starts against that request; the parked asks are then awaited together, with no <c>Lock</c> held, and each
|
||||
/// request's status becomes its engine's verdict. Never throws past the SDK's own behaviour (the waits are guarded).
|
||||
/// starts against that request; the ask is then settled with no <c>Lock</c> held (its verdict becomes the request's
|
||||
/// status; a refusal reverts the node) before the next request runs. SDK 2.0.1's <c>StandardServer.CallAsync</c>
|
||||
/// awaits <c>MasterNodeManager.CallAsync</c> (no request thread is held while this waits). Never throws past the
|
||||
/// SDK's own behaviour (the waits are guarded).
|
||||
/// </summary>
|
||||
private async Task CallLocalAsync(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall, IList<CallMethodResult> results,
|
||||
IList<ServiceResult> errors)
|
||||
@@ -150,21 +152,16 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
|
||||
return;
|
||||
}
|
||||
|
||||
var bound = ScriptedCommandBound(context.OperationDeadline);
|
||||
List<(int Index, Task<(ServiceResult Status, bool Unknown)> Verdict)>? verdicts = null;
|
||||
// #937 review r1: one request at a time, each verdict (and any revert) settled before the next request runs, so a
|
||||
// later request in the batch (e.g. Confirm after a refused Acknowledge) never runs against a node state the engine
|
||||
// refused. The bound is taken per request, when its ask is sent.
|
||||
for (var i = 0; i < methodsToCall.Count; i++)
|
||||
{
|
||||
if (methodsToCall[i] is not { Processed: false }) continue;
|
||||
if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound) is { } pending)
|
||||
(verdicts ??= []).Add((i, AwaitScriptedVerdictAsync(pending, bound)));
|
||||
}
|
||||
if (verdicts is null) return;
|
||||
// Each verdict task is guarded (never faults), so WhenAll never throws.
|
||||
await Task.WhenAll(verdicts.Select(v => v.Verdict)).ConfigureAwait(false);
|
||||
foreach (var (index, verdict) in verdicts)
|
||||
{
|
||||
var status = verdict.Result.Status;
|
||||
if (!ServiceResult.IsGood(status)) errors[index] = status;
|
||||
var bound = ScriptedCommandBound(context.OperationDeadline);
|
||||
if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound) is not { } pending) continue;
|
||||
var status = await SettleScriptedVerdictAsync(pending, bound).ConfigureAwait(false);
|
||||
if (!ServiceResult.IsGood(status)) errors[i] = status;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+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);
|
||||
}
|
||||
|
||||
@@ -3089,6 +3089,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
{
|
||||
var before = ReadConditionDelta(alarm);
|
||||
var retainBefore = alarm.Retain!.Value;
|
||||
// #937: inside a verdict-awaiting Call, remember what a refusal must put back.
|
||||
var revertCapture = BeginScriptedMethodCapture(alarm, conditionKey);
|
||||
|
||||
var result = sdkHandler();
|
||||
// A rebuild may have discarded this instance mid-call; its replacement is not what was called.
|
||||
@@ -3120,6 +3122,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
if (alwaysReport || ReadConditionDelta(alarm) != before)
|
||||
ReportConditionEvent(alarm, UtcNow);
|
||||
|
||||
CompleteScriptedMethodCapture(revertCapture);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -3220,6 +3223,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
if (scriptedEngine && ScriptedAlarmCommandPreflight?.Invoke() is { } notReady)
|
||||
return new ServiceResult(StatusCodes.BadInvalidState, new LocalizedText(notReady));
|
||||
|
||||
// #937 review r1: a scripted comment the engine would refuse (blank text) is refused here, before the SDK writes it.
|
||||
if (scriptedEngine && operation == "AddComment" && string.IsNullOrWhiteSpace(comment?.Text))
|
||||
return new ServiceResult(StatusCodes.BadInvalidArgument, new LocalizedText("AddComment requires comment text."));
|
||||
|
||||
var cmd = new AlarmCommand(
|
||||
AlarmId: condition.NodeId.IdentifierAsString,
|
||||
Operation: operation,
|
||||
@@ -3229,7 +3236,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
|
||||
// #937: inside a Call that awaits the engine's verdict (CallAsync / ExecuteConditionMethodAsync), start the
|
||||
// bounded ask — non-blocking: it only sends — and let the caller await it once Lock is released.
|
||||
if (scriptedEngine && TryStartScriptedCommandAsk(cmd)) return ServiceResult.Good;
|
||||
if (scriptedEngine && TryStartScriptedCommandAsk(cmd) is { } started) return started;
|
||||
|
||||
// Non-blocking by contract (host wires a fire-and-forget mediator.Tell); safe to call under Lock.
|
||||
AlarmCommandRouter?.Invoke(cmd);
|
||||
|
||||
@@ -436,9 +436,10 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
|
||||
|
||||
private void OnLoadFailed(Status.Failure msg)
|
||||
{
|
||||
// #937: loads serialize on the engine's gate, so completions arrive in start order — this is the latest
|
||||
// completed load, and the engine now holds no complete generation (it rejects every operator command).
|
||||
_readiness?.SetLoadOutcome(loaded: false);
|
||||
// #937: loads serialize on the engine's gate, so completions arrive in start order — this is the latest completed
|
||||
// load. Publish what the ENGINE says rather than infer it from the fault (review r1 L6): a load can fault after it
|
||||
// completed its generation (e.g. subscribing), and then the engine still accepts commands.
|
||||
_readiness?.SetLoadOutcome(loaded: _engine.HasCompleteGeneration);
|
||||
_log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded; operator commands are refused until the next successful deploy");
|
||||
}
|
||||
|
||||
@@ -830,6 +831,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
|
||||
replyTo.Tell(outcome);
|
||||
}
|
||||
|
||||
private const string NotYetLoadedRefusal =
|
||||
"This server's scripted-alarm engine has not completed loading its configuration yet; the command was not applied.";
|
||||
|
||||
private const string NotLoadedRefusal =
|
||||
"The alarm is not loaded by this server's scripted-alarm engine; the command was not applied.";
|
||||
|
||||
@@ -924,7 +928,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
|
||||
// redundant peer's copy) has only this Warning. The next successful deploy re-asserts the node from the store.
|
||||
_log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} NOT applied — {Reason}",
|
||||
cmd.Operation, cmd.AlarmId, ex.Message);
|
||||
return Refused(ScriptedAlarmCommandReadinessView.LoadFailedRefusal);
|
||||
// Before the first load completes there is no failure to name (the readiness view is clear then).
|
||||
return Refused(_readiness?.Refusal() ?? (_loadedGeneration == 0 && _readiness is not null ? NotYetLoadedRefusal
|
||||
: ScriptedAlarmCommandReadinessView.LoadFailedRefusal));
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user