feat(grpc-data): A2b — CallConditionMethod RPC, origin TryExecuteConditionMethod through the wrapped SDK handler, bits 128/256 understood, Galaxy service-ack rule, operation registry + audit log
This commit is contained in:
@@ -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<string> Methods = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe", "HistoryRead"];
|
||||
private static readonly HashSet<string> Methods = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe", "HistoryRead", "CallConditionMethod"];
|
||||
|
||||
public static bool IsDataRequest(HttpContext context, DataConnectionOptions options) => options.Enabled
|
||||
&& context.Connection.LocalPort == options.ListenPort
|
||||
|
||||
@@ -49,18 +49,19 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
return negotiated;
|
||||
}
|
||||
|
||||
/// <summary>A2: the v1 shape of a capabilities response with respect to conditions: no field 17, no AlarmSubscribe bit.</summary>
|
||||
/// <summary>A2: the v1 shape of a capabilities response with respect to conditions: no field 17, no AlarmSubscribe bit
|
||||
/// and (A2b) no AlarmAcknowledge/AlarmConfirm bit.</summary>
|
||||
internal static void StripConditions(W.CapabilitiesResponse response)
|
||||
{
|
||||
response.Conditions = null;
|
||||
response.Operations &= ~(uint)DataOperations.AlarmSubscribe;
|
||||
response.Operations &= ~(uint)DataOperationSets.ConditionGrants;
|
||||
}
|
||||
|
||||
/// <summary>A2: a metadata item never carries AlarmSubscribe on a call without conditions (it is a root-scope grant).</summary>
|
||||
internal static void StripConditions(W.Metadata? metadata)
|
||||
{
|
||||
if (metadata is null) return;
|
||||
metadata.AllowedOperations &= ~(uint)DataOperations.AlarmSubscribe;
|
||||
metadata.AllowedOperations &= ~(uint)DataOperationSets.ConditionGrants;
|
||||
}
|
||||
|
||||
/// <summary>The v1 shape of a capabilities response: no history field and no HistoryRead bit.</summary>
|
||||
@@ -237,6 +238,29 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
return response;
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A2b remote condition method (plan §5.6). Order: the call negotiated <c>conditions</c> (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 <c>RejectedBeforeDispatch</c> outcome with its status — never retried here.
|
||||
/// </summary>
|
||||
public override Task<W.ConditionMethodResponse> 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;
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
|
||||
@@ -14,6 +14,12 @@ public interface IOriginConditionSource
|
||||
/// <param name="maxConditionsPerHold">The most conditions one Lock hold copies.</param>
|
||||
/// <returns>The slices (at least one, even for an empty scope).</returns>
|
||||
IReadOnlyList<ConditionSnapshotSlice> SnapshotConditions(Func<AddressSpaceRealm, string, bool> scope, int maxConditionsPerHold);
|
||||
|
||||
/// <summary>A2b: see <see cref="OtOpcUaNodeManager.TryExecuteConditionMethod"/> — 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.</summary>
|
||||
/// <param name="call">The call.</param>
|
||||
/// <returns>The verdict.</returns>
|
||||
OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call);
|
||||
}
|
||||
|
||||
/// <summary>Resolves the port against the SDK sink bound at server start; throws while the server is not running.</summary>
|
||||
@@ -26,4 +32,9 @@ public sealed class DeferredOriginConditionSource(DeferredAddressSpaceSink defer
|
||||
public IReadOnlyList<ConditionSnapshotSlice> SnapshotConditions(Func<AddressSpaceRealm, string, bool> scope, int maxConditionsPerHold) =>
|
||||
deferred.GetCapability<IOriginConditionSource>() is { } inner ? inner.SnapshotConditions(scope, maxConditionsPerHold)
|
||||
: throw new InvalidOperationException("The OPC UA server is not running.");
|
||||
|
||||
/// <inheritdoc />
|
||||
public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call) =>
|
||||
deferred.GetCapability<IOriginConditionSource>() is { } inner ? inner.TryExecuteConditionMethod(call)
|
||||
: throw new InvalidOperationException("The OPC UA server is not running.");
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// A2b: one session-less condition method call from a data-connection peer (plan §5.6 "Origin"). Already authorized by
|
||||
/// the caller (the Runtime facade checks the export grant and the origin ACL on the PLACEMENT's subject for the service
|
||||
/// principal); the node manager applies the redundancy, standby, native preflight and activation-marker checks.
|
||||
/// </summary>
|
||||
/// <param name="Realm">The condition's realm key (Raw for a native condition, Uns for a scripted one).</param>
|
||||
/// <param name="ConditionId">The condition id (RawPath / ScriptedAlarmId). Origin-internal; never from the wire.</param>
|
||||
/// <param name="Method">The Part 9 method name: <c>Acknowledge</c>, <c>AddComment</c> or <c>Confirm</c>.</param>
|
||||
/// <param name="Comment">The Part 9 comment, or null.</param>
|
||||
/// <param name="ExpectedActivation">The marker the caller last applied; a different current marker ⇒ <c>BadEventIdUnknown</c>.</param>
|
||||
/// <param name="Principal">The service principal (recorded as the command's <c>User</c> and the condition's <c>ClientUserId</c>).</param>
|
||||
/// <param name="ApiKeyId">The service key's public id (the Galaxy ack identity lookup key, §6).</param>
|
||||
public sealed record OriginConditionMethodCall(AddressSpaceRealm Realm, string ConditionId, string Method, string? Comment,
|
||||
ConditionActivationMarker ExpectedActivation, string Principal, string? ApiKeyId);
|
||||
|
||||
/// <summary>The node manager's verdict on an <see cref="OriginConditionMethodCall"/>.</summary>
|
||||
/// <param name="Applied">True when the node state changed (or a native ack was accepted and routed); false = refused
|
||||
/// before ANY state change, nothing routed or reported.</param>
|
||||
/// <param name="Native">Whether the condition is native (driver-fed): an applied native call is accepted, not confirmed.</param>
|
||||
/// <param name="StatusCode">The OPC UA status (Good when applied).</param>
|
||||
/// <param name="Diagnostic">A refusal's reason text, when the gate gave one.</param>
|
||||
public sealed record OriginConditionMethodOutcome(bool Applied, bool Native, uint StatusCode, string? Diagnostic);
|
||||
|
||||
public sealed partial class OtOpcUaNodeManager
|
||||
{
|
||||
/// <summary>
|
||||
/// A2b (§5.6 Origin): executes one remote condition method through the SAME wrapped SDK method handler a local
|
||||
/// client's call runs (<c>WireMethodTransitionReporting</c> → SDK handler → <see cref="HandleNativeAlarmAck"/> /
|
||||
/// <see cref="HandleAlarmCommand"/>), so neither path goes around the other: one condition event, the native
|
||||
/// Confirmed/Retain re-assert, the non-blocking <see cref="NativeAlarmAckRouter"/> /
|
||||
/// <see cref="AlarmCommandRouter"/> (an unchanged <c>AlarmCommand</c>) and the #760 revert contract all hold.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Runs entirely under <c>Lock</c> and never waits under it (the routers are fire-and-forget). Check order, each
|
||||
/// refusing before any state change: the condition exists; Warm Standby; Primary (both kinds — remote methods are
|
||||
/// Primary-only); method supported (native Confirm ⇒ <c>BadNotSupported</c>); the activation marker (mismatch ⇒
|
||||
/// <c>BadEventIdUnknown</c>: a new occurrence the caller has not seen); then the handler's own native preflight.
|
||||
/// The session gate (<see cref="EvaluateAlarmCommandGate"/>) is skipped ONLY for the condition this call's
|
||||
/// context was created for: the caller authorized it on the placement's subject.
|
||||
/// </remarks>
|
||||
/// <param name="call">The call.</param>
|
||||
/// <returns>The verdict.</returns>
|
||||
public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(call);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(call.ConditionId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(call.Principal);
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// A2b: the system context of one remote condition method call. Carries the service principal (so the SDK records
|
||||
/// it as <c>ClientUserId</c> and the handlers as the command's <c>User</c>) and marks the call as pre-authorized for
|
||||
/// exactly <see cref="Condition"/>. Internal: no OPC UA client can ever present one.
|
||||
/// </summary>
|
||||
private sealed class RemoteConditionMethodContext : ServerSystemContext
|
||||
{
|
||||
public RemoteConditionMethodContext(IServerInternal server, ConditionState condition, RoleCarryingUserIdentity identity)
|
||||
: base(server)
|
||||
{
|
||||
Condition = condition;
|
||||
Identity = identity;
|
||||
UserIdentity = identity;
|
||||
}
|
||||
|
||||
public ConditionState Condition { get; }
|
||||
public RoleCarryingUserIdentity Identity { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The calling identity of an alarm method handler and whether the session gate applies: a
|
||||
/// <see cref="RemoteConditionMethodContext"/> for this very condition was authorized by its caller (§5.6).
|
||||
/// </summary>
|
||||
private static (RoleCarryingUserIdentity? Identity, bool PreAuthorized) AlarmCaller(ISystemContext context, ConditionState condition) =>
|
||||
context is RemoteConditionMethodContext remote && ReferenceEquals(remote.Condition, condition)
|
||||
? (remote.Identity, true)
|
||||
: ((context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity, false);
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -36,6 +36,10 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
|
||||
Func<ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AddressSpaceRealm, string, bool> scope, int maxConditionsPerHold) =>
|
||||
_nodeManager.SnapshotConditions(scope, maxConditionsPerHold);
|
||||
|
||||
/// <inheritdoc />
|
||||
OriginConditionMethodOutcome IOriginConditionSource.TryExecuteConditionMethod(OriginConditionMethodCall call) =>
|
||||
_nodeManager.TryExecuteConditionMethod(call);
|
||||
|
||||
/// <summary>Initializes a new instance of the SdkAddressSpaceSink class.</summary>
|
||||
/// <param name="nodeManager">The OPC UA node manager.</param>
|
||||
public SdkAddressSpaceSink(OtOpcUaNodeManager nodeManager)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -31,9 +31,15 @@ public readonly record struct OriginConditionRef(AddressSpaceRealm Realm, string
|
||||
/// ⚠️ ORIGIN-INTERNAL (carries <see cref="Condition"/>). What may reach a peer is
|
||||
/// <see cref="ConditionPlacementView"/>, via <see cref="LocalExportCatalog.ListConditions"/>.
|
||||
/// </summary>
|
||||
/// <param name="DriverType">A2b: the backing driver's type for a native condition (null for scripted); decides the Galaxy
|
||||
/// service-ack opt-in (§6).</param>
|
||||
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)
|
||||
{
|
||||
/// <summary>A2b: a Galaxy-sourced native condition (remote Acknowledge/AddComment need the export's opt-in).</summary>
|
||||
public bool IsGalaxy => SourceKind == ConditionSourceKind.Native
|
||||
&& string.Equals(DriverType, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DriverTypeNames.Galaxy, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The peer-safe projection: address, parent and name, in the placement's own realm.</summary>
|
||||
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
|
||||
/// (<see cref="Ref"/> names a RawPath for a native condition); only <see cref="Exported"/> may reach a peer.
|
||||
/// </summary>
|
||||
internal sealed record ScopedCondition(OriginConditionRef Ref, ExportedCondition Exported);
|
||||
/// <param name="Methods">A2b: the methods the listing principal may call on it (0 when methods are not servable).</param>
|
||||
internal sealed record ScopedCondition(OriginConditionRef Ref, ExportedCondition Exported, DataConditionMethods Methods = DataConditionMethods.None);
|
||||
|
||||
@@ -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<DataValueKind>().Where(x => x != DataValueKind.Unspecified).ToHashSet(),
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Strictly caller-bound local data facade; it creates no namespace projection.</summary>
|
||||
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
|
||||
/// <inheritdoc />
|
||||
public Task ReleaseForTransportAsync(IReadOnlyList<byte[]> continuations, DataHistoryChannel channel, CancellationToken cancellationToken)
|
||||
{ Check(); return _services.ReleaseHistoryAsync(_context, continuations, channel, cancellationToken); }
|
||||
/// <summary>A2b: one remote condition method (plan §5.6 origin), bound to this facade's caller.</summary>
|
||||
public Task<DataConditionMethodResult> 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);
|
||||
|
||||
+223
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// A2b: one entry of the origin's data-connection audit log (plan §6 "Audit"). <see cref="OnBehalfOf"/> is the peer's
|
||||
/// untrusted text AFTER <see cref="LocalDataServices.SanitizeAuditText"/>; it goes here and nowhere else (never into
|
||||
/// <c>AlarmCommand</c>, <c>ClientUserId</c> or alarm history).
|
||||
/// </summary>
|
||||
public sealed record DataConditionMethodAuditEntry(DateTimeOffset TimeUtc, string Principal, string? ApiKeyId, DataView Placement,
|
||||
string OperationId, DataConditionMethods Method, DataWriteState State, uint StatusCode, bool Joined, string? OnBehalfOf);
|
||||
|
||||
/// <summary>A2b: the origin's data-connection audit log.</summary>
|
||||
public interface IDataConnectionAuditLog
|
||||
{
|
||||
/// <summary>Records one condition method call's outcome. Must not block or throw.</summary>
|
||||
void RecordConditionMethod(DataConditionMethodAuditEntry entry);
|
||||
}
|
||||
|
||||
/// <summary>The default audit log: structured entries on a dedicated logger category.</summary>
|
||||
public sealed class LoggerDataConnectionAuditLog(ILogger logger) : IDataConnectionAuditLog
|
||||
{
|
||||
/// <summary>The logger category operators route to the audit sink.</summary>
|
||||
public const string Category = "ZB.MOM.WW.OtOpcUa.DataConnections.Audit";
|
||||
|
||||
/// <inheritdoc />
|
||||
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 ?? "-");
|
||||
}
|
||||
|
||||
/// <summary>A2b: the origin side of <c>CallConditionMethod</c> (plan §5.6 "Origin", §6).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>A2b: the data-connection audit log (default: <see cref="LoggerDataConnectionAuditLog"/> over <see cref="Logger"/>).</summary>
|
||||
public IDataConnectionAuditLog Audit { get => _audit ??= new LoggerDataConnectionAuditLog(Logger); init => _audit = value; }
|
||||
|
||||
/// <summary>A2b: how long a completed operation id is remembered (a duplicate within it joins the stored outcome).</summary>
|
||||
public TimeSpan ConditionMethodRetention { get; init; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>Whether this origin serves remote condition methods: the condition port is up (same as streaming).</summary>
|
||||
internal bool ConditionMethodsServable => ConditionsServable;
|
||||
|
||||
/// <summary>The duplicate-protection registry of the current serving incarnation (a new incarnation starts empty).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Executes one remote condition method (§5.6). Order, each refusal <see cref="DataWriteState.RejectedBeforeDispatch"/>
|
||||
/// with no state change: servable; catalog ready; <b>Primary</b> (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 <c>BadNodeIdUnknown</c> — existence is not disclosed); the origin ACL on the placement's subject
|
||||
/// (<c>BadUserAccessDenied</c>); native Confirm (<c>BadNotSupported</c>); the Galaxy service-ack opt-in
|
||||
/// (<c>BadUserAccessDenied</c>); then the operation registry (a duplicate id joins) and the node manager (Warm
|
||||
/// Standby, Primary, activation marker, native preflight). Never retried.
|
||||
/// </summary>
|
||||
internal async Task<DataConditionMethodResult> 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<string, object?>("method", request.Method.ToString()),
|
||||
new KeyValuePair<string, object?>("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);
|
||||
|
||||
/// <summary>The call's meaning for duplicate detection: placement, method, expected marker, comment (never the audit text).</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// §6: the peer's <c>on_behalf_of</c> as the audit log may record it — control (Cc), format (Cf), line/paragraph
|
||||
/// separator and unpaired surrogate characters removed, then capped at
|
||||
/// <see cref="DataConditionMethodRequest.MaxOnBehalfOfLength"/> characters without splitting a surrogate pair.
|
||||
/// Null/empty-after-sanitising ⇒ null.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
+3
-2
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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<LocalDataNode> nodes, IEnumerable<DataExport> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A2b (§6, Q2): whether <paramref name="principal"/> 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
|
||||
/// (<c>DataExport.AllowGalaxyServiceAck</c>).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A2b: the methods <paramref name="principal"/>'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.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A1: the conditions under one export root as a listing presents them to <paramref name="principal"/> — each with
|
||||
/// its <c>condition_key</c> and only the placements inside <paramref name="root"/>, all in the root's realm and each
|
||||
@@ -298,7 +330,7 @@ public sealed partial class LocalExportCatalog
|
||||
/// is never put on the wire. <paramref name="placementFilter"/> applies a further per-placement check (the origin ACL).
|
||||
/// </summary>
|
||||
internal IReadOnlyList<ScopedCondition> ListConditionScope(string principal, DataView root, DataOperations operation,
|
||||
ConditionKeys keys, Func<LocalConditionPlacement, bool>? placementFilter = null)
|
||||
ConditionKeys keys, Func<LocalConditionPlacement, bool>? 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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user