Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionMethods.cs
T
Joseph Doherty d6f2a1b5e2 fix(alarms): a scripted condition's Part 9 method returns the engine's verdict (#937)
Before: the alarm-commands topic is fire-and-forget, so an OPC UA method (and a
remote gRPC-data condition method) returned Good even when the engine rejected
the command because its last load failed.

- ScriptedAlarmCommandReadinessView: the host's latest load outcome; the node
  manager's handler refuses BadInvalidState before the SDK applies anything
  while the last load failed (lock-free read).
- Bounded ask: inside CallAsync (off Lock) each local request runs base.Call
  alone; the handler only STARTS AlarmCommandAsker (broadcast for the peer +
  DriverHostActor -> ScriptedAlarmHostActor.ExecuteAlarmCommand on the local
  engine, CommandId-deduplicated) and the Call awaits the verdict: refused =>
  BadInvalidState, no answer => BadTimeout OutcomeUnknown.
- Remote CallConditionMethod: ExecuteConditionMethodAsync => DriverConfirmedFailure
  / OutcomeUnknown on the origin.
- Host ownership uses the latest plan set (stable across a load in flight and a
  failed load's half-built set).
- Docs: ScriptedAlarms.md (verdicts, residual, duplicate-activation trade-off),
  DataConnections.md, rules/alarms.md. Live leg scenario F937 + seeder
  scripted_predicate mutation.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-28 09:40:35 -05:00

158 lines
9.6 KiB
C#

using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// A2b: one session-less condition method call from a data-connection peer (plan §5.6 "Origin"). Already authorized by
/// the caller (the Runtime facade checks the export grant and the origin ACL on the PLACEMENT's subject for the service
/// principal); the node manager applies the redundancy, standby, native preflight and activation-marker checks.
/// </summary>
/// <param name="Realm">The condition's realm key (Raw for a native condition, Uns for a scripted one).</param>
/// <param name="ConditionId">The condition id (RawPath / ScriptedAlarmId). Origin-internal; never from the wire.</param>
/// <param name="Method">The Part 9 method name: <c>Acknowledge</c>, <c>AddComment</c> or <c>Confirm</c>.</param>
/// <param name="Comment">The Part 9 comment, or null.</param>
/// <param name="ExpectedActivation">The marker the caller last applied; a different current marker ⇒ <c>BadEventIdUnknown</c>.</param>
/// <param name="Principal">The service principal (recorded as the command's <c>User</c> and the condition's <c>ClientUserId</c>).</param>
/// <param name="ApiKeyId">The service key's public id (the Galaxy ack identity lookup key, §6).</param>
public sealed record OriginConditionMethodCall(AddressSpaceRealm Realm, string ConditionId, string Method, string? Comment,
ConditionActivationMarker ExpectedActivation, string Principal, string? ApiKeyId);
/// <summary>The node manager's verdict on an <see cref="OriginConditionMethodCall"/>.</summary>
/// <param name="Applied">True when the node state changed (or a native ack was accepted and routed); false = refused
/// before ANY state change, nothing routed or reported.</param>
/// <param name="Native">Whether the condition is native (driver-fed): an applied native call is accepted, not confirmed.</param>
/// <param name="StatusCode">The OPC UA status (Good when applied).</param>
/// <param name="Diagnostic">A refusal's reason text, when the gate gave one.</param>
/// <param name="Dispatched">#937: <see cref="Applied"/> is false, but the call reached the scripted-alarm engine — which refused
/// it, or did not answer (<see cref="Unknown"/>). The node manager had already applied its node state.</param>
/// <param name="Unknown">#937: the engine did not answer inside the budget (or failed): the command may still apply.</param>
public sealed record OriginConditionMethodOutcome(bool Applied, bool Native, uint StatusCode, string? Diagnostic,
bool Dispatched = false, bool Unknown = false);
public sealed partial class OtOpcUaNodeManager
{
/// <summary>
/// A2b (§5.6 Origin): executes one remote condition method through the SAME wrapped SDK method handler a local
/// client's call runs (<c>WireMethodTransitionReporting</c> → SDK handler → <see cref="HandleNativeAlarmAck"/> /
/// <see cref="HandleAlarmCommand"/>), so neither path goes around the other: one condition event, the native
/// Confirmed/Retain re-assert, the non-blocking <see cref="NativeAlarmAckRouter"/> /
/// <see cref="AlarmCommandRouter"/> (an unchanged <c>AlarmCommand</c>) and the #760 revert contract all hold.
/// </summary>
/// <remarks>
/// Runs entirely under <c>Lock</c> and never waits under it (the routers are fire-and-forget). Check order, each
/// refusing before any state change: the condition exists; Warm Standby; Primary (both kinds — remote methods are
/// Primary-only); method supported (native Confirm ⇒ <c>BadNotSupported</c>); the activation marker (mismatch ⇒
/// <c>BadEventIdUnknown</c>: a new occurrence the caller has not seen); then the handler's own native preflight.
/// The session gate (<see cref="EvaluateAlarmCommandGate"/>) is skipped ONLY for the condition this call's
/// context was created for: the caller authorized it on the placement's subject.
/// </remarks>
/// <param name="call">The call.</param>
/// <returns>The verdict.</returns>
public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call)
{
ArgumentNullException.ThrowIfNull(call);
ArgumentException.ThrowIfNullOrWhiteSpace(call.ConditionId);
ArgumentException.ThrowIfNullOrWhiteSpace(call.Principal);
// Security review: a remote caller never waits on Lock without bound (a long rebuild or a stalled holder would
// otherwise pin one gRPC worker per call). Not acquired ⇒ refused before ANY state change.
var lockTaken = false;
try
{
Monitor.TryEnter(Lock, ConditionMethodLockTimeout, ref lockTaken);
if (!lockTaken)
return Refused(false, StatusCodes.BadTimeout, "The node manager is busy; the condition method was not applied.");
return TryExecuteConditionMethodLocked(call);
}
finally
{
if (lockTaken) Monitor.Exit(Lock);
}
}
/// <summary>
/// How long a remote condition method waits for the node manager's <c>Lock</c> before it is refused
/// (<c>BadTimeout</c>, nothing applied). Default 5 s — the consumer's default <c>ConditionMethodTimeoutMilliseconds</c>,
/// after which the caller has given up anyway.
/// </summary>
internal TimeSpan ConditionMethodLockTimeout { get; set; } = TimeSpan.FromSeconds(5);
private OriginConditionMethodOutcome TryExecuteConditionMethodLocked(OriginConditionMethodCall call)
{
var key = MapKey(call.Realm, call.ConditionId);
if (!_alarmConditions.TryGetValue(key, out var alarm))
return Refused(false, StatusCodes.BadNodeIdUnknown, "The condition is not materialised.");
var native = _nativeAlarmNodeIds.Contains(key);
if (_standby.RefusesMutations)
return RefusedBy(native, WarmStandbyState.StandbyRefusal($"call {call.Method}"));
if (NativeAlarmAckPrimaryGate is { } primary && !primary())
return Refused(native, StatusCodes.BadInvalidState, "This server is not the redundancy Primary.");
MethodState? method = call.Method switch
{
"Acknowledge" => alarm.Acknowledge,
"AddComment" => alarm.AddComment,
"Confirm" when !native => alarm.Confirm,
_ => null,
};
if (method is null) return Refused(native, StatusCodes.BadNotSupported, "The condition does not support this method.");
// T3: the marker moves only on a new occurrence; an unchanged re-projection keeps the caller's EventIds valid.
var current = _activation.TryGetValue(key, out var entry) ? entry.Sequence : 0UL;
if (!string.Equals(call.ExpectedActivation.Incarnation, ConditionIncarnation, StringComparison.Ordinal)
|| call.ExpectedActivation.Sequence != current)
return Refused(native, StatusCodes.BadEventIdUnknown, "The condition has a newer occurrence.");
var identity = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = call.Principal }, [],
principal: call.Principal, apiKeyId: call.ApiKeyId);
var context = new RemoteConditionMethodContext(Server, alarm, identity);
var eventId = alarm.EventId?.Value ?? default;
var comment = call.Comment is null ? default : new LocalizedText(call.Comment);
var result = method switch
{
AddCommentMethodState { OnCall: { } onCall } m => onCall(context, m, alarm.NodeId, eventId, comment),
_ => new ServiceResult(StatusCodes.BadNotSupported),
};
return ServiceResult.IsGood(result)
? new OriginConditionMethodOutcome(true, native, StatusCodes.Good.Code, null)
: RefusedBy(native, result);
}
private static OriginConditionMethodOutcome RefusedBy(bool native, ServiceResult result) =>
new(false, native, result.StatusCode.Code, result.LocalizedText.IsNullOrEmpty ? null : result.LocalizedText.Text);
private static OriginConditionMethodOutcome Refused(bool native, StatusCode status, string diagnostic) =>
new(false, native, status.Code, diagnostic);
/// <summary>
/// A2b: the system context of one remote condition method call. Carries the service principal (so the SDK records
/// it as <c>ClientUserId</c> and the handlers as the command's <c>User</c>) and marks the call as pre-authorized for
/// exactly <see cref="Condition"/>. Internal: no OPC UA client can ever present one.
/// </summary>
private sealed class RemoteConditionMethodContext : ServerSystemContext
{
public RemoteConditionMethodContext(IServerInternal server, ConditionState condition, RoleCarryingUserIdentity identity)
: base(server)
{
Condition = condition;
Identity = identity;
UserIdentity = identity;
}
public ConditionState Condition { get; }
public RoleCarryingUserIdentity Identity { get; }
}
/// <summary>
/// The calling identity of an alarm method handler and whether the session gate applies: a
/// <see cref="RemoteConditionMethodContext"/> for this very condition was authorized by its caller (§5.6).
/// </summary>
private static (RoleCarryingUserIdentity? Identity, bool PreAuthorized) AlarmCaller(ISystemContext context, ConditionState condition) =>
context is RemoteConditionMethodContext remote && ReferenceEquals(remote.Condition, condition)
? (remote.Identity, true)
: ((context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity, false);
}