From 5b03c8a26ee47fa2584ee41b1fb3ad1282c360c0 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 12:08:08 -0500 Subject: [PATCH] =?UTF-8?q?feat(grpc-data):=20A2a=20=E2=80=94=20origin=20c?= =?UTF-8?q?ondition=20streaming:=20root-scoped=20items=20over=20the=20A1?= =?UTF-8?q?=20hub,=20priority=20queue,=20host=20negotiation,=20consumer=20?= =?UTF-8?q?decode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Observability/OtOpcUaTelemetry.cs | 15 + .../DataConnectionRegistration.cs | 4 +- .../Grpc/DataConnectionGrpcService.cs | 74 ++++- .../ConditionStateRecords.cs | 8 +- .../OriginConditionSource.cs | 29 ++ .../OtOpcUaNodeManager.ConditionState.cs | 13 +- .../SdkAddressSpaceSink.cs | 7 +- .../DataConnections/ConditionItemStream.cs | 292 ++++++++++++++++++ .../DataConnections/ConditionPlacements.cs | 6 + .../DataSubscriptionSession.Conditions.cs | 210 +++++++++++++ .../DataSubscriptionSession.cs | 29 +- .../GrpcDataConnection.History.cs | 2 +- .../DataConnections/GrpcDataConnection.cs | 16 +- .../LocalDataRuntimeComposition.cs | 9 +- .../LocalDataServices.Conditions.cs | 84 +++++ .../DataConnections/LocalDataServices.cs | 6 +- .../DataConnections/LocalExportCatalog.cs | 48 ++- 17 files changed, 809 insertions(+), 43 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs index 34cbb7c61..d516cfe5e 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs @@ -239,6 +239,21 @@ public static class OtOpcUaTelemetry Meter.CreateCounter("otopcua.dataconn.conditions.partition_overflows", unit: "{overflow}", description: "Condition-state hub partition overflows (epoch invalidated)."); + /// A2: origin root-scoped condition items currently open (plan §6 metrics). + public static readonly UpDownCounter DataConnConditionItems = + Meter.CreateUpDownCounter("otopcua.dataconn.conditions.items", unit: "{item}", + description: "Open root-scoped condition items on this origin."); + + /// A2: condition-item re-snapshots after a hub reader reset (records evicted before the item read them). + public static readonly Counter DataConnConditionResyncs = + Meter.CreateCounter("otopcua.dataconn.conditions.resyncs", unit: "{resync}", + description: "Root-scoped condition items re-snapshotted after a condition-state hub reader reset."); + + /// A2: root-scoped condition items whose listing exceeded the item's MaxConditions (total reported, no records). + public static readonly Counter DataConnConditionCapacityRejections = + Meter.CreateCounter("otopcua.dataconn.conditions.capacity_rejections", unit: "{item}", + description: "Root-scoped condition items over their MaxConditions at snapshot begin."); + /// A1 (G3): deferred MarkConditionsKnown discarded because an alarm projection of the same source did not land. public static readonly Counter DataConnConditionMarksDiscarded = Meter.CreateCounter("otopcua.dataconn.conditions.marks_discarded", unit: "{mark}", diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index ca680e696..b1496d1c2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -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()), LoggerFor(sp), - sp.GetRequiredService()); + sp.GetRequiredService(), + // A2: root-scoped condition items over the A1 hub and the node manager's snapshot port. + sp.GetService(), new DeferredOriginConditionSource(sp.GetRequiredService())); }); services.AddSingleton(sp => new DeferredFactory(() => sp.GetRequiredService().Services)); services.AddSingleton(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs index 4122a3a71..aa474b2c9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs @@ -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 ). A header-less call keeps v1 shapes exactly. /// - internal static DataFeatures SupportedFeatures => DataFeatures.History; + internal static DataFeatures SupportedFeatures => DataFeatures.History | DataFeatures.Conditions; /// /// Whether this call negotiated history against . Refines the recorded effective set: an @@ -36,6 +36,33 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO return negotiated; } + /// + /// A2: whether this call negotiated conditions against (the origin serves them: the connection's + /// capabilities carry ). Refines the recorded effective set like history. + /// + 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; + } + + /// A2: the v1 shape of a capabilities response with respect to conditions: no field 17, no AlarmSubscribe bit. + internal static void StripConditions(W.CapabilitiesResponse response) + { + response.Conditions = null; + response.Operations &= ~(uint)DataOperations.AlarmSubscribe; + } + + /// A2: a metadata item never carries AlarmSubscribe on a call without conditions (it is a root-scope grant). + internal static void StripConditions(W.Metadata? metadata) + { + if (metadata is null) return; + metadata.AllowedOperations &= ~(uint)DataOperations.AlarmSubscribe; + } + /// The v1 shape of a capabilities response: no history field and no HistoryRead bit. 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.")); } } + /// + /// 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. + /// + 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 writer, ServerCallContext context, - DataCapabilities caps, int maximumBytes, bool compact, Func hostGuard) : IDataSubscriptionDeliverySink + DataCapabilities caps, int maximumBytes, bool compact, Func hostGuard, bool conditions = false) : IDataSubscriptionDeliverySink { public ValueTask 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(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs index 0719d030d..b808d376e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ConditionStateRecords.cs @@ -41,6 +41,9 @@ public readonly record struct ConditionActivationMarker(string Incarnation, ulon /// Who left that comment, if recorded. /// For a timed shelve, the absolute UTC expiry (A2 projects the remaining time from it); /// otherwise null. +/// A2: the condition's type definition, namespace-URI qualified (nsu=…;i=…). +/// A2: the Part 9 ConditionName. +/// A2: the ConditionClassId's numeric id when it is an ns=0 class type (0 otherwise). 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); /// /// The node manager's SDK-free delta callback (plan §5.1). Implemented by the Runtime's ConditionStateHub. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs new file mode 100644 index 000000000..1aa92bd83 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs @@ -0,0 +1,29 @@ +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// A2: the origin's condition snapshot port — behind an SDK-free +/// facade, so the Runtime's condition streams never reference the node manager. Resolved like the H2 history port. +/// +public interface IOriginConditionSource +{ + /// See : slices of at most + /// (clamped to 5,000), each with its watermark, start cursor and readiness. + /// Realm + id filter, evaluated outside the node manager's Lock. + /// The most conditions one Lock hold copies. + /// The slices (at least one, even for an empty scope). + IReadOnlyList SnapshotConditions(Func scope, int maxConditionsPerHold); +} + +/// Resolves the port against the SDK sink bound at server start; throws while the server is not running. +public sealed class DeferredOriginConditionSource(DeferredAddressSpaceSink deferred) : IOriginConditionSource +{ + /// Whether the OPC UA server (and so the node manager) is up. + public bool IsAvailable => deferred.GetCapability() is not null; + + /// + public IReadOnlyList SnapshotConditions(Func scope, int maxConditionsPerHold) => + deferred.GetCapability() is { } inner ? inner.SnapshotConditions(scope, maxConditionsPerHold) + : throw new InvalidOperationException("The OPC UA server is not running."); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs index 09decc183..30a083f6a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionState.cs @@ -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); + } + + /// A2: the condition's type definition as a namespace-URI-qualified string (nsu=…;i=…). + 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(); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index 9f7e7c5bf..a85472550 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs @@ -11,7 +11,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// been started (so the node manager exists). /// 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 items, CancellationToken cancellationToken) => HistoryPort.ReadAsync(cursors, principal, servingIncarnation, details, items, cancellationToken); + /// + IReadOnlyList IOriginConditionSource.SnapshotConditions( + Func scope, int maxConditionsPerHold) => + _nodeManager.SnapshotConditions(scope, maxConditionsPerHold); + /// Initializes a new instance of the SdkAddressSpaceSink class. /// The OPC UA node manager. public SdkAddressSpaceSink(OtOpcUaNodeManager nodeManager) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs new file mode 100644 index 000000000..7be3e979c --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionItemStream.cs @@ -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; + +/// One chunk of a root-scoped condition item, ready to become a frame. +internal sealed record ConditionChunk(bool IsSnapshot, int? Total, IReadOnlyList Items, bool SnapshotComplete); + +/// The condition set an item may currently see: the catalog it was listed from and the listing (null = revoked). +internal sealed record ConditionItemScope(object Catalog, IReadOnlyList? Conditions); + +/// +/// 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. +/// +/// +/// Snapshot. 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 total and nothing else, before any record +/// (§5.5 admission before materialising). Otherwise 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 snapshot_complete only when +/// holds. An incomplete snapshot is retaken (rate-limited) once +/// the hub reports readiness. +/// Deltas are replayed per hub partition from the snapshot's StartCursor; 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. +/// Scope changes (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. +/// +internal sealed class ConditionItemStream +{ + /// The most records one chunk carries. + internal const int MaxRecordsPerChunk = 128; + + /// The least time between two snapshots of one item (re-snapshot storms after an overflow). + internal static readonly TimeSpan MinResnapshotInterval = TimeSpan.FromSeconds(1); + + private readonly ConditionStateHub _hub; + private readonly IOriginConditionSource _source; + private readonly Func _scope; + private readonly int _limit; + private readonly bool _includeInfo; + private readonly TimeProvider _clock; + private readonly Queue _snapshotRecords = new(); + private readonly Dictionary _sliceWatermarks = new(); + private readonly Dictionary _inScope = new(); + private readonly HashSet _sent = new(); + private readonly Queue _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 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; + } + + /// The item's grant was withdrawn (its scope listing became null): the session must stop delivering it. + internal bool IsRevoked => _state == State.Revoked; + + /// The last listing exceeded the item's limit (only total was reported). + internal bool IsOverCapacity => _state == State.OverCapacity; + + /// Whether the last snapshot of this item was sent with snapshot_complete. + internal bool SnapshotComplete => _snapshotComplete; + + /// How many snapshots were taken (the first plus every reset or retake). + internal int Snapshots { get; private set; } + + /// How many snapshots were forced by a hub reader reset (records evicted before this item read them). + internal int Resets { get; private set; } + + /// + /// 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. + /// + internal bool Overflowed { get; private set; } + + /// Produce the next chunk, or null when there is nothing to send now. + 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(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); + } + + /// Reads every partition after its cursor into the pending deltas. False when a reader reset is required. + 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(Math.Min(MaxRecordsPerChunk, _pendingDeltas.Count)); + while (batch.Count < MaxRecordsPerChunk && _pendingDeltas.TryDequeue(out var record)) batch.Add(record); + return new ConditionChunk(false, null, batch, false); + } + + /// A new catalog: conditions leaving the listing get a removal record; joining ones a small snapshot as deltas. + 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); + + /// Maps a node-manager record to the wire record. Never carries the origin ConditionId (a RawPath for native). + 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); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs index fb99d040c..26ebe0976 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs @@ -48,3 +48,9 @@ public sealed record ConditionPlacementView(DataView View, DataView Parent, stri /// public sealed record ExportedCondition(string ConditionKey, ConditionSourceKind SourceKind, IReadOnlyList Placements); + +/// +/// A2: one condition of an export listing together with its origin-internal identity. ⚠️ ORIGIN-INTERNAL +/// ( names a RawPath for a native condition); only may reach a peer. +/// +internal sealed record ScopedCondition(OriginConditionRef Ref, ExportedCondition Exported); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs new file mode 100644 index 000000000..a9b14ecd0 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs @@ -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; + +/// +/// 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 (): 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. +/// +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 _conditionItems = new(); + private readonly Dictionary> _conditionActivations = new(StringComparer.Ordinal); + private Channel? _conditionOutboundChannel; + private int _conditionCursor; + + /// The bounded condition queue (created lazily on the first condition item; v1 streams never allocate it). + private Channel ConditionOutbound + { + get + { + if (_conditionOutboundChannel is { } existing) return existing; + var created = Channel.CreateBounded(new BoundedChannelOptions(Math.Max(1, _limits.MaxPendingFrames)) + { SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.Wait }); + return Interlocked.CompareExchange(ref _conditionOutboundChannel, created, null) ?? created; + } + } + + /// Test seam: the condition items' streams, by handle. + internal IReadOnlyDictionary ConditionStreamsForTests + { + get { lock (_gate) return _conditionItems.ToDictionary(x => x.Key, x => x.Value.Stream); } + } + + /// Admits one root-scoped condition item; it starts producing once its ack has been delivered. + 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); + } + + /// The command's ack was delivered: its condition items may now produce (their frames follow their ack). + private void ActivateConditionItems(string commandId) + { + List? 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; + } + + /// One production round: round-robin over active items while the condition queue has room. + 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); + } + + /// + /// 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. + /// + private async ValueTask 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; + } + } + + /// Called from the worker's teardown: completes and drains the condition queue, releases condition items. + 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(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs index bd764b3fe..fea3c571d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -5,7 +5,7 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// One caller-bound subscription with bounded commands and one ordered delivery mode. -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); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs index c61bfc20c..47fcdaef8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -37,7 +37,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } /// The features this consumer understands; sent on every capabilities probe (coordinator decision, plan §4.1). - 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> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) => diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs index c23e1253a..50b5624cc 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs @@ -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(_versions); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs index 3236f8848..445133a63 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs @@ -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; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs new file mode 100644 index 000000000..d98fac2cd --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.Conditions.cs @@ -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; + +/// An admitted root-scoped condition item's authority (plan §5.5, service-principal model). +/// The export root the item listens under (canonical catalog view). +/// The item's MaxConditions (min over the AlarmSubscribe exports that contain the root). +/// The serving identity it was admitted under. +/// The current listing (null once the grant is gone), recomputed only when the catalog changes. +/// Whether a frame of this item may still be delivered. +internal sealed record ConditionItemAuthority(DataView Root, int Limit, ServingIdentity Serving, Func Scope, + Func CanPublish); + +/// A2: the origin side of root-scoped condition items (plan §5.5). +public sealed partial class LocalDataServices +{ + /// A1/A2: the condition-state hub the node manager feeds (null ⇒ conditions are not servable). + public ConditionStateHub? ConditionHub { get; init; } + + /// A2: the node manager's condition snapshot port (null ⇒ conditions are not servable). + public IOriginConditionSource? ConditionSource { get; init; } + + /// A2: the origin's condition-key derivation (unavailable ⇒ no conditions capability, fail closed). + public Func ConditionKeysSource { get; init; } = static () => ConditionKeys.Unavailable; + + /// Whether this origin can serve condition items at all (§5.2: no secret ⇒ no capability). + 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); + } + + /// + /// Admits a root-scoped condition item (§5.5): this origin serves conditions, the catalog is ready and this node is + /// Primary (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 + /// (CreateMonitoredItems on the placement's scope) whenever the listing is computed. + /// + 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; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs index 38cf003de..7e3fd7b24 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -49,10 +49,12 @@ public sealed partial class LocalDataServices : IDataConnectionFactory public TimeProvider Clock { get; } /// Diagnostics sink (history wiring faults); defaults to no logging. 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) }); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs index c3bd65945..fc1533358 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -21,7 +21,8 @@ public sealed partial class LocalExportCatalog private readonly Dictionary _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 nodes, IEnumerable 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)); } + /// + /// A2: the most conditions one root-scoped item at admits for — + /// the minimum MaxConditions 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). + /// + 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); + } + + /// A2: the largest per-item condition limit of the principal's AlarmSubscribe exports (0 = none). + 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. /// - public IReadOnlyList ListConditions(string principal, DataView root, DataOperations operation, ConditionKeys keys) + public IReadOnlyList ListConditions(string principal, DataView root, DataOperations operation, ConditionKeys keys) => + ListConditionScope(principal, root, operation, keys).Select(x => x.Exported).ToArray(); + + /// + /// A2: 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: + /// is never put on the wire. applies a further per-placement check (the origin ACL). + /// + internal IReadOnlyList ListConditionScope(string principal, DataView root, DataOperations operation, + ConditionKeys keys, Func? 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(); }