feat(grpc-data): A3b consumer method port — per-caller AlarmAcknowledge/AlarmConfirm gate, mapping timeout, stream serving incarnation, lease condition methods, host wiring

This commit is contained in:
Joseph Doherty
2026-11-24 17:11:05 -05:00
parent c1be5725b9
commit 28098a8d32
4 changed files with 117 additions and 2 deletions
@@ -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;
@@ -524,8 +524,22 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
}
/// <summary>A non-owning handle with the deployed operation and resource policy.</summary>
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDisposable
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDataConditionMethodService, IDisposable
{
/// <summary>
/// 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).
/// </summary>
public Task<DataConditionMethodResult> 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."));
}
/// <summary>
/// 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.
@@ -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;
/// <summary>
/// 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 <c>CallConditionMethod</c> (A2b), addressed by the placement and the serving
/// incarnation of the stream the condition's records arrived on.
/// </summary>
public sealed partial class ProjectedConditionAccess : IProjectedConditionMethods
{
private const uint BadNoCommunication = 0x80310000u;
private const uint BadNotSupported = 0x803D0000u;
private const uint BadUserAccessDenied = 0x801F0000u;
/// <inheritdoc />
public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> 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;
}
/// <inheritdoc />
public async Task<DataConditionMethodResult> 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.");
}
}
}
}
@@ -77,7 +77,7 @@ public enum ProjectedConditionMappingStatus { Pending, Snapshotting, Complete, U
/// <c>BadNoCommunication</c> (one event each) — never "known inactive" (§5.1 T2).</item>
/// </list>
/// </summary>
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;
/// <summary>A3b: the serving identity of the CURRENT condition stream (null while no stream is open).</summary>
public ServingIdentity? Serving => Volatile.Read(ref _serving);
public IReadOnlyDictionary<string, ProjectedConditionMappingStatus> 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();