using System.Collections.ObjectModel; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// An origin-owned view, with policy placement separate from its backing acquisition. public sealed record LocalDataNode(string EntityKind, string EntityId, DataMetadata Metadata, NodeScope Scope, DataView? Parent, BackingSourceKey? Source, bool Supported = true, bool SourceEnabled = true); /// Immutable origin-only catalog. Projected peer nodes cannot become export authority. public sealed partial class LocalExportCatalog { private readonly Dictionary<(DataAddress Address, DataRealm Realm), LocalDataNode> _nodes = new(); private readonly Dictionary _children; private readonly ExportRule[] _exports; private readonly IDataMappedCatalogAuthority _activation; private sealed record ExportRule(string Identity, string Principal, DataRealm Realm, DataView? Root, bool WholeRealm, DataOperations Operations, int Batch, int Page, int Items, int Streams); public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation, IEnumerable nodes, IEnumerable exports, int maximumNodes = 100_000) { ArgumentException.ThrowIfNullOrWhiteSpace(clusterId); ArgumentNullException.ThrowIfNull(serving); ArgumentNullException.ThrowIfNull(activation); ArgumentNullException.ThrowIfNull(nodes); ArgumentNullException.ThrowIfNull(exports); serving.Validate(requireEpochs: true); if (maximumNodes <= 0) throw new ArgumentOutOfRangeException(nameof(maximumNodes)); ClusterId = clusterId; Serving = serving; _activation = activation; foreach (var input in nodes) { if (_nodes.Count >= maximumNodes) throw new ArgumentOutOfRangeException(nameof(nodes), "Catalog node budget exceeded."); ArgumentNullException.ThrowIfNull(input); input.Metadata.Validate(); var view = input.Metadata.View; if (view.MappingId is not null || !string.Equals(view.Address.OriginClusterId, clusterId, StringComparison.OrdinalIgnoreCase) || !string.Equals(input.Scope.ClusterId, clusterId, StringComparison.OrdinalIgnoreCase) || input.EntityKind == "RemoteNamespaceMapping" || input.Metadata.CatalogRevision != serving.CatalogEpoch || input.Scope.Kind is not (NodeHierarchyKind.Raw or NodeHierarchyKind.Uns) || view.Address.NamespaceUri != (view.Realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri) || view.Realm != (input.Scope.Kind == NodeHierarchyKind.Raw ? DataRealm.Raw : DataRealm.Uns) || (input.Source is { } source && (!string.Equals(source.OriginClusterId, clusterId, StringComparison.OrdinalIgnoreCase) || source.ServingNodeId != serving.NodeId || source.ServingIncarnation != serving.Incarnation))) throw new ArgumentException("Catalog contains a nonlocal or projected node.", nameof(nodes)); var node = input with { Metadata = input.Metadata with { View = view with { Address = view.Address with { OriginClusterId = clusterId } }, Dimensions = Array.AsReadOnly(input.Metadata.Dimensions.ToArray()) }, Scope = input.Scope with { Segments = Array.AsReadOnly(input.Scope.Segments.ToArray()) } }; if (!_nodes.TryAdd((node.Metadata.View.Address, view.Realm), node)) throw new ArgumentException("Catalog contains duplicate addresses.", nameof(nodes)); } foreach (var pair in _nodes.ToArray()) if (pair.Value.Parent is { } parent) { if (!TryResolve(parent, out var resolved)) throw new ArgumentException("Catalog parent is not origin-local.", nameof(nodes)); _nodes[pair.Key] = pair.Value with { Parent = resolved.Metadata.View }; } // A bounded parent walk makes a corrupt cycle a rejected generation, rather than an export escape. foreach (var node in _nodes.Values) { var seen = new HashSet(); var current = node; while (current.Parent is { } parent) { if (!seen.Add(parent)) throw new ArgumentException("Catalog contains a parent cycle.", nameof(nodes)); current = _nodes[(parent.Address, parent.Realm)]; } } _children = _nodes.Values.Where(x => x.Parent is not null).GroupBy(x => x.Parent!) .ToDictionary(x => x.Key, x => x.OrderBy(n => n.Metadata.BrowseName, StringComparer.Ordinal) .ThenBy(n => n.Metadata.View.Address.Identifier, StringComparer.Ordinal).ToArray()); var rules = new List(); var dropped = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var export in exports.Where(x => x.Enabled && string.Equals(x.ClusterId, clusterId, StringComparison.OrdinalIgnoreCase))) { var wholeRealm = export.RootKind == "Cluster" && string.Equals(export.RootEntityId, clusterId, StringComparison.OrdinalIgnoreCase); var roots = _nodes.Values.Where(x => x.EntityKind == export.RootKind && string.Equals(x.EntityId, export.RootEntityId, StringComparison.OrdinalIgnoreCase) && x.Metadata.View.Realm == export.Realm).ToArray(); 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) 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)); if (UnknownOperationDrops.Unknown(export.AllowedOperations) is var unknown && unknown != DataOperations.None) dropped[export.DataExportId] = unknown; } _exports = rules.ToArray(); DroppedUnknownOperations = dropped; Nodes = new ReadOnlyCollection(_nodes.Values.ToArray()); } public string ClusterId { get; } /// X0 diagnostics: exports whose operation bits this build does not implement were dropped, by export id. public IReadOnlyDictionary DroppedUnknownOperations { get; } public ServingIdentity Serving { get; } internal IDataMappedCatalogAuthority MappingAuthority => _activation; public long AuthorityEpoch => _activation.AuthorityEpoch; public bool IsActive => _activation.IsActive && _activation.CatalogEpoch == Serving.CatalogEpoch && _activation.AuthorityEpoch == Serving.AuthorityEpoch; public IReadOnlyList Nodes { get; } private LocalExportCatalog(LocalExportCatalog current, ServingIdentity serving) { serving.Validate(requireEpochs: true); if (serving.NodeId != current.Serving.NodeId || serving.Incarnation != current.Serving.Incarnation || serving.CatalogEpoch != current.Serving.CatalogEpoch || serving.AuthorityEpoch != current.Serving.AuthorityEpoch) throw new ArgumentException("A new process or catalog generation requires a newly compiled catalog.", nameof(serving)); ClusterId = current.ClusterId; Serving = serving; _activation = current._activation; _nodes = current._nodes; _children = current._children; _exports = current._exports; Nodes = current.Nodes; DroppedUnknownOperations = current.DroppedUnknownOperations; } /// A role-only transition changes serving provenance without freshening source acquisitions. public LocalExportCatalog WithServingRole(ServingIdentity serving) => new(this, serving); public bool TryResolve(DataView view, out LocalDataNode node) { var address = LocalAddress(view.Address); if (_nodes.TryGetValue((address, view.Realm), out var found) && found.Metadata.View == (view with { Address = address })) { node = found; return true; } node = null!; return false; } private DataAddress LocalAddress(DataAddress address) => string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase) ? address with { OriginClusterId = ClusterId } : address; internal bool ContainsAddress(DataView view) => _nodes.ContainsKey((LocalAddress(view.Address), view.Realm)); internal bool TryResolveAddress(DataView view, out LocalDataNode node) { if (view.MappingId is null && view.MappingRevision == 0 && _nodes.TryGetValue((LocalAddress(view.Address), view.Realm), out var found)) { node = found; return true; } node = null!; return false; } public IReadOnlyList Children(LocalDataNode parent) => _children.TryGetValue(parent.Metadata.View, out var children) ? Array.AsReadOnly(children) : []; internal bool AllowsExport(string principal, LocalDataNode node, DataOperations operation) { foreach (var rule in _exports) { if (!string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) || rule.Realm != node.Metadata.View.Realm || (rule.Operations & operation) != operation) continue; if (rule.WholeRealm || IsAncestor(rule.Root!, node.Metadata.View) || (operation == DataOperations.Browse && IsAncestor(node.Metadata.View, rule.Root!))) return true; } return false; } internal string SubscriptionExportScope(string principal, LocalDataNode node) { var ids = _exports.Where(rule => string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) && rule.Realm == node.Metadata.View.Realm && (rule.Operations & DataOperations.Subscribe) != 0 && (rule.WholeRealm || IsAncestor(rule.Root!, node.Metadata.View))) .Select(rule => rule.Identity).Order(StringComparer.Ordinal).ToArray(); // Invalid/missing export identities must not accidentally share across views. if (ids.Length == 0 || ids.Any(string.IsNullOrWhiteSpace)) return $"view:{node.Metadata.View.Realm}:{node.Metadata.View.Address.NamespaceUri.Length}:{node.Metadata.View.Address.NamespaceUri}:{node.Metadata.View.Address.IdentifierKind.Length}:{node.Metadata.View.Address.IdentifierKind}:{node.Metadata.View.Address.Identifier.Length}:{node.Metadata.View.Address.Identifier}"; return string.Concat(ids.Select(id => $"{id.Length}:{id}")); } private bool IsAncestor(DataView ancestor, DataView candidate) { var current = candidate; for (var depth = 0; depth <= _nodes.Count; depth++) { if (current == ancestor) return true; if (!TryResolve(current, out var node) || node.Parent is null) return false; current = node.Parent; } return false; } internal DataLimits LimitsFor(string principal, DataLimits limits) { var rules = _exports.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)).ToArray(); return rules.Length == 0 ? limits : limits with { MaxBatchItems = Math.Min(limits.MaxBatchItems, rules.Min(x => x.Batch)), MaxPageItems = Math.Min(limits.MaxPageItems, rules.Min(x => x.Page)), MaxMonitoredItems = Math.Min(limits.MaxMonitoredItems, rules.Min(x => x.Items)), MaxStreams = Math.Min(limits.MaxStreams, rules.Min(x => x.Streams)) }; } internal DataOperations ExportOperations(string principal) => _exports .Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)) .Aggregate(DataOperations.None, (operations, rule) => operations | rule.Operations); }