feat(grpc-data): A2a — origin condition streaming: root-scoped items over the A1 hub, priority queue, host negotiation, consumer decode
This commit is contained in:
@@ -179,7 +179,9 @@ public static class DataConnectionRegistration
|
||||
128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5)),
|
||||
// H2: remote history over the node manager's history port, resolved once the SDK server is up.
|
||||
new DeferredOriginHistoryPort(sp.GetRequiredService<DeferredAddressSpaceSink>()), LoggerFor<LocalDataServices>(sp),
|
||||
sp.GetRequiredService<DataConnectionHistoryDiagnostics>());
|
||||
sp.GetRequiredService<DataConnectionHistoryDiagnostics>(),
|
||||
// A2: root-scoped condition items over the A1 hub and the node manager's snapshot port.
|
||||
sp.GetService<ConditionStateHub>(), new DeferredOriginConditionSource(sp.GetRequiredService<DeferredAddressSpaceSink>()));
|
||||
});
|
||||
services.AddSingleton<IDataConnectionFactory>(sp => new DeferredFactory(() => sp.GetRequiredService<LocalDataRuntimeComposition>().Services));
|
||||
services.AddSingleton<DataConnectionSecretChangeHandler>();
|
||||
|
||||
@@ -21,7 +21,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
/// a call only when the header asked for it, this server supports it AND the origin can serve it (history: the
|
||||
/// connection's capabilities carry <see cref="DataCapabilities.History"/>). A header-less call keeps v1 shapes exactly.
|
||||
/// </summary>
|
||||
internal static DataFeatures SupportedFeatures => DataFeatures.History;
|
||||
internal static DataFeatures SupportedFeatures => DataFeatures.History | DataFeatures.Conditions;
|
||||
|
||||
/// <summary>
|
||||
/// Whether this call negotiated history against <paramref name="caps"/>. Refines the recorded effective set: an
|
||||
@@ -36,6 +36,33 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
return negotiated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A2: whether this call negotiated conditions against <paramref name="caps"/> (the origin serves them: the connection's
|
||||
/// capabilities carry <see cref="DataCapabilities.Conditions"/>). Refines the recorded effective set like history.
|
||||
/// </summary>
|
||||
internal static bool ConditionsNegotiated(ServerCallContext context, DataCapabilities caps)
|
||||
{
|
||||
var features = CallFeatures(context);
|
||||
var negotiated = (features.Effective & DataFeatures.Conditions) != 0 && caps.Conditions is not null;
|
||||
if (!negotiated && (features.Effective & DataFeatures.Conditions) != 0)
|
||||
context.UserState[typeof(DataCallFeatures)] = features with { Effective = features.Effective & ~DataFeatures.Conditions };
|
||||
return negotiated;
|
||||
}
|
||||
|
||||
/// <summary>A2: the v1 shape of a capabilities response with respect to conditions: no field 17, no AlarmSubscribe bit.</summary>
|
||||
internal static void StripConditions(W.CapabilitiesResponse response)
|
||||
{
|
||||
response.Conditions = null;
|
||||
response.Operations &= ~(uint)DataOperations.AlarmSubscribe;
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
|
||||
/// <summary>The v1 shape of a capabilities response: no history field and no HistoryRead bit.</summary>
|
||||
internal static void StripHistory(W.CapabilitiesResponse response)
|
||||
{
|
||||
@@ -79,6 +106,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
var response = DataProtoMapper.EncodeCapabilities(capabilities with
|
||||
{ ProtocolMinor = Math.Max(3, capabilities.ProtocolMinor), ResponseServingIdentity = true, SubscriptionAgeReadiness = true });
|
||||
if (!HistoryNegotiated(context, capabilities)) StripHistory(response);
|
||||
if (!ConditionsNegotiated(context, capabilities)) StripConditions(response);
|
||||
CheckSize(response);
|
||||
var current = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false);
|
||||
if (!authenticator.IsCurrent(caller) || current.Serving != capabilities.Serving
|
||||
@@ -98,6 +126,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
var result = await connection.BrowseAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false);
|
||||
var response = DataProtoMapper.EncodeBrowseResponse(result);
|
||||
if (!HistoryNegotiated(context, caps)) foreach (var item in response.Items) StripHistory(item);
|
||||
if (!ConditionsNegotiated(context, caps)) foreach (var item in response.Items) StripConditions(item);
|
||||
response.Serving = DataProtoMapper.EncodeServing(caps.Serving);
|
||||
CheckSize(response);
|
||||
Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving));
|
||||
@@ -112,6 +141,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
var result = await connection.GetMetadataAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false);
|
||||
var response = DataProtoMapper.EncodeMetadataResponse(result);
|
||||
if (!HistoryNegotiated(context, caps)) foreach (var item in response.Items) StripHistory(item.Value);
|
||||
if (!ConditionsNegotiated(context, caps)) foreach (var item in response.Items) StripConditions(item.Value);
|
||||
response.Serving = DataProtoMapper.EncodeServing(caps.Serving);
|
||||
CheckSize(response);
|
||||
Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving));
|
||||
@@ -252,9 +282,16 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
using (var initial = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken))
|
||||
{
|
||||
initial.CancelAfter(_options.UnaryTimeout);
|
||||
caps = await Ready(connection, DataOperations.Subscribe, initial.Token).ConfigureAwait(false);
|
||||
caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, initial.Token).ConfigureAwait(false);
|
||||
if (caps.Readiness != DataReadiness.Ready) throw Unavailable();
|
||||
}
|
||||
HistoryNegotiated(context, caps); // records the effective set; no stream frame carries history in H2
|
||||
// A2: condition items (frame arm 9) exist only on a stream that negotiated `conditions`. A stream that did not
|
||||
// has every condition_scope stripped before decode, so the session can never produce arm 9 for it.
|
||||
var conditions = ConditionsNegotiated(context, caps);
|
||||
if (!caps.Operations.HasFlag(DataOperations.Subscribe)
|
||||
&& !(conditions && caps.Operations.HasFlag(DataOperations.AlarmSubscribe)))
|
||||
throw new RpcException(new Status(StatusCode.PermissionDenied, "Data operation denied."));
|
||||
var codecHeaders = context.RequestHeaders.Where(entry => string.Equals(entry.Key, DataConnectionProtoContract.CompactCodecHeader, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
if (codecHeaders.Length > 1 || codecHeaders.Length == 1 &&
|
||||
(codecHeaders[0].IsBinary || codecHeaders[0].Value != "1"))
|
||||
@@ -267,7 +304,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
throw new RpcException(new Status(StatusCode.Unavailable, "Subscription transport is unavailable."));
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken);
|
||||
var sink = new GrpcDeliverySink(responses, context, caps, _options.MaxMessageBytes, compact,
|
||||
() => CanPublish(connection, caller, caps.Serving));
|
||||
() => CanPublish(connection, caller, caps.Serving), conditions);
|
||||
var delivery = transport.RunDeliveryAsync(sink, stop.Token);
|
||||
var commands = ReceiveCommands();
|
||||
try { await await Task.WhenAny(delivery, commands).ConfigureAwait(false); }
|
||||
@@ -285,6 +322,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
while (await requests.MoveNext(stop.Token).ConfigureAwait(false))
|
||||
{
|
||||
if (!CanPublish(connection, caller, caps.Serving)) throw Unavailable();
|
||||
if (!conditions) StripConditionScopes(requests.Current);
|
||||
var command = DataProtoMapper.DecodeCommand(requests.Current, limits);
|
||||
var ack = command.AcknowledgementTimeout <= _options.StreamCommandTimeout
|
||||
? command.AcknowledgementTimeout : _options.StreamCommandTimeout;
|
||||
@@ -312,8 +350,19 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
catch (OperationCanceledException) { throw new RpcException(new Status(StatusCode.Cancelled, "Data stream canceled.")); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A2: a header-less stream keeps the v1 shape — a v1 server ignores the unknown field 4 of SubscriptionItem, so the
|
||||
/// item is decoded as the plain value item it would be on v1.
|
||||
/// </summary>
|
||||
internal static void StripConditionScopes(W.SubscriptionCommand command)
|
||||
{
|
||||
var items = command.Open?.Items ?? command.Add?.Items ?? command.Modify?.Items;
|
||||
if (items is null) return;
|
||||
foreach (var item in items) item.ConditionScope = null;
|
||||
}
|
||||
|
||||
private sealed class GrpcDeliverySink(IServerStreamWriter<W.SubscriptionFrame> writer, ServerCallContext context,
|
||||
DataCapabilities caps, int maximumBytes, bool compact, Func<bool> hostGuard) : IDataSubscriptionDeliverySink
|
||||
DataCapabilities caps, int maximumBytes, bool compact, Func<bool> hostGuard, bool conditions = false) : IDataSubscriptionDeliverySink
|
||||
{
|
||||
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
|
||||
CancellationToken cancellationToken)
|
||||
@@ -328,12 +377,23 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
|
||||
DataSubscriptionAck ack => ack.Items.Aggregate(charge, (sum, item) => checked(sum + 2048L
|
||||
+ 4L * (item.ClientItemId.Length + (item.Diagnostic?.Length ?? 0)))),
|
||||
DataSubscriptionControl control => checked(charge + 128L * control.Watermarks.Count + 4L * (control.Diagnostic?.Length ?? 0)),
|
||||
// A2: never on a stream that did not negotiate conditions (v1 clients fault on an unknown arm).
|
||||
DataSubscriptionConditions states when conditions => states.Items.Aggregate(charge, (sum, item) => checked(sum + 2048L
|
||||
+ 4L * (item.ConditionKey.Length + item.Message.Length + (item.Comment?.Length ?? 0) + (item.ClientUserId?.Length ?? 0)
|
||||
+ (item.Activation?.Incarnation.Length ?? 0)
|
||||
+ (item.Info is { } info ? info.ConditionType.Length + info.ConditionName.Length
|
||||
+ info.Placements.Sum(p => 256 + p.Subject.Length + p.Address.Identifier.Length + p.Address.NamespaceUri.Length
|
||||
+ p.Address.OriginClusterId.Length) : 0)))),
|
||||
_ => throw new ArgumentException("Unsupported subscription frame.")
|
||||
};
|
||||
if (charge > reservedBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Prepared frame exceeds its reservation."));
|
||||
var wire = frame is DataSubscriptionValues valuesFrame
|
||||
? DataProtoMapper.EncodeValues(valuesFrame, compactNegotiated: compact && valuesFrame.Items.Count > 0, subscriptionAgeReadiness: true)
|
||||
: DataProtoMapper.EncodeControlOrAck(frame);
|
||||
var wire = frame switch
|
||||
{
|
||||
DataSubscriptionValues valuesFrame =>
|
||||
DataProtoMapper.EncodeValues(valuesFrame, compactNegotiated: compact && valuesFrame.Items.Count > 0, subscriptionAgeReadiness: true),
|
||||
DataSubscriptionConditions states => DataConditionProtoMapper.EncodeFrame(states),
|
||||
_ => DataProtoMapper.EncodeControlOrAck(frame),
|
||||
};
|
||||
wire.Serving = DataProtoMapper.EncodeServing(caps.Serving);
|
||||
if (wire.CalculateSize() > maximumBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Stream message exceeds transport limits."));
|
||||
var payload = wire.ToByteArray();
|
||||
|
||||
@@ -41,6 +41,9 @@ public readonly record struct ConditionActivationMarker(string Incarnation, ulon
|
||||
/// <param name="ClientUserId">Who left that comment, if recorded.</param>
|
||||
/// <param name="UnshelveTimeUtc">For a timed shelve, the absolute UTC expiry (A2 projects the remaining time from it);
|
||||
/// otherwise null.</param>
|
||||
/// <param name="ConditionType">A2: the condition's type definition, namespace-URI qualified (<c>nsu=…;i=…</c>).</param>
|
||||
/// <param name="ConditionName">A2: the Part 9 ConditionName.</param>
|
||||
/// <param name="ConditionClass">A2: the ConditionClassId's numeric id when it is an ns=0 class type (0 otherwise).</param>
|
||||
public sealed record ConditionStateRecord(
|
||||
AddressSpaceRealm Realm,
|
||||
string ConditionId,
|
||||
@@ -62,7 +65,10 @@ public sealed record ConditionStateRecord(
|
||||
ConditionActivationMarker Activation,
|
||||
string? Comment = null,
|
||||
string? ClientUserId = null,
|
||||
DateTime? UnshelveTimeUtc = null);
|
||||
DateTime? UnshelveTimeUtc = null,
|
||||
string? ConditionType = null,
|
||||
string? ConditionName = null,
|
||||
int ConditionClass = 0);
|
||||
|
||||
/// <summary>
|
||||
/// The node manager's SDK-free delta callback (plan §5.1). Implemented by the Runtime's <c>ConditionStateHub</c>.
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
/// <summary>
|
||||
/// A2: the origin's condition snapshot port — <see cref="OtOpcUaNodeManager.SnapshotConditions"/> behind an SDK-free
|
||||
/// facade, so the Runtime's condition streams never reference the node manager. Resolved like the H2 history port.
|
||||
/// </summary>
|
||||
public interface IOriginConditionSource
|
||||
{
|
||||
/// <summary>See <see cref="OtOpcUaNodeManager.SnapshotConditions"/>: slices of at most
|
||||
/// <paramref name="maxConditionsPerHold"/> (clamped to 5,000), each with its watermark, start cursor and readiness.</summary>
|
||||
/// <param name="scope">Realm + id filter, evaluated outside the node manager's Lock.</param>
|
||||
/// <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>Resolves the port against the SDK sink bound at server start; throws while the server is not running.</summary>
|
||||
public sealed class DeferredOriginConditionSource(DeferredAddressSpaceSink deferred) : IOriginConditionSource
|
||||
{
|
||||
/// <summary>Whether the OPC UA server (and so the node manager) is up.</summary>
|
||||
public bool IsAvailable => deferred.GetCapability<IOriginConditionSource>() is not null;
|
||||
|
||||
/// <inheritdoc />
|
||||
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.");
|
||||
}
|
||||
@@ -354,6 +354,17 @@ public sealed partial class OtOpcUaNodeManager
|
||||
new ConditionActivationMarker(ConditionIncarnation, entry?.Sequence ?? 0),
|
||||
c.Comment?.Value.Text,
|
||||
c.ClientUserId?.Value,
|
||||
delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null);
|
||||
delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null,
|
||||
ConditionTypeOf(c), c.ConditionName?.Value,
|
||||
c.ConditionClassId?.Value is { NamespaceIndex: 0 } classId && classId.TryGetValue(out uint classNumber) ? (int)classNumber : 0);
|
||||
}
|
||||
|
||||
/// <summary>A2: the condition's type definition as a namespace-URI-qualified string (<c>nsu=…;i=…</c>).</summary>
|
||||
private string? ConditionTypeOf(AlarmConditionState c)
|
||||
{
|
||||
var type = c.TypeDefinitionId;
|
||||
if (type.IsNull) return null;
|
||||
var uri = type.NamespaceIndex == 0 ? Opc.Ua.Namespaces.OpcUa : Server?.NamespaceUris.GetString(type.NamespaceIndex);
|
||||
return uri is null ? null : new Opc.Ua.ExpandedNodeId(type, uri).ToString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
/// been started (so the node manager exists).
|
||||
/// </summary>
|
||||
public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink,
|
||||
IOriginHistoryPort
|
||||
IOriginHistoryPort, IOriginConditionSource
|
||||
{
|
||||
private readonly OtOpcUaNodeManager _nodeManager;
|
||||
private OriginHistoryPort? _historyPort;
|
||||
@@ -31,6 +31,11 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
|
||||
IReadOnlyList<OriginHistoryItem> items, CancellationToken cancellationToken) =>
|
||||
HistoryPort.ReadAsync(cursors, principal, servingIncarnation, details, items, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
IReadOnlyList<ConditionSnapshotSlice> IOriginConditionSource.SnapshotConditions(
|
||||
Func<ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AddressSpaceRealm, string, bool> scope, int maxConditionsPerHold) =>
|
||||
_nodeManager.SnapshotConditions(scope, maxConditionsPerHold);
|
||||
|
||||
/// <summary>Initializes a new instance of the SdkAddressSpaceSink class.</summary>
|
||||
/// <param name="nodeManager">The OPC UA node manager.</param>
|
||||
public SdkAddressSpaceSink(OtOpcUaNodeManager nodeManager)
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>One chunk of a root-scoped condition item, ready to become a <see cref="DataSubscriptionConditions"/> frame.</summary>
|
||||
internal sealed record ConditionChunk(bool IsSnapshot, int? Total, IReadOnlyList<DataConditionState> Items, bool SnapshotComplete);
|
||||
|
||||
/// <summary>The condition set an item may currently see: the catalog it was listed from and the listing (null = revoked).</summary>
|
||||
internal sealed record ConditionItemScope(object Catalog, IReadOnlyList<ScopedCondition>? Conditions);
|
||||
|
||||
/// <summary>
|
||||
/// A2 origin producer for ONE root-scoped condition item (plan §5.1 "A2 consumer of a sliced snapshot", §5.5 "Stream
|
||||
/// mechanics"). Pull-based and single-threaded (the session's worker calls it): it never buffers more than one chunk, so
|
||||
/// the session's bounded condition queue is the only buffer and a slow consumer back-pressures into the hub, whose
|
||||
/// bounded partitions then evict — which this producer sees as a reader reset and answers with a fresh snapshot.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para><b>Snapshot.</b> The scope is listed first (export grant + origin ACL per placement, keyed); a listing above
|
||||
/// the item's limit is reported as a snapshot-begin chunk carrying <c>total</c> and nothing else, before any record
|
||||
/// (§5.5 admission before materialising). Otherwise <see cref="IOriginConditionSource.SnapshotConditions"/> is taken in
|
||||
/// slices of at most the limit (the node manager clamps to 5,000 per hold); a begin chunk carries the copied count,
|
||||
/// record chunks follow, and the last carries <c>snapshot_complete</c> only when
|
||||
/// <see cref="ConditionStateHub.IsSnapshotCompleteFor"/> holds. An incomplete snapshot is retaken (rate-limited) once
|
||||
/// the hub reports readiness.</para>
|
||||
/// <para><b>Deltas</b> are replayed per hub partition from the snapshot's <c>StartCursor</c>; a delta for a condition
|
||||
/// held in a slice at or below that slice's watermark is skipped (the slice already holds it). Versions are global, so
|
||||
/// per-partition cursors are exact: a condition always lives in one partition.</para>
|
||||
/// <para><b>Scope changes</b> (a deploy, an ACL or grant change that leaves the stream open): conditions that leave the
|
||||
/// listing get a removal record; conditions that join it are copied with a small snapshot and sent as ordinary delta
|
||||
/// records, so a deploy that adds or removes conditions arrives as delta records.</para>
|
||||
/// </remarks>
|
||||
internal sealed class ConditionItemStream
|
||||
{
|
||||
/// <summary>The most records one chunk carries.</summary>
|
||||
internal const int MaxRecordsPerChunk = 128;
|
||||
|
||||
/// <summary>The least time between two snapshots of one item (re-snapshot storms after an overflow).</summary>
|
||||
internal static readonly TimeSpan MinResnapshotInterval = TimeSpan.FromSeconds(1);
|
||||
|
||||
private readonly ConditionStateHub _hub;
|
||||
private readonly IOriginConditionSource _source;
|
||||
private readonly Func<ConditionItemScope> _scope;
|
||||
private readonly int _limit;
|
||||
private readonly bool _includeInfo;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly Queue<DataConditionState> _snapshotRecords = new();
|
||||
private readonly Dictionary<OriginConditionRef, long> _sliceWatermarks = new();
|
||||
private readonly Dictionary<OriginConditionRef, ScopedCondition> _inScope = new();
|
||||
private readonly HashSet<OriginConditionRef> _sent = new();
|
||||
private readonly Queue<DataConditionState> _pendingDeltas = new();
|
||||
private long[] _cursors = [];
|
||||
private object? _catalog;
|
||||
private State _state = State.NeedSnapshot;
|
||||
private bool _beginSent, _snapshotComplete, _retakeWhenReady, _readSinceSnapshot;
|
||||
private int _total;
|
||||
private long _lastSnapshotAt = long.MinValue;
|
||||
|
||||
private enum State { NeedSnapshot, Snapshotting, Live, OverCapacity, Revoked }
|
||||
|
||||
internal ConditionItemStream(ConditionStateHub hub, IOriginConditionSource source, Func<ConditionItemScope> scope, int limit,
|
||||
bool includeInfo, TimeProvider clock)
|
||||
{
|
||||
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
|
||||
_source = source ?? throw new ArgumentNullException(nameof(source));
|
||||
_scope = scope ?? throw new ArgumentNullException(nameof(scope));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(limit, 1);
|
||||
_limit = limit;
|
||||
_includeInfo = includeInfo;
|
||||
}
|
||||
|
||||
/// <summary>The item's grant was withdrawn (its scope listing became null): the session must stop delivering it.</summary>
|
||||
internal bool IsRevoked => _state == State.Revoked;
|
||||
|
||||
/// <summary>The last listing exceeded the item's limit (only <c>total</c> was reported).</summary>
|
||||
internal bool IsOverCapacity => _state == State.OverCapacity;
|
||||
|
||||
/// <summary>Whether the last snapshot of this item was sent with <c>snapshot_complete</c>.</summary>
|
||||
internal bool SnapshotComplete => _snapshotComplete;
|
||||
|
||||
/// <summary>How many snapshots were taken (the first plus every reset or retake).</summary>
|
||||
internal int Snapshots { get; private set; }
|
||||
|
||||
/// <summary>How many snapshots were forced by a hub reader reset (records evicted before this item read them).</summary>
|
||||
internal int Resets { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// A reset arrived while the previous snapshot was still being delivered: the consumer cannot drain one snapshot
|
||||
/// before the hub evicts. The session answers it with a stream Reset.
|
||||
/// </summary>
|
||||
internal bool Overflowed { get; private set; }
|
||||
|
||||
/// <summary>Produce the next chunk, or null when there is nothing to send now.</summary>
|
||||
internal ConditionChunk? Next()
|
||||
{
|
||||
if (_state is State.Revoked) return null;
|
||||
var scope = _scope();
|
||||
if (scope.Conditions is null) { _state = State.Revoked; return null; }
|
||||
if (_state == State.NeedSnapshot)
|
||||
{
|
||||
if (!CanSnapshotNow()) return null;
|
||||
return TakeSnapshot(scope);
|
||||
}
|
||||
if (_state == State.OverCapacity)
|
||||
{
|
||||
// Re-admit only when the listing itself changed (a deploy); otherwise stay parked with total reported.
|
||||
if (ReferenceEquals(scope.Catalog, _catalog) || !CanSnapshotNow()) return null;
|
||||
return TakeSnapshot(scope);
|
||||
}
|
||||
if (_state == State.Snapshotting) return NextSnapshotChunk();
|
||||
// Live.
|
||||
if (_retakeWhenReady && _hub.IsSnapshotComplete && CanSnapshotNow()) return TakeSnapshot(scope);
|
||||
if (!ReferenceEquals(scope.Catalog, _catalog)) ApplyScopeChange(scope);
|
||||
if (!ReadDeltas()) return ResetSnapshot(scope);
|
||||
return NextDeltaChunk();
|
||||
}
|
||||
|
||||
private bool CanSnapshotNow() =>
|
||||
_lastSnapshotAt == long.MinValue || _clock.GetElapsedTime(_lastSnapshotAt) >= MinResnapshotInterval;
|
||||
|
||||
private ConditionChunk? ResetSnapshot(ConditionItemScope scope)
|
||||
{
|
||||
Resets++;
|
||||
OtOpcUaTelemetry.DataConnConditionResyncs.Add(1);
|
||||
_state = State.NeedSnapshot;
|
||||
return CanSnapshotNow() ? TakeSnapshot(scope) : null;
|
||||
}
|
||||
|
||||
private ConditionChunk TakeSnapshot(ConditionItemScope scope)
|
||||
{
|
||||
Snapshots++;
|
||||
_lastSnapshotAt = _clock.GetTimestamp();
|
||||
_catalog = scope.Catalog;
|
||||
_snapshotRecords.Clear(); _sliceWatermarks.Clear(); _pendingDeltas.Clear(); _sent.Clear(); _inScope.Clear();
|
||||
_beginSent = false; _snapshotComplete = false; _retakeWhenReady = false; _readSinceSnapshot = false;
|
||||
var listing = scope.Conditions!;
|
||||
if (listing.Count > _limit)
|
||||
{
|
||||
// §5.5: total above the limit is reported at snapshot begin, before (and instead of) any record.
|
||||
_state = State.OverCapacity;
|
||||
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
|
||||
_total = listing.Count;
|
||||
return new ConditionChunk(true, listing.Count, [], false);
|
||||
}
|
||||
foreach (var condition in listing) _inScope[condition.Ref] = condition;
|
||||
var slices = _source.SnapshotConditions((realm, id) => _inScope.ContainsKey(new(realm, id)), _limit);
|
||||
var records = new List<(ConditionStateRecord Record, long Watermark)>();
|
||||
foreach (var slice in slices)
|
||||
foreach (var record in slice.Records)
|
||||
records.Add((record, slice.Watermark));
|
||||
if (records.Count > _limit)
|
||||
{
|
||||
_state = State.OverCapacity;
|
||||
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
|
||||
_total = records.Count;
|
||||
return new ConditionChunk(true, records.Count, [], false);
|
||||
}
|
||||
var start = slices.Count == 0 ? _hub.Watermark : slices[0].StartCursor;
|
||||
_cursors = Enumerable.Repeat(start, _hub.PartitionCount).ToArray();
|
||||
foreach (var (record, watermark) in records)
|
||||
{
|
||||
var key = new OriginConditionRef(record.Realm, record.ConditionId);
|
||||
if (!_inScope.TryGetValue(key, out var scoped)) continue;
|
||||
_sliceWatermarks[key] = watermark;
|
||||
_sent.Add(key);
|
||||
_snapshotRecords.Enqueue(Map(record with { Version = watermark }, scoped, includeInfo: _includeInfo));
|
||||
}
|
||||
_snapshotComplete = _hub.IsSnapshotCompleteFor(slices);
|
||||
_retakeWhenReady = !_snapshotComplete;
|
||||
_total = _snapshotRecords.Count;
|
||||
_state = State.Snapshotting;
|
||||
return NextSnapshotChunk();
|
||||
}
|
||||
|
||||
private ConditionChunk NextSnapshotChunk()
|
||||
{
|
||||
if (!_beginSent)
|
||||
{
|
||||
_beginSent = true;
|
||||
// The begin chunk carries only the count, so the consumer decides capacity before materialising anything.
|
||||
if (_snapshotRecords.Count == 0) { _state = State.Live; return new ConditionChunk(true, _total, [], _snapshotComplete); }
|
||||
return new ConditionChunk(true, _total, [], false);
|
||||
}
|
||||
var batch = new List<DataConditionState>(Math.Min(MaxRecordsPerChunk, _snapshotRecords.Count));
|
||||
while (batch.Count < MaxRecordsPerChunk && _snapshotRecords.TryDequeue(out var record)) batch.Add(record);
|
||||
var last = _snapshotRecords.Count == 0;
|
||||
if (last) _state = State.Live;
|
||||
return new ConditionChunk(true, null, batch, last && _snapshotComplete);
|
||||
}
|
||||
|
||||
/// <summary>Reads every partition after its cursor into the pending deltas. False when a reader reset is required.</summary>
|
||||
private bool ReadDeltas()
|
||||
{
|
||||
if (_pendingDeltas.Count >= MaxRecordsPerChunk) return true;
|
||||
for (var p = 0; p < _cursors.Length; p++)
|
||||
{
|
||||
var read = _hub.Read(p, _cursors[p], MaxRecordsPerChunk);
|
||||
if (read.ResetRequired)
|
||||
{
|
||||
// Evicted before the first read after a snapshot: the consumer could not drain one snapshot in time.
|
||||
if (!_readSinceSnapshot) Overflowed = true;
|
||||
return false;
|
||||
}
|
||||
foreach (var record in read.Records)
|
||||
{
|
||||
_cursors[p] = record.Version;
|
||||
var key = new OriginConditionRef(record.Realm, record.ConditionId);
|
||||
if (!_inScope.TryGetValue(key, out var scoped)) continue;
|
||||
// A1 replay contract: the slice already holds every change at or below its watermark.
|
||||
if (_sliceWatermarks.TryGetValue(key, out var watermark) && record.Version <= watermark) continue;
|
||||
if (record.Removed)
|
||||
{
|
||||
if (!_sent.Remove(key)) continue;
|
||||
_sliceWatermarks.Remove(key);
|
||||
_pendingDeltas.Enqueue(Map(record, scoped, includeInfo: false));
|
||||
continue;
|
||||
}
|
||||
var first = _sent.Add(key);
|
||||
_pendingDeltas.Enqueue(Map(record, scoped, includeInfo: first && _includeInfo));
|
||||
}
|
||||
}
|
||||
_readSinceSnapshot = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
private ConditionChunk? NextDeltaChunk()
|
||||
{
|
||||
if (_pendingDeltas.Count == 0) return null;
|
||||
var batch = new List<DataConditionState>(Math.Min(MaxRecordsPerChunk, _pendingDeltas.Count));
|
||||
while (batch.Count < MaxRecordsPerChunk && _pendingDeltas.TryDequeue(out var record)) batch.Add(record);
|
||||
return new ConditionChunk(false, null, batch, false);
|
||||
}
|
||||
|
||||
/// <summary>A new catalog: conditions leaving the listing get a removal record; joining ones a small snapshot as deltas.</summary>
|
||||
private void ApplyScopeChange(ConditionItemScope scope)
|
||||
{
|
||||
_catalog = scope.Catalog;
|
||||
var listing = scope.Conditions!;
|
||||
if (listing.Count > _limit)
|
||||
{
|
||||
// The deploy pushed this root over its limit: report it like a first snapshot would.
|
||||
_state = State.NeedSnapshot;
|
||||
_lastSnapshotAt = long.MinValue;
|
||||
return;
|
||||
}
|
||||
var next = listing.ToDictionary(x => x.Ref);
|
||||
var version = _hub.Watermark;
|
||||
foreach (var (key, scoped) in _inScope)
|
||||
{
|
||||
if (next.ContainsKey(key)) continue;
|
||||
_sliceWatermarks.Remove(key);
|
||||
if (_sent.Remove(key))
|
||||
_pendingDeltas.Enqueue(Removal(scoped, version));
|
||||
}
|
||||
var added = next.Keys.Where(k => !_inScope.ContainsKey(k)).ToHashSet();
|
||||
_inScope.Clear();
|
||||
foreach (var (key, scoped) in next) _inScope[key] = scoped;
|
||||
if (added.Count == 0) return;
|
||||
foreach (var slice in _source.SnapshotConditions((realm, id) => added.Contains(new(realm, id)), _limit))
|
||||
foreach (var record in slice.Records)
|
||||
{
|
||||
var key = new OriginConditionRef(record.Realm, record.ConditionId);
|
||||
if (!_inScope.TryGetValue(key, out var scoped)) continue;
|
||||
_sliceWatermarks[key] = slice.Watermark;
|
||||
_sent.Add(key);
|
||||
_pendingDeltas.Enqueue(Map(record with { Version = slice.Watermark }, scoped, includeInfo: _includeInfo));
|
||||
}
|
||||
}
|
||||
|
||||
private static DataConditionState Removal(ScopedCondition scoped, long version) =>
|
||||
new(scoped.Exported.ConditionKey, version, Removed: true, StateKnown: false, null, false, false, false, false, 0, 0, "",
|
||||
0, null, 0, null, false, null);
|
||||
|
||||
/// <summary>Maps a node-manager record to the wire record. Never carries the origin ConditionId (a RawPath for native).</summary>
|
||||
internal static DataConditionState Map(ConditionStateRecord record, ScopedCondition scoped, bool includeInfo)
|
||||
{
|
||||
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)
|
||||
: 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,
|
||||
record.Message ?? "", record.Quality,
|
||||
record.UnshelveTimeUtc is { } unshelve ? new DateTimeOffset(DateTime.SpecifyKind(unshelve, DateTimeKind.Utc)) : null,
|
||||
record.ConditionClass, new DateTimeOffset(DateTime.SpecifyKind(record.TimeUtc, DateTimeKind.Utc)), record.Retain,
|
||||
new DataActivationMarker(record.Activation.Incarnation, record.Activation.Sequence), record.Comment, record.ClientUserId);
|
||||
}
|
||||
}
|
||||
@@ -48,3 +48,9 @@ public sealed record ConditionPlacementView(DataView View, DataView Parent, stri
|
||||
/// </summary>
|
||||
public sealed record ExportedCondition(string ConditionKey, ConditionSourceKind SourceKind,
|
||||
IReadOnlyList<ConditionPlacementView> Placements);
|
||||
|
||||
/// <summary>
|
||||
/// 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);
|
||||
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
using System.Threading.Channels;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// A2: root-scoped condition items (plan §5.5). They share the stream, the handle table (one monitored item each) and the
|
||||
/// principal's interest capacity with value items, but have their own non-coalescing bounded queue: the delivery loop
|
||||
/// takes a queued control/ack first, then a condition frame, then a value (priority control > condition > value).
|
||||
/// Production is pull-based (<see cref="ConditionItemStream"/>): an item produces only while the queue has room, so a slow
|
||||
/// consumer back-pressures into the hub, whose eviction resets the item to a fresh snapshot.
|
||||
/// </summary>
|
||||
internal sealed partial class DataSubscriptionSession
|
||||
{
|
||||
private sealed class ConditionItem(string clientItemId, DataItemHandle handle, ConditionItemAuthority authority,
|
||||
ConditionItemStream stream, IDisposable reservation) : IDisposable
|
||||
{
|
||||
internal readonly string ClientItemId = clientItemId;
|
||||
internal readonly DataItemHandle Handle = handle;
|
||||
internal readonly ConditionItemAuthority Authority = authority;
|
||||
internal readonly ConditionItemStream Stream = stream;
|
||||
internal volatile bool Active;
|
||||
private IDisposable? _reservation = reservation;
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _reservation, null) is { } r)
|
||||
{
|
||||
r.Dispose();
|
||||
OtOpcUaTelemetry.DataConnConditionItems.Add(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private readonly Dictionary<ulong, ConditionItem> _conditionItems = new();
|
||||
private readonly Dictionary<string, List<ConditionItem>> _conditionActivations = new(StringComparer.Ordinal);
|
||||
private Channel<PendingDelivery>? _conditionOutboundChannel;
|
||||
private int _conditionCursor;
|
||||
|
||||
/// <summary>The bounded condition queue (created lazily on the first condition item; v1 streams never allocate it).</summary>
|
||||
private Channel<PendingDelivery> ConditionOutbound
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_conditionOutboundChannel is { } existing) return existing;
|
||||
var created = Channel.CreateBounded<PendingDelivery>(new BoundedChannelOptions(Math.Max(1, _limits.MaxPendingFrames))
|
||||
{ SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.Wait });
|
||||
return Interlocked.CompareExchange(ref _conditionOutboundChannel, created, null) ?? created;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the condition items' streams, by handle.</summary>
|
||||
internal IReadOnlyDictionary<ulong, ConditionItemStream> ConditionStreamsForTests
|
||||
{
|
||||
get { lock (_gate) return _conditionItems.ToDictionary(x => x.Key, x => x.Value.Stream); }
|
||||
}
|
||||
|
||||
/// <summary>Admits one root-scoped condition item; it starts producing once its ack has been delivered.</summary>
|
||||
private DataSubscriptionItemAck AddConditionItem(DataSubscriptionItem request, string commandId)
|
||||
{
|
||||
var services = _services;
|
||||
if (services.ConditionHub is not { } hub || services.ConditionSource is not { } source)
|
||||
return new(request.ClientItemId, DataItemStatus.Unsupported, null, null, null);
|
||||
DataItemStatus status;
|
||||
ConditionItemAuthority? authority;
|
||||
try { status = services.AuthorizeConditionItem(_context, _target, request.View, out authority); }
|
||||
catch (ArgumentException) { return new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, null); }
|
||||
if (status != DataItemStatus.Good || authority is null) return new(request.ClientItemId, status, null, null, null);
|
||||
if (authority.Serving != _serving) return new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null);
|
||||
lock (_gate)
|
||||
if (_conditionItems.Values.Any(x => x.ClientItemId == request.ClientItemId) || _itemsByClient.ContainsKey(request.ClientItemId))
|
||||
return new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, "Duplicate client item id.");
|
||||
var fixedBytes = checked(4096L + 2L * (request.ClientItemId.Length + authority.Root.Subject.Length
|
||||
+ authority.Root.Address.Identifier.Length + authority.Root.Address.NamespaceUri.Length));
|
||||
var itemLimit = services.SubscriptionItemLimit(_context);
|
||||
if (itemLimit <= 0 || !_capacity.TryReserveInterest(_context.PrincipalId, itemLimit, fixedBytes, out var reservation))
|
||||
return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null);
|
||||
DataItemHandle handle;
|
||||
try { handle = _handles!.Add(request.ClientItemId); }
|
||||
catch (Exception ex) when (ex is InvalidOperationException or OverflowException)
|
||||
{ reservation!.Dispose(); return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null); }
|
||||
_ = ConditionOutbound; // exists before the ack is queued, so the delivery loop waits on it from then on
|
||||
var stream = new ConditionItemStream(hub, source, authority.Scope, authority.Limit,
|
||||
request.ConditionScope!.IncludeInfo, services.Clock);
|
||||
var item = new ConditionItem(request.ClientItemId, handle, authority, stream, reservation!);
|
||||
OtOpcUaTelemetry.DataConnConditionItems.Add(1);
|
||||
lock (_gate)
|
||||
{
|
||||
_conditionItems.Add(handle.Handle, item);
|
||||
if (!_conditionActivations.TryGetValue(commandId, out var list)) _conditionActivations[commandId] = list = [];
|
||||
list.Add(item);
|
||||
}
|
||||
return new(request.ClientItemId, DataItemStatus.Good, handle, request.Settings, null);
|
||||
}
|
||||
|
||||
/// <summary>The command's ack was delivered: its condition items may now produce (their frames follow their ack).</summary>
|
||||
private void ActivateConditionItems(string commandId)
|
||||
{
|
||||
List<ConditionItem>? list;
|
||||
lock (_gate) _conditionActivations.Remove(commandId, out list);
|
||||
if (list is null) return;
|
||||
foreach (var item in list) item.Active = true;
|
||||
QueueTick();
|
||||
}
|
||||
|
||||
private bool TryRemoveConditionItem(DataItemHandle handle, out DataSubscriptionItemAck ack)
|
||||
{
|
||||
ConditionItem? item;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_handles!.IsCurrent(handle) || !_conditionItems.Remove(handle.Handle, out item)) { ack = null!; return false; }
|
||||
_handles.Remove(handle);
|
||||
}
|
||||
item.Dispose();
|
||||
ack = new(item.ClientItemId, DataItemStatus.Good, handle, null, null);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>One production round: round-robin over active items while the condition queue has room.</summary>
|
||||
private Task PumpConditionsAsync()
|
||||
{
|
||||
ConditionItem[] items;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_conditionItems.Count == 0) return Task.CompletedTask;
|
||||
items = _conditionItems.Values.Where(x => x.Active).ToArray();
|
||||
}
|
||||
if (items.Length == 0) return Task.CompletedTask;
|
||||
var queue = ConditionOutbound;
|
||||
var budget = Math.Max(1, _limits.MaxPendingFrames - queue.Reader.Count);
|
||||
var idle = 0;
|
||||
while (budget > 0 && idle < items.Length && Volatile.Read(ref _closing) == 0 && Volatile.Read(ref _closed) == 0)
|
||||
{
|
||||
var item = items[_conditionCursor++ % items.Length];
|
||||
lock (_gate) if (!_conditionItems.ContainsKey(item.Handle.Handle)) { idle++; continue; }
|
||||
if (!item.Authority.CanPublish()) { Stop(); break; }
|
||||
var chunk = item.Stream.Next();
|
||||
if (item.Stream.Overflowed) { CloseWithReset("Condition stream overflow; retry later."); break; }
|
||||
if (item.Stream.IsRevoked) { Stop(); break; }
|
||||
if (chunk is null) { idle++; continue; }
|
||||
idle = 0;
|
||||
if (!queue.Writer.TryWrite(ConditionDelivery(item, chunk))) { CloseWithReset("Pending condition capacity exhausted."); break; }
|
||||
budget--;
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private PendingDelivery ConditionDelivery(ConditionItem item, ConditionChunk chunk)
|
||||
{
|
||||
var serving = _serving ?? throw new InvalidOperationException("Stream serving identity is unavailable.");
|
||||
return new PendingDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch, sequence, item.Handle,
|
||||
chunk.IsSnapshot, chunk.Total, chunk.Items, chunk.SnapshotComplete),
|
||||
() => Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0
|
||||
&& _services.CanUseSubscription(_context, _target, serving) && IsConditionItemCurrent(item) && item.Authority.CanPublish(),
|
||||
obsolete: () => Volatile.Read(ref _closing) != 0 || !IsConditionItemCurrent(item));
|
||||
}
|
||||
|
||||
private bool IsConditionItemCurrent(ConditionItem item)
|
||||
{
|
||||
lock (_gate) return _conditionItems.TryGetValue(item.Handle.Handle, out var current) && ReferenceEquals(current, item);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The next delivery by priority: a queued control or ack first, then a condition frame, then the queued value. Null
|
||||
/// when the stream's queues are completed and drained.
|
||||
/// </summary>
|
||||
private async ValueTask<PendingDelivery?> NextPendingAsync(CancellationToken token)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _coalesced, 0) != 0) return CoalescedControl();
|
||||
if (_outbound.Reader.TryPeek(out var head) && !head.IsValue)
|
||||
{
|
||||
if (_outbound.Reader.TryRead(out var control)) { Dequeued(control); return control; }
|
||||
continue;
|
||||
}
|
||||
if (_conditionOutboundChannel is { } conditions && conditions.Reader.TryRead(out var condition))
|
||||
{
|
||||
QueueTick();
|
||||
return condition;
|
||||
}
|
||||
if (_outbound.Reader.TryRead(out var value)) { Dequeued(value); return value; }
|
||||
if (_conditionOutboundChannel is null)
|
||||
{
|
||||
if (!await _outbound.Reader.WaitToReadAsync(token).ConfigureAwait(false)) return null;
|
||||
continue;
|
||||
}
|
||||
var values = _outbound.Reader.WaitToReadAsync(token).AsTask();
|
||||
var conditionsReady = _conditionOutboundChannel.Reader.WaitToReadAsync(token).AsTask();
|
||||
await Task.WhenAny(values, conditionsReady).ConfigureAwait(false);
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (values.IsCompletedSuccessfully && !values.Result && (!conditionsReady.IsCompletedSuccessfully || !conditionsReady.Result)
|
||||
&& _outbound.Reader.Completion.IsCompleted)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Called from the worker's teardown: completes and drains the condition queue, releases condition items.</summary>
|
||||
private void TearDownConditions()
|
||||
{
|
||||
if (_conditionOutboundChannel is { } queue)
|
||||
{
|
||||
queue.Writer.TryComplete();
|
||||
while (queue.Reader.TryRead(out var pending)) pending.Dispose();
|
||||
}
|
||||
foreach (var item in _conditionItems.Values) item.Dispose();
|
||||
_conditionItems.Clear();
|
||||
_conditionActivations.Clear();
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>One caller-bound subscription with bounded commands and one ordered delivery mode.</summary>
|
||||
internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
|
||||
internal sealed partial class DataSubscriptionSession : IDataSubscriptionTransport
|
||||
{
|
||||
private readonly LocalDataServices _services;
|
||||
private readonly DataAuthenticatedContext _context;
|
||||
@@ -310,8 +310,10 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_ackByCommand.Remove(command, out var entry) || _services.Clock.GetTimestamp() >= entry.Deadline) return false;
|
||||
_ackDeadlines.Remove(entry); ArmAckTimer(); return true;
|
||||
_ackDeadlines.Remove(entry); ArmAckTimer();
|
||||
}
|
||||
ActivateConditionItems(command); // A2: a condition item's frames follow its delivered ack
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task ProcessCommandsAsync(CancellationToken lifetimeToken)
|
||||
@@ -379,6 +381,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
|
||||
_snapshotJobs.Clear();
|
||||
foreach (var change in _pendingChanges.ToArray()) CleanupStaged(change);
|
||||
_pendingChanges.Clear();
|
||||
TearDownConditions();
|
||||
}
|
||||
_sessionLease.Dispose();
|
||||
}
|
||||
@@ -438,6 +441,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
|
||||
_stop.Token.ThrowIfCancellationRequested();
|
||||
if (request is null || string.IsNullOrWhiteSpace(request.ClientItemId) || request.View is null || request.Settings is null)
|
||||
{ acks.Add(new(request?.ClientItemId ?? "", DataItemStatus.InvalidArgument, null, null, null)); continue; }
|
||||
// A2: a root-scoped condition item (the host only lets one through on a call that negotiated `conditions`).
|
||||
if (request.ConditionScope is not null) { acks.Add(AddConditionItem(request, commandId)); continue; }
|
||||
DataItemStatus status;
|
||||
SubscriptionAuthorizedView? view;
|
||||
try { request.Settings.Validate(); status = _services.AuthorizeSubscription(_context, _target, request.View, out view); }
|
||||
@@ -596,6 +601,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
|
||||
if (!_handles!.IsCurrent(handle) || !_items.Remove(handle.Handle, out item)) item = null;
|
||||
else { _handles.Remove(handle); _itemsByClient.Remove(item.ClientItemId); }
|
||||
}
|
||||
if (item is null && TryRemoveConditionItem(handle, out var conditionAck)) { acks.Add(conditionAck); continue; }
|
||||
if (item is null) { acks.Add(new("", DataItemStatus.NotFound, null, null, null)); continue; }
|
||||
ReleaseItem(item);
|
||||
acks.Add(new(item.ClientItemId, DataItemStatus.Good, handle, null, null));
|
||||
@@ -863,6 +869,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
|
||||
}
|
||||
}
|
||||
await PumpSnapshotsAsync().ConfigureAwait(false);
|
||||
await PumpConditionsAsync().ConfigureAwait(false);
|
||||
BeforeDirtyTickForTests?.Invoke(_outbound.Reader.Count, Volatile.Read(ref _queuedValues), interests.Count);
|
||||
foreach (var interest in interests)
|
||||
{
|
||||
@@ -1208,14 +1215,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
PendingDelivery pending;
|
||||
if (Interlocked.Exchange(ref owner._coalesced, 0) != 0) pending = owner.CoalescedControl();
|
||||
else
|
||||
{
|
||||
if (!await owner._outbound.Reader.WaitToReadAsync(_linked!.Token).ConfigureAwait(false)) break;
|
||||
if (!owner._outbound.Reader.TryRead(out pending!)) continue;
|
||||
owner.Dequeued(pending);
|
||||
}
|
||||
if (await owner.NextPendingAsync(_linked!.Token).ConfigureAwait(false) is not { } pending) break;
|
||||
if (!pending.Gate()) { pending.Dispose(); if (pending.IsObsolete()) continue; owner.Stop(); return false; }
|
||||
if (!pending.IsEligible()) { pending.Dispose(); continue; }
|
||||
var rate = pending.ConsumeSnapshot();
|
||||
@@ -1251,14 +1251,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
PendingDelivery pending;
|
||||
if (Interlocked.Exchange(ref _coalesced, 0) != 0) pending = CoalescedControl();
|
||||
else
|
||||
{
|
||||
if (!await _outbound.Reader.WaitToReadAsync(linked.Token).ConfigureAwait(false)) break;
|
||||
if (!_outbound.Reader.TryRead(out pending!)) continue;
|
||||
Dequeued(pending);
|
||||
}
|
||||
if (await NextPendingAsync(linked.Token).ConfigureAwait(false) is not { } pending) break;
|
||||
if (!pending.Gate()) { pending.Dispose(); if (pending.IsObsolete()) continue; Stop(); return; }
|
||||
IDisposable? reservation;
|
||||
try { reservation = await _capacity.ReserveAsync(_context.PrincipalId, _limits.MaxPendingBytes, linked.Token).ConfigureAwait(false); }
|
||||
|
||||
@@ -37,7 +37,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
|
||||
}
|
||||
|
||||
/// <summary>The features this consumer understands; sent on every capabilities probe (coordinator decision, plan §4.1).</summary>
|
||||
internal const DataFeatures ClientFeatures = DataFeatures.History;
|
||||
internal const DataFeatures ClientFeatures = DataFeatures.History | DataFeatures.Conditions;
|
||||
|
||||
// Explicit: IDataReadService.ReadAsync(ReadRequest) shares the name, and target-typed `new(...)` callers must stay unambiguous.
|
||||
Task<IReadOnlyList<DataHistoryReadResult>> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) =>
|
||||
|
||||
@@ -220,7 +220,9 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
internal static DataFeatures RequestedFeatures(DataCapabilities capabilities)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(capabilities);
|
||||
return capabilities.History is not null ? ClientFeatures & DataFeatures.History : DataFeatures.None;
|
||||
return (capabilities.History is not null ? ClientFeatures & DataFeatures.History : DataFeatures.None)
|
||||
// A2: `conditions` iff the endpoint advertised ConditionCapabilities.
|
||||
| (capabilities.Conditions is not null ? ClientFeatures & DataFeatures.Conditions : DataFeatures.None);
|
||||
}
|
||||
private Metadata Headers(ChannelEntry channel, DataFeatures features = DataFeatures.None)
|
||||
{
|
||||
@@ -774,7 +776,14 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
DataSubscriptionFrame frame;
|
||||
if (wire.CompactValues is not null && !compactNegotiated)
|
||||
throw new InvalidOperationException("Unnegotiated compact subscription frame.");
|
||||
if (wire.Values is not null || wire.CompactValues is not null)
|
||||
if (wire.ConditionStates is not null)
|
||||
{
|
||||
// A2: only on a stream that negotiated conditions, and only for a handle this stream holds.
|
||||
if ((RequestedFeatures(selected.Capabilities) & DataFeatures.Conditions) == 0)
|
||||
throw new InvalidOperationException("Unnegotiated condition subscription frame.");
|
||||
frame = DataConditionProtoMapper.DecodeFrame(wire);
|
||||
}
|
||||
else if (wire.Values is not null || wire.CompactValues is not null)
|
||||
frame = DataProtoMapper.DecodeValues(wire, _handles, maxItems,
|
||||
Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes), selected.Capabilities.Serving,
|
||||
selected.Capabilities.Limits.MaxValueElements, selected.Capabilities.SubscriptionAgeReadiness);
|
||||
@@ -849,6 +858,9 @@ public sealed partial class GrpcDataConnection : IDataConnection
|
||||
Volatile.Write(ref DiagnosticRegistrationCount, next.Count);
|
||||
}
|
||||
}
|
||||
if (frame is DataSubscriptionConditions conditionFrame
|
||||
&& (!_handles.TryGetValue(conditionFrame.Handle.Handle, out var conditionHandle) || conditionHandle != conditionFrame.Handle))
|
||||
throw new InvalidOperationException("Condition frame for an unknown handle.");
|
||||
if (frame is DataSubscriptionValues values)
|
||||
{
|
||||
var nextVersions = new Dictionary<ulong, long>(_versions);
|
||||
|
||||
@@ -19,7 +19,8 @@ public sealed class LocalDataRuntimeComposition : IDisposable
|
||||
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, DataWriteRuntime writes,
|
||||
IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits,
|
||||
ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null,
|
||||
DataConnectionHistoryDiagnostics? historyDiagnostics = null)
|
||||
DataConnectionHistoryDiagnostics? historyDiagnostics = null,
|
||||
ConditionStateHub? conditionHub = null, ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginConditionSource? conditionSource = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub);
|
||||
ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities);
|
||||
@@ -39,7 +40,11 @@ public sealed class LocalDataRuntimeComposition : IDisposable
|
||||
writes: context => writes.ForCaller(context, () => host),
|
||||
targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity),
|
||||
subscriptionFreshnessChallenges: true, history: history)
|
||||
{ Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, HistoryDiagnostics = historyDiagnostics };
|
||||
{
|
||||
Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, HistoryDiagnostics = historyDiagnostics,
|
||||
// A2: condition streams over the A1 hub and the node manager's snapshot port; keys from the coordinator.
|
||||
ConditionHub = conditionHub, ConditionSource = conditionSource, ConditionKeysSource = () => catalog.ConditionKeys,
|
||||
};
|
||||
Services = services;
|
||||
}
|
||||
public LocalDataServices Services { get; }
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
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>An admitted root-scoped condition item's authority (plan §5.5, service-principal model).</summary>
|
||||
/// <param name="Root">The export root the item listens under (canonical catalog view).</param>
|
||||
/// <param name="Limit">The item's <c>MaxConditions</c> (min over the AlarmSubscribe exports that contain the root).</param>
|
||||
/// <param name="Serving">The serving identity it was admitted under.</param>
|
||||
/// <param name="Scope">The current listing (null once the grant is gone), recomputed only when the catalog changes.</param>
|
||||
/// <param name="CanPublish">Whether a frame of this item may still be delivered.</param>
|
||||
internal sealed record ConditionItemAuthority(DataView Root, int Limit, ServingIdentity Serving, Func<ConditionItemScope> Scope,
|
||||
Func<bool> CanPublish);
|
||||
|
||||
/// <summary>A2: the origin side of root-scoped condition items (plan §5.5).</summary>
|
||||
public sealed partial class LocalDataServices
|
||||
{
|
||||
/// <summary>A1/A2: the condition-state hub the node manager feeds (null ⇒ conditions are not servable).</summary>
|
||||
public ConditionStateHub? ConditionHub { get; init; }
|
||||
|
||||
/// <summary>A2: the node manager's condition snapshot port (null ⇒ conditions are not servable).</summary>
|
||||
public IOriginConditionSource? ConditionSource { get; init; }
|
||||
|
||||
/// <summary>A2: the origin's condition-key derivation (unavailable ⇒ no <c>conditions</c> capability, fail closed).</summary>
|
||||
public Func<ConditionKeys> ConditionKeysSource { get; init; } = static () => ConditionKeys.Unavailable;
|
||||
|
||||
/// <summary>Whether this origin can serve condition items at all (§5.2: no secret ⇒ no capability).</summary>
|
||||
internal bool ConditionsServable => ConditionHub is not null && ConditionSource is not null && ConditionKeysSource().IsAvailable
|
||||
&& (ConditionSource is not DeferredOriginConditionSource deferred || deferred.IsAvailable);
|
||||
|
||||
private DataConditionCapabilities? ConditionCapabilitiesFor(LocalExportCatalog? catalog, DataAuthenticatedContext context)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Admits a root-scoped condition item (§5.5): this origin serves conditions, the catalog is ready and this node is
|
||||
/// <b>Primary</b> (the stream is Primary-only, §5.1), the caller is usable, the root resolves and an AlarmSubscribe
|
||||
/// export of the root's realm contains it. Each placement is further checked against the origin ACL
|
||||
/// (<c>CreateMonitoredItems</c> on the placement's scope) whenever the listing is computed.
|
||||
/// </summary>
|
||||
internal DataItemStatus AuthorizeConditionItem(DataAuthenticatedContext context, DataTarget target, DataView view,
|
||||
out ConditionItemAuthority? authority)
|
||||
{
|
||||
authority = null;
|
||||
view.Validate(); target.Validate();
|
||||
if (!ConditionsServable) return DataItemStatus.Unsupported;
|
||||
var catalog = _catalog();
|
||||
if (catalog is null || !Ready(catalog) || !RoleAllows(target, catalog.Serving)) return DataItemStatus.Unavailable;
|
||||
if (!string.Equals(catalog.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) return DataItemStatus.Unavailable;
|
||||
if (context.AuthorityEpoch != catalog.AuthorityEpoch || !_policy.IsCallerUsable(Caller(context))) return DataItemStatus.Denied;
|
||||
if (!catalog.TryResolve(view, out var node)) return catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound;
|
||||
var root = node.Metadata.View;
|
||||
if (catalog.ConditionLimitFor(context.PrincipalId, root) is not { } limit) return DataItemStatus.Denied;
|
||||
var serving = catalog.Serving;
|
||||
object? listedFrom = null;
|
||||
ConditionItemScope? cached = null;
|
||||
ConditionItemScope Scope()
|
||||
{
|
||||
var current = _catalog();
|
||||
if (current is null) return cached ??= new ConditionItemScope(new object(), null);
|
||||
if (ReferenceEquals(current, listedFrom) && cached is not null) return cached;
|
||||
listedFrom = current;
|
||||
var allowed = Ready(current) && current.Serving == serving && current.TryResolve(root, out _)
|
||||
&& 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))
|
||||
: null);
|
||||
return cached;
|
||||
}
|
||||
authority = new ConditionItemAuthority(root, limit, serving, Scope, () =>
|
||||
{
|
||||
var current = _catalog();
|
||||
return current is not null && Ready(current) && current.Serving == serving && ConditionsServable
|
||||
&& current.ConditionLimitFor(context.PrincipalId, root) is not null && _policy.IsCallerUsable(Caller(context));
|
||||
});
|
||||
return DataItemStatus.Good;
|
||||
}
|
||||
}
|
||||
@@ -49,10 +49,12 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
|
||||
public TimeProvider Clock { get; }
|
||||
/// <summary>Diagnostics sink (history wiring faults); defaults to no logging.</summary>
|
||||
public Microsoft.Extensions.Logging.ILogger Logger { get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
|
||||
// Grow site (plan §4.3): HistoryRead is implemented only while this origin can serve history (a historian backend).
|
||||
// Grow site (plan §4.3): HistoryRead is implemented only while this origin can serve history (a historian backend);
|
||||
// A2a AlarmSubscribe only while it can serve conditions (hub + snapshot port + condition-key secret).
|
||||
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)
|
||||
| (ConditionsServable ? DataOperations.AlarmSubscribe : 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 =>
|
||||
@@ -235,6 +237,8 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
|
||||
capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None };
|
||||
// H2: the transport strips History (and the bit) from a call that did not negotiate history.
|
||||
capabilities = capabilities with { History = HistoryCapabilitiesFor(catalog, context) };
|
||||
// A2: likewise Conditions (and the AlarmSubscribe bit) from a call that did not negotiate conditions.
|
||||
capabilities = capabilities with { Conditions = ConditionCapabilitiesFor(catalog, context) };
|
||||
return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, SubscriptionAgeReadiness = true,
|
||||
ResponseServingIdentity = true, SubscriptionFreshnessChallenges = _subscriptionFreshnessChallenges,
|
||||
MetadataItemLeases = true, ProtocolMinor = Math.Max(5, capabilities.ProtocolMinor) });
|
||||
|
||||
@@ -21,7 +21,8 @@ public sealed partial class LocalExportCatalog
|
||||
private readonly Dictionary<OriginConditionRef, LocalConditionPlacement[]> _placementsByCondition;
|
||||
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 HistoryReads = 4, int HistoryValuesPerPage = 10_000, int HistoryResponseBytes = 4 * 1024 * 1024,
|
||||
int Conditions = 1000);
|
||||
|
||||
public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation,
|
||||
IEnumerable<LocalDataNode> nodes, IEnumerable<DataExport> exports, int maximumNodes = 100_000,
|
||||
@@ -92,12 +93,12 @@ public sealed partial class LocalExportCatalog
|
||||
if ((!wholeRealm && roots.Length != 1) || string.IsNullOrWhiteSpace(export.PrincipalId)
|
||||
|| export.AllowedOperations == DataOperations.None || export.MaxBatchItems <= 0 || export.MaxPageItems <= 0
|
||||
|| export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0 || export.MaxConcurrentHistoryReads <= 0
|
||||
|| export.MaxHistoryValuesPerPage <= 0 || export.MaxHistoryResponseBytes <= 0)
|
||||
|| export.MaxHistoryValuesPerPage <= 0 || export.MaxHistoryResponseBytes <= 0 || export.MaxConditions <= 0)
|
||||
throw new ArgumentException("Export has no valid origin root or policy.", nameof(exports));
|
||||
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.MaxConcurrentHistoryReads, export.MaxHistoryValuesPerPage, export.MaxHistoryResponseBytes, export.MaxConditions));
|
||||
if (UnknownOperationDrops.Unknown(export.AllowedOperations) is var unknown && unknown != DataOperations.None)
|
||||
dropped[export.DataExportId] = unknown;
|
||||
}
|
||||
@@ -217,6 +218,27 @@ public sealed partial class LocalExportCatalog
|
||||
: (rules.Min(x => x.HistoryReads), rules.Min(x => x.HistoryValuesPerPage), rules.Min(x => x.HistoryResponseBytes));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A2: the most conditions one root-scoped item at <paramref name="root"/> admits for <paramref name="principal"/> —
|
||||
/// the minimum <c>MaxConditions</c> over the AlarmSubscribe export rules of the root's realm whose root contains it;
|
||||
/// null when no such rule exists (the item is not admitted).
|
||||
/// </summary>
|
||||
internal int? ConditionLimitFor(string principal, DataView root)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(root);
|
||||
if (!TryResolve(root, out var node)) return null;
|
||||
var view = node.Metadata.View;
|
||||
var rules = _exports.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)
|
||||
&& x.Realm == view.Realm && (x.Operations & DataOperations.AlarmSubscribe) != 0
|
||||
&& (x.WholeRealm || IsAncestor(x.Root!, view))).ToArray();
|
||||
return rules.Length == 0 ? null : rules.Min(x => x.Conditions);
|
||||
}
|
||||
|
||||
/// <summary>A2: the largest per-item condition limit of the principal's AlarmSubscribe exports (0 = none).</summary>
|
||||
internal int MaxConditionsFor(string principal) => _exports
|
||||
.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase) && (x.Operations & DataOperations.AlarmSubscribe) != 0)
|
||||
.Select(x => x.Conditions).DefaultIfEmpty(0).Max();
|
||||
|
||||
internal DataOperations ExportOperations(string principal) => _exports
|
||||
.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase))
|
||||
.Aggregate(DataOperations.None, (operations, rule) => operations | rule.Operations);
|
||||
@@ -267,7 +289,16 @@ public sealed partial class LocalExportCatalog
|
||||
/// listing is empty). Fails closed (empty) when the root is not an origin node or no condition-key secret is
|
||||
/// provisioned. A UNS listing never names a RawPath: native UNS placements are the reserved reference ids.
|
||||
/// </summary>
|
||||
public IReadOnlyList<ExportedCondition> ListConditions(string principal, DataView root, DataOperations operation, ConditionKeys keys)
|
||||
public IReadOnlyList<ExportedCondition> ListConditions(string principal, DataView root, DataOperations operation, ConditionKeys keys) =>
|
||||
ListConditionScope(principal, root, operation, keys).Select(x => x.Exported).ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// A2: <see cref="ListConditions"/> with each condition's origin-internal identity (the node-manager realm key the
|
||||
/// condition-state hub records), for the origin's condition stream. ⚠️ ORIGIN-INTERNAL: <see cref="ScopedCondition.Ref"/>
|
||||
/// 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)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
|
||||
ArgumentNullException.ThrowIfNull(root);
|
||||
@@ -275,11 +306,12 @@ public sealed partial class LocalExportCatalog
|
||||
if (!keys.IsAvailable || operation == DataOperations.None || !TryResolve(root, out var rootNode)) return [];
|
||||
var rootView = rootNode.Metadata.View;
|
||||
return _placements.Values
|
||||
.Where(p => p.View.Realm == rootView.Realm && IsAncestor(rootView, p.Parent) && AllowsConditionPlacement(principal, p, operation))
|
||||
.Where(p => p.View.Realm == rootView.Realm && IsAncestor(rootView, p.Parent) && AllowsConditionPlacement(principal, p, operation)
|
||||
&& (placementFilter?.Invoke(p) ?? true))
|
||||
.GroupBy(p => p.Condition)
|
||||
.Select(g => 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())))
|
||||
.OrderBy(x => x.ConditionKey, StringComparer.Ordinal)
|
||||
.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()))))
|
||||
.OrderBy(x => x.Exported.ConditionKey, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user