274 lines
21 KiB
C#
274 lines
21 KiB
C#
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||
|
||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||
|
||
public sealed partial class LocalExportCatalog
|
||
{
|
||
/// <summary>Stable data-service realm root; its identifier kind cannot collide with an SDK string NodeId.</summary>
|
||
public static DataView RealmRoot(string clusterId, DataRealm realm)
|
||
{
|
||
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId); DataContractValidation.Required(realm);
|
||
return new(new(clusterId, realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri,
|
||
"realm-root", clusterId), realm, null, 0, realm == DataRealm.Raw ? "raw" : "uns");
|
||
}
|
||
|
||
/// <summary>Compile origin views from the deployed snapshot using the same identity and ACL producers as the SDK.</summary>
|
||
public static LocalExportCatalog Compile(DraftSnapshot snapshot, ServingIdentity serving,
|
||
IDataMappedCatalogAuthority activation, int maximumNodes = 100_000,
|
||
Microsoft.Extensions.Logging.ILogger? logger = null)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(snapshot);
|
||
serving.Validate(requireEpochs: true);
|
||
if (DataConnectionValidator.ValidateDeployed(snapshot).Count != 0)
|
||
throw new InvalidDataException("Origin catalog configuration is invalid.");
|
||
var cluster = snapshot.ClusterId;
|
||
var ids = StringComparer.OrdinalIgnoreCase;
|
||
bool Same(string a, string b) => ids.Equals(a, b);
|
||
var folders = snapshot.RawFolders.Where(x => Same(x.ClusterId, cluster)).ToArray();
|
||
var drivers = snapshot.DriverInstances.Where(x => Same(x.ClusterId, cluster)).ToArray();
|
||
var driverIds = drivers.Select(x => x.DriverInstanceId).ToHashSet(ids);
|
||
var devices = snapshot.Devices.Where(x => driverIds.Contains(x.DriverInstanceId)).ToArray();
|
||
var deviceIds = devices.Select(x => x.DeviceId).ToHashSet(ids);
|
||
var groups = snapshot.TagGroups.Where(x => deviceIds.Contains(x.DeviceId)).ToArray();
|
||
var tags = snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId)).ToArray();
|
||
var areas = snapshot.UnsAreas.Where(x => Same(x.ClusterId, cluster)).ToArray();
|
||
var areaIds = areas.Select(x => x.UnsAreaId).ToHashSet(ids);
|
||
var lines = snapshot.UnsLines.Where(x => areaIds.Contains(x.UnsAreaId)).ToArray();
|
||
var lineIds = lines.Select(x => x.UnsLineId).ToHashSet(ids);
|
||
var equipment = snapshot.Equipment.Where(x => lineIds.Contains(x.UnsLineId)).ToArray();
|
||
var equipmentIds = equipment.Select(x => x.EquipmentId).ToHashSet(ids);
|
||
var tagIds = tags.Select(x => x.TagId).ToHashSet(ids);
|
||
var references = snapshot.UnsTagReferences.Where(x => equipmentIds.Contains(x.EquipmentId) && tagIds.Contains(x.TagId)).ToArray();
|
||
var virtuals = snapshot.VirtualTags.Where(x => equipmentIds.Contains(x.EquipmentId)).ToArray();
|
||
var count = 2L + folders.Length + drivers.Length + devices.Length + groups.Length + tags.Length
|
||
+ areas.Length + lines.Length + equipment.Length + references.Length + virtuals.Length;
|
||
if (maximumNodes <= 0 || count > maximumNodes) throw new ArgumentOutOfRangeException(nameof(maximumNodes), "Origin catalog node budget exceeded.");
|
||
var tagById = tags.ToDictionary(x => x.TagId, ids);
|
||
var deviceById = devices.ToDictionary(x => x.DeviceId, ids);
|
||
var driverById = drivers.ToDictionary(x => x.DriverInstanceId, ids);
|
||
var referenceNames = references.Select(x => (x.EquipmentId, x.TagId, EffectiveName: x.DisplayNameOverride ?? tagById[x.TagId].Name)).ToArray();
|
||
var scopeResolver = new AclScopePathResolver(
|
||
folders.ToDictionary(x => x.RawFolderId, x => (x.ParentRawFolderId, x.Name), ids),
|
||
drivers.ToDictionary(x => x.DriverInstanceId, x => (x.RawFolderId, x.Name), ids),
|
||
devices.ToDictionary(x => x.DeviceId, x => (x.DriverInstanceId, x.Name), ids),
|
||
groups.ToDictionary(x => x.TagGroupId, x => (x.ParentTagGroupId, x.DeviceId, x.Name), ids),
|
||
tags.ToDictionary(x => x.TagId, x => (x.DeviceId, x.TagGroupId, x.Name), ids),
|
||
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);
|
||
// 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;
|
||
// H2: every value node MAY offer HistoryRead; whether it does for a caller is decided live (export grant, origin
|
||
// ACL, a registered historian tagname) and the bit never reaches a call that did not negotiate history.
|
||
const DataOperations data = navigation | DataOperations.Read | DataOperations.Subscribe | DataOperations.HistoryRead;
|
||
|
||
NodeScope Scope(NodeAclScopeKind kind, string id, DataRealm realm)
|
||
{
|
||
var token = realm == DataRealm.Raw ? "raw" : "uns";
|
||
var paths = scopeResolver.ResolveOne(kind, id).Where(x => x.Segments.Count > 0 && x.Segments[0] == token).ToArray();
|
||
if (paths.Length != 1) throw new InvalidDataException("Origin entity has ambiguous or missing policy ancestry.");
|
||
return new() { ClusterId = cluster, Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns,
|
||
Segments = Array.AsReadOnly(paths[0].Segments.Skip(1).ToArray()) };
|
||
}
|
||
DataView View(DataRealm realm, string identifier, NodeScope scope) => new(
|
||
new(cluster, realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, "string", identifier),
|
||
realm, null, 0, string.Join('/', scope.Segments));
|
||
void Add(string kind, string id, string name, DataView view, NodeScope scope, DataView? parent,
|
||
BackingSourceKey? source = null, DataValueKind valueKind = DataValueKind.Null, bool writable = false,
|
||
bool array = false, uint? length = null, bool supported = true, bool enabled = true)
|
||
{
|
||
writable &= supported; // #917 review: an unsupported value node is never writable, not even in internal metadata
|
||
var operations = source is null ? navigation : data | (writable ? DataOperations.Write : DataOperations.None);
|
||
var metadata = new DataMetadata(view, name, source is null ? "Folder" : supported ? "Variable" : "UnsupportedVariable",
|
||
array && supported ? DataValueKind.Array : valueKind, array && supported ? 1 : -1,
|
||
array && supported ? Array.AsReadOnly(new[] { length is { } n ? checked((int)n) : 0 }) : [],
|
||
// #916: Metadata.stable_source_id is never sent. The internal key of a driver source is
|
||
// "<len>:<driverInstanceId><RawPath>" (SourceKey.ForDriver), which told a UNS-only peer the origin's driver ids
|
||
// and RawPaths; no consumer uses the field (it is optional on the wire and old consumers decode its absence as
|
||
// null). Acquisition keys on the LocalDataNode.Source BackingSourceKey, which is unchanged.
|
||
writable, operations, serving.CatalogEpoch, null, null, false,
|
||
array && supported ? valueKind : null);
|
||
nodes.Add(new(kind, id, metadata, scope, parent, source, supported, enabled));
|
||
views.Add((view.Realm, kind, id.ToUpperInvariant()), view);
|
||
if (view.Realm == DataRealm.Raw && view.Address.IdentifierKind == "string") rawViewsByPath.Add(view.Address.Identifier, view);
|
||
}
|
||
foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns })
|
||
{
|
||
var root = RealmRoot(cluster, realm);
|
||
Add("Cluster", cluster, realm.ToString(), root,
|
||
new() { ClusterId = cluster, Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = [] }, null);
|
||
}
|
||
DataView RawParent(NodeScope scope) => scope.Segments.Count <= 1 ? RealmRoot(cluster, DataRealm.Raw)
|
||
: rawViewsByPath.GetValueOrDefault(string.Join('/', scope.Segments.Take(scope.Segments.Count - 1)))
|
||
?? throw new InvalidDataException("Origin raw parent is not compiled.");
|
||
|
||
var rawEntities = new List<(string Kind, string Id, string Name, NodeScope Scope)>();
|
||
rawEntities.AddRange(folders.Select(x => ("RawFolder", x.RawFolderId, x.Name, Scope(NodeAclScopeKind.RawFolder, x.RawFolderId, DataRealm.Raw))));
|
||
rawEntities.AddRange(drivers.Select(x => ("RawDriver", x.DriverInstanceId, x.Name, Scope(NodeAclScopeKind.RawDriver, x.DriverInstanceId, DataRealm.Raw))));
|
||
rawEntities.AddRange(devices.Select(x => ("RawDevice", x.DeviceId, x.Name, Scope(NodeAclScopeKind.RawDevice, x.DeviceId, DataRealm.Raw))));
|
||
rawEntities.AddRange(groups.Select(x => ("RawTagGroup", x.TagGroupId, x.Name, Scope(NodeAclScopeKind.RawTagGroup, x.TagGroupId, DataRealm.Raw))));
|
||
foreach (var entity in rawEntities.OrderBy(x => x.Scope.Segments.Count).ThenBy(x => x.Id, StringComparer.Ordinal))
|
||
{
|
||
var path = RawPaths.Build(entity.Scope.Segments);
|
||
Add(entity.Kind, entity.Id, entity.Name, View(DataRealm.Raw, path, entity.Scope), entity.Scope, RawParent(entity.Scope));
|
||
}
|
||
var rawPlans = composition.RawTags.ToDictionary(x => x.NodeId, StringComparer.Ordinal);
|
||
var rawSources = new Dictionary<string, (BackingSourceKey Key, bool Enabled)>(StringComparer.Ordinal);
|
||
foreach (var plan in composition.RawTags)
|
||
{
|
||
var scope = Scope(NodeAclScopeKind.Tag, plan.TagId, DataRealm.Raw);
|
||
var source = SourceKey.ForDriver(cluster, driverById[plan.DriverInstanceId].DriverInstanceId, plan.NodeId, serving.NodeId, serving.Incarnation);
|
||
var enabled = deviceById[tagById[plan.TagId].DeviceId].Enabled && driverById[plan.DriverInstanceId].Enabled;
|
||
rawSources.Add(plan.NodeId, (source, enabled));
|
||
var kind = ValueKind(plan.DataType);
|
||
// #917: an alarm-bearing tag never gets a value (DriverHostActor keeps it out of the value fan-out; #896 gives it
|
||
// no UNS variable), so it is an unsupported value node: Browse does not list it (LocalDataServices) and every
|
||
// value operation answers Unsupported, instead of a Variable a consumer would wait on forever. The node is KEPT so
|
||
// an export rooted at it still compiles, but such a root grants nothing: its values are unsupported and its
|
||
// condition placement sits under its folder, not under the tag. The alarm is forwarded as a condition (A1–A4).
|
||
var supported = plan.Alarm is null && kind != DataValueKind.Unspecified
|
||
&& (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
|
||
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, driverById[plan.DriverInstanceId].DriverType));
|
||
}
|
||
foreach (var area in areas)
|
||
{
|
||
var scope = Scope(NodeAclScopeKind.UnsArea, area.UnsAreaId, DataRealm.Uns);
|
||
Add("UnsArea", area.UnsAreaId, area.Name, View(DataRealm.Uns, area.UnsAreaId, scope), scope, RealmRoot(cluster, DataRealm.Uns));
|
||
}
|
||
foreach (var line in lines)
|
||
{
|
||
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())]);
|
||
}
|
||
foreach (var reference in composition.UnsReferenceVariables)
|
||
{
|
||
var scope = new NodeScope { ClusterId = cluster, Kind = NodeHierarchyKind.Uns,
|
||
Segments = Array.AsReadOnly(reference.NodeId.Split(RawPaths.Separator)) };
|
||
var source = rawSources[reference.BackingRawPath];
|
||
var plan = rawPlans[reference.BackingRawPath];
|
||
var kind = ValueKind(reference.DataType);
|
||
var supported = kind != DataValueKind.Unspecified && (!reference.BackingIsArray || DataValue.IsSupportedArrayElementKind(kind));
|
||
Add("UnsTagReference", reference.UnsTagReferenceId, reference.EffectiveName, View(DataRealm.Uns, reference.NodeId, scope), scope,
|
||
views[(DataRealm.Uns, "Equipment", reference.EquipmentId.ToUpperInvariant())], source.Key, supported ? kind : DataValueKind.Null,
|
||
reference.Writable && (!reference.BackingIsArray || reference.BackingArrayWritable),
|
||
reference.BackingIsArray, plan.ArrayLength, supported, source.Enabled);
|
||
}
|
||
foreach (var value in composition.EquipmentVirtualTags)
|
||
{
|
||
var owner = Scope(NodeAclScopeKind.Equipment, value.EquipmentId, DataRealm.Uns);
|
||
var scope = DataScopeSubjects.Owned(owner);
|
||
var identifier = string.IsNullOrWhiteSpace(value.FolderPath) ? V3NodeIds.Uns(value.EquipmentId, value.Name)
|
||
: V3NodeIds.Uns(new[] { value.EquipmentId }.Concat(value.FolderPath.Split(RawPaths.Separator)).Append(value.Name));
|
||
var view = View(DataRealm.Uns, identifier, owner) with { Subject = string.Join('/', owner.Segments.Append(value.Name)) };
|
||
var kind = ValueKind(value.DataType);
|
||
Add("VirtualTag", value.VirtualTagId, value.Name, view, scope, views[(DataRealm.Uns, "Equipment", value.EquipmentId.ToUpperInvariant())],
|
||
SourceKey.ForVirtual(cluster, value.VirtualTagId, serving.NodeId, serving.Incarnation),
|
||
kind == DataValueKind.Unspecified ? DataValueKind.Null : kind, supported: kind != DataValueKind.Unspecified, enabled: value.Enabled);
|
||
}
|
||
AddConditionPlacements();
|
||
return new(cluster, serving, activation, nodes, snapshot.DataExports, maximumNodes, DistinctPlacements(conditionPlacements, logger));
|
||
|
||
// 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,
|
||
driverById[plan.DriverInstanceId].DriverType));
|
||
}
|
||
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>
|
||
/// <remarks>Review nit: the drop is logged at Warning — LOCALLY only (the identifiers may be RawPaths; nothing about
|
||
/// the collision reaches a peer, which simply does not see those conditions listed).</remarks>
|
||
private static IReadOnlyList<LocalConditionPlacement> DistinctPlacements(IEnumerable<LocalConditionPlacement> placements,
|
||
Microsoft.Extensions.Logging.ILogger? logger)
|
||
{
|
||
var groups = placements.GroupBy(x => (x.View.Realm, x.View.Address.Identifier)).ToList();
|
||
var colliding = groups.Where(x => x.Count() > 1).ToList();
|
||
if (colliding.Count > 0 && logger is not null)
|
||
{
|
||
Microsoft.Extensions.Logging.LoggerExtensions.LogWarning(logger,
|
||
"Origin catalog: {Count} condition placement address(es) are claimed by more than one placement and are not listed (fail closed): {Addresses}",
|
||
colliding.Count, string.Join(", ", colliding.Take(10).Select(g => $"{g.Key.Realm}:{g.Key.Identifier} x{g.Count()}")));
|
||
}
|
||
|
||
return groups.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,
|
||
"Int16" => DataValueKind.Int16, "Int32" => DataValueKind.Int32, "Int64" => DataValueKind.Int64,
|
||
"UInt16" => DataValueKind.UInt16, "UInt32" => DataValueKind.UInt32, "UInt64" => DataValueKind.UInt64,
|
||
"Float" or "Single" => DataValueKind.Float, "Double" => DataValueKind.Double, "String" => DataValueKind.String,
|
||
"ByteString" => DataValueKind.Bytes, "DateTime" => DataValueKind.Timestamp, "Guid" => DataValueKind.Guid,
|
||
_ => DataValueKind.Unspecified
|
||
};
|
||
}
|