diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs new file mode 100644 index 000000000..fb99d040c --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionPlacements.cs @@ -0,0 +1,50 @@ +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// A1: where an origin condition comes from (wire ConditionInfo.source_kind NATIVE / SCRIPTED). +public enum ConditionSourceKind { Unspecified = 0, Native = 1, Scripted = 2 } + +/// +/// A1: an origin condition's identity in the node manager — the realm key its condition is registered under +/// ((Raw, RawPath) for a native condition, (Uns, ScriptedAlarmId) for a scripted one). +/// ⚠️ ORIGIN-INTERNAL: a native IS a RawPath; it never goes on the wire (the wire carries +/// the keyed condition_key instead, ). +/// +public readonly record struct OriginConditionRef(AddressSpaceRealm Realm, string ConditionId); + +/// +/// A1 (§5.2 "Addressing within the listing export's realm"): one realm-local placement of an origin condition, as the +/// origin's catalog knows it. +/// +/// Raw: = the raw namespace at the RawPath; = its device/group folder; +/// = the raw tag's ACL subject. +/// UNS native: = the uns namespace at the RESERVED reference id +/// Area/Line/Equipment/EffectiveName of each UnsTagReference to the alarm-bearing tag (no UNS node +/// exists there, #896; the effective-name guard reserves it); = that equipment; +/// = the equipment-owned subject. +/// UNS scripted: = the uns namespace at the ScriptedAlarmId; = its +/// equipment; = the equipment-owned subject. Scripted conditions have no Raw placement. +/// +/// ⚠️ ORIGIN-INTERNAL (carries ). What may reach a peer is +/// , via . +/// +public sealed record LocalConditionPlacement(DataView View, DataView Parent, NodeScope Scope, string BrowseName, + ConditionSourceKind SourceKind, OriginConditionRef Condition, string EntityKind, string EntityId) +{ + /// The peer-safe projection: address, parent and name, in the placement's own realm. + public ConditionPlacementView ToView() => new(View, Parent, BrowseName); +} + +/// A1: a placement as a listing may carry it (no origin condition id, no backing source). +public sealed record ConditionPlacementView(DataView View, DataView Parent, string BrowseName); + +/// +/// A1: one condition as an export listing presents it — the opaque (equal across every +/// listing, principal, restart and pair member) and its placements INSIDE the listed export root, all in that root's +/// realm. Nothing here names a RawPath unless the listing is itself a Raw listing. +/// +public sealed record ExportedCondition(string ConditionKey, ConditionSourceKind SourceKind, + IReadOnlyList Placements); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs index 388416776..39c29d926 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs @@ -50,6 +50,25 @@ public sealed class LocalCatalogCoordinator /// Diagnostics sink for the X0 dropped export-operation warning. public Microsoft.Extensions.Logging.ILogger Logger { private get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; + /// + /// A1: the origin's condition-key deriver (DataConnections:ConditionKeySecret). Unavailable by default, so an + /// origin without a secret lists no conditions (fail closed). + /// + public ConditionKeys ConditionKeys { get; init; } = ConditionKeys.Unavailable; + + /// + /// A1: the served catalog's condition listing for one export root (). + /// False — nothing listed — while no catalog is served or no condition-key secret is provisioned. + /// + public bool TryListConditions(string principal, DataView root, DataOperations operation, + out IReadOnlyList conditions) + { + conditions = []; + if (!ConditionKeys.IsAvailable || Current is not { } catalog) return false; + conditions = catalog.ListConditions(principal, root, operation, ConditionKeys); + return true; + } + public LocalCatalogCoordinator(CatalogActivation activation, DataPlaneAuthorityState authority, Func serving) { _activation = activation ?? throw new ArgumentNullException(nameof(activation)); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs index e04f05ec5..9b4969bd1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs @@ -62,9 +62,13 @@ public sealed partial class LocalExportCatalog areas.ToDictionary(x => x.UnsAreaId, x => x.Name, ids), lines.ToDictionary(x => x.UnsLineId, x => (x.UnsAreaId, x.Name), ids), equipment.ToDictionary(x => x.EquipmentId, x => (x.UnsLineId, x.Name), ids), referenceNames); - var composition = AddressSpaceComposer.Compose(areas, lines, equipment, drivers, [], virtuals, + // A1: the cluster's scripted alarms ride the same composition so their placements come from the producer the node + // manager materialises (EquipmentScriptedAlarms); nothing the v1 catalog reads depends on them. + var scriptedAlarms = snapshot.ScriptedAlarms.Where(x => equipmentIds.Contains(x.EquipmentId)).ToArray(); + var composition = AddressSpaceComposer.Compose(areas, lines, equipment, drivers, scriptedAlarms, virtuals, snapshot.Scripts, references, tags, folders, devices, groups); var nodes = new List((int)count); + var conditionPlacements = new List(); var views = new Dictionary<(DataRealm Realm, string Kind, string Id), DataView>(); var rawViewsByPath = new Dictionary(StringComparer.Ordinal); const DataOperations navigation = DataOperations.Browse | DataOperations.Metadata; @@ -127,9 +131,14 @@ public sealed partial class LocalExportCatalog rawSources.Add(plan.NodeId, (source, enabled)); var kind = ValueKind(plan.DataType); var supported = kind != DataValueKind.Unspecified && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind)); - Add("RawTag", plan.TagId, plan.Name, View(DataRealm.Raw, plan.NodeId, scope), scope, RawParent(scope), source, + var rawView = View(DataRealm.Raw, plan.NodeId, scope); + Add("RawTag", plan.TagId, plan.Name, rawView, scope, RawParent(scope), source, supported ? kind : DataValueKind.Null, plan.Writable && (!plan.IsArray || plan.ArrayWritable), plan.IsArray, plan.ArrayLength, supported, enabled); + // A1: a native condition's Raw placement is its RawPath (ConditionId = RawPath), under its device/group folder. + if (plan.Alarm is not null) + conditionPlacements.Add(new(rawView, RawParent(scope), scope, plan.Name, ConditionSourceKind.Native, + new(AddressSpaceRealm.Raw, plan.NodeId), "RawTag", plan.TagId)); } foreach (var area in areas) { @@ -141,9 +150,11 @@ public sealed partial class LocalExportCatalog var scope = Scope(NodeAclScopeKind.UnsLine, line.UnsLineId, DataRealm.Uns); Add("UnsLine", line.UnsLineId, line.Name, View(DataRealm.Uns, line.UnsLineId, scope), scope, views[(DataRealm.Uns, "UnsArea", line.UnsAreaId.ToUpperInvariant())]); } + var equipmentScopes = new Dictionary(ids); foreach (var item in equipment) { var scope = Scope(NodeAclScopeKind.Equipment, item.EquipmentId, DataRealm.Uns); + equipmentScopes[item.EquipmentId] = scope; Add("Equipment", item.EquipmentId, item.Name, View(DataRealm.Uns, item.EquipmentId, scope), scope, views[(DataRealm.Uns, "UnsLine", item.UnsLineId.ToUpperInvariant())]); } @@ -172,9 +183,57 @@ public sealed partial class LocalExportCatalog SourceKey.ForVirtual(cluster, value.VirtualTagId, serving.NodeId, serving.Incarnation), kind == DataValueKind.Unspecified ? DataValueKind.Null : kind, supported: kind != DataValueKind.Unspecified, enabled: value.Enabled); } - return new(cluster, serving, activation, nodes, snapshot.DataExports, maximumNodes); + AddConditionPlacements(); + return new(cluster, serving, activation, nodes, snapshot.DataExports, maximumNodes, DistinctPlacements(conditionPlacements)); + + // A1 (§5.2): the UNS placements. Native: the RESERVED reference id Area/Line/Equipment/EffectiveName of every + // reference to an alarm-bearing tag — the same derivation as AddressSpaceComposer.BuildUnsReferenceVariables, which + // skips exactly these references (#896), so no UNS node exists there and the guard keeps the id unique. Scripted: + // the ScriptedAlarmId the node manager registers the condition under. Both are authorized against the + // equipment-owned subject and parented at the equipment. Nothing here carries a RawPath except the internal + // OriginConditionRef of a native condition. + void AddConditionPlacements() + { + var alarmPlans = composition.RawTags.Where(x => x.Alarm is not null).ToDictionary(x => x.TagId, ids); + var areaById = areas.ToDictionary(x => x.UnsAreaId, ids); + var lineById = lines.ToDictionary(x => x.UnsLineId, ids); + var equipmentById = equipment.ToDictionary(x => x.EquipmentId, ids); + foreach (var reference in references.OrderBy(x => x.UnsTagReferenceId, StringComparer.Ordinal)) + { + if (!alarmPlans.TryGetValue(reference.TagId, out var plan) + || !equipmentById.TryGetValue(reference.EquipmentId, out var owner) + || !lineById.TryGetValue(owner.UnsLineId, out var line) || !areaById.TryGetValue(line.UnsAreaId, out var area)) + continue; + var effectiveName = string.IsNullOrEmpty(reference.DisplayNameOverride) ? tagById[reference.TagId].Name + : reference.DisplayNameOverride!; + string reserved; + try { reserved = V3NodeIds.UnsChild(V3NodeIds.Uns(area.Name, line.Name, owner.Name), effectiveName); } + catch (ArgumentException) { continue; } // an invalid name segment: the deploy gate rejects it; never listed + var view = new DataView(new(cluster, V3NodeIds.UnsNamespaceUri, "string", reserved), DataRealm.Uns, null, 0, reserved); + conditionPlacements.Add(new(view, views[(DataRealm.Uns, "Equipment", owner.EquipmentId.ToUpperInvariant())], + DataScopeSubjects.Owned(equipmentScopes[owner.EquipmentId]), effectiveName, ConditionSourceKind.Native, + new(AddressSpaceRealm.Raw, plan.NodeId), "UnsTagReference", reference.UnsTagReferenceId)); + } + foreach (var alarm in composition.EquipmentScriptedAlarms) + { + // The node manager materialises only enabled scripted alarms (AddressSpaceApplier). + if (!alarm.Enabled || !equipmentScopes.TryGetValue(alarm.EquipmentId, out var owner)) continue; + var view = new DataView(new(cluster, V3NodeIds.UnsNamespaceUri, "string", alarm.ScriptedAlarmId), DataRealm.Uns, + null, 0, string.Join('/', owner.Segments.Append(alarm.Name))); + conditionPlacements.Add(new(view, views[(DataRealm.Uns, "Equipment", alarm.EquipmentId.ToUpperInvariant())], + DataScopeSubjects.Owned(owner), alarm.Name, ConditionSourceKind.Scripted, + new(AddressSpaceRealm.Uns, alarm.ScriptedAlarmId), "ScriptedAlarm", alarm.ScriptedAlarmId)); + } + } } + /// + /// An address claimed by two placements is ambiguous: neither is listed (fail closed for conditions), and the v1 + /// catalog compiles exactly as before. + /// + private static IReadOnlyList DistinctPlacements(IEnumerable placements) => + placements.GroupBy(x => (x.View.Realm, x.View.Address.Identifier)).Where(x => x.Count() == 1).Select(x => x.Single()).ToArray(); + private static DataValueKind ValueKind(string type) => type switch { "Boolean" => DataValueKind.Boolean, "SByte" => DataValueKind.Int8, "Byte" => DataValueKind.UInt8, 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 a15f08bde..c3bd65945 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -17,12 +17,15 @@ public sealed partial class LocalExportCatalog private readonly Dictionary _children; private readonly ExportRule[] _exports; private readonly IDataMappedCatalogAuthority _activation; + private readonly Dictionary<(DataRealm Realm, string Identifier), LocalConditionPlacement> _placements; + 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); public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation, - IEnumerable nodes, IEnumerable exports, int maximumNodes = 100_000) + IEnumerable nodes, IEnumerable exports, int maximumNodes = 100_000, + IEnumerable? conditionPlacements = null) { ArgumentException.ThrowIfNullOrWhiteSpace(clusterId); ArgumentNullException.ThrowIfNull(serving); @@ -101,6 +104,8 @@ public sealed partial class LocalExportCatalog _exports = rules.ToArray(); DroppedUnknownOperations = dropped; Nodes = new ReadOnlyCollection(_nodes.Values.ToArray()); + (_placements, _placementsByCondition) = IndexPlacements(conditionPlacements ?? []); + ConditionPlacements = new ReadOnlyCollection(_placements.Values.ToArray()); } public string ClusterId { get; } @@ -122,6 +127,8 @@ public sealed partial class LocalExportCatalog ClusterId = current.ClusterId; Serving = serving; _activation = current._activation; _nodes = current._nodes; _children = current._children; _exports = current._exports; Nodes = current.Nodes; DroppedUnknownOperations = current.DroppedUnknownOperations; + _placements = current._placements; _placementsByCondition = current._placementsByCondition; + ConditionPlacements = current.ConditionPlacements; } /// A role-only transition changes serving provenance without freshening source acquisitions. @@ -213,4 +220,107 @@ public sealed partial class LocalExportCatalog internal DataOperations ExportOperations(string principal) => _exports .Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)) .Aggregate(DataOperations.None, (operations, rule) => operations | rule.Operations); + + // ---- A1: realm-local condition placements (§5.2). The v1 node set, listing and wire bytes are untouched. ---- + + /// A1: every condition placement of this origin, in every realm (origin-internal; see ). + public IReadOnlyList ConditionPlacements { get; } + + /// A1: the placement at an (unmapped) origin address in its realm; the claimed Subject is ignored. + public bool TryResolveConditionPlacement(DataView view, out LocalConditionPlacement placement) + { + ArgumentNullException.ThrowIfNull(view); + if (view.MappingId is null && view.MappingRevision == 0 && view.Address is { } address + && string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase) + && address.IdentifierKind == "string" && address.NamespaceUri == RealmNamespace(view.Realm) + && _placements.TryGetValue((view.Realm, address.Identifier), out var found)) + { placement = found; return true; } + placement = null!; return false; + } + + /// A1: every placement of one origin condition (Raw and UNS), ordered by realm then identifier. + public IReadOnlyList PlacementsOf(OriginConditionRef condition) => + _placementsByCondition.TryGetValue(condition, out var found) ? Array.AsReadOnly(found) : []; + + /// + /// A1: whether holds an export of the placement's realm granting + /// whose root contains the placement (whole realm, or an ancestor of its parent). + /// + internal bool AllowsConditionPlacement(string principal, LocalConditionPlacement placement, DataOperations operation) + { + ArgumentNullException.ThrowIfNull(placement); + if (operation == DataOperations.None) return false; + foreach (var rule in _exports) + { + if (!string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) + || rule.Realm != placement.View.Realm || (rule.Operations & operation) != operation) continue; + if (rule.WholeRealm || IsAncestor(rule.Root!, placement.Parent)) return true; + } + return false; + } + + /// + /// A1: the conditions under one export root as a listing presents them to — each with + /// its condition_key and only the placements inside , all in the root's realm and each + /// passing the principal's export check for (A2 passes + /// ; until A2 makes that bit understood, no export grants it and the + /// 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) + { + ArgumentException.ThrowIfNullOrWhiteSpace(principal); + ArgumentNullException.ThrowIfNull(root); + ArgumentNullException.ThrowIfNull(keys); + 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)) + .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) + .ToArray(); + } + + private static string RealmNamespace(DataRealm realm) => + realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : realm == DataRealm.Uns ? V3NodeIds.UnsNamespaceUri : string.Empty; + + private (Dictionary<(DataRealm, string), LocalConditionPlacement>, Dictionary) + IndexPlacements(IEnumerable placements) + { + var byAddress = new Dictionary<(DataRealm, string), LocalConditionPlacement>(); + foreach (var input in placements) + { + ArgumentNullException.ThrowIfNull(input); + input.View.Validate(); + var view = input.View; + var address = view.Address; + var nativeRawPlacement = view.Realm == DataRealm.Raw && input.SourceKind == ConditionSourceKind.Native + && input.Condition.Realm == AddressSpaceRealm.Raw && input.Condition.ConditionId == address.Identifier; + var nativeUnsPlacement = view.Realm == DataRealm.Uns && input.SourceKind == ConditionSourceKind.Native + && input.Condition.Realm == AddressSpaceRealm.Raw; + var scriptedPlacement = view.Realm == DataRealm.Uns && input.SourceKind == ConditionSourceKind.Scripted + && input.Condition.Realm == AddressSpaceRealm.Uns && input.Condition.ConditionId == address.Identifier; + if (view.MappingId is not null || !string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase) + || address.IdentifierKind != "string" || address.NamespaceUri != RealmNamespace(view.Realm) + || string.IsNullOrEmpty(input.Condition.ConditionId) || string.IsNullOrWhiteSpace(input.BrowseName) + || !(nativeRawPlacement || nativeUnsPlacement || scriptedPlacement) + || !string.Equals(input.Scope.ClusterId, ClusterId, StringComparison.OrdinalIgnoreCase) + || input.Scope.Kind != (view.Realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns) + || !TryResolve(input.Parent, out var parent) || parent.Metadata.View.Realm != view.Realm) + throw new ArgumentException("Condition placement is nonlocal, cross-realm or not parented in this catalog.", nameof(placements)); + var placement = input with + { + View = view with { Address = address with { OriginClusterId = ClusterId } }, + Parent = parent.Metadata.View, + Scope = input.Scope with { Segments = Array.AsReadOnly(input.Scope.Segments.ToArray()) } + }; + if (!byAddress.TryAdd((view.Realm, address.Identifier), placement)) + throw new ArgumentException("Catalog contains duplicate condition placements.", nameof(placements)); + } + var byCondition = byAddress.Values.GroupBy(x => x.Condition).ToDictionary(x => x.Key, + x => x.OrderBy(p => p.View.Realm).ThenBy(p => p.View.Address.Identifier, StringComparer.Ordinal).ToArray()); + return (byAddress, byCondition); + } }