feat(grpc-data): A1 — realm-local condition placement enumeration and per-export condition listing

This commit is contained in:
Joseph Doherty
2026-11-24 09:18:08 -05:00
parent 6584c8535a
commit cbc8d431f3
4 changed files with 242 additions and 4 deletions
@@ -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;
/// <summary>A1: where an origin condition comes from (wire <c>ConditionInfo.source_kind</c> NATIVE / SCRIPTED).</summary>
public enum ConditionSourceKind { Unspecified = 0, Native = 1, Scripted = 2 }
/// <summary>
/// A1: an origin condition's identity in the node manager — the realm key its condition is registered under
/// (<c>(Raw, RawPath)</c> for a native condition, <c>(Uns, ScriptedAlarmId)</c> for a scripted one).
/// ⚠️ ORIGIN-INTERNAL: a native <see cref="ConditionId"/> IS a RawPath; it never goes on the wire (the wire carries
/// the keyed <c>condition_key</c> instead, <see cref="ConditionKeys"/>).
/// </summary>
public readonly record struct OriginConditionRef(AddressSpaceRealm Realm, string ConditionId);
/// <summary>
/// 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.
/// <list type="bullet">
/// <item>Raw: <see cref="View"/> = the raw namespace at the RawPath; <see cref="Parent"/> = its device/group folder;
/// <see cref="Scope"/> = the raw tag's ACL subject.</item>
/// <item>UNS native: <see cref="View"/> = the uns namespace at the RESERVED reference id
/// <c>Area/Line/Equipment/EffectiveName</c> of each <c>UnsTagReference</c> to the alarm-bearing tag (no UNS node
/// exists there, #896; the effective-name guard reserves it); <see cref="Parent"/> = that equipment;
/// <see cref="Scope"/> = the equipment-owned subject.</item>
/// <item>UNS scripted: <see cref="View"/> = the uns namespace at the ScriptedAlarmId; <see cref="Parent"/> = its
/// equipment; <see cref="Scope"/> = the equipment-owned subject. Scripted conditions have no Raw placement.</item>
/// </list>
/// ⚠️ ORIGIN-INTERNAL (carries <see cref="Condition"/>). What may reach a peer is
/// <see cref="ConditionPlacementView"/>, via <see cref="LocalExportCatalog.ListConditions"/>.
/// </summary>
public sealed record LocalConditionPlacement(DataView View, DataView Parent, NodeScope Scope, string BrowseName,
ConditionSourceKind SourceKind, OriginConditionRef Condition, string EntityKind, string EntityId)
{
/// <summary>The peer-safe projection: address, parent and name, in the placement's own realm.</summary>
public ConditionPlacementView ToView() => new(View, Parent, BrowseName);
}
/// <summary>A1: a placement as a listing may carry it (no origin condition id, no backing source).</summary>
public sealed record ConditionPlacementView(DataView View, DataView Parent, string BrowseName);
/// <summary>
/// A1: one condition as an export listing presents it — the opaque <see cref="ConditionKey"/> (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.
/// </summary>
public sealed record ExportedCondition(string ConditionKey, ConditionSourceKind SourceKind,
IReadOnlyList<ConditionPlacementView> Placements);
@@ -50,6 +50,25 @@ public sealed class LocalCatalogCoordinator
/// <summary>Diagnostics sink for the X0 dropped export-operation warning.</summary>
public Microsoft.Extensions.Logging.ILogger Logger { private get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
/// <summary>
/// A1: the origin's condition-key deriver (<c>DataConnections:ConditionKeySecret</c>). Unavailable by default, so an
/// origin without a secret lists no conditions (fail closed).
/// </summary>
public ConditionKeys ConditionKeys { get; init; } = ConditionKeys.Unavailable;
/// <summary>
/// A1: the served catalog's condition listing for one export root (<see cref="LocalExportCatalog.ListConditions"/>).
/// False — nothing listed — while no catalog is served or no condition-key secret is provisioned.
/// </summary>
public bool TryListConditions(string principal, DataView root, DataOperations operation,
out IReadOnlyList<ExportedCondition> 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<ServingIdentity> serving)
{
_activation = activation ?? throw new ArgumentNullException(nameof(activation));
@@ -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<LocalDataNode>((int)count);
var conditionPlacements = new List<LocalConditionPlacement>();
var views = new Dictionary<(DataRealm Realm, string Kind, string Id), DataView>();
var rawViewsByPath = new Dictionary<string, DataView>(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<string, NodeScope>(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));
}
}
}
/// <summary>
/// An address claimed by two placements is ambiguous: neither is listed (fail closed for conditions), and the v1
/// catalog compiles exactly as before.
/// </summary>
private static IReadOnlyList<LocalConditionPlacement> DistinctPlacements(IEnumerable<LocalConditionPlacement> 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,
@@ -17,12 +17,15 @@ public sealed partial class LocalExportCatalog
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<LocalDataNode> nodes, IEnumerable<DataExport> exports, int maximumNodes = 100_000,
IEnumerable<LocalConditionPlacement>? 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<LocalDataNode>(_nodes.Values.ToArray());
(_placements, _placementsByCondition) = IndexPlacements(conditionPlacements ?? []);
ConditionPlacements = new ReadOnlyCollection<LocalConditionPlacement>(_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;
}
/// <summary>A role-only transition changes serving provenance without freshening source acquisitions.</summary>
@@ -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. ----
/// <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);
}
}