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; /// /// 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. /// /// The condition's realm key (Raw for a native condition, Uns for a scripted one). /// The condition id (RawPath / ScriptedAlarmId). Origin-internal; never from the wire. /// The Part 9 method name: Acknowledge, AddComment or Confirm. /// The Part 9 comment, or null. /// The marker the caller last applied; a different current marker ⇒ BadEventIdUnknown. /// The service principal (recorded as the command's User and the condition's ClientUserId). /// The service key's public id (the Galaxy ack identity lookup key, §6). public sealed record OriginConditionMethodCall(AddressSpaceRealm Realm, string ConditionId, string Method, string? Comment, ConditionActivationMarker ExpectedActivation, string Principal, string? ApiKeyId); /// The node manager's verdict on an . /// True when the node state changed (or a native ack was accepted and routed); false = refused /// before ANY state change, nothing routed or reported. /// Whether the condition is native (driver-fed): an applied native call is accepted, not confirmed. /// The OPC UA status (Good when applied). /// A refusal's reason text, when the gate gave one. /// #937: is false, but the call reached the scripted-alarm engine — which refused /// it, or did not answer (). The node manager had already applied its node state. /// #937: the engine did not answer inside the budget (or failed): the command may still apply. public sealed record OriginConditionMethodOutcome(bool Applied, bool Native, uint StatusCode, string? Diagnostic, bool Dispatched = false, bool Unknown = false); public sealed partial class OtOpcUaNodeManager { /// /// A2b (§5.6 Origin): executes one remote condition method through the SAME wrapped SDK method handler a local /// client's call runs (WireMethodTransitionReporting → SDK handler → / /// ), so neither path goes around the other: one condition event, the native /// Confirmed/Retain re-assert, the non-blocking / /// (an unchanged AlarmCommand) and the #760 revert contract all hold. /// /// /// Runs entirely under Lock 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 ⇒ BadNotSupported); the activation marker (mismatch ⇒ /// BadEventIdUnknown: a new occurrence the caller has not seen); then the handler's own native preflight. /// The session gate () is skipped ONLY for the condition this call's /// context was created for: the caller authorized it on the placement's subject. /// /// The call. /// The verdict. 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); } } /// /// How long a remote condition method waits for the node manager's Lock before it is refused /// (BadTimeout, nothing applied). Default 5 s — the consumer's default ConditionMethodTimeoutMilliseconds, /// after which the caller has given up anyway. /// 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); /// /// A2b: the system context of one remote condition method call. Carries the service principal (so the SDK records /// it as ClientUserId and the handlers as the command's User) and marks the call as pre-authorized for /// exactly . Internal: no OPC UA client can ever present one. /// 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; } } /// /// The calling identity of an alarm method handler and whether the session gate applies: a /// for this very condition was authorized by its caller (§5.6). /// 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); }