327 lines
21 KiB
C#
327 lines
21 KiB
C#
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;
|
|
|
|
/// <summary>An origin-owned view, with policy placement separate from its backing acquisition.</summary>
|
|
public sealed record LocalDataNode(string EntityKind, string EntityId, DataMetadata Metadata,
|
|
NodeScope Scope, DataView? Parent, BackingSourceKey? Source, bool Supported = true, bool SourceEnabled = true);
|
|
|
|
/// <summary>Immutable origin-only catalog. Projected peer nodes cannot become export authority.</summary>
|
|
public sealed partial class LocalExportCatalog
|
|
{
|
|
private readonly Dictionary<(DataAddress Address, DataRealm Realm), LocalDataNode> _nodes = new();
|
|
private readonly Dictionary<DataView, LocalDataNode[]> _children;
|
|
private readonly ExportRule[] _exports;
|
|
private readonly IDataMappedCatalogAuthority _activation;
|
|
private readonly Dictionary<(DataRealm Realm, string Identifier), LocalConditionPlacement> _placements;
|
|
private readonly Dictionary<OriginConditionRef, LocalConditionPlacement[]> _placementsByCondition;
|
|
private sealed record ExportRule(string Identity, string Principal, DataRealm Realm, DataView? Root, bool WholeRealm,
|
|
DataOperations Operations, int Batch, int Page, int Items, int Streams,
|
|
int HistoryReads = 4, int HistoryValuesPerPage = 10_000, int HistoryResponseBytes = 4 * 1024 * 1024);
|
|
|
|
public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation,
|
|
IEnumerable<LocalDataNode> nodes, IEnumerable<DataExport> exports, int maximumNodes = 100_000,
|
|
IEnumerable<LocalConditionPlacement>? conditionPlacements = null)
|
|
{
|
|
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<DataView>();
|
|
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<ExportRule>();
|
|
var dropped = new Dictionary<string, DataOperations>(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 || export.MaxConcurrentHistoryReads <= 0
|
|
|| export.MaxHistoryValuesPerPage <= 0 || export.MaxHistoryResponseBytes <= 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));
|
|
if (UnknownOperationDrops.Unknown(export.AllowedOperations) is var unknown && unknown != DataOperations.None)
|
|
dropped[export.DataExportId] = unknown;
|
|
}
|
|
_exports = rules.ToArray();
|
|
DroppedUnknownOperations = dropped;
|
|
Nodes = new ReadOnlyCollection<LocalDataNode>(_nodes.Values.ToArray());
|
|
(_placements, _placementsByCondition) = IndexPlacements(conditionPlacements ?? []);
|
|
ConditionPlacements = new ReadOnlyCollection<LocalConditionPlacement>(_placements.Values.ToArray());
|
|
}
|
|
|
|
public string ClusterId { get; }
|
|
/// <summary>X0 diagnostics: exports whose operation bits this build does not implement were dropped, by export id.</summary>
|
|
public IReadOnlyDictionary<string, DataOperations> 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<LocalDataNode> 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;
|
|
_placements = current._placements; _placementsByCondition = current._placementsByCondition;
|
|
ConditionPlacements = current.ConditionPlacements;
|
|
}
|
|
|
|
/// <summary>A role-only transition changes serving provenance without freshening source acquisitions.</summary>
|
|
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<LocalDataNode> 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)
|
|
{
|
|
// An inert rule (X0: only operation bits this build does not implement) grants nothing, so it cannot lower the
|
|
// principal's limits on its other exports either.
|
|
var rules = _exports.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)
|
|
&& x.Operations != DataOperations.None).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))
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// H2: the principal's remote-history limits — the minimum over every export rule that grants it HistoryRead (an
|
|
/// export without the bit cannot lower them); null when no rule grants HistoryRead.
|
|
/// </summary>
|
|
internal (int ConcurrentReads, int ValuesPerPage, int ResponseBytes)? HistoryLimitsFor(string principal)
|
|
{
|
|
var rules = _exports.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)
|
|
&& (x.Operations & DataOperations.HistoryRead) != 0).ToArray();
|
|
return rules.Length == 0 ? null
|
|
: (rules.Min(x => x.HistoryReads), rules.Min(x => x.HistoryValuesPerPage), rules.Min(x => x.HistoryResponseBytes));
|
|
}
|
|
|
|
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. ----
|
|
|
|
/// <summary>A1: every condition placement of this origin, in every realm (origin-internal; see <see cref="ListConditions"/>).</summary>
|
|
public IReadOnlyList<LocalConditionPlacement> ConditionPlacements { get; }
|
|
|
|
/// <summary>A1: the placement at an (unmapped) origin address in its realm; the claimed Subject is ignored.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>A1: every placement of one origin condition (Raw and UNS), ordered by realm then identifier.</summary>
|
|
public IReadOnlyList<LocalConditionPlacement> PlacementsOf(OriginConditionRef condition) =>
|
|
_placementsByCondition.TryGetValue(condition, out var found) ? Array.AsReadOnly(found) : [];
|
|
|
|
/// <summary>
|
|
/// A1: whether <paramref name="principal"/> holds an export of the placement's realm granting
|
|
/// <paramref name="operation"/> whose root contains the placement (whole realm, or an ancestor of its parent).
|
|
/// </summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A1: the conditions under one export root as a listing presents them to <paramref name="principal"/> — each with
|
|
/// its <c>condition_key</c> and only the placements inside <paramref name="root"/>, all in the root's realm and each
|
|
/// passing the principal's export check for <paramref name="operation"/> (A2 passes
|
|
/// <see cref="DataOperations.AlarmSubscribe"/>; 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.
|
|
/// </summary>
|
|
public IReadOnlyList<ExportedCondition> 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<OriginConditionRef, LocalConditionPlacement[]>)
|
|
IndexPlacements(IEnumerable<LocalConditionPlacement> 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);
|
|
}
|
|
}
|