feat: expose mapped raw and uns data through grpc adapters
This commit is contained in:
+249
@@ -0,0 +1,249 @@
|
||||
using System.Text.Json;
|
||||
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>A mapped root placed under an applied local catalog parent.</summary>
|
||||
public sealed record ProjectedMappingPlacement(RemoteNamespaceMapping Mapping, DataView Parent, DataView Anchor,
|
||||
NodeScope Scope, IReadOnlyList<string> LocalAncestry, IDataMappedCatalogAuthority Authority);
|
||||
|
||||
/// <summary>Owns mapping placements tied to one activated catalog attempt.</summary>
|
||||
public sealed class ProjectedMappingDeploymentRuntime : IDisposable
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly LocalCatalogCoordinator _coordinator;
|
||||
private readonly RemoteNamespaceResolver _resolver;
|
||||
private CatalogAttempt? _attempt;
|
||||
private RemoteNamespaceMapping[] _staged = [];
|
||||
private DataConnection[] _connections = [];
|
||||
private IReadOnlyList<ProjectedMappingPlacement> _active = Array.Empty<ProjectedMappingPlacement>();
|
||||
private Dictionary<string, ProjectedMappingPlacement> _byMapping = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, ConfiguredProjectionCapability> _configuredCapabilities = new(StringComparer.OrdinalIgnoreCase);
|
||||
private object _configuredStamp = new();
|
||||
private bool _disposed;
|
||||
|
||||
public ProjectedMappingDeploymentRuntime(LocalCatalogCoordinator coordinator, RemoteNamespaceResolver resolver)
|
||||
{
|
||||
_coordinator = coordinator ?? throw new ArgumentNullException(nameof(coordinator));
|
||||
_resolver = resolver ?? throw new ArgumentNullException(nameof(resolver));
|
||||
_coordinator.AttachProjectedMappings(this);
|
||||
}
|
||||
|
||||
private static T Copy<T>(T value) => JsonSerializer.Deserialize<T>(JsonSerializer.SerializeToUtf8Bytes(value))!;
|
||||
private long _placementCopiesForTests;
|
||||
internal long PlacementCopiesForTests => Interlocked.Read(ref _placementCopiesForTests);
|
||||
private IReadOnlyList<ProjectedMappingPlacement> CopyPlacements(IReadOnlyList<ProjectedMappingPlacement> source)
|
||||
{
|
||||
Interlocked.Add(ref _placementCopiesForTests, source.Count);
|
||||
return Array.AsReadOnly(source.Select(x => x with { Mapping = Copy(x.Mapping) }).ToArray());
|
||||
}
|
||||
// Mint only from an exact currently published placement. The capability guard is
|
||||
// deliberately lock-free: cache validation can run under the cache lock while a
|
||||
// mapping transition holds _gate and calls into that cache.
|
||||
internal bool TryAcquireConfiguredCapability(string mappingId, DataRealm realm,
|
||||
out ConfiguredProjectionCapability? capability, out ProjectedMappingPlacement? placement)
|
||||
{
|
||||
capability = null;
|
||||
placement = null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || _attempt is null || !_byMapping.TryGetValue(mappingId, out var original) ||
|
||||
!original.Authority.IsActive || original.Mapping.Realm != realm || original.Mapping.RemoteRealm != realm ||
|
||||
!original.Mapping.Enabled ||
|
||||
(original.Mapping.AllowedOperations & (DataOperations.Browse | DataOperations.Subscribe)) !=
|
||||
(DataOperations.Browse | DataOperations.Subscribe)) return false;
|
||||
var catalog = _coordinator.MappingCatalog(_attempt);
|
||||
if (catalog is null || !ReferenceEquals(catalog.MappingAuthority, original.Authority)) return false;
|
||||
var published = Volatile.Read(ref _active);
|
||||
if (!published.Any(item => ReferenceEquals(item, original))) return false;
|
||||
placement = CopyPlacements([original])[0];
|
||||
if (!_configuredCapabilities.TryGetValue(original.Mapping.RemoteNamespaceMappingId, out capability))
|
||||
{
|
||||
var stamp = Volatile.Read(ref _configuredStamp);
|
||||
capability = new ConfiguredProjectionCapability(original.Mapping.RemoteNamespaceMappingId, original.Mapping.Revision,
|
||||
original.Mapping.Realm, original.Mapping.AllowedOperations, original.Authority,
|
||||
() => ReferenceEquals(Volatile.Read(ref _configuredStamp), stamp));
|
||||
_configuredCapabilities.Add(original.Mapping.RemoteNamespaceMappingId, capability);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal bool IsCurrentPlacement(ProjectedMappingPlacement placement)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || _attempt is null || !placement.Authority.IsActive ||
|
||||
!_byMapping.TryGetValue(placement.Mapping.RemoteNamespaceMappingId, out var current) ||
|
||||
!ReferenceEquals(current.Authority, placement.Authority) ||
|
||||
current.Mapping.RemoteNamespaceMappingId != placement.Mapping.RemoteNamespaceMappingId ||
|
||||
current.Mapping.Revision != placement.Mapping.Revision ||
|
||||
!string.Equals(current.Mapping.DataConnectionId, placement.Mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase) ||
|
||||
current.Parent != placement.Parent || current.Anchor != placement.Anchor) return false;
|
||||
var catalog = _coordinator.MappingCatalog(_attempt);
|
||||
return catalog is not null && ReferenceEquals(catalog.MappingAuthority, current.Authority);
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<ProjectedMappingPlacement> Active
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
return _active.All(x => x.Authority.IsActive) ? CopyPlacements(_active) : Array.Empty<ProjectedMappingPlacement>();
|
||||
}
|
||||
}
|
||||
public event Action<IReadOnlyList<ProjectedMappingPlacement>>? Changed;
|
||||
/// <summary>Resolve a mapping only while its original activated authority remains current.</summary>
|
||||
public bool TryGetConnectionId(string mappingId, out string? connectionId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
connectionId = null;
|
||||
if (_disposed || _attempt is null || !_byMapping.TryGetValue(mappingId, out var placement) || !placement.Authority.IsActive)
|
||||
return false;
|
||||
var current = _coordinator.MappingCatalog(_attempt);
|
||||
if (current is null || !ReferenceEquals(current.MappingAuthority, placement.Authority)) return false;
|
||||
connectionId = placement.Mapping.DataConnectionId;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Stage(CatalogAttempt attempt, IReadOnlyList<RemoteNamespaceMapping> mappings, IReadOnlyList<DataConnection> connections)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(attempt);
|
||||
ArgumentNullException.ThrowIfNull(mappings);
|
||||
ArgumentNullException.ThrowIfNull(connections);
|
||||
var frozenMappings = mappings.Select(Copy).ToArray();
|
||||
var frozenConnections = connections.Select(Copy).ToArray();
|
||||
lock (_gate)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (!ReferenceEquals(attempt, _attempt)) return;
|
||||
_staged = frozenMappings;
|
||||
_connections = frozenConnections;
|
||||
}
|
||||
}
|
||||
|
||||
internal void AttemptBegan(CatalogAttempt attempt)
|
||||
{
|
||||
bool changed;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || _attempt is not null && attempt.Epoch <= _attempt.Epoch) return;
|
||||
_attempt = attempt;
|
||||
Volatile.Write(ref _configuredStamp, new object());
|
||||
_configuredCapabilities.Clear();
|
||||
_staged = []; _connections = [];
|
||||
changed = _active.Count != 0;
|
||||
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
|
||||
_byMapping.Clear();
|
||||
_resolver.ApplyMappings([]);
|
||||
}
|
||||
if (changed) Notify([]);
|
||||
}
|
||||
|
||||
internal void AttemptCompleted(CatalogAttempt attempt, bool completed)
|
||||
{
|
||||
IReadOnlyList<ProjectedMappingPlacement> published;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || !ReferenceEquals(_attempt, attempt)) return;
|
||||
Volatile.Write(ref _configuredStamp, new object());
|
||||
_configuredCapabilities.Clear();
|
||||
var catalog = completed ? _coordinator.MappingCatalog(attempt) : null;
|
||||
if (catalog is null || !catalog.IsActive)
|
||||
{
|
||||
_resolver.ApplyMappings([]);
|
||||
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
var placements = Build(catalog, _staged, _connections);
|
||||
var bindings = placements.Select(p => new ProjectedMappingBinding(p.Mapping, p.Anchor, p.Scope,
|
||||
p.LocalAncestry, p.Authority, (_, _) => false)).ToArray();
|
||||
_resolver.ApplyMappings(bindings);
|
||||
var current = _coordinator.MappingCatalog(attempt);
|
||||
if (current is null || !ReferenceEquals(current.MappingAuthority, catalog.MappingAuthority) || !catalog.IsActive)
|
||||
throw new InvalidOperationException("Catalog attempt changed during projection activation.");
|
||||
Volatile.Write(ref _active, Array.AsReadOnly(placements));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException)
|
||||
{
|
||||
_resolver.ApplyMappings([]);
|
||||
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
|
||||
}
|
||||
}
|
||||
_byMapping = _active.ToDictionary(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.OrdinalIgnoreCase);
|
||||
published = CopyPlacements(_active);
|
||||
}
|
||||
Notify(published);
|
||||
}
|
||||
|
||||
private static ProjectedMappingPlacement[] Build(LocalExportCatalog catalog, IReadOnlyList<RemoteNamespaceMapping> mappings,
|
||||
IReadOnlyList<DataConnection> connections)
|
||||
{
|
||||
var placements = new List<ProjectedMappingPlacement>();
|
||||
foreach (var mapping in mappings.Where(x => x.Enabled))
|
||||
{
|
||||
var parentMatches = catalog.Nodes.Where(x => x.EntityKind == mapping.LocalParentKind &&
|
||||
string.Equals(x.EntityId, mapping.LocalParentId, StringComparison.OrdinalIgnoreCase) && x.Metadata.View.Realm == mapping.Realm).ToArray();
|
||||
var connectionMatches = connections.Where(x => x.Enabled && string.Equals(x.DataConnectionId, mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase) &&
|
||||
string.Equals(x.ClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
if (parentMatches.Length != 1 || connectionMatches.Length != 1 || string.IsNullOrWhiteSpace(connectionMatches[0].ExpectedClusterId) ||
|
||||
!string.Equals(mapping.ClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(mapping.BranchName) ||
|
||||
mapping.BranchName.Contains('/') || mapping.BranchName.Contains('\\') || mapping.Realm != mapping.RemoteRealm ||
|
||||
catalog.Children(parentMatches[0]).Any(x => string.Equals(x.Metadata.BrowseName, mapping.BranchName, StringComparison.OrdinalIgnoreCase)) ||
|
||||
placements.Any(x => x.Parent == parentMatches[0].Metadata.View && string.Equals(x.Mapping.BranchName, mapping.BranchName, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new ArgumentException("Invalid or colliding mapping placement.");
|
||||
var parent = parentMatches[0];
|
||||
var ancestry = new List<string>();
|
||||
var cursor = parent;
|
||||
var seen = new HashSet<DataView>();
|
||||
while (true)
|
||||
{
|
||||
if (!seen.Add(cursor.Metadata.View)) throw new ArgumentException("Catalog parent cycle.");
|
||||
ancestry.Add(cursor.EntityId);
|
||||
if (cursor.Parent is null) break;
|
||||
if (!catalog.TryResolve(cursor.Parent, out cursor!)) throw new ArgumentException("Catalog parent missing.");
|
||||
}
|
||||
ancestry.Reverse();
|
||||
var segments = Array.AsReadOnly(parent.Scope.Segments.Concat([mapping.BranchName]).ToArray());
|
||||
var scope = parent.Scope with { Segments = segments };
|
||||
var address = new DataAddress(connectionMatches[0].ExpectedClusterId, mapping.RemoteNamespaceUri,
|
||||
mapping.RemoteIdentifierKind, mapping.RemoteIdentifier);
|
||||
var anchor = new DataView(address, mapping.Realm, mapping.RemoteNamespaceMappingId, mapping.Revision, string.Join('/', segments));
|
||||
anchor.Validate();
|
||||
placements.Add(new(mapping, parent.Metadata.View, anchor, scope, Array.AsReadOnly(ancestry.ToArray()), catalog.MappingAuthority));
|
||||
}
|
||||
return placements.ToArray();
|
||||
}
|
||||
|
||||
private void Notify(IReadOnlyList<ProjectedMappingPlacement> placements)
|
||||
{
|
||||
var handlers = Changed;
|
||||
if (handlers is null) return;
|
||||
foreach (Action<IReadOnlyList<ProjectedMappingPlacement>> handler in handlers.GetInvocationList())
|
||||
try { handler(CopyPlacements(placements)); } catch (Exception) { }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
Volatile.Write(ref _configuredStamp, new object());
|
||||
_configuredCapabilities.Clear();
|
||||
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
|
||||
_byMapping.Clear();
|
||||
_resolver.ApplyMappings([]);
|
||||
_coordinator.DetachProjectedMappings(this);
|
||||
}
|
||||
Notify([]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user