From 28098a8d32ce1556bab4b3ad5ab897383689d26e Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:11:05 -0500 Subject: [PATCH] =?UTF-8?q?feat(grpc-data):=20A3b=20consumer=20method=20po?= =?UTF-8?q?rt=20=E2=80=94=20per-caller=20AlarmAcknowledge/AlarmConfirm=20g?= =?UTF-8?q?ate,=20mapping=20timeout,=20stream=20serving=20incarnation,=20l?= =?UTF-8?q?ease=20condition=20methods,=20host=20wiring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../OpcUa/OtOpcUaServerHostedService.cs | 2 + .../DataConnectionDeploymentRuntime.cs | 16 +++- .../ProjectedConditionAccess.Methods.cs | 93 +++++++++++++++++++ .../ProjectedConditionAccess.cs | 8 +- 4 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index 614744bd3..5175283e4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -278,6 +278,8 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl _server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess; // A3: imported conditions — the gate/demand into the node manager, the node manager as the runtime's sink. _server.NodeManager.ProjectedConditionAccess = _projectedConditionAccess; + // A3b (§5.6): remote condition methods go through the same condition runtime (its per-caller method gate + the lease). + _server.NodeManager.ProjectedConditionMethods = _projectedConditionAccess as ZB.MOM.WW.OtOpcUa.OpcUaServer.IProjectedConditionMethods; if (_projectedConditionAccess is ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedConditionAccess conditions) conditions.Sink = _server.NodeManager; _server.NodeManager.ConditionStateSink = _conditionStateSink; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 307f0e3b0..6a2a904df 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -524,8 +524,22 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable } /// A non-owning handle with the deployed operation and resource policy. -public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDisposable +public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDataConditionMethodService, IDisposable { + /// + /// A3b: a remote condition method through the deployed connection — needs the row's AlarmAcknowledge / AlarmConfirm + /// bit (refused unsent otherwise) and an inner connection that serves methods. The outcome is passed through untouched + /// (no post-check: once sent, an answer is the only truth about whether the origin applied it). + /// + public Task CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + Check(DataConditionMethodSets.OperationFor(request.Method)); + return _inner is IDataConditionMethodService methods + ? methods.CallConditionMethodAsync(request, cancellationToken) + : Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, 0x803D0000u, "The connection does not serve condition methods.")); + } + /// /// H2 remote history through the deployed connection: needs the connection row's HistoryRead bit (masked to the /// understood set) and an inner connection that implements history; otherwise every item is unsupported. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs new file mode 100644 index 000000000..9583eb9f5 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs @@ -0,0 +1,93 @@ +using Microsoft.Extensions.Logging; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// A3b (plan §5.6): the consumer's remote condition method port. The gate is per LOCAL caller (the condition stream runs +/// under the connection's service principal, so nothing it carries authorizes a local session); the call goes through the +/// deployed connection lease to the origin's CallConditionMethod (A2b), addressed by the placement and the serving +/// incarnation of the stream the condition's records arrived on. +/// +public sealed partial class ProjectedConditionAccess : IProjectedConditionMethods +{ + private const uint BadNoCommunication = 0x80310000u; + private const uint BadNotSupported = 0x803D0000u; + private const uint BadUserAccessDenied = 0x801F0000u; + + /// + public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList placements, + DataConditionMethods method) + { + if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || placements is null || placements.Count == 0 + || !DataConditionMethodSets.IsSingle(method)) return null; + var required = DataConditionMethodSets.OperationFor(method); + var operation = method == DataConditionMethods.Confirm ? OpcUaOperation.AlarmConfirm : OpcUaOperation.AlarmAcknowledge; + var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + var current = _mappings.Current; + foreach (var placement in placements) + { + var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, placement.MappingId, StringComparison.OrdinalIgnoreCase)); + if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || mapping.Mapping.Realm != placement.Realm + || (mapping.Mapping.AllowedOperations & required) != required) continue; + if (!TryFolderScope(mapping, placement.FolderLocalSubject, out var scope)) continue; + try + { + // AuthorizeLocal re-checks the caller's key (usable, version, expiry: #563) on every call. + if (_policy.AuthorizeLocal(identity, operation, scope)) + return new ImportedConditionMethodRoute(placement, + TimeSpan.FromMilliseconds(Math.Max(1, mapping.Mapping.ConditionMethodTimeoutMilliseconds))); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { } + } + return null; + } + + /// + public async Task CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(call); + ServingIdentity? serving; + lock (_gate) serving = _runners.TryGetValue(call.ConnectionId, out var runner) ? runner.Serving : null; + // No open condition stream ⇒ no serving incarnation to address: the connection is down for this purpose. Nothing sent. + if (serving is null) + return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "No condition stream is open on the connection."); + + IGrpcDataAdapterConnectionLease? lease; + try { lease = await _connections.AcquireAsync(call.ConnectionId, cancellationToken).ConfigureAwait(false); } + catch (Exception ex) when (ex is InvalidOperationException or OperationCanceledException or TimeoutException) + { return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "The connection is unavailable."); } + if (lease is null) return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "The connection is unavailable."); + await using (lease.ConfigureAwait(false)) + { + if (lease.Connection is not IDataConditionMethodService methods) + return new(DataWriteState.RejectedBeforeDispatch, BadNotSupported, "The connection does not serve condition methods."); + var request = new DataConditionMethodRequest(call.OperationId, call.Placement.Placement, call.Method, call.ExpectedActivation, + call.Comment, serving.Incarnation, call.RemainingBudget, call.OnBehalfOf); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lease.CancellationToken); + try + { + var result = await methods.CallConditionMethodAsync(request, linked.Token).ConfigureAwait(false); + if (result.State == DataWriteState.OutcomeUnknown) + _log.LogWarning("Imported condition method {Method} on {Connection}/{Key} (op {Operation}): outcome unknown — {Diagnostic}", + call.Method, call.ConnectionId, call.ConditionKey, call.OperationId, result.Diagnostic); + return result; + } + catch (UnauthorizedAccessException) + { + // The deployed connection row does not enable the method's operation: refused by the lease, nothing sent. + return new(DataWriteState.RejectedBeforeDispatch, BadUserAccessDenied, "The connection does not allow this condition method."); + } + catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException + || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + { + // The lease's own scope check (connection no longer ready / disposed) refuses before anything is sent. + return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "The connection is no longer ready."); + } + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 182bbca6d..482d45f2a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -77,7 +77,7 @@ public enum ProjectedConditionMappingStatus { Pending, Snapshotting, Complete, U /// BadNoCommunication (one event each) — never "known inactive" (§5.1 T2). /// /// -public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDisposable +public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess, IDisposable { private readonly IProjectedConditionMappings _mappings; private readonly IGrpcDataAdapterConnectionSource _connections; @@ -315,6 +315,9 @@ public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDispo public string Signature { get; } public int Barriers => Volatile.Read(ref _barriers); + private ServingIdentity? _serving; + /// A3b: the serving identity of the CURRENT condition stream (null while no stream is open). + public ServingIdentity? Serving => Volatile.Read(ref _serving); public IReadOnlyDictionary Statuses { @@ -333,6 +336,7 @@ public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDispo public void Stop(bool removeConditions) { _stop.Cancel(); + Volatile.Write(ref _serving, null); _stale?.Dispose(); if (!removeConditions) return; _ = _loop.ContinueWith(_ => @@ -355,6 +359,7 @@ public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDispo { _owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", _connectionId); } + finally { Volatile.Write(ref _serving, null); } // §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead. ArmStale(); OtOpcUaTelemetry.DataConnConditionResyncs.Add(1); @@ -400,6 +405,7 @@ public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDispo catch (Exception ex) when (ex is not OperationCanceledException) { } await using var subscription = await connection.SubscribeAsync(token).ConfigureAwait(false); + Volatile.Write(ref _serving, (subscription as IDataSubscriptionProvenance)?.Serving); var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N"); var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); var items = states.Select(x => new DataSubscriptionItem(x.MappingId, x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray();