Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs
T
Joseph Doherty e7cacd2ac9 feat(grpc-data): H2 origin HistoryRead ingress, header gating, LocalDataConnection history
Service: HistoryRead rpc; history (field 16, Metadata.history, bit 32) emitted only on a call whose header requested
history AND whose origin can serve it, otherwise stripped to the v1 shape; un-negotiated HistoryRead is
FAILED_PRECONDITION. Origin: Implemented(target) grows by HistoryRead when a historian backend is configured;
per-item gate catalog -> export grant + origin ACL HistoryRead -> tagname, every refusal the same
BadHistoryOperationUnsupported; per-principal admission (BadTooManyOperations), per-page ceiling, response-byte chunking
with single-use chunk tokens; one session per (principal, credential, HTTP/2 connection) cleared on close; wiring
faults BadInternalError + error log; caller cancel never a backend outcome. DataOperationPolicy maps HistoryRead.
2026-11-23 20:42:51 -05:00

188 lines
14 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)
{
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);
var composition = AddressSpaceComposer.Compose(areas, lines, equipment, drivers, [], virtuals,
snapshot.Scripts, references, tags, folders, devices, groups);
var nodes = new List<LocalDataNode>((int)count);
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)
{
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 }) : [],
writable, operations, serving.CatalogEpoch, source?.StableSourceId, 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);
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,
supported ? kind : DataValueKind.Null, plan.Writable && (!plan.IsArray || plan.ArrayWritable),
plan.IsArray, plan.ArrayLength, supported, enabled);
}
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())]);
}
foreach (var item in equipment)
{
var scope = Scope(NodeAclScopeKind.Equipment, item.EquipmentId, DataRealm.Uns);
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);
}
return new(cluster, serving, activation, nodes, snapshot.DataExports, maximumNodes);
}
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
};
}