From 1e78c64b92b8b91d3493ad4f25e9de1ebe96a497 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 13:31:03 -0500 Subject: [PATCH] =?UTF-8?q?feat(grpc-data):=20A2b=20=E2=80=94=20CallCondit?= =?UTF-8?q?ionMethod=20RPC,=20origin=20TryExecuteConditionMethod=20through?= =?UTF-8?q?=20the=20wrapped=20SDK=20handler,=20bits=20128/256=20understood?= =?UTF-8?q?,=20Galaxy=20service-ack=20rule,=20operation=20registry=20+=20a?= =?UTF-8?q?udit=20log?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DataConditionProtoMapper.cs | 56 +++++ .../DataConnections/DataProtoMapper.cs | 10 +- .../Observability/OtOpcUaTelemetry.cs | 5 + .../Protos/data_connection.proto | 21 ++ .../DataConnections/DataConditionContracts.cs | 117 +++++++++ .../DataConnections/DataContracts.cs | 18 +- .../Configuration/DataConnectionEndpoints.cs | 2 +- .../Grpc/DataConnectionGrpcService.cs | 30 ++- .../OriginConditionSource.cs | 11 + .../OtOpcUaNodeManager.ConditionMethods.cs | 131 ++++++++++ .../OtOpcUaNodeManager.cs | 10 +- .../SdkAddressSpaceSink.cs | 4 + .../DataConnections/ConditionItemStream.cs | 2 +- .../DataConnections/ConditionPlacements.cs | 11 +- .../DataCapabilitiesProvider.cs | 4 +- .../DataConnections/LocalDataConnection.cs | 5 +- .../LocalDataServices.ConditionMethods.cs | 223 ++++++++++++++++++ .../LocalDataServices.Conditions.cs | 9 +- .../DataConnections/LocalDataServices.cs | 5 +- .../LocalExportCatalog.Compilation.cs | 5 +- .../DataConnections/LocalExportCatalog.cs | 41 +++- 21 files changed, 686 insertions(+), 34 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionMethods.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataConditionProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataConditionProtoMapper.cs index 1ead97ca7..9ed8a9503 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataConditionProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataConditionProtoMapper.cs @@ -105,4 +105,60 @@ public static class DataConditionProtoMapper return new DataSubscriptionConditions(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence, handle, c.IsSnapshot, c.HasTotal ? c.Total : null, c.Items.Select(DecodeState).ToArray(), c.SnapshotComplete); } + + // ---- A2b CallConditionMethod (§4.2) ---- + + /// Encodes a condition method request. + public static W.ConditionMethodRequest EncodeMethodRequest(DataConditionMethodRequest x) + { + ArgumentNullException.ThrowIfNull(x); + x.Validate(); + var v = new W.ConditionMethodRequest + { + OperationId = x.OperationId, Placement = DataProtoMapper.EncodeView(x.Placement), Method = (int)x.Method, + ExpectedActivation = new W.ActivationMarker { Incarnation = x.ExpectedActivation.Incarnation, Sequence = x.ExpectedActivation.Sequence }, + ExpectedServingIncarnation = x.ExpectedServingIncarnation, RemainingBudgetTicks = x.RemainingBudget.Ticks, + }; + if (x.Comment is not null) v.Comment = x.Comment; + if (x.OnBehalfOf is not null) v.OnBehalfOf = x.OnBehalfOf; + return v; + } + + /// + /// Decodes a condition method request. A malformed request (no placement, an unknown or multi-bit method, no marker, + /// an oversized comment or id) is an ⇒ INVALID_ARGUMENT. on_behalf_of is NOT + /// refused for its content: it is untrusted audit text the origin caps and sanitises (§6). + /// + public static DataConditionMethodRequest DecodeMethodRequest(W.ConditionMethodRequest x) + { + ArgumentNullException.ThrowIfNull(x); + if (x.Placement is null || x.ExpectedActivation is null) throw new ArgumentException("Missing placement or activation marker."); + if (x.Method <= 0) throw new ArgumentException("Unknown condition method."); + var decoded = new DataConditionMethodRequest(x.OperationId, DataProtoMapper.DecodeView(x.Placement), (DataConditionMethods)(uint)x.Method, + new DataActivationMarker(x.ExpectedActivation.Incarnation, x.ExpectedActivation.Sequence), x.HasComment ? x.Comment : null, + x.ExpectedServingIncarnation, TimeSpan.FromTicks(x.RemainingBudgetTicks), x.HasOnBehalfOf ? x.OnBehalfOf : null); + decoded.Validate(); + return decoded; + } + + /// Encodes a condition method response. + public static W.ConditionMethodResponse EncodeMethodResponse(DataConditionMethodResult x) + { + ArgumentNullException.ThrowIfNull(x); + x.Validate(); + var v = new W.ConditionMethodResponse { State = (int)x.State, StatusCode = x.StatusCode }; + if (x.Diagnostic is not null) v.Diagnostic = x.Diagnostic; + if (x.Serving is { } serving) v.Serving = DataProtoMapper.EncodeServing(serving); + return v; + } + + /// Decodes a condition method response (an unknown state is an ). + public static DataConditionMethodResult DecodeMethodResponse(W.ConditionMethodResponse x) + { + ArgumentNullException.ThrowIfNull(x); + var state = (DataWriteState)x.State; + if (state == DataWriteState.Unspecified || !System.Enum.IsDefined(state)) throw new ArgumentException("Unknown method outcome state."); + return new DataConditionMethodResult(state, x.StatusCode, x.HasDiagnostic ? x.Diagnostic : null, + x.Serving is null ? null : DataProtoMapper.DecodeServing(x.Serving)); + } } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index f293ccdeb..ba7a6bc84 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -284,9 +284,9 @@ public static class DataProtoMapper x.ValueRank, x.Dimensions.ToArray(), x.Writable, - // X0 tolerant reader: an operation bit this build does not understand is no grant. A2: AlarmSubscribe is a - // root-scope grant, never a node operation, so a metadata item carrying it is masked too. - (DataOperations)(x.AllowedOperations & (uint)DataOperationSets.Understood & ~(uint)DataOperations.AlarmSubscribe), + // X0 tolerant reader: an operation bit this build does not understand is no grant. A2: AlarmSubscribe and the + // A2b method bits are condition grants, never node operations, so a metadata item carrying them is masked too. + (DataOperations)(x.AllowedOperations & (uint)DataOperationSets.Understood & ~(uint)DataOperationSets.ConditionGrants), x.CatalogRevision, x.HasStableSourceId ? x.StableSourceId : null, x.HasEngineeringUnits ? x.EngineeringUnits : null, @@ -1070,8 +1070,8 @@ public static class DataProtoMapper // H2: HistoryRead without the history capabilities field is no grant (the two only ever travel together). (DataOperations)(x.Operations & (uint)DataOperationSets.Understood & (DataHistoryProtoMapper.DecodeCapabilities(x.History) is null ? ~(uint)DataOperations.HistoryRead : uint.MaxValue) - // A2: likewise AlarmSubscribe without the conditions field. - & (x.Conditions is null ? ~(uint)DataOperations.AlarmSubscribe : uint.MaxValue)), + // A2: likewise AlarmSubscribe and the A2b method bits without the conditions field. + & (x.Conditions is null ? ~(uint)DataOperationSets.ConditionGrants : uint.MaxValue)), kinds, new DataLimits( l.MaxPageItems, diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs index d516cfe5e..7158a833c 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs @@ -254,6 +254,11 @@ public static class OtOpcUaTelemetry Meter.CreateCounter("otopcua.dataconn.conditions.capacity_rejections", unit: "{item}", description: "Root-scoped condition items over their MaxConditions at snapshot begin."); + /// A2b: remote condition method calls served by this origin, by method and outcome (plan §6 metrics; no ids). + public static readonly Counter DataConnConditionMethods = + Meter.CreateCounter("otopcua.dataconn.condition_methods", unit: "{call}", + description: "Remote condition method calls served by this origin (tags: method, outcome)."); + /// A1 (G3): deferred MarkConditionsKnown discarded because an alarm projection of the same source did not land. public static readonly Counter DataConnConditionMarksDiscarded = Meter.CreateCounter("otopcua.dataconn.conditions.marks_discarded", unit: "{mark}", diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto index 9c58c4c00..188c4416f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto @@ -11,6 +11,8 @@ service DataConnectionService { rpc Subscribe(stream SubscriptionCommand) returns (stream SubscriptionFrame); // H2: header-gated (x-otopcua-data-features: history). Without the negotiated feature ⇒ FAILED_PRECONDITION. rpc HistoryRead(HistoryReadRequest) returns (HistoryReadResponse); + // A2b: header-gated (x-otopcua-data-features: conditions). Without the negotiated feature ⇒ FAILED_PRECONDITION. + rpc CallConditionMethod(ConditionMethodRequest) returns (ConditionMethodResponse); } enum ValueKind { VALUE_KIND_UNSPECIFIED = 0; @@ -457,3 +459,22 @@ message HistoryReadResponse { repeated HistoryReadResult items = 1; Serving serving = 2; } +// A2b remote condition methods (plan §4.2, §5.6). method: 1 Acknowledge, 2 AddComment, 4 Confirm (exactly one). +message ConditionMethodRequest { + string operation_id = 1; + View placement = 2; + int32 method = 3; + ActivationMarker expected_activation = 4; + optional string comment = 5; + string expected_serving_incarnation = 6; + int64 remaining_budget_ticks = 7; + // Untrusted audit text; capped, sanitised, written only to the origin's audit log (§6). + optional string on_behalf_of = 8; +} +message ConditionMethodResponse { + // DataWriteState: 1 RejectedBeforeDispatch, 2 applied (scripted), 4 applied + routed (native), 5 outcome unknown. + int32 state = 1; + uint32 status_code = 2; + optional string diagnostic = 3; + Serving serving = 4; +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataConditionContracts.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataConditionContracts.cs index f75db0b39..9d6068c45 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataConditionContracts.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataConditionContracts.cs @@ -54,3 +54,120 @@ public sealed record DataConditionState(string ConditionKey, long Version, bool public sealed record DataSubscriptionConditions(string SubscriptionId, long StreamEpoch, long Sequence, DataItemHandle Handle, bool IsSnapshot, int? Total, IReadOnlyList Items, bool SnapshotComplete) : DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence); + +// --------------------------------------------------------------------------------------------------------------------- +// A2b condition methods (plan §4.2 CallConditionMethod, §5.6). Header-gated by the same `conditions` feature: a call +// without it is refused FAILED_PRECONDITION and never reaches the origin. +// --------------------------------------------------------------------------------------------------------------------- + +/// +/// The remote condition methods. The values are wire values: ConditionMethodRequest.method carries exactly one, +/// ConditionCapabilities.methods and ConditionInfo.supported_methods a mask. Never renumber. +/// +[Flags] +public enum DataConditionMethods : uint +{ + None = 0, + /// Part 9 Acknowledge (grant ). + Acknowledge = 1, + /// Part 9 AddComment (grant ). + AddComment = 2, + /// Part 9 Confirm (grant ; scripted conditions only). + Confirm = 4, +} + +/// A2b: the one authority mapping a condition method onto its grant (M8, mirrors AlarmOperationFor). +public static class DataConditionMethodSets +{ + /// Every method this build implements. + public const DataConditionMethods All = DataConditionMethods.Acknowledge | DataConditionMethods.AddComment | DataConditionMethods.Confirm; + + /// What a native (driver-fed) condition supports: Confirm has no upstream path (BadNotSupported). + public const DataConditionMethods Native = DataConditionMethods.Acknowledge | DataConditionMethods.AddComment; + + /// What a scripted condition supports. + public const DataConditionMethods Scripted = All; + + /// The data operation a method requires. + public static DataOperations OperationFor(DataConditionMethods method) => method switch + { + DataConditionMethods.Confirm => DataOperations.AlarmConfirm, + DataConditionMethods.Acknowledge or DataConditionMethods.AddComment => DataOperations.AlarmAcknowledge, + _ => DataOperations.None, + }; + + /// The methods a grant set allows. + public static DataConditionMethods AllowedBy(DataOperations operations) => + ((operations & DataOperations.AlarmAcknowledge) != 0 ? DataConditionMethods.Acknowledge | DataConditionMethods.AddComment : DataConditionMethods.None) + | ((operations & DataOperations.AlarmConfirm) != 0 ? DataConditionMethods.Confirm : DataConditionMethods.None); + + /// Whether names exactly one implemented method. + public static bool IsSingle(DataConditionMethods method) => + method is DataConditionMethods.Acknowledge or DataConditionMethods.AddComment or DataConditionMethods.Confirm; + + /// The Part 9 method name (the operation name the node manager and AlarmOperationFor use). + public static string Part9Name(DataConditionMethods method) => method switch + { + DataConditionMethods.Acknowledge => "Acknowledge", + DataConditionMethods.AddComment => "AddComment", + DataConditionMethods.Confirm => "Confirm", + _ => throw new ArgumentOutOfRangeException(nameof(method)), + }; +} + +/// +/// One remote condition method call (ConditionMethodRequest). +/// +/// Caller-chosen id; a duplicate (same principal) joins the first call (§5.6 step 5). +/// A realm-local placement address of the condition (from a listing), never a condition key. +/// Exactly one method. +/// The activation marker of the latest record the caller applied (T3). +/// The Part 9 comment, or null. +/// The serving incarnation the caller selected (a restarted origin refuses). +/// What is left of the caller's deadline; ≤ 0 is refused before dispatch. +/// Untrusted audit text: capped, sanitised, written only to the origin's audit log (§6). +public sealed record DataConditionMethodRequest(string OperationId, DataView Placement, DataConditionMethods Method, + DataActivationMarker ExpectedActivation, string? Comment, string ExpectedServingIncarnation, TimeSpan RemainingBudget, + string? OnBehalfOf = null) +{ + /// The most characters of the origin keeps (§6). + public const int MaxOnBehalfOfLength = 128; + /// The most characters of an operation id. + public const int MaxOperationIdLength = 128; + /// The most characters of a comment (a Part 9 LocalizedText, bounded like a value string). + public const int MaxCommentLength = 4096; + + public void Validate() + { + ArgumentException.ThrowIfNullOrWhiteSpace(OperationId); + if (OperationId.Length > MaxOperationIdLength) throw new ArgumentException("Operation id too long.", nameof(OperationId)); + ArgumentNullException.ThrowIfNull(Placement); + Placement.Validate(); + if (!DataConditionMethodSets.IsSingle(Method)) throw new ArgumentException("Exactly one known method.", nameof(Method)); + ArgumentNullException.ThrowIfNull(ExpectedActivation); + ArgumentException.ThrowIfNullOrWhiteSpace(ExpectedActivation.Incarnation); + ArgumentException.ThrowIfNullOrWhiteSpace(ExpectedServingIncarnation); + if (Comment is { Length: > MaxCommentLength }) throw new ArgumentException("Comment too long.", nameof(Comment)); + // OnBehalfOf is untrusted free text: never refused for its content, only capped and sanitised by the origin. + } +} + +/// +/// The answer to one condition method call (ConditionMethodResponse). reuses the write +/// outcome states: = refused before any state change (status says +/// why); = applied at the origin (scripted); +/// = applied and routed to the driver, whose confirmation (or revert) +/// arrives on the condition stream (native); = the transport failed after +/// the request was sent (never retried). +/// +public sealed record DataConditionMethodResult(DataWriteState State, uint StatusCode, string? Diagnostic, ServingIdentity? Serving = null) +{ + public void Validate() => DataContractValidation.Required(State); +} + +/// A2b: remote condition methods (CallConditionMethod), bound to the caller of the containing facade. +public interface IDataConditionMethodService +{ + /// Calls one method. Never retried: a duplicate joins. + Task CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs index 095a5b5fe..1320f3e64 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs @@ -239,9 +239,9 @@ public sealed record DataBudget(TimeSpan Timeout, int MaxItems, long MaxBytes) HistoryRead = 32, /// A2: root-scoped condition items (origin-side grant; plan §5.5). AlarmSubscribe = 64, - /// Reserved (A2): Acknowledge and AddComment. + /// A2b: remote condition Acknowledge and AddComment (CallConditionMethod; plan §5.6). AlarmAcknowledge = 128, - /// Reserved (A2): Confirm. + /// A2b: remote condition Confirm. AlarmConfirm = 256, /// Reserved for the deferred shelve methods. AlarmShelve = 512, @@ -255,13 +255,17 @@ public static class DataOperationSets /// /// What tolerant readers keep; every other bit is dropped fail-closed. Grows only in the phase that implements /// a bit (H2 added ; A2a ; A2b - /// the method bits). + /// the method bits and ). /// - public const DataOperations Understood = V1 | DataOperations.HistoryRead | DataOperations.AlarmSubscribe; + public const DataOperations Understood = V1 | DataOperations.HistoryRead | ConditionGrants; /// Bits reserved by X0 that no phase has implemented yet (H2 took out, - /// A2a ). - public const DataOperations Reserved = - DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm | DataOperations.AlarmShelve; + /// A2a , A2b the Acknowledge/Confirm method bits). + public const DataOperations Reserved = DataOperations.AlarmShelve; + /// A2b: the remote condition-method grants (CallConditionMethod). + public const DataOperations ConditionMethods = DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm; + /// A2: every grant that travels only with the negotiated conditions feature (field 17): the + /// root-scoped item grant and the method grants. A header-less call never sees any of them. + public const DataOperations ConditionGrants = DataOperations.AlarmSubscribe | ConditionMethods; } /// /// Optional per-call protocol features negotiated through the x-otopcua-data-features request header. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs index 487feb26d..bb76e51ed 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs @@ -7,7 +7,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; public static class DataConnectionEndpoints { public const string ServicePrefix = "/data_connection.v1.DataConnectionService/"; - private static readonly HashSet Methods = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe", "HistoryRead"]; + private static readonly HashSet Methods = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe", "HistoryRead", "CallConditionMethod"]; public static bool IsDataRequest(HttpContext context, DataConnectionOptions options) => options.Enabled && context.Connection.LocalPort == options.ListenPort diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs index aa474b2c9..886e76e58 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs @@ -49,18 +49,19 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO return negotiated; } - /// A2: the v1 shape of a capabilities response with respect to conditions: no field 17, no AlarmSubscribe bit. + /// A2: the v1 shape of a capabilities response with respect to conditions: no field 17, no AlarmSubscribe bit + /// and (A2b) no AlarmAcknowledge/AlarmConfirm bit. internal static void StripConditions(W.CapabilitiesResponse response) { response.Conditions = null; - response.Operations &= ~(uint)DataOperations.AlarmSubscribe; + response.Operations &= ~(uint)DataOperationSets.ConditionGrants; } /// A2: a metadata item never carries AlarmSubscribe on a call without conditions (it is a root-scope grant). internal static void StripConditions(W.Metadata? metadata) { if (metadata is null) return; - metadata.AllowedOperations &= ~(uint)DataOperations.AlarmSubscribe; + metadata.AllowedOperations &= ~(uint)DataOperationSets.ConditionGrants; } /// The v1 shape of a capabilities response: no history field and no HistoryRead bit. @@ -237,6 +238,29 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO return response; }); + /// + /// A2b remote condition method (plan §5.6). Order: the call negotiated conditions (header) and the origin can + /// serve them, else FAILED_PRECONDITION — a header-less or v1 client never reaches it; a malformed request is + /// INVALID_ARGUMENT; everything else (readiness, Primary, grants, ACL, Galaxy opt-in, marker) is the origin facade's + /// per-call verdict, answered as a RejectedBeforeDispatch outcome with its status — never retried here. + /// + public override Task CallConditionMethod(W.ConditionMethodRequest request, ServerCallContext context) => + Execute(context, async (connection, caller, token) => + { + if ((CallFeatures(context).Effective & DataFeatures.Conditions) == 0 + || connection is not IDataConditionMethodService methods) throw NotNegotiated(); + var caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false); + if (!ConditionsNegotiated(context, caps)) throw NotNegotiated(); + var decoded = DataConditionProtoMapper.DecodeMethodRequest(request); + if (decoded.RemainingBudget > _options.UnaryTimeout) decoded = decoded with { RemainingBudget = _options.UnaryTimeout }; + var result = await methods.CallConditionMethodAsync(decoded, token).ConfigureAwait(false); + var response = DataConditionProtoMapper.EncodeMethodResponse(result with { Serving = result.Serving ?? caps.Serving }); + CheckSize(response); + // The outcome is already decided (and audited) at the origin: publish it while the caller is still current. + Register(context, response, () => !token.IsCancellationRequested && authenticator.IsCurrent(caller)); + return response; + }); + /// /// The transport channel of this call: its HTTP/2 connection. Origin continuations are partitioned by it and cleared /// when Kestrel reports the connection closed (idle expiry is the backstop where the feature is absent). diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs index 1aa92bd83..74e3beb55 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs @@ -14,6 +14,12 @@ public interface IOriginConditionSource /// The most conditions one Lock hold copies. /// The slices (at least one, even for an empty scope). IReadOnlyList SnapshotConditions(Func scope, int maxConditionsPerHold); + + /// A2b: see — one pre-authorized remote condition + /// method, applied under the node manager's Lock through the same handler a local client's call runs. Never blocks. + /// The call. + /// The verdict. + OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call); } /// Resolves the port against the SDK sink bound at server start; throws while the server is not running. @@ -26,4 +32,9 @@ public sealed class DeferredOriginConditionSource(DeferredAddressSpaceSink defer public IReadOnlyList SnapshotConditions(Func scope, int maxConditionsPerHold) => deferred.GetCapability() is { } inner ? inner.SnapshotConditions(scope, maxConditionsPerHold) : throw new InvalidOperationException("The OPC UA server is not running."); + + /// + public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call) => + deferred.GetCapability() is { } inner ? inner.TryExecuteConditionMethod(call) + : throw new InvalidOperationException("The OPC UA server is not running."); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionMethods.cs new file mode 100644 index 000000000..702952662 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionMethods.cs @@ -0,0 +1,131 @@ +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. +public sealed record OriginConditionMethodOutcome(bool Applied, bool Native, uint StatusCode, string? Diagnostic); + +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); + lock (Lock) + { + 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); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index b3883eeca..2d1fceb3c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -3156,8 +3156,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage { // Resolve the principal the SAME way the SDK's own GetCurrentUserId does, then narrow to the // role-carrying identity T17 attached. Anonymous / non-role-carrying identities ⇒ null ⇒ denied. - var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity; - var gate = EvaluateAlarmCommandGate(identity, condition, operation); + // A2b: a remote condition method (TryExecuteConditionMethod) arrives pre-authorized on the placement's subject. + var (identity, preAuthorized) = AlarmCaller(context, condition); + var gate = preAuthorized ? null : EvaluateAlarmCommandGate(identity, condition, operation); if (gate is not null) return gate; // Gitea #717 owner answer Q4: a Warm Standby refuses every Part 9 condition method before it changes any state @@ -3201,8 +3202,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage { // Resolve + gate the SAME way HandleAlarmCommand does so native and scripted acks share one authz // contract. Anonymous / non-role-carrying identities ⇒ null ⇒ denied (fail closed, never route). - var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity; - var gate = EvaluateAlarmCommandGate(identity, condition, "Acknowledge"); + // A2b: a remote condition method (TryExecuteConditionMethod) arrives pre-authorized on the placement's subject. + var (identity, preAuthorized) = AlarmCaller(context, condition); + var gate = preAuthorized ? null : EvaluateAlarmCommandGate(identity, condition, "Acknowledge"); if (gate is not null) return gate; // Gitea #717 owner answer Q4: refused on a Warm Standby, ahead of (and whatever) the Primary gate below says. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index a85472550..e05abc500 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs @@ -36,6 +36,10 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre Func scope, int maxConditionsPerHold) => _nodeManager.SnapshotConditions(scope, maxConditionsPerHold); + /// + OriginConditionMethodOutcome IOriginConditionSource.TryExecuteConditionMethod(OriginConditionMethodCall call) => + _nodeManager.TryExecuteConditionMethod(call); + /// Initializes a new instance of the SdkAddressSpaceSink class. /// The OPC UA node manager. public SdkAddressSpaceSink(OtOpcUaNodeManager nodeManager) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs index b81039c55..35207f473 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs @@ -313,7 +313,7 @@ internal sealed class ConditionItemStream var info = includeInfo && !record.Removed ? new DataConditionInfo(record.ConditionType ?? "", record.ConditionName ?? "", (DataConditionSourceKind)(int)scoped.Exported.SourceKind, - scoped.Exported.Placements.Select(p => p.View).ToArray(), 0) + scoped.Exported.Placements.Select(p => p.View).ToArray(), (uint)scoped.Methods) : null; return new DataConditionState(scoped.Exported.ConditionKey, record.Version, record.Removed, record.StateKnown && !record.Removed, info, record.Active, record.Acknowledged, record.Confirmed, record.Enabled, (int)record.Shelving, record.Severity, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs index 26ebe0976..3b327aa0b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs @@ -31,9 +31,15 @@ public readonly record struct OriginConditionRef(AddressSpaceRealm Realm, string /// ⚠️ ORIGIN-INTERNAL (carries ). What may reach a peer is /// , via . /// +/// A2b: the backing driver's type for a native condition (null for scripted); decides the Galaxy +/// service-ack opt-in (§6). public sealed record LocalConditionPlacement(DataView View, DataView Parent, NodeScope Scope, string BrowseName, - ConditionSourceKind SourceKind, OriginConditionRef Condition, string EntityKind, string EntityId) + ConditionSourceKind SourceKind, OriginConditionRef Condition, string EntityKind, string EntityId, string? DriverType = null) { + /// A2b: a Galaxy-sourced native condition (remote Acknowledge/AddComment need the export's opt-in). + public bool IsGalaxy => SourceKind == ConditionSourceKind.Native + && string.Equals(DriverType, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DriverTypeNames.Galaxy, StringComparison.OrdinalIgnoreCase); + /// The peer-safe projection: address, parent and name, in the placement's own realm. public ConditionPlacementView ToView() => new(View, Parent, BrowseName); } @@ -53,4 +59,5 @@ public sealed record ExportedCondition(string ConditionKey, ConditionSourceKind /// A2: one condition of an export listing together with its origin-internal identity. ⚠️ ORIGIN-INTERNAL /// ( names a RawPath for a native condition); only may reach a peer. /// -internal sealed record ScopedCondition(OriginConditionRef Ref, ExportedCondition Exported); +/// A2b: the methods the listing principal may call on it (0 when methods are not servable). +internal sealed record ScopedCondition(OriginConditionRef Ref, ExportedCondition Exported, DataConditionMethods Methods = DataConditionMethods.None); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs index a1fa67ea2..1990584c3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs @@ -25,7 +25,9 @@ public sealed class DataCapabilitiesProvider var serving = Serving; var ready = IsReady; serving.Validate(requireEpochs: ready); - if (!string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) operations &= ~DataOperations.Write; + // Writes and (A2b, plan §5.6) remote condition methods are Primary-only; ingress re-checks. + if (!string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) + operations &= ~(DataOperations.Write | DataOperationSets.ConditionMethods); return new(1, 1, serving, ready ? DataReadiness.Ready : DataReadiness.Unavailable, ready ? operations : DataOperations.None, Enum.GetValues().Where(x => x != DataValueKind.Unspecified).ToHashSet(), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs index edba25926..b71bcf4c1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs @@ -4,7 +4,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Strictly caller-bound local data facade; it creates no namespace projection. public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate, - IDataHistoryService, IDataHistoryTransport + IDataHistoryService, IDataHistoryTransport, IDataConditionMethodService { private readonly LocalDataServices _services; private readonly DataAuthenticatedContext _context; @@ -48,6 +48,9 @@ public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublic /// public Task ReleaseForTransportAsync(IReadOnlyList continuations, DataHistoryChannel channel, CancellationToken cancellationToken) { Check(); return _services.ReleaseHistoryAsync(_context, continuations, channel, cancellationToken); } + /// A2b: one remote condition method (plan §5.6 origin), bound to this facade's caller. + public Task CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken) + { Check(); return _services.CallConditionMethodAsync(_context, Target, request, cancellationToken); } private readonly CancellationTokenSource _closed = new(); private DataHistoryChannel? _channel; private DataHistoryChannel OwnChannel => _channel ??= new("facade:" + Guid.NewGuid().ToString("N"), _closed.Token); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs new file mode 100644 index 000000000..026b18c6f --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs @@ -0,0 +1,223 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Extensions.Logging; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// A2b: one entry of the origin's data-connection audit log (plan §6 "Audit"). is the peer's +/// untrusted text AFTER ; it goes here and nowhere else (never into +/// AlarmCommand, ClientUserId or alarm history). +/// +public sealed record DataConditionMethodAuditEntry(DateTimeOffset TimeUtc, string Principal, string? ApiKeyId, DataView Placement, + string OperationId, DataConditionMethods Method, DataWriteState State, uint StatusCode, bool Joined, string? OnBehalfOf); + +/// A2b: the origin's data-connection audit log. +public interface IDataConnectionAuditLog +{ + /// Records one condition method call's outcome. Must not block or throw. + void RecordConditionMethod(DataConditionMethodAuditEntry entry); +} + +/// The default audit log: structured entries on a dedicated logger category. +public sealed class LoggerDataConnectionAuditLog(ILogger logger) : IDataConnectionAuditLog +{ + /// The logger category operators route to the audit sink. + public const string Category = "ZB.MOM.WW.OtOpcUa.DataConnections.Audit"; + + /// + public void RecordConditionMethod(DataConditionMethodAuditEntry entry) => + logger.LogInformation( + "Data-connection condition method {Method} by {Principal} (key {ApiKeyId}) on {PlacementRealm}:{PlacementNamespace}:{Placement} op {OperationId}: {State} 0x{StatusCode:X8}{Joined}; on behalf of {OnBehalfOf}", + entry.Method, entry.Principal, entry.ApiKeyId ?? "-", entry.Placement.Realm, entry.Placement.Address.NamespaceUri, + entry.Placement.Address.Identifier, entry.OperationId, entry.State, entry.StatusCode, entry.Joined ? " (joined)" : "", + entry.OnBehalfOf ?? "-"); +} + +/// A2b: the origin side of CallConditionMethod (plan §5.6 "Origin", §6). +public sealed partial class LocalDataServices +{ + private const uint BadNotSupported = 0x803D0000u, BadNoCommunication = 0x80310000u, BadInvalidState = 0x80AF0000u, + BadTimeout = 0x800A0000u, BadUserAccessDenied = 0x801F0000u, BadNodeIdUnknown = 0x80340000u, + BadInvalidArgument = 0x80AB0000u; + + private readonly object _methodRegistryGate = new(); + private WriteOperationRegistry? _methodRegistry; + private IDataConnectionAuditLog? _audit; + + /// A2b: the data-connection audit log (default: over ). + public IDataConnectionAuditLog Audit { get => _audit ??= new LoggerDataConnectionAuditLog(Logger); init => _audit = value; } + + /// A2b: how long a completed operation id is remembered (a duplicate within it joins the stored outcome). + public TimeSpan ConditionMethodRetention { get; init; } = TimeSpan.FromMinutes(5); + + /// Whether this origin serves remote condition methods: the condition port is up (same as streaming). + internal bool ConditionMethodsServable => ConditionsServable; + + /// The duplicate-protection registry of the current serving incarnation (a new incarnation starts empty). + private WriteOperationRegistry MethodRegistry(string incarnation) + { + lock (_methodRegistryGate) + { + if (_methodRegistry is null || _methodRegistryIncarnation != incarnation) + { + _methodRegistry = new WriteOperationRegistry(incarnation, 4096, 8L * 1024 * 1024, ConditionMethodRetention, Clock); + _methodRegistryIncarnation = incarnation; + } + return _methodRegistry; + } + } + private string? _methodRegistryIncarnation; + + /// + /// Executes one remote condition method (§5.6). Order, each refusal + /// with no state change: servable; catalog ready; Primary (and the target's role); the expected serving + /// incarnation; budget; caller usable; the placement resolves AND an export of its realm grants the method's bit + /// (else BadNodeIdUnknown — existence is not disclosed); the origin ACL on the placement's subject + /// (BadUserAccessDenied); native Confirm (BadNotSupported); the Galaxy service-ack opt-in + /// (BadUserAccessDenied); then the operation registry (a duplicate id joins) and the node manager (Warm + /// Standby, Primary, activation marker, native preflight). Never retried. + /// + internal async Task CallConditionMethodAsync(DataAuthenticatedContext context, DataTarget target, + DataConditionMethodRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + request.Validate(); + target.Validate(); + cancellationToken.ThrowIfCancellationRequested(); + var onBehalfOf = SanitizeAuditText(request.OnBehalfOf); + var catalog = _catalog(); + var serving = catalog?.Serving; + var (result, joined) = await DecideAsync().ConfigureAwait(false); + result = result with { Serving = serving }; + Audit.RecordConditionMethod(new(Clock.GetUtcNow(), context.PrincipalId, context.ApiKeyId, request.Placement, request.OperationId, + request.Method, result.State, result.StatusCode, joined, onBehalfOf)); + OtOpcUaTelemetry.DataConnConditionMethods.Add(1, new KeyValuePair("method", request.Method.ToString()), + new KeyValuePair("outcome", result.State.ToString())); + return result; + + async Task<(DataConditionMethodResult, bool)> DecideAsync() + { + if (!ConditionMethodsServable) return (Reject(BadNotSupported, "Condition methods are not served."), false); + if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving)) + return (Reject(BadNoCommunication, "Condition methods unavailable."), false); + // §5.6: remote condition methods are Primary-only for both kinds (the capability bits are stripped off-Primary too). + if (!string.Equals(catalog.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) + return (Reject(BadInvalidState, "This server is not the redundancy Primary."), false); + if (!string.Equals(request.ExpectedServingIncarnation, catalog.Serving.Incarnation, StringComparison.Ordinal)) + return (Reject(BadInvalidState, "Serving incarnation changed."), false); + if (request.RemainingBudget <= TimeSpan.Zero) return (Reject(BadTimeout, "Budget expired before dispatch."), false); + if (!_policy.IsCallerUsable(Caller(context))) return (Reject(BadUserAccessDenied, "Caller unusable."), false); + var operation = DataConditionMethodSets.OperationFor(request.Method); + if (!catalog.TryResolveConditionPlacement(request.Placement, out var placement) + || !catalog.AllowsConditionPlacement(context.PrincipalId, placement, operation)) + return (Reject(BadNodeIdUnknown, "Unknown condition placement."), false); + // The origin ACL on the PLACEMENT's subject (a UNS placement ⇒ its equipment), ACL flag on or off. + var acl = operation == DataOperations.AlarmConfirm ? OpcUaOperation.AlarmConfirm : OpcUaOperation.AlarmAcknowledge; + if (!_policy.AuthorizeLocal(Caller(context), acl, placement.Scope)) + return (Reject(BadUserAccessDenied, "Denied by the origin ACL."), false); + if (placement.SourceKind == ConditionSourceKind.Native && (request.Method & DataConditionMethodSets.Native) == 0) + return (Reject(BadNotSupported, "A native condition supports Acknowledge and AddComment only."), false); + if (placement.IsGalaxy && !catalog.AllowsGalaxyServiceAck(context.PrincipalId, placement)) + return (Reject(BadUserAccessDenied, "Galaxy service acknowledge is not enabled on this export."), false); + + var claim = MethodRegistry(catalog.Serving.Incarnation).Claim(context.PrincipalId, request.OperationId, + request.ExpectedServingIncarnation, SemanticHash(request)); + switch (claim.Kind) + { + case WriteClaimKind.Stale: return (Reject(BadInvalidState, "Serving incarnation changed."), false); + case WriteClaimKind.Conflict: return (Reject(BadInvalidArgument, "Operation id reused for a different call."), false); + case WriteClaimKind.Capacity: return (Reject(BadTooManyOperations, "Too many condition operations."), false); + case WriteClaimKind.Existing: + try + { + var joinedOutcome = await claim.Claim!.Completion.WaitAsync(request.RemainingBudget, Clock, cancellationToken).ConfigureAwait(false); + return (FromOutcome(claim.Claim.CurrentOutcome ?? joinedOutcome), true); + } + catch (TimeoutException) { return (new(DataWriteState.OutcomeUnknown, BadTimeout, "Joined operation still running."), true); } + } + + var owner = claim.Claim!; + OriginConditionMethodOutcome verdict; + try + { + verdict = ConditionSource!.TryExecuteConditionMethod(new(placement.Condition.Realm, placement.Condition.ConditionId, + DataConditionMethodSets.Part9Name(request.Method), request.Comment, + new ConditionActivationMarker(request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence), + context.PrincipalId, context.ApiKeyId)); + } + catch (InvalidOperationException ex) + { + verdict = new(false, placement.SourceKind == ConditionSourceKind.Native, BadNoCommunication, ex.Message); + } + DataWriteOutcome outcome; + if (verdict.Applied) + { + owner.TryMarkDispatched(); + outcome = verdict.Native + ? new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode, "AcceptedUnconfirmed: routed to the driver; its confirmation or revert arrives on the condition stream.") + : new(DataWriteState.DriverConfirmedSuccess, verdict.StatusCode, null); + } + else outcome = new(DataWriteState.RejectedBeforeDispatch, verdict.StatusCode, verdict.Diagnostic); + owner.Complete(outcome); + owner.PhysicalFinished(); + return (FromOutcome(outcome), false); + } + } + + private static DataConditionMethodResult Reject(uint status, string diagnostic) => + new(DataWriteState.RejectedBeforeDispatch, status, diagnostic); + + private static DataConditionMethodResult FromOutcome(DataWriteOutcome outcome) => new(outcome.State, outcome.StatusCode, outcome.Diagnostic); + + /// The call's meaning for duplicate detection: placement, method, expected marker, comment (never the audit text). + private static byte[] SemanticHash(DataConditionMethodRequest request) + { + var a = request.Placement.Address; + var text = string.Join('\0', a.OriginClusterId, a.NamespaceUri, a.IdentifierKind, a.Identifier, + ((int)request.Placement.Realm).ToString(CultureInfo.InvariantCulture), ((uint)request.Method).ToString(CultureInfo.InvariantCulture), + request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence.ToString(CultureInfo.InvariantCulture), + request.Comment is null ? "\u0001" : "\u0002" + request.Comment); + return SHA256.HashData(Encoding.UTF8.GetBytes(text)); + } + + /// + /// §6: the peer's on_behalf_of as the audit log may record it — control (Cc), format (Cf), line/paragraph + /// separator and unpaired surrogate characters removed, then capped at + /// characters without splitting a surrogate pair. + /// Null/empty-after-sanitising ⇒ null. + /// + public static string? SanitizeAuditText(string? text) + { + if (string.IsNullOrEmpty(text)) return null; + var builder = new StringBuilder(Math.Min(text.Length, DataConditionMethodRequest.MaxOnBehalfOfLength)); + for (var i = 0; i < text.Length && builder.Length < DataConditionMethodRequest.MaxOnBehalfOfLength; i++) + { + var c = text[i]; + if (char.IsHighSurrogate(c)) + { + if (i + 1 < text.Length && char.IsLowSurrogate(text[i + 1])) + { + var category = CharUnicodeInfo.GetUnicodeCategory(text, i); + if (category != UnicodeCategory.Format && builder.Length + 2 <= DataConditionMethodRequest.MaxOnBehalfOfLength) + builder.Append(c).Append(text[i + 1]); + i++; + } + continue; + } + if (char.IsLowSurrogate(c)) continue; + switch (CharUnicodeInfo.GetUnicodeCategory(c)) + { + case UnicodeCategory.Control or UnicodeCategory.Format or UnicodeCategory.LineSeparator + or UnicodeCategory.ParagraphSeparator or UnicodeCategory.OtherNotAssigned: continue; + default: builder.Append(c); break; + } + } + return builder.Length == 0 ? null : builder.ToString(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs index d98fac2cd..d00e2f2a6 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs @@ -34,7 +34,11 @@ public sealed partial class LocalDataServices if (!ConditionsServable) return null; var max = catalog is null ? 0 : catalog.MaxConditionsFor(context.PrincipalId); // An ungranted caller learns only that the origin serves conditions, not the limits (cf. H2 review fix 7a). - return new DataConditionCapabilities(RootScopeItems: true, Methods: 0, MaxConditions: max); + // A2b: the methods this caller's exports grant (0 when ungranted or not servable; Primary-only like the bits). + var methods = ConditionMethodsServable && catalog is not null + && string.Equals(catalog.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) + ? DataConditionMethodSets.AllowedBy(catalog.ExportOperations(context.PrincipalId)) : DataConditionMethods.None; + return new DataConditionCapabilities(RootScopeItems: true, Methods: (uint)methods, MaxConditions: max); } /// @@ -69,7 +73,8 @@ public sealed partial class LocalDataServices && current.ConditionLimitFor(context.PrincipalId, root) is not null && _policy.IsCallerUsable(Caller(context)); cached = new ConditionItemScope(current, allowed ? current.ListConditionScope(context.PrincipalId, root, DataOperations.AlarmSubscribe, ConditionKeysSource(), - placement => _policy.AuthorizeLocal(Caller(context), OpcUaOperation.CreateMonitoredItems, placement.Scope)) + placement => _policy.AuthorizeLocal(Caller(context), OpcUaOperation.CreateMonitoredItems, placement.Scope), + methods: ConditionMethodsServable) : null); return cached; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs index 7e3fd7b24..b5345ac8d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -54,7 +54,9 @@ public sealed partial class LocalDataServices : IDataConnectionFactory private DataOperations Implemented(DataTarget target) => DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | (_writes is null ? DataOperations.None : DataOperations.Write) | (HistoryServing is null ? DataOperations.None : DataOperations.HistoryRead) + // A2b: the method bits ride the same servability plus the node manager's method port. | (ConditionsServable ? DataOperations.AlarmSubscribe : DataOperations.None) + | (ConditionMethodsServable ? DataOperationSets.ConditionMethods : DataOperations.None) | (_targetSubscriptions is not null || _subscriptions is not null && target.Mode == DataTargetMode.Node ? DataOperations.Subscribe : DataOperations.None); private DataCallerIdentity Caller(DataAuthenticatedContext context) => _callers.GetValue(context, static value => @@ -88,7 +90,8 @@ public sealed partial class LocalDataServices : IDataConnectionFactory var ready = catalog is not null && Ready(catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch && RoleAllows(target, catalog.Serving); var operations = ready ? catalog!.ExportOperations(context.PrincipalId) & Implemented(target) : DataOperations.None; - if (!string.Equals(expected.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) operations &= ~DataOperations.Write; + if (!string.Equals(expected.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) + operations &= ~(DataOperations.Write | DataOperationSets.ConditionMethods); return expected.Readiness == (ready ? DataReadiness.Ready : DataReadiness.Unavailable) && expected.Operations == operations && _capabilities.Serving == expected.Serving && _policy.IsCallerUsable(Caller(context)) && context.AuthorityEpoch == _policy.AuthorityEpoch; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs index 9d6077ce3..887178e5a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs @@ -139,7 +139,7 @@ public sealed partial class LocalExportCatalog // A1: a native condition's Raw placement is its RawPath (ConditionId = RawPath), under its device/group folder. if (plan.Alarm is not null) conditionPlacements.Add(new(rawView, RawParent(scope), scope, plan.Name, ConditionSourceKind.Native, - new(AddressSpaceRealm.Raw, plan.NodeId), "RawTag", plan.TagId)); + new(AddressSpaceRealm.Raw, plan.NodeId), "RawTag", plan.TagId, driverById[plan.DriverInstanceId].DriverType)); } foreach (var area in areas) { @@ -213,7 +213,8 @@ public sealed partial class LocalExportCatalog var view = new DataView(new(cluster, V3NodeIds.UnsNamespaceUri, "string", reserved), DataRealm.Uns, null, 0, reserved); conditionPlacements.Add(new(view, views[(DataRealm.Uns, "Equipment", owner.EquipmentId.ToUpperInvariant())], DataScopeSubjects.Owned(equipmentScopes[owner.EquipmentId]), effectiveName, ConditionSourceKind.Native, - new(AddressSpaceRealm.Raw, plan.NodeId), "UnsTagReference", reference.UnsTagReferenceId)); + new(AddressSpaceRealm.Raw, plan.NodeId), "UnsTagReference", reference.UnsTagReferenceId, + driverById[plan.DriverInstanceId].DriverType)); } foreach (var alarm in composition.EquipmentScriptedAlarms) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs index fc1533358..fe08e8590 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -22,7 +22,7 @@ public sealed partial class LocalExportCatalog private sealed record ExportRule(string Identity, string Principal, DataRealm Realm, DataView? Root, bool WholeRealm, DataOperations Operations, int Batch, int Page, int Items, int Streams, int HistoryReads = 4, int HistoryValuesPerPage = 10_000, int HistoryResponseBytes = 4 * 1024 * 1024, - int Conditions = 1000); + int Conditions = 1000, bool GalaxyServiceAck = false); public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation, IEnumerable nodes, IEnumerable exports, int maximumNodes = 100_000, @@ -98,7 +98,9 @@ public sealed partial class LocalExportCatalog rules.Add(new(export.DataExportId, export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm, // X0: an export bit this build does not implement grants nothing (a None-after-mask rule is kept and inert). export.AllowedOperations & DataOperationSets.Understood, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams, - export.MaxConcurrentHistoryReads, export.MaxHistoryValuesPerPage, export.MaxHistoryResponseBytes, export.MaxConditions)); + export.MaxConcurrentHistoryReads, export.MaxHistoryValuesPerPage, export.MaxHistoryResponseBytes, export.MaxConditions, + // A2b (§6, Q2): the Galaxy service-ack opt-in counts only with the AlarmAcknowledge grant it qualifies. + export.AllowGalaxyServiceAck && (export.AllowedOperations & DataOperations.AlarmAcknowledge) != 0)); if (UnknownOperationDrops.Unknown(export.AllowedOperations) is var unknown && unknown != DataOperations.None) dropped[export.DataExportId] = unknown; } @@ -281,6 +283,36 @@ public sealed partial class LocalExportCatalog return false; } + /// + /// A2b (§6, Q2): whether holds an export of the placement's realm that grants + /// AlarmAcknowledge on it AND opts in to acknowledging Galaxy-sourced native conditions under the service identity + /// (DataExport.AllowGalaxyServiceAck). + /// + internal bool AllowsGalaxyServiceAck(string principal, LocalConditionPlacement placement) + { + ArgumentNullException.ThrowIfNull(placement); + foreach (var rule in _exports) + { + if (!rule.GalaxyServiceAck || !string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) + || rule.Realm != placement.View.Realm || (rule.Operations & DataOperations.AlarmAcknowledge) == 0) continue; + if (rule.WholeRealm || IsAncestor(rule.Root!, placement.Parent)) return true; + } + return false; + } + + /// A2b: the methods 's exports allow on one placement (kind support, grants and, + /// for a Galaxy-sourced native condition, the service-ack opt-in). Advisory: ingress re-checks everything. + internal DataConditionMethods MethodsFor(string principal, LocalConditionPlacement placement) + { + var supported = placement.SourceKind == ConditionSourceKind.Native ? DataConditionMethodSets.Native : DataConditionMethodSets.Scripted; + var granted = DataConditionMethods.None; + foreach (var operation in new[] { DataOperations.AlarmAcknowledge, DataOperations.AlarmConfirm }) + if (AllowsConditionPlacement(principal, placement, operation)) granted |= DataConditionMethodSets.AllowedBy(operation); + if (placement.IsGalaxy && !AllowsGalaxyServiceAck(principal, placement)) + granted &= ~(DataConditionMethods.Acknowledge | DataConditionMethods.AddComment); + return supported & granted; + } + /// /// A1: the conditions under one export root as a listing presents them to — each with /// its condition_key and only the placements inside , all in the root's realm and each @@ -298,7 +330,7 @@ public sealed partial class LocalExportCatalog /// is never put on the wire. applies a further per-placement check (the origin ACL). /// internal IReadOnlyList ListConditionScope(string principal, DataView root, DataOperations operation, - ConditionKeys keys, Func? placementFilter = null) + ConditionKeys keys, Func? placementFilter = null, bool methods = false) { ArgumentException.ThrowIfNullOrWhiteSpace(principal); ArgumentNullException.ThrowIfNull(root); @@ -310,7 +342,8 @@ public sealed partial class LocalExportCatalog && (placementFilter?.Invoke(p) ?? true)) .GroupBy(p => p.Condition) .Select(g => new ScopedCondition(g.Key, new ExportedCondition(keys.Derive(ClusterId, g.Key.Realm, g.Key.ConditionId), g.First().SourceKind, - Array.AsReadOnly(g.OrderBy(p => p.View.Address.Identifier, StringComparer.Ordinal).Select(p => p.ToView()).ToArray())))) + Array.AsReadOnly(g.OrderBy(p => p.View.Address.Identifier, StringComparer.Ordinal).Select(p => p.ToView()).ToArray())), + methods ? g.Aggregate(DataConditionMethods.None, (m, p) => m | MethodsFor(principal, p)) : DataConditionMethods.None)) .OrderBy(x => x.Exported.ConditionKey, StringComparer.Ordinal) .ToArray(); }