19b8163045
Resolves, authorizes (HistoryRead demand: mapping bit + local grant on the mapping scope, ACLs on or off) and pins each projected node, groups the batch per connection / details / issuing endpoint and forwards through IDataHistoryService. Remote cursors bind caller, mapping id+revision, connection route, projection generation, origin view and serving identity, and resend the ORIGINAL details; any change => BadContinuationPointInvalid with the origin token released. Shared per-request assembly budget (min mapping MaxHistoryAssemblyBytesPerRequest) => BadTooManyOperations for the remaining nodes. Releases coalesce per connection. Replaces the H2 refusal pin with the intended behaviour (granted => served, no grant => BadUserAccessDenied).
316 lines
17 KiB
C#
316 lines
17 KiB
C#
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();
|
|
// Serializes placement transitions with the SDK anchor reconciler without holding
|
|
// the catalog gate across SDK calls or introducing SDK -> transition lock ordering.
|
|
internal object TransitionGate { get; } = new();
|
|
private bool _suspended;
|
|
internal bool Suspended => Volatile.Read(ref _suspended);
|
|
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;
|
|
|
|
private IReadOnlyDictionary<string, (string ConnectionId, DataOperations Bits)> _droppedOperations =
|
|
new Dictionary<string, (string, DataOperations)>();
|
|
private string? _droppedRevision;
|
|
/// <summary>Diagnostics sink for the X0 dropped-operation warning (init so the DI constructor shape is unchanged).</summary>
|
|
public Microsoft.Extensions.Logging.ILogger Logger { private get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
/// <summary>H3: the mapping's per-request history assembly budget, while its activated authority is current.</summary>
|
|
public bool TryGetHistoryAssemblyBudget(string mappingId, out long bytes)
|
|
{
|
|
bytes = 0;
|
|
if (!TryGetConnectionId(mappingId, out _)) return false;
|
|
lock (_gate)
|
|
{
|
|
if (!_byMapping.TryGetValue(mappingId, out var placement)) return false;
|
|
bytes = placement.Mapping.MaxHistoryAssemblyBytesPerRequest;
|
|
return bytes > 0;
|
|
}
|
|
}
|
|
|
|
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();
|
|
// X0 tolerant reader: a mapping bit this build does not implement grants nothing. Mask the frozen copies (the
|
|
// caller's rows are untouched) so every downstream check sees only understood operations.
|
|
var dropped = new Dictionary<string, (string ConnectionId, DataOperations Bits)>(StringComparer.OrdinalIgnoreCase);
|
|
foreach (var mapping in frozenMappings)
|
|
{
|
|
var unknown = UnknownOperationDrops.Unknown(mapping.AllowedOperations);
|
|
if (unknown == DataOperations.None) continue;
|
|
mapping.AllowedOperations &= DataOperationSets.Understood;
|
|
// Every mapping is masked; only an enabled one is a live grant worth reporting (as for connections/exports).
|
|
if (mapping.Enabled) dropped[mapping.RemoteNamespaceMappingId] = (mapping.DataConnectionId, unknown);
|
|
}
|
|
var report = false;
|
|
lock (_gate)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
if (!ReferenceEquals(attempt, _attempt)) return;
|
|
_staged = frozenMappings;
|
|
_connections = frozenConnections;
|
|
_droppedOperations = dropped;
|
|
report = dropped.Count != 0 && !string.Equals(_droppedRevision, attempt.Revision, StringComparison.Ordinal);
|
|
_droppedRevision = attempt.Revision;
|
|
}
|
|
// Collected under _gate, reported after release.
|
|
if (report)
|
|
UnknownOperationDrops.Report(Logger, UnknownOperationDrops.MappingKind, attempt.Revision,
|
|
dropped.ToDictionary(x => x.Key, x => x.Value.Bits, StringComparer.OrdinalIgnoreCase));
|
|
}
|
|
|
|
/// <summary>X0 diagnostics: the staged mappings whose unknown operation bits were dropped, by mapping id.</summary>
|
|
public IReadOnlyDictionary<string, DataOperations> DroppedUnknownOperations
|
|
{
|
|
get { lock (_gate) return _droppedOperations.ToDictionary(x => x.Key, x => x.Value.Bits, StringComparer.OrdinalIgnoreCase); }
|
|
}
|
|
|
|
/// <summary>Per data connection id, how many of the staged mappings had unknown operation bits dropped.</summary>
|
|
public IReadOnlyDictionary<string, int> CaptureDroppedByConnection()
|
|
{
|
|
lock (_gate)
|
|
return _droppedOperations.Values.GroupBy(x => x.ConnectionId, StringComparer.OrdinalIgnoreCase)
|
|
.ToDictionary(x => x.Key, x => x.Count(), StringComparer.OrdinalIgnoreCase);
|
|
}
|
|
|
|
internal void AttemptBegan(CatalogAttempt attempt)
|
|
{
|
|
bool changed;
|
|
lock (TransitionGate)
|
|
lock (_gate)
|
|
{
|
|
if (_disposed || _attempt is not null && attempt.Epoch <= _attempt.Epoch) return;
|
|
_attempt = attempt;
|
|
Volatile.Write(ref _suspended, true);
|
|
Volatile.Write(ref _configuredStamp, new object());
|
|
_configuredCapabilities.Clear();
|
|
_staged = []; _connections = [];
|
|
_droppedOperations = new Dictionary<string, (string, DataOperations)>();
|
|
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 (TransitionGate)
|
|
lock (_gate)
|
|
{
|
|
if (_disposed || !ReferenceEquals(_attempt, attempt)) return;
|
|
Volatile.Write(ref _configuredStamp, new object());
|
|
_configuredCapabilities.Clear();
|
|
var catalog = completed ? _coordinator.MappingCatalog(attempt) : null;
|
|
var success = false;
|
|
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));
|
|
success = true;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException)
|
|
{
|
|
_resolver.ApplyMappings([]);
|
|
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
|
|
}
|
|
}
|
|
Volatile.Write(ref _suspended, !success);
|
|
_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 (TransitionGate)
|
|
lock (_gate)
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
Volatile.Write(ref _suspended, false);
|
|
Volatile.Write(ref _configuredStamp, new object());
|
|
_configuredCapabilities.Clear();
|
|
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
|
|
_byMapping.Clear();
|
|
_resolver.ApplyMappings([]);
|
|
_coordinator.DetachProjectedMappings(this);
|
|
}
|
|
Notify([]);
|
|
}
|
|
}
|