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:
@@ -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) ----
|
||||
|
||||
/// <summary>Encodes a condition method request.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="ArgumentException"/> ⇒ INVALID_ARGUMENT. <c>on_behalf_of</c> is NOT
|
||||
/// refused for its content: it is untrusted audit text the origin caps and sanitises (§6).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Encodes a condition method response.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Decodes a condition method response (an unknown state is an <see cref="ArgumentException"/>).</summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -254,6 +254,11 @@ public static class OtOpcUaTelemetry
|
||||
Meter.CreateCounter<long>("otopcua.dataconn.conditions.capacity_rejections", unit: "{item}",
|
||||
description: "Root-scoped condition items over their MaxConditions at snapshot begin.");
|
||||
|
||||
/// <summary>A2b: remote condition method calls served by this origin, by method and outcome (plan §6 metrics; no ids).</summary>
|
||||
public static readonly Counter<long> DataConnConditionMethods =
|
||||
Meter.CreateCounter<long>("otopcua.dataconn.condition_methods", unit: "{call}",
|
||||
description: "Remote condition method calls served by this origin (tags: method, outcome).");
|
||||
|
||||
/// <summary>A1 (G3): deferred MarkConditionsKnown discarded because an alarm projection of the same source did not land.</summary>
|
||||
public static readonly Counter<long> DataConnConditionMarksDiscarded =
|
||||
Meter.CreateCounter<long>("otopcua.dataconn.conditions.marks_discarded", unit: "{mark}",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+117
@@ -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<DataConditionState> 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.
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// The remote condition methods. The values are wire values: <c>ConditionMethodRequest.method</c> carries exactly one,
|
||||
/// <c>ConditionCapabilities.methods</c> and <c>ConditionInfo.supported_methods</c> a mask. Never renumber.
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum DataConditionMethods : uint
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>Part 9 Acknowledge (grant <see cref="DataOperations.AlarmAcknowledge"/>).</summary>
|
||||
Acknowledge = 1,
|
||||
/// <summary>Part 9 AddComment (grant <see cref="DataOperations.AlarmAcknowledge"/>).</summary>
|
||||
AddComment = 2,
|
||||
/// <summary>Part 9 Confirm (grant <see cref="DataOperations.AlarmConfirm"/>; scripted conditions only).</summary>
|
||||
Confirm = 4,
|
||||
}
|
||||
|
||||
/// <summary>A2b: the one authority mapping a condition method onto its grant (M8, mirrors <c>AlarmOperationFor</c>).</summary>
|
||||
public static class DataConditionMethodSets
|
||||
{
|
||||
/// <summary>Every method this build implements.</summary>
|
||||
public const DataConditionMethods All = DataConditionMethods.Acknowledge | DataConditionMethods.AddComment | DataConditionMethods.Confirm;
|
||||
|
||||
/// <summary>What a native (driver-fed) condition supports: Confirm has no upstream path (<c>BadNotSupported</c>).</summary>
|
||||
public const DataConditionMethods Native = DataConditionMethods.Acknowledge | DataConditionMethods.AddComment;
|
||||
|
||||
/// <summary>What a scripted condition supports.</summary>
|
||||
public const DataConditionMethods Scripted = All;
|
||||
|
||||
/// <summary>The data operation a method requires.</summary>
|
||||
public static DataOperations OperationFor(DataConditionMethods method) => method switch
|
||||
{
|
||||
DataConditionMethods.Confirm => DataOperations.AlarmConfirm,
|
||||
DataConditionMethods.Acknowledge or DataConditionMethods.AddComment => DataOperations.AlarmAcknowledge,
|
||||
_ => DataOperations.None,
|
||||
};
|
||||
|
||||
/// <summary>The methods a grant set allows.</summary>
|
||||
public static DataConditionMethods AllowedBy(DataOperations operations) =>
|
||||
((operations & DataOperations.AlarmAcknowledge) != 0 ? DataConditionMethods.Acknowledge | DataConditionMethods.AddComment : DataConditionMethods.None)
|
||||
| ((operations & DataOperations.AlarmConfirm) != 0 ? DataConditionMethods.Confirm : DataConditionMethods.None);
|
||||
|
||||
/// <summary>Whether <paramref name="method"/> names exactly one implemented method.</summary>
|
||||
public static bool IsSingle(DataConditionMethods method) =>
|
||||
method is DataConditionMethods.Acknowledge or DataConditionMethods.AddComment or DataConditionMethods.Confirm;
|
||||
|
||||
/// <summary>The Part 9 method name (the operation name the node manager and <c>AlarmOperationFor</c> use).</summary>
|
||||
public static string Part9Name(DataConditionMethods method) => method switch
|
||||
{
|
||||
DataConditionMethods.Acknowledge => "Acknowledge",
|
||||
DataConditionMethods.AddComment => "AddComment",
|
||||
DataConditionMethods.Confirm => "Confirm",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(method)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One remote condition method call (<c>ConditionMethodRequest</c>).
|
||||
/// </summary>
|
||||
/// <param name="OperationId">Caller-chosen id; a duplicate (same principal) joins the first call (§5.6 step 5).</param>
|
||||
/// <param name="Placement">A realm-local placement address of the condition (from a listing), never a condition key.</param>
|
||||
/// <param name="Method">Exactly one method.</param>
|
||||
/// <param name="ExpectedActivation">The activation marker of the latest record the caller applied (T3).</param>
|
||||
/// <param name="Comment">The Part 9 comment, or null.</param>
|
||||
/// <param name="ExpectedServingIncarnation">The serving incarnation the caller selected (a restarted origin refuses).</param>
|
||||
/// <param name="RemainingBudget">What is left of the caller's deadline; ≤ 0 is refused before dispatch.</param>
|
||||
/// <param name="OnBehalfOf">Untrusted audit text: capped, sanitised, written only to the origin's audit log (§6).</param>
|
||||
public sealed record DataConditionMethodRequest(string OperationId, DataView Placement, DataConditionMethods Method,
|
||||
DataActivationMarker ExpectedActivation, string? Comment, string ExpectedServingIncarnation, TimeSpan RemainingBudget,
|
||||
string? OnBehalfOf = null)
|
||||
{
|
||||
/// <summary>The most characters of <see cref="OnBehalfOf"/> the origin keeps (§6).</summary>
|
||||
public const int MaxOnBehalfOfLength = 128;
|
||||
/// <summary>The most characters of an operation id.</summary>
|
||||
public const int MaxOperationIdLength = 128;
|
||||
/// <summary>The most characters of a comment (a Part 9 LocalizedText, bounded like a value string).</summary>
|
||||
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.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The answer to one condition method call (<c>ConditionMethodResponse</c>). <see cref="State"/> reuses the write
|
||||
/// outcome states: <see cref="DataWriteState.RejectedBeforeDispatch"/> = refused before any state change (status says
|
||||
/// why); <see cref="DataWriteState.DriverConfirmedSuccess"/> = applied at the origin (scripted);
|
||||
/// <see cref="DataWriteState.AcceptedUnconfirmed"/> = applied and routed to the driver, whose confirmation (or revert)
|
||||
/// arrives on the condition stream (native); <see cref="DataWriteState.OutcomeUnknown"/> = the transport failed after
|
||||
/// the request was sent (never retried).
|
||||
/// </summary>
|
||||
public sealed record DataConditionMethodResult(DataWriteState State, uint StatusCode, string? Diagnostic, ServingIdentity? Serving = null)
|
||||
{
|
||||
public void Validate() => DataContractValidation.Required(State);
|
||||
}
|
||||
|
||||
/// <summary>A2b: remote condition methods (<c>CallConditionMethod</c>), bound to the caller of the containing facade.</summary>
|
||||
public interface IDataConditionMethodService
|
||||
{
|
||||
/// <summary>Calls one method. Never retried: a duplicate <see cref="DataConditionMethodRequest.OperationId"/> joins.</summary>
|
||||
Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -239,9 +239,9 @@ public sealed record DataBudget(TimeSpan Timeout, int MaxItems, long MaxBytes)
|
||||
HistoryRead = 32,
|
||||
/// <summary>A2: root-scoped condition items (origin-side grant; plan §5.5).</summary>
|
||||
AlarmSubscribe = 64,
|
||||
/// <summary>Reserved (A2): Acknowledge and AddComment.</summary>
|
||||
/// <summary>A2b: remote condition Acknowledge and AddComment (<c>CallConditionMethod</c>; plan §5.6).</summary>
|
||||
AlarmAcknowledge = 128,
|
||||
/// <summary>Reserved (A2): Confirm.</summary>
|
||||
/// <summary>A2b: remote condition Confirm.</summary>
|
||||
AlarmConfirm = 256,
|
||||
/// <summary>Reserved for the deferred shelve methods.</summary>
|
||||
AlarmShelve = 512,
|
||||
@@ -255,13 +255,17 @@ public static class DataOperationSets
|
||||
/// <summary>
|
||||
/// What tolerant readers keep; every other bit is dropped fail-closed. Grows only in the phase that implements
|
||||
/// a bit (H2 added <see cref="DataOperations.HistoryRead"/>; A2a <see cref="DataOperations.AlarmSubscribe"/>; A2b
|
||||
/// the method bits).
|
||||
/// the method bits <see cref="DataOperations.AlarmAcknowledge"/> and <see cref="DataOperations.AlarmConfirm"/>).
|
||||
/// </summary>
|
||||
public const DataOperations Understood = V1 | DataOperations.HistoryRead | DataOperations.AlarmSubscribe;
|
||||
public const DataOperations Understood = V1 | DataOperations.HistoryRead | ConditionGrants;
|
||||
/// <summary>Bits reserved by X0 that no phase has implemented yet (H2 took <see cref="DataOperations.HistoryRead"/> out,
|
||||
/// A2a <see cref="DataOperations.AlarmSubscribe"/>).</summary>
|
||||
public const DataOperations Reserved =
|
||||
DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm | DataOperations.AlarmShelve;
|
||||
/// A2a <see cref="DataOperations.AlarmSubscribe"/>, A2b the Acknowledge/Confirm method bits).</summary>
|
||||
public const DataOperations Reserved = DataOperations.AlarmShelve;
|
||||
/// <summary>A2b: the remote condition-method grants (<c>CallConditionMethod</c>).</summary>
|
||||
public const DataOperations ConditionMethods = DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm;
|
||||
/// <summary>A2: every grant that travels only with the negotiated <c>conditions</c> feature (field 17): the
|
||||
/// root-scoped item grant and the method grants. A header-less call never sees any of them.</summary>
|
||||
public const DataOperations ConditionGrants = DataOperations.AlarmSubscribe | ConditionMethods;
|
||||
}
|
||||
/// <summary>
|
||||
/// Optional per-call protocol features negotiated through the <c>x-otopcua-data-features</c> request header.
|
||||
|
||||
@@ -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